@holistics/anfra-sdk 0.20.0 → 0.22.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.
Files changed (38) hide show
  1. package/README.md +5 -0
  2. package/dist/api.d.ts +11 -8
  3. package/dist/api.js +45 -22
  4. package/dist/app.d.ts +5 -5
  5. package/dist/app.js +5 -4
  6. package/dist/{bootstrap-DHU2haC5.d.ts → bootstrap-fGoj2ap1.d.ts} +324 -27
  7. package/dist/build.d.ts +2 -2
  8. package/dist/{chunk-32566ZNE.js → chunk-2TTGSNHA.js} +1 -1
  9. package/dist/{chunk-H52PO7MP.js → chunk-33HI2ODM.js} +25 -0
  10. package/dist/chunk-4UEESYHH.js +32 -0
  11. package/dist/{chunk-KKSOTHP4.js → chunk-7GQZU5FL.js} +1 -1
  12. package/dist/{chunk-4TXKXLWK.js → chunk-7I2HXY72.js} +1 -1
  13. package/dist/{chunk-DITKCHFQ.js → chunk-CLXZMA5D.js} +1 -1
  14. package/dist/{chunk-GBXK7F2V.js → chunk-D7DIJRAC.js} +14 -1
  15. package/dist/{chunk-ACKFOANJ.js → chunk-DWQUIHUX.js} +4 -1
  16. package/dist/{chunk-FTTVLHNN.js → chunk-EOFPMSND.js} +1 -1
  17. package/dist/{chunk-SXKJQU7A.js → chunk-GPBYPSWK.js} +22 -36
  18. package/dist/{chunk-EIPHDMZ7.js → chunk-UWRQXPPG.js} +69 -24
  19. package/dist/{chunk-T5T76SAR.js → chunk-YPGMBSOZ.js} +1209 -274
  20. package/dist/common.d.ts +3 -3
  21. package/dist/common.js +1 -1
  22. package/dist/{data-ESPFZ5IM.js → data-SZDYO55C.js} +7 -5
  23. package/dist/{declaration-RYRBX7PH.js → declaration-GYV6OUR3.js} +5 -3
  24. package/dist/{errors-189T_Mnc.d.ts → errors-kH5eHvNO.d.ts} +1 -1
  25. package/dist/host.d.ts +2 -2
  26. package/dist/host.js +31 -8
  27. package/dist/{overview-AWPXJACF.js → overview-CD6NY3VQ.js} +28 -13
  28. package/dist/{plugin-rRd-zHGt.d.ts → plugin-DG2NDTCT.d.ts} +7 -2
  29. package/dist/plugins.d.ts +1 -7
  30. package/dist/plugins.js +53 -17
  31. package/dist/{queries-FWMX7H5Z.js → queries-BWKWZQMG.js} +70 -17
  32. package/dist/{structure-VFRJFC4C.js → structure-JO4YZHKZ.js} +5 -3
  33. package/dist/{tab-XL2HS5W4.js → tab-QPHE7YUQ.js} +3 -3
  34. package/dist/testing.d.ts +2 -1
  35. package/dist/testing.js +8 -7
  36. package/dist/{menu-Cam-hOdJ.d.ts → theme-FQ_1b569.d.ts} +72 -55
  37. package/dist/{types-N0V9n38H.d.ts → types-BE767W6G.d.ts} +879 -129
  38. package/package.json +1 -1
@@ -2,11 +2,10 @@ import {
2
2
  FILTER_AGGREGATIONS
3
3
  } from "./chunk-XIUFHRZE.js";
4
4
  import {
5
- createEndpoint,
6
5
  eventShortcut,
7
6
  isTyping,
8
7
  normalizeShortcut
9
- } from "./chunk-SXKJQU7A.js";
8
+ } from "./chunk-4UEESYHH.js";
10
9
  import {
11
10
  DEFAULT_TOKENS,
12
11
  PROVISION_ELEMENT_ID,
@@ -15,7 +14,11 @@ import {
15
14
  } from "./chunk-RXPNL7UR.js";
16
15
  import {
17
16
  version
18
- } from "./chunk-FTTVLHNN.js";
17
+ } from "./chunk-EOFPMSND.js";
18
+ import {
19
+ abortError,
20
+ createEndpoint
21
+ } from "./chunk-GPBYPSWK.js";
19
22
  import {
20
23
  DataAppError,
21
24
  MESSAGE_LIMIT,
@@ -132,14 +135,303 @@ var Observable = class {
132
135
  }
133
136
  };
134
137
 
138
+ // src/app/suggest.ts
139
+ function editDistance(a, b) {
140
+ const rows = a.length + 1;
141
+ const cols = b.length + 1;
142
+ let prev = Array.from({ length: cols }, (_, j) => j);
143
+ for (let i = 1; i < rows; i++) {
144
+ const curr = [i];
145
+ for (let j = 1; j < cols; j++) {
146
+ curr[j] = Math.min(
147
+ prev[j] + 1,
148
+ curr[j - 1] + 1,
149
+ prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
150
+ );
151
+ }
152
+ prev = curr;
153
+ }
154
+ return prev[cols - 1];
155
+ }
156
+ function suggest(value, candidates) {
157
+ let best;
158
+ let bestDistance = Infinity;
159
+ candidates.forEach((candidate) => {
160
+ const distance = editDistance(value.toLowerCase(), candidate.toLowerCase());
161
+ if (distance < bestDistance) {
162
+ bestDistance = distance;
163
+ best = candidate;
164
+ }
165
+ });
166
+ const threshold = Math.max(2, Math.floor(value.length / 3));
167
+ return bestDistance <= threshold ? best : void 0;
168
+ }
169
+ function withSuggestion(message, value, candidates) {
170
+ const hint = suggest(value, candidates);
171
+ return hint ? `${message} Did you mean '${hint}'?` : message;
172
+ }
173
+
174
+ // src/app/validation.ts
175
+ var DatasetIndex = class {
176
+ constructor(descriptor) {
177
+ __publicField(this, "descriptor");
178
+ __publicField(this, "fields", /* @__PURE__ */ new Map());
179
+ __publicField(this, "references");
180
+ this.descriptor = descriptor;
181
+ descriptor.data_models.forEach((model) => {
182
+ model.fields.forEach((field) => {
183
+ const modelName = String(model.name);
184
+ this.fields.set(`${modelName}.${field.name}`, {
185
+ modelName,
186
+ fieldName: field.name,
187
+ isMetric: false,
188
+ type: field.type,
189
+ label: field.label ?? field.name
190
+ });
191
+ });
192
+ });
193
+ descriptor.metrics.forEach((metric) => {
194
+ this.fields.set(metric.name, {
195
+ fieldName: metric.name,
196
+ isMetric: true,
197
+ type: metric.type,
198
+ label: metric.label ?? metric.name
199
+ });
200
+ });
201
+ this.references = [...this.fields.keys()];
202
+ }
203
+ resolve(reference, entity) {
204
+ const field = this.fields.get(reference);
205
+ if (field) return field;
206
+ throw new ValidationError(
207
+ withSuggestion(
208
+ `Unknown field '${reference}' on dataset '${this.descriptor.name}'.`,
209
+ reference,
210
+ this.references
211
+ ),
212
+ entity
213
+ );
214
+ }
215
+ };
216
+ function resolveDataset(datasets, uname, entity) {
217
+ const dataset = datasets[uname];
218
+ if (dataset) return dataset;
219
+ throw new ValidationError(
220
+ withSuggestion(
221
+ `Unknown dataset '${uname}'.`,
222
+ uname,
223
+ Object.keys(datasets)
224
+ ),
225
+ entity
226
+ );
227
+ }
228
+ function assertValidFilterAggregation(aggregation, entity) {
229
+ if (!FILTER_AGGREGATIONS.includes(aggregation)) {
230
+ throw new ValidationError(
231
+ withSuggestion(
232
+ `Invalid filter aggregation '${aggregation}'.`,
233
+ aggregation,
234
+ [...FILTER_AGGREGATIONS]
235
+ ),
236
+ entity
237
+ );
238
+ }
239
+ }
240
+ function assertUniqueName(taken, name, kind) {
241
+ if (!name) {
242
+ throw new ValidationError(`A ${kind} needs a name.`);
243
+ }
244
+ for (const existing of taken) {
245
+ if (existing === name) {
246
+ throw new ValidationError(`'${name}' is already declared in this app.`, name);
247
+ }
248
+ }
249
+ }
250
+ var DURATION_UNITS = { ns: 1e-6, us: 1e-3, "\xB5s": 1e-3, ms: 1, s: 1e3, m: 6e4, h: 36e5 };
251
+ var MAX_CACHE_DURATION_MS = 168 * 36e5;
252
+ function parseDuration(text) {
253
+ if (text === "0") return 0;
254
+ const part = /(\d+(?:\.\d*)?|\.\d+)(ns|us|µs|ms|s|m|h)/y;
255
+ let total = 0;
256
+ let end = 0;
257
+ for (let match = part.exec(text); match; match = part.exec(text)) {
258
+ total += parseFloat(match[1]) * DURATION_UNITS[match[2]];
259
+ end = part.lastIndex;
260
+ }
261
+ return end > 0 && end === text.length ? total : void 0;
262
+ }
263
+ function gave(declarer, setting, value, how) {
264
+ const shown = JSON.stringify(value);
265
+ return how === "sets" ? `${declarer} sets ${setting} to ${shown}` : `${declarer} declares ${setting} ${shown}`;
266
+ }
267
+ var WEEK_START_DAYS = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"];
268
+ function assertWeekStartDay(day, declarer, setting, how = "declares") {
269
+ if (day === void 0 || WEEK_START_DAYS.includes(day)) return;
270
+ const said = `${gave(declarer, setting, day, how)}.`;
271
+ const meant = typeof day === "string" ? suggest(day.trim(), [...WEEK_START_DAYS]) : void 0;
272
+ if (meant) throw new ValidationError(`${said} Did you mean ${JSON.stringify(meant)}?`);
273
+ const choices = WEEK_START_DAYS.map((d) => JSON.stringify(d));
274
+ throw new ValidationError(`${said} Use one of: ${choices.slice(0, -1).join(", ")}, or ${choices[choices.length - 1]}.`);
275
+ }
276
+ function assertCacheDuration(duration, declarer, setting, entity, how = "declares") {
277
+ if (duration === void 0) return;
278
+ const ms = typeof duration === "string" ? parseDuration(duration) : void 0;
279
+ if (ms === void 0) {
280
+ throw new ValidationError(`${gave(declarer, setting, duration, how)}, which isn't a duration. Use one such as 30s, 10m or 2h.`, entity);
281
+ }
282
+ if (ms > MAX_CACHE_DURATION_MS) {
283
+ throw new ValidationError(`${gave(declarer, setting, duration, how)}, which is over 168h (7 days), the longest a result can be cached.`, entity);
284
+ }
285
+ }
286
+
287
+ // src/app/annotations.ts
288
+ var ANNOTATION_KINDS = ["mark", "focus", "line", "band", "series"];
289
+ var SEVERITIES = ["info", "warning", "critical"];
290
+ var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
291
+ function checkAnnotations(plugin, queryName, result, annotations) {
292
+ if (!Array.isArray(annotations)) {
293
+ throw new ValidationError(`Plugin '${plugin}' annotated query '${queryName}' with something other than a list of annotations.`, queryName);
294
+ }
295
+ const ids = /* @__PURE__ */ new Set();
296
+ return annotations.map((annotation, position) => {
297
+ const at = `Annotation ${position} of plugin '${plugin}' on query '${queryName}'`;
298
+ const fail = (message) => {
299
+ throw new ValidationError(`${at} ${message}`, queryName);
300
+ };
301
+ if (!isObject(annotation)) return fail("is not an object.");
302
+ const { kind } = annotation;
303
+ if (!ANNOTATION_KINDS.includes(kind)) {
304
+ return fail(`has kind '${String(kind)}', but a kind is one of ${ANNOTATION_KINDS.map((k) => `'${k}'`).join(", ")}.`);
305
+ }
306
+ const text = {};
307
+ for (const field of ["id", "label", "detail"]) {
308
+ const value = annotation[field];
309
+ if (value === void 0) continue;
310
+ if (typeof value !== "string") fail(`has a ${field} that isn't a string.`);
311
+ text[field] = value;
312
+ }
313
+ if (text.id !== void 0) {
314
+ if (ids.has(text.id)) fail(`has the id '${text.id}', which another annotation in the set has.`);
315
+ ids.add(text.id);
316
+ }
317
+ if (annotation.severity !== void 0) {
318
+ if (!SEVERITIES.includes(annotation.severity)) {
319
+ fail(`has severity '${String(annotation.severity)}', but a severity is 'info', 'warning' or 'critical'.`);
320
+ }
321
+ text.severity = annotation.severity;
322
+ }
323
+ const check = anchorChecker(result.columns, fail);
324
+ const anchor = isObject(annotation.anchor) ? annotation.anchor : fail("has no anchor.");
325
+ return { kind, ...text, anchor: check(kind, anchor) };
326
+ });
327
+ }
328
+ function anchorChecker(columns, fail) {
329
+ const column = (name, role) => {
330
+ const found = typeof name === "string" ? columns.find((candidate) => candidate.name === name) : void 0;
331
+ if (found) return found;
332
+ return fail(typeof name === "string" ? withSuggestion(`names ${role} '${name}', but the result has no column '${name}'.`, name, columns.map((c) => c.name)) : `has no ${role}.`);
333
+ };
334
+ const measure = (name) => {
335
+ const found = column(name, "the measure");
336
+ if (!found.isMeasure) fail(`names '${found.name}' as its measure, but '${found.name}' is not a measure column.`);
337
+ return found.name;
338
+ };
339
+ const string = (value, what) => typeof value === "string" ? value : fail(`has a ${what} that isn't a string. Values are strings, as rows carry them.`);
340
+ const dimensions = (row, what) => {
341
+ if (!isObject(row) || !Object.keys(row).length) return fail(`has a ${what} that doesn't name a row by its dimension values.`);
342
+ for (const name of Object.keys(row)) {
343
+ if (column(name, "the column").isMeasure) fail(`names a ${what} by '${name}', a measure; name rows by their dimension values.`);
344
+ }
345
+ return { ...row };
346
+ };
347
+ return (kind, anchor) => {
348
+ if (kind === "mark" || kind === "focus") {
349
+ if (!Array.isArray(anchor.rows) || !anchor.rows.length) fail("has no rows in its anchor.");
350
+ const rows = anchor.rows.map((row) => dimensions(row, "row"));
351
+ return { rows, ...anchor.measure !== void 0 ? { measure: measure(anchor.measure) } : {} };
352
+ }
353
+ if (kind === "line") {
354
+ return { column: column(anchor.column, "the column").name, value: string(anchor.value, "value") };
355
+ }
356
+ if (kind === "band") {
357
+ if (anchor.from === void 0 || anchor.to === void 0) fail("needs a from and a to in its anchor.");
358
+ return { column: column(anchor.column, "the column").name, from: string(anchor.from, "from"), to: string(anchor.to, "to") };
359
+ }
360
+ const name = measure(anchor.measure);
361
+ if (!Array.isArray(anchor.points) || !anchor.points.length) fail("has no points in its anchor.");
362
+ const points = anchor.points.map((point) => {
363
+ if (!isObject(point)) return fail("has a point that is not an object.");
364
+ const hasBounds = point.lower !== void 0 && point.upper !== void 0;
365
+ if (point.value === void 0 && !hasBounds) fail("has a point with neither a value nor both bounds (lower and upper).");
366
+ if (point.lower === void 0 !== (point.upper === void 0)) fail("has a point with one bound: give its value or bounds, both lower and upper.");
367
+ return {
368
+ at: dimensions(point.at, "point"),
369
+ ...point.value !== void 0 ? { value: string(point.value, "value") } : {},
370
+ ...hasBounds ? { lower: string(point.lower, "lower bound"), upper: string(point.upper, "upper bound") } : {}
371
+ };
372
+ });
373
+ return { measure: name, points };
374
+ };
375
+ }
376
+ var sameValue = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
377
+ var rowMatches = (named, row) => Object.keys(named).every((name) => sameValue(named[name], row[name]));
378
+ function resolveAnnotations(sets, rows) {
379
+ const merged = [];
380
+ for (const [plugin, set] of sets) {
381
+ set.forEach((annotation, position) => {
382
+ const key = `${plugin}:${annotation.id ?? position}`;
383
+ if (annotation.kind !== "mark" && annotation.kind !== "focus") {
384
+ merged.push({ ...annotation, plugin, key });
385
+ return;
386
+ }
387
+ const found = [];
388
+ const index = [];
389
+ for (const named of annotation.anchor.rows) {
390
+ let any = false;
391
+ rows.forEach((row, at) => {
392
+ if (!rowMatches(named, row)) return;
393
+ any = true;
394
+ if (!index.includes(at)) index.push(at);
395
+ });
396
+ if (any) found.push(named);
397
+ }
398
+ if (!index.length) return;
399
+ merged.push({
400
+ ...annotation,
401
+ anchor: { ...annotation.anchor, rows: found, index: index.sort((a, b) => a - b) },
402
+ plugin,
403
+ key
404
+ });
405
+ });
406
+ }
407
+ return merged;
408
+ }
409
+
135
410
  // src/app/query.ts
411
+ function assertDeclaration(name, declaration, how = "declares") {
412
+ if (!declaration.aql?.trim()) {
413
+ throw new ValidationError(`Query '${name}' ${how} no AQL.`, name);
414
+ }
415
+ const { pageSize } = declaration;
416
+ if (pageSize !== void 0 && !(Number.isInteger(pageSize) && pageSize >= 1)) {
417
+ throw new ValidationError(`${gave(`Query '${name}'`, "pageSize", pageSize, how)}, but it must be a whole number of at least 1.`, name);
418
+ }
419
+ assertCacheDuration(declaration.cache?.duration, `Query '${name}'`, "cache.duration", name, how);
420
+ }
136
421
  var Query = class extends Observable {
137
- constructor(name, app, declaration) {
422
+ constructor(name, app, declaration, id) {
138
423
  super(app);
139
424
  __publicField(this, "kind", "query");
140
425
  __publicField(this, "name");
141
- __publicField(this, "declaration");
142
- __publicField(this, "dataset");
426
+ /**
427
+ * @internal Which query of its name: its app numbers them as they are created, so one removed and
428
+ * created again by its name is told apart from the first, in the stamp on its calls.
429
+ */
430
+ __publicField(this, "id");
431
+ __publicField(this, "_declaration");
432
+ __publicField(this, "_dataset");
433
+ /** Set once `remove()` took it out of its app; every method then throws. */
434
+ __publicField(this, "removed", false);
143
435
  __publicField(this, "app");
144
436
  __publicField(this, "_state", "idle");
145
437
  /** Its last run failed: not a `fetchMore`, whose failure leaves the pages already loaded to keep. */
@@ -147,12 +439,19 @@ var Query = class extends Observable {
147
439
  __publicField(this, "_result");
148
440
  __publicField(this, "_error");
149
441
  __publicField(this, "_page", 1);
442
+ // The input the result's run came back with: its next page and its export replay it.
443
+ __publicField(this, "_run");
150
444
  /**
151
445
  * A sort applied to the result, independent of the query's own AQL — the same mechanism a click
152
446
  * on a table's column header uses. Kept off the declaration so setting it never re-authors the
153
447
  * query. See docs/adr/0001.
154
448
  */
155
449
  __publicField(this, "_sort", []);
450
+ /**
451
+ * The result belongs to the declaration before the last `update`: it stays on screen until the
452
+ * rerun, but its pages can't be continued with the new AQL. Cleared when a run's first page lands.
453
+ */
454
+ __publicField(this, "resultSuperseded", false);
156
455
  /** The input signature of the last successful run; undefined until one has happened. */
157
456
  __publicField(this, "lastRunSignature");
158
457
  /**
@@ -162,20 +461,93 @@ var Query = class extends Observable {
162
461
  __publicField(this, "lastPageRows", 0);
163
462
  /** @internal Set by the executor so `abort()` can reach the in-flight request. */
164
463
  __publicField(this, "controller");
165
- if (!declaration.aql?.trim()) {
166
- throw new ValidationError(`Query '${name}' declares no AQL.`, name);
167
- }
168
- const { pageSize } = declaration;
169
- if (pageSize !== void 0 && !(Number.isInteger(pageSize) && pageSize >= 1)) {
170
- throw new ValidationError(
171
- `Query '${name}' declares pageSize ${pageSize}; it must be a whole number of at least 1.`,
172
- name
173
- );
174
- }
464
+ /**
465
+ * @internal The signature the run or page in flight was sent with; set and cleared with
466
+ * `controller`, so a run the reader is waiting on is not counted as a change.
467
+ */
468
+ __publicField(this, "runningSignature");
469
+ /** The signature of its last run, when that run failed. */
470
+ __publicField(this, "failedSignature");
471
+ /** Each plugin's annotations on the current result, by plugin, in the order they were first set. */
472
+ __publicField(this, "annotationSets", /* @__PURE__ */ new Map());
473
+ /**
474
+ * The results that are the current one: the last run's, and each that a page extended it into, so
475
+ * annotations computed before a `fetchMore` still land.
476
+ */
477
+ __publicField(this, "currentResults", /* @__PURE__ */ new WeakSet());
478
+ /** `annotations` as last read, until a set or the result changes. */
479
+ __publicField(this, "resolvedAnnotations");
480
+ assertDeclaration(name, declaration);
175
481
  this.name = name;
482
+ this.id = id;
176
483
  this.app = app;
177
- this.declaration = declaration;
178
- this.dataset = app.datasetIndex(declaration.dataset, name);
484
+ this._declaration = declaration;
485
+ this._dataset = app.datasetIndex(declaration.dataset, name);
486
+ }
487
+ /** What it was declared with, or last updated to. */
488
+ get declaration() {
489
+ return this._declaration;
490
+ }
491
+ /** The dataset its declaration names, resolved. */
492
+ get dataset() {
493
+ return this._dataset;
494
+ }
495
+ /** False once `remove()` took it out of its app. */
496
+ get isRemoved() {
497
+ return this.removed;
498
+ }
499
+ /**
500
+ * Swaps what this query is: its dataset, its AQL, its page size, its cache, checked as `createQuery` checks
501
+ * them. Its name, its edges and its result stay; the result until the rerun replaces it, but its
502
+ * annotations go at once, and plugins can't annotate that result any more. Runs
503
+ * nothing: the query is dirty, and the next `app.execute()` reruns it, so several edits go out
504
+ * as one run. Back to the first page. A run or page in flight is aborted, and `fetchMore` does
505
+ * nothing until the rerun. A new AQL or dataset clears the sort (unless `sort` is given) and a
506
+ * selection made in this query, whose rows no longer mean the same.
507
+ */
508
+ update(changes) {
509
+ this.assertLive();
510
+ this.app.updateQuery(this, changes);
511
+ }
512
+ /**
513
+ * Takes this query out of its app: its control mappings and cross-filters go with it, a run in
514
+ * flight is aborted, a selection made in it is cleared, and its name is free again. The queries
515
+ * it cross-filtered rerun without it at the next `app.execute()`. Every method of it throws from
516
+ * then on.
517
+ */
518
+ remove() {
519
+ this.assertLive();
520
+ this.app.removeEntity(this);
521
+ }
522
+ /** @internal Throws once the query was removed. */
523
+ assertLive() {
524
+ if (this.removed) {
525
+ throw new ValidationError(`Query '${this.name}' was removed from its app; it can't be used any more.`, this.name);
526
+ }
527
+ }
528
+ /** @internal The app's half of `update`, checked by then: swap the declaration. */
529
+ replaceDeclaration(declaration, dataset, sort) {
530
+ this.controller?.abort();
531
+ this.controller = void 0;
532
+ this.runningSignature = void 0;
533
+ if (this._state === "executing") this._state = this._result ? "success" : "idle";
534
+ this.resultSuperseded = true;
535
+ this.clearAnnotations();
536
+ this.currentResults = /* @__PURE__ */ new WeakSet();
537
+ this._declaration = declaration;
538
+ this._dataset = dataset;
539
+ this._sort = [...sort];
540
+ this._run = void 0;
541
+ this.resetPage();
542
+ this.notify();
543
+ }
544
+ /** @internal The app's half of `remove`: stop what is in flight, and stay quiet from then on. */
545
+ markRemoved() {
546
+ this.removed = true;
547
+ this.clearAnnotations();
548
+ this.controller?.abort();
549
+ this.controller = void 0;
550
+ this.runningSignature = void 0;
179
551
  }
180
552
  /**
181
553
  * Bring the elements marked `data-anfra-query` with this query's name into view: scroll to the
@@ -183,6 +555,7 @@ var Query = class extends Observable {
183
555
  * marked with it yet; never throws, so an author's own button is safe.
184
556
  */
185
557
  locate() {
558
+ this.assertLive();
186
559
  return this.app.locate("query", this.name);
187
560
  }
188
561
  get state() {
@@ -206,39 +579,41 @@ var Query = class extends Observable {
206
579
  }
207
580
  /** Replaces the sort applied to this query's result. Pass `[]` to clear it back to the AQL's own. */
208
581
  setSort(sort) {
582
+ this.assertLive();
209
583
  this._sort = [...sort];
210
584
  this.notify();
211
585
  }
212
586
  /**
213
587
  * Whether another page may follow: as the backend said of the last page, or, when it did not
214
- * say, whether that page came back full.
588
+ * say, whether that page came back full. False after `update` until the rerun.
215
589
  */
216
590
  get hasMore() {
217
- if (!this._result || this.pageSize === void 0) return false;
591
+ if (!this._result || this.pageSize === void 0 || this.resultSuperseded) return false;
218
592
  return this._result.meta.hasMore ?? this.lastPageRows >= this.pageSize;
219
593
  }
220
594
  /**
221
595
  * Everything that changes the rows: the declaration, the conditions reaching this query through
222
596
  * mappings, the conditions reaching it from the selection, the sort override, the app's timezone,
223
597
  * and the page. Compared against the last successful run to decide whether re-running would
224
- * produce anything new.
598
+ * produce anything new. `pending` reads the controls and selection as the reader has them,
599
+ * `applied` as the app last applied them; they differ only between a change and `app.execute()`.
225
600
  */
226
- signature() {
601
+ signature(phase = "pending") {
227
602
  const conditions = this.app.mappingsTo(this.name).map((mapping) => ({
228
603
  field: mapping.field,
229
604
  aggregation: mapping.aggregation,
230
- condition: mapping.from.condition
605
+ condition: phase === "pending" ? mapping.from.condition : mapping.from.appliedCondition
231
606
  })).sort((a, b) => a.field.localeCompare(b.field) || JSON.stringify(a).localeCompare(JSON.stringify(b)));
232
607
  return JSON.stringify({
233
608
  declaration: this.declaration,
234
609
  conditions,
235
- selection: this.app.selectionConditionsFor(this.name, "pending"),
610
+ selection: this.app.selectionConditionsFor(this.name, phase),
236
611
  // Separate from `selection`, and not optional: a selection sent as one expression leaves
237
612
  // `conditions` empty, so without this every such selection has the same signature as the
238
613
  // next one and the query is never re-run.
239
- selectionExpression: this.app.selectionExpressionFor(this.name, "pending"),
614
+ selectionExpression: this.app.selectionExpressionFor(this.name, phase),
240
615
  sort: this._sort,
241
- timezone: this.app.timezone,
616
+ inputDefaults: this.app.queryInputDefaults,
242
617
  page: this._page
243
618
  });
244
619
  }
@@ -249,6 +624,19 @@ var Query = class extends Observable {
249
624
  get isDirty() {
250
625
  return this.lastRunSignature !== void 0 && this.signature() !== this.lastRunSignature;
251
626
  }
627
+ /**
628
+ * @internal For `app.hasChanges`: whether the next `app.execute()` would run it with inputs no run
629
+ * of it has had. Not when its pending inputs are those of its run in flight, its last successful
630
+ * run or, when it last failed, its failed run: a failure is not a change. Never attempted, only
631
+ * once `executed` (the app has run): before that, nothing has been applied to differ from.
632
+ */
633
+ hasUnappliedChange(executed) {
634
+ const pending = this.signature();
635
+ if (pending === this.runningSignature) return false;
636
+ if (this.runFailed) return pending !== this.failedSignature;
637
+ if (this.lastRunSignature === void 0) return executed && this.runningSignature === void 0;
638
+ return pending !== this.lastRunSignature;
639
+ }
252
640
  /**
253
641
  * @internal Also when its last run failed, whatever its inputs: so `execute()` is the retry, of
254
642
  * the failed queries only, even after a forced run (`refresh()`) failed with unchanged inputs. Not
@@ -257,13 +645,33 @@ var Query = class extends Observable {
257
645
  shouldRun(force = false) {
258
646
  return force || this.runFailed || this.lastRunSignature === void 0 || this.isDirty;
259
647
  }
648
+ /**
649
+ * @internal For `query.execute()`: like `shouldRun`, but against what is applied, since applying
650
+ * the reader's pending changes is the app's, for every query at once. Its own sort and the
651
+ * timezone count; a control or selection the reader changed and the app has not applied does not.
652
+ */
653
+ shouldRunAlone(force = false) {
654
+ return force || this.runFailed || this.lastRunSignature === void 0 || this.signature("applied") !== this.lastRunSignature;
655
+ }
656
+ /**
657
+ * Runs this query alone, with the inputs the app last applied, if that would produce something
658
+ * new; with `force`, whatever its inputs (a paged query starts over at its first page). Applies
659
+ * none of the reader's pending changes: that is `app.execute()`'s, so the query stays dirty and
660
+ * the next `app.execute()` runs it with them. Never rejects, as `app.execute()` doesn't.
661
+ */
662
+ execute(options = {}) {
663
+ this.assertLive();
664
+ return this.app.executeQuery(this, options);
665
+ }
260
666
  /** Stops the in-flight request for this query. The pending `execute()` resolves without it. */
261
667
  abort() {
668
+ this.assertLive();
262
669
  this.controller?.abort();
263
670
  }
264
671
  /** Fetches the next page and appends it. Rejects rather than swallowing, unlike `execute()`. */
265
672
  async fetchMore() {
266
673
  try {
674
+ this.assertLive();
267
675
  if (this.pageSize === void 0) {
268
676
  throw new ValidationError(`Query '${this.name}' declares no pageSize, so it has no more pages.`, this.name);
269
677
  }
@@ -284,6 +692,7 @@ var Query = class extends Observable {
284
692
  * browser's menu) is prevented, and when none would (no plugin offers one), nothing happens.
285
693
  */
286
694
  menu(event, rows, options = {}) {
695
+ this.assertLive();
287
696
  return this.app.menu(this, event, Array.isArray(rows) ? rows : [rows], options.fields, options.measure);
288
697
  }
289
698
  /**
@@ -297,6 +706,7 @@ var Query = class extends Observable {
297
706
  * returned. A measure or an adhoc column never takes part, whether or not it is named here.
298
707
  */
299
708
  select(rows, options = {}) {
709
+ this.assertLive();
300
710
  this.app.select(this, Array.isArray(rows) ? rows : [rows], options.fields);
301
711
  }
302
712
  /**
@@ -321,30 +731,81 @@ var Query = class extends Observable {
321
731
  const picked = new Set(selection.rows.map(key));
322
732
  return rows.filter((row) => picked.has(key(row)));
323
733
  }
734
+ /**
735
+ * What plugins say about this query's current result, every plugin's merged: draw the kinds your
736
+ * chart declares in `data-anfra-annotations`, by `index` for a rows anchor. Each has its plugin
737
+ * and a stable `key`. A change notifies through `subscribe`; they go when the result is replaced.
738
+ */
739
+ get annotations() {
740
+ this.resolvedAnnotations ?? (this.resolvedAnnotations = Object.freeze(resolveAnnotations(this.annotationSets, this._result?.rows ?? [])));
741
+ return this.resolvedAnnotations;
742
+ }
743
+ /** @internal Whether `result` is this query's current result, or one a page has since extended. */
744
+ isCurrentResult(result) {
745
+ return this.currentResults.has(result);
746
+ }
747
+ /** @internal `kernel.annotate`'s, checked by then: replace one plugin's set, `[]` clearing it. */
748
+ setAnnotations(plugin, annotations) {
749
+ if (annotations.length) this.annotationSets.set(plugin, annotations);
750
+ else if (!this.annotationSets.delete(plugin)) return;
751
+ this.resolvedAnnotations = void 0;
752
+ this.notify();
753
+ }
754
+ /** Every plugin's annotations go, with the result they were about. */
755
+ clearAnnotations() {
756
+ this.annotationSets.clear();
757
+ this.resolvedAnnotations = void 0;
758
+ }
324
759
  /** @internal */
325
760
  markExecuting() {
761
+ if (this.removed) return;
326
762
  this._state = "executing";
327
763
  this._error = void 0;
328
764
  this.notify();
329
765
  }
766
+ /** @internal The cache duration it runs with: its own, or its app's default. Absent: the backend's default. */
767
+ get cacheDuration() {
768
+ return this.declaration.cache?.duration ?? this.app.queryCacheDefaultDuration;
769
+ }
770
+ /** @internal The run the result on screen came from, for its next page and its export. */
771
+ get run() {
772
+ return this._run;
773
+ }
330
774
  /** @internal */
331
- markSuccess(result, signature, append) {
775
+ markSuccess(result, signature, append, run) {
776
+ if (this.removed) return;
332
777
  this._state = "success";
778
+ if (!append) {
779
+ this._run = run;
780
+ this.resultSuperseded = false;
781
+ }
333
782
  this._error = void 0;
334
783
  if (!append) this.runFailed = false;
335
784
  this.lastRunSignature = signature;
336
785
  this.lastPageRows = result.rows.length;
786
+ if (!append) this.clearAnnotations();
787
+ else this.resolvedAnnotations = void 0;
337
788
  if (append && this._result) {
338
- const rows = [...this._result.rows, ...result.rows];
789
+ const added = result.meta.pivot ? newGridRows(this._result.rows, result.rows) : result.rows;
790
+ const rows = [...this._result.rows, ...added];
339
791
  this._result = { ...result, rows, meta: { ...result.meta, numRows: rows.length } };
340
792
  } else {
341
793
  this._result = result;
794
+ this.currentResults = /* @__PURE__ */ new WeakSet();
342
795
  }
796
+ this.currentResults.add(this._result);
343
797
  this.notify();
344
798
  }
345
- /** @internal `page` when it is a `fetchMore` that failed, not a run. */
346
- markError(error, page = false) {
347
- if (!page) this.runFailed = true;
799
+ /**
800
+ * @internal `page` when it is a `fetchMore` that failed, not a run; `signature`, a failed run's
801
+ * inputs.
802
+ */
803
+ markError(error, page = false, signature) {
804
+ if (this.removed) return;
805
+ if (!page) {
806
+ this.runFailed = true;
807
+ this.failedSignature = signature;
808
+ }
348
809
  this._state = "error";
349
810
  this._error = error;
350
811
  this.notify();
@@ -359,9 +820,26 @@ var Query = class extends Observable {
359
820
  this.lastPageRows = 0;
360
821
  }
361
822
  toJSON() {
362
- return this.declaration;
823
+ return this._declaration;
363
824
  }
364
825
  };
826
+ var PIVOT_ROW = "__pivot_row__";
827
+ function newGridRows(loaded, page) {
828
+ const ranks = new Set(loaded.map((row) => String(row[PIVOT_ROW])));
829
+ return page.filter((row) => !ranks.has(String(row[PIVOT_ROW])));
830
+ }
831
+
832
+ // src/app/changes.ts
833
+ function withChanges(base, changes, keys = Object.keys(changes)) {
834
+ const merged = { ...base };
835
+ keys.forEach((key) => {
836
+ if (!(key in changes)) return;
837
+ const value = changes[key];
838
+ if (value === void 0) delete merged[key];
839
+ else merged[key] = value;
840
+ });
841
+ return merged;
842
+ }
365
843
 
366
844
  // src/app/controls.ts
367
845
  var DATE_GRAINS = ["year", "quarter", "month", "week", "day", "hour", "minute"];
@@ -396,6 +874,8 @@ var Control = class extends Observable {
396
874
  __publicField(this, "pending");
397
875
  __publicField(this, "applied");
398
876
  __publicField(this, "initial");
877
+ /** Set once `remove()` took it out of its app; every method then throws. */
878
+ __publicField(this, "removed", false);
399
879
  this.name = name;
400
880
  this.app = app;
401
881
  this.initial = initial;
@@ -406,8 +886,44 @@ var Control = class extends Observable {
406
886
  * none is on the page yet; never throws.
407
887
  */
408
888
  locate() {
889
+ this.assertLive();
409
890
  return this.app.locate("control", this.name);
410
891
  }
892
+ /** False once `remove()` took it out of its app. */
893
+ get isRemoved() {
894
+ return this.removed;
895
+ }
896
+ /**
897
+ * Takes this control out of its app, with its mappings: the queries it was mapped to rerun
898
+ * without its condition at the next `app.execute()`. Its name is free again, and every method
899
+ * of it throws from then on.
900
+ */
901
+ remove() {
902
+ this.assertLive();
903
+ this.app.removeEntity(this);
904
+ }
905
+ /** @internal Throws once the control was removed. */
906
+ assertLive() {
907
+ if (this.removed) {
908
+ throw new ValidationError(`Control '${this.name}' was removed from its app; it can't be used any more.`, this.name);
909
+ }
910
+ }
911
+ /** @internal The app's half of `remove`: stop what is in flight. */
912
+ markRemoved() {
913
+ this.removed = true;
914
+ this.dropInFlight();
915
+ }
916
+ /** @internal Drops work in flight that the control's current declaration no longer wants. */
917
+ dropInFlight() {
918
+ }
919
+ /**
920
+ * @internal A new declaration's default: `reset()` goes back to it. `restart` also sets the
921
+ * reader's condition to it, for a control that now filters something else.
922
+ */
923
+ redefault(initial, restart) {
924
+ this.initial = initial;
925
+ if (restart) this.pending = initial;
926
+ }
411
927
  /** The reader's current value, which `execute()` will commit. */
412
928
  get condition() {
413
929
  return this.pending;
@@ -424,10 +940,12 @@ var Control = class extends Observable {
424
940
  return this.applied !== void 0 && !sameCondition(this.pending, this.applied);
425
941
  }
426
942
  setCondition(condition) {
943
+ this.assertLive();
427
944
  this.pending = condition;
428
945
  this.notify();
429
946
  }
430
947
  reset() {
948
+ this.assertLive();
431
949
  this.setCondition(this.initial);
432
950
  }
433
951
  /** @internal Called by the executor once the queries reading this control have been submitted. */
@@ -435,18 +953,23 @@ var Control = class extends Observable {
435
953
  this.applied = this.pending;
436
954
  }
437
955
  };
438
- var Filter = class extends Control {
956
+ var Filter = class _Filter extends Control {
439
957
  constructor(name, app, declaration, dataset, backend) {
440
958
  super(name, app, declaration.default ?? { operator: "is", values: [] });
441
959
  __publicField(this, "kind", "filter");
442
- __publicField(this, "declaration");
443
- __publicField(this, "type");
444
- __publicField(this, "resolved");
445
- __publicField(this, "datasetName");
960
+ __publicField(this, "_declaration");
961
+ __publicField(this, "resolution");
446
962
  __publicField(this, "backend");
447
963
  __publicField(this, "loadedOptions");
448
- this.declaration = declaration;
964
+ /** The `loadOptions` calls in flight, so a removal or a new field can drop them. */
965
+ __publicField(this, "loading", /* @__PURE__ */ new Set());
449
966
  this.backend = backend;
967
+ this.resolution = _Filter.resolve(name, declaration, dataset);
968
+ this._declaration = declaration;
969
+ this.assertValues(this.condition.values ?? []);
970
+ this.assertValues(declaration.options ?? []);
971
+ }
972
+ static resolve(name, declaration, dataset) {
450
973
  if (declaration.field) {
451
974
  if (!dataset) {
452
975
  throw new ValidationError(
@@ -454,32 +977,69 @@ var Filter = class extends Control {
454
977
  name
455
978
  );
456
979
  }
457
- this.resolved = dataset.resolve(declaration.field, name);
458
- this.datasetName = dataset.descriptor.name;
459
- this.type = declaration.type ?? inferType(this.resolved.type);
460
- } else {
461
- if (!declaration.type) {
462
- throw new ValidationError(
463
- `Filter '${name}' is a manual filter, so it needs a \`type\`.`,
464
- name
465
- );
466
- }
467
- this.type = declaration.type;
980
+ const resolved = dataset.resolve(declaration.field, name);
981
+ return { resolved, datasetName: dataset.descriptor.name, type: declaration.type ?? inferType(resolved.type) };
468
982
  }
469
- this.assertValues(this.condition.values ?? []);
470
- this.assertValues(declaration.options ?? []);
983
+ if (!declaration.type) {
984
+ throw new ValidationError(
985
+ `Filter '${name}' is a manual filter, so it needs a \`type\`.`,
986
+ name
987
+ );
988
+ }
989
+ return { type: declaration.type };
990
+ }
991
+ /** What it was declared with, or last updated to. */
992
+ get declaration() {
993
+ return this._declaration;
994
+ }
995
+ get type() {
996
+ return this.resolution.type;
471
997
  }
472
998
  setCondition(condition) {
999
+ this.assertLive();
473
1000
  this.assertValues(condition.values ?? []);
474
1001
  super.setCondition(condition);
475
1002
  }
1003
+ /**
1004
+ * Edits this filter in place. A new label, options or default keep the reader's condition, and
1005
+ * `reset()` goes to the new default. A new field, dataset or type is checked as `createFilter`
1006
+ * checks it, and the condition goes back to the new default: the old values filtered something
1007
+ * else. Its mappings stay as they are: each mapping's own field decides what its condition applies to.
1008
+ */
1009
+ update(changes) {
1010
+ this.assertLive();
1011
+ const declaration = withChanges(this._declaration, changes);
1012
+ const previous = this._declaration;
1013
+ const redefined = ["field", "dataset", "type"].some((key) => declaration[key] !== previous[key]);
1014
+ const resolution = redefined ? _Filter.resolve(this.name, declaration, this.app.filterDataset(this.name, declaration)) : this.resolution;
1015
+ const initial = declaration.default ?? { operator: "is", values: [] };
1016
+ const values = (condition) => condition.values ?? [];
1017
+ this.assertValuesOf(resolution.type, values(initial));
1018
+ this.assertValuesOf(resolution.type, declaration.options ?? []);
1019
+ if (!redefined) this.assertValuesOf(resolution.type, values(this.condition));
1020
+ this._declaration = declaration;
1021
+ this.resolution = resolution;
1022
+ this.redefault(initial, redefined);
1023
+ if (redefined) {
1024
+ this.loadedOptions = void 0;
1025
+ this.dropInFlight();
1026
+ }
1027
+ this.notify();
1028
+ }
1029
+ dropInFlight() {
1030
+ this.loading.forEach((controller) => controller.abort());
1031
+ this.loading.clear();
1032
+ }
476
1033
  /**
477
1034
  * A number filter's values are strings, as query results give them, which keep every digit. A JS
478
1035
  * number may already have lost some (`Number("9007199254740993")` is ...992), and nothing after
479
1036
  * can tell, so the core API refuses one; this says so where the app hands it over.
480
1037
  */
481
1038
  assertValues(values) {
482
- if (this.type !== "number") return;
1039
+ this.assertValuesOf(this.type, values);
1040
+ }
1041
+ assertValuesOf(type, values) {
1042
+ if (type !== "number") return;
483
1043
  const number = values.find((value) => typeof value === "number");
484
1044
  if (number === void 0) return;
485
1045
  throw new ValidationError(
@@ -489,68 +1049,117 @@ var Filter = class extends Control {
489
1049
  }
490
1050
  /** True for a field-backed filter, false for a manual one. The two are separate axes from `type`. */
491
1051
  get isFieldBacked() {
492
- return this.resolved !== void 0;
1052
+ return this.resolution.resolved !== void 0;
493
1053
  }
494
1054
  /** A manual filter's static list, or whatever the last `loadOptions()` returned. */
495
1055
  get options() {
496
- return this.loadedOptions ?? this.declaration.options ?? [];
1056
+ return this.loadedOptions ?? this._declaration.options ?? [];
497
1057
  }
498
1058
  /**
499
1059
  * Fetches option values for a field-backed filter.
500
1060
  *
501
1061
  * Lazy rather than fetched up front: building a distinct-values query for every filter is slow,
502
1062
  * and readers often touch none of them. The backend decides which values this reader may see.
1063
+ * Rejects with an `AbortError` when the filter is removed, or its field changes, before the list
1064
+ * arrives: the list is dropped.
503
1065
  */
504
1066
  async loadOptions(search, signal = new AbortController().signal) {
505
- const model = this.resolved?.modelName;
506
- if (!this.resolved || !model || !this.backend || !this.datasetName) return this.options;
507
- const options = await this.backend.fieldSuggestions(
508
- {
509
- dataset: this.datasetName,
510
- model,
511
- field: this.resolved.fieldName,
512
- q: search ?? ""
513
- },
514
- signal
515
- ).catch((err) => {
516
- tagCall(err, "load_options");
517
- throw err;
518
- });
519
- this.loadedOptions = [...options ?? []];
520
- this.notify();
521
- return this.loadedOptions;
1067
+ this.assertLive();
1068
+ const { resolved, datasetName } = this.resolution;
1069
+ const model = resolved?.modelName;
1070
+ if (!resolved || !model || !this.backend || !datasetName) return this.options;
1071
+ const controller = new AbortController();
1072
+ const follow = () => controller.abort();
1073
+ if (signal.aborted) controller.abort();
1074
+ else signal.addEventListener("abort", follow, { once: true });
1075
+ this.loading.add(controller);
1076
+ try {
1077
+ const options = await this.backend.fieldSuggestions(
1078
+ {
1079
+ dataset: datasetName,
1080
+ model,
1081
+ field: resolved.fieldName,
1082
+ q: search ?? ""
1083
+ },
1084
+ controller.signal
1085
+ ).catch((err) => {
1086
+ tagCall(err, "load_options");
1087
+ throw err;
1088
+ });
1089
+ if (controller.signal.aborted && !this.loading.has(controller)) throw abortError();
1090
+ this.loadedOptions = [...options ?? []];
1091
+ this.notify();
1092
+ return this.loadedOptions;
1093
+ } finally {
1094
+ this.loading.delete(controller);
1095
+ signal.removeEventListener("abort", follow);
1096
+ }
522
1097
  }
523
1098
  toJSON() {
524
- return this.declaration;
1099
+ return this._declaration;
525
1100
  }
526
1101
  };
527
1102
  var DateDrillControl = class extends Control {
528
1103
  constructor(name, app, declaration = {}) {
529
1104
  super(name, app, drillCondition(name, declaration.default));
530
1105
  __publicField(this, "kind", "dateDrill");
531
- __publicField(this, "declaration");
532
- this.declaration = declaration;
1106
+ __publicField(this, "_declaration");
1107
+ this._declaration = declaration;
1108
+ }
1109
+ /** What it was declared with, or last updated to. */
1110
+ get declaration() {
1111
+ return this._declaration;
1112
+ }
1113
+ /** Edits its label or default. The reader's grain stays; `reset()` goes to the new default. */
1114
+ update(changes) {
1115
+ this.assertLive();
1116
+ const declaration = withChanges(this._declaration, changes);
1117
+ const initial = drillCondition(this.name, declaration.default);
1118
+ this._declaration = declaration;
1119
+ this.redefault(initial, false);
1120
+ this.notify();
533
1121
  }
534
1122
  setGrain(grain) {
1123
+ this.assertLive();
535
1124
  this.setCondition(drillCondition(this.name, grain));
536
1125
  }
537
1126
  toJSON() {
538
- return this.declaration;
1127
+ return this._declaration;
539
1128
  }
540
1129
  };
541
1130
 
542
1131
  // src/app/mapping.ts
1132
+ function assertLive(edge, removed) {
1133
+ if (removed) {
1134
+ throw new ValidationError(`Edge '${edge.id}' was removed from its app; map again to have it back.`, edge.from.name);
1135
+ }
1136
+ }
543
1137
  var Mapping = class {
544
- constructor(from, to, field, aggregation) {
1138
+ constructor(from, to, field, aggregation, owner) {
545
1139
  __publicField(this, "kind", "control");
546
1140
  __publicField(this, "from");
547
1141
  __publicField(this, "to");
548
1142
  __publicField(this, "field");
549
1143
  __publicField(this, "aggregation");
1144
+ __publicField(this, "owner");
1145
+ __publicField(this, "removed", false);
550
1146
  this.from = from;
551
1147
  this.to = to;
552
1148
  this.field = field;
553
1149
  this.aggregation = aggregation;
1150
+ this.owner = owner;
1151
+ }
1152
+ /**
1153
+ * Takes this mapping out of its app: its query reruns without the control's condition at the
1154
+ * next `app.execute()`. An edge never changes: to change one, remove it and map again.
1155
+ */
1156
+ remove() {
1157
+ assertLive(this, this.removed);
1158
+ this.owner?.removeEdge(this);
1159
+ }
1160
+ /** @internal */
1161
+ markRemoved() {
1162
+ this.removed = true;
554
1163
  }
555
1164
  /**
556
1165
  * Includes the field, unlike Dashboard as Code's `${from}.${to}` — that form collides the moment
@@ -571,12 +1180,27 @@ var Mapping = class {
571
1180
  }
572
1181
  };
573
1182
  var CrossFilter = class {
574
- constructor(from, to) {
1183
+ constructor(from, to, owner) {
575
1184
  __publicField(this, "kind", "crossFilter");
576
1185
  __publicField(this, "from");
577
1186
  __publicField(this, "to");
1187
+ __publicField(this, "owner");
1188
+ __publicField(this, "removed", false);
578
1189
  this.from = from;
579
1190
  this.to = to;
1191
+ this.owner = owner;
1192
+ }
1193
+ /**
1194
+ * Takes this cross-filter out of its app: a selection in `from` stops reaching `to`, which
1195
+ * reruns without it at the next `app.execute()`. To change one, remove it and map again.
1196
+ */
1197
+ remove() {
1198
+ assertLive(this, this.removed);
1199
+ this.owner?.removeEdge(this);
1200
+ }
1201
+ /** @internal */
1202
+ markRemoved() {
1203
+ this.removed = true;
580
1204
  }
581
1205
  /** No field to disambiguate, and one pair may only be declared once, so the pair is the id. */
582
1206
  get id() {
@@ -754,6 +1378,33 @@ function describeNode(node, element, structure) {
754
1378
  }
755
1379
 
756
1380
  // src/app/menu.ts
1381
+ function annotationNote(annotation) {
1382
+ return {
1383
+ label: annotation.label || defaultLabel(annotation),
1384
+ ...annotation.detail ? { detail: annotation.detail } : {},
1385
+ ...annotation.severity ? { severity: annotation.severity } : {},
1386
+ plugin: annotation.plugin
1387
+ };
1388
+ }
1389
+ function defaultLabel(annotation) {
1390
+ switch (annotation.kind) {
1391
+ case "line":
1392
+ return `${annotation.anchor.column} at ${annotation.anchor.value}`;
1393
+ case "band":
1394
+ return `${annotation.anchor.column} from ${annotation.anchor.from} to ${annotation.anchor.to}`;
1395
+ case "series":
1396
+ return `A series of ${annotation.anchor.measure}`;
1397
+ case "focus":
1398
+ return "In focus";
1399
+ case "mark":
1400
+ return "Marked";
1401
+ }
1402
+ }
1403
+ function forHost(target) {
1404
+ if (target.kind !== "rows" || !target.annotations) return target;
1405
+ const { annotations: _, ...rest } = target;
1406
+ return rest;
1407
+ }
757
1408
  var rowsOpener;
758
1409
  function openRowsMenu(event, target) {
759
1410
  return rowsOpener ? rowsOpener(event, target) : false;
@@ -777,12 +1428,14 @@ function installContentUi(kernel) {
777
1428
  let hostKinds = /* @__PURE__ */ new Set();
778
1429
  let listening = false;
779
1430
  let current;
1431
+ let currentAbout;
780
1432
  const ui = () => kernel.body();
781
1433
  const root = () => layerRoot(doc, "anfra-ui");
782
1434
  const offered = (kind) => hostKinds.has(kind) || items.some((item) => item.target === kind);
783
1435
  const closeCurrent = () => {
784
1436
  const close = current;
785
1437
  current = void 0;
1438
+ currentAbout = void 0;
786
1439
  close?.();
787
1440
  };
788
1441
  function blockOf(target) {
@@ -842,21 +1495,22 @@ function installContentUi(kernel) {
842
1495
  const entries = [...own.entries];
843
1496
  if (hostKinds.has(target.kind)) {
844
1497
  try {
845
- const answered = await kernel.call("anfra.menu", target);
1498
+ const answered = await kernel.call("anfra.menu", forHost(target));
846
1499
  for (const entry of Array.isArray(answered) ? answered : []) {
847
1500
  if (typeof entry?.id !== "string" || typeof entry.label !== "string") continue;
848
1501
  const key = `host:${entry.id}:${target.kind}`;
849
1502
  entries.push({ id: key, label: entry.label, ...typeof entry.disabled === "string" ? { disabled: entry.disabled } : {} });
850
- run.set(key, () => kernel.call("anfra.run", { id: entry.id, target }));
1503
+ run.set(key, () => kernel.call("anfra.run", { id: entry.id, target: forHost(target) }));
851
1504
  }
852
1505
  } catch {
853
1506
  }
854
1507
  }
855
1508
  return { entries, run };
856
1509
  }
857
- function open(event, targets) {
1510
+ function open(event, targets, about) {
1511
+ const notes = targets.flatMap((target) => target.kind === "rows" ? target.annotations ?? [] : []).map(annotationNote);
858
1512
  const relevant = targets.map((target) => ({ target, own: frameEntries(target) })).filter(({ target, own }) => own.entries.length || hostKinds.has(target.kind));
859
- if (!relevant.length) return false;
1513
+ if (!relevant.length && !notes.length) return false;
860
1514
  event.preventDefault();
861
1515
  const point = event;
862
1516
  const x = typeof point.clientX === "number" ? point.clientX : 0;
@@ -864,11 +1518,12 @@ function installContentUi(kernel) {
864
1518
  void (async () => {
865
1519
  const [body, ...found] = await Promise.all([ui(), ...relevant.map(({ target, own }) => entriesFor(target, own))]);
866
1520
  const groups = found.map((group) => group.entries).filter((group) => group.length);
867
- if (!groups.length) return;
1521
+ if (!groups.length && !notes.length) return;
868
1522
  closeCurrent();
869
1523
  const close = body.menu(root(), {
870
1524
  x,
871
1525
  y,
1526
+ ...notes.length ? { notes } : {},
872
1527
  groups,
873
1528
  onPick: (key) => {
874
1529
  const action = found.map((group) => group.run.get(key)).find(Boolean);
@@ -882,6 +1537,7 @@ function installContentUi(kernel) {
882
1537
  }
883
1538
  });
884
1539
  current = close;
1540
+ currentAbout = about;
885
1541
  })().catch((err) => {
886
1542
  win.console?.error("anfra: the menu failed to open:", err);
887
1543
  reportError("plugin.uncaught", err);
@@ -902,9 +1558,14 @@ function installContentUi(kernel) {
902
1558
  if (event.defaultPrevented || event.shiftKey) return false;
903
1559
  const element = blockOf(event.target);
904
1560
  const node = element ? nodeTarget(element) : void 0;
905
- const rows = node ? { ...target, node } : target;
906
- return open(event, node ? [rows, node] : [rows]);
1561
+ const point = event;
1562
+ const at = typeof point.clientX === "number" && typeof point.clientY === "number" ? { x: point.clientX, y: point.clientY } : void 0;
1563
+ const rows = { ...target, ...node ? { node } : {}, ...at ? { at } : {} };
1564
+ return open(event, node ? [rows, node] : [rows], { app: target.app, query: target.query });
907
1565
  };
1566
+ kernel.onApp((app) => app.onRemoved((entity) => {
1567
+ if (entity.kind === "query" && currentAbout?.app === app.index && currentAbout.query === entity.name) closeCurrent();
1568
+ }));
908
1569
  kernel.on("menu", (payload) => {
909
1570
  const kinds = payload?.kinds;
910
1571
  hostKinds = new Set((Array.isArray(kinds) ? kinds : []).filter((kind) => kind === "node" || kind === "rows"));
@@ -932,11 +1593,12 @@ function installContentUi(kernel) {
932
1593
  };
933
1594
  close = draw(body, onClose);
934
1595
  current = close;
1596
+ currentAbout = input.about ? { app: input.about.app, query: input.about.query } : void 0;
935
1597
  return { close };
936
1598
  }
937
1599
  return {
938
1600
  addItem(plugin, item) {
939
- items.push({ ...item, full: `${plugin}.${item.id}` });
1601
+ items.push({ ...item, full: `${plugin}.${item.id}`, plugin });
940
1602
  listen();
941
1603
  },
942
1604
  modal: (input) => show(input, (body, onClose) => body.modal(root(), {
@@ -945,6 +1607,26 @@ function installContentUi(kernel) {
945
1607
  mount: reported(input.mount),
946
1608
  onClose
947
1609
  })),
1610
+ popoverAt: (anchor, input) => show(input, (body, onClose) => body.popover(root(), {
1611
+ anchor,
1612
+ side: input.side,
1613
+ mount: reported(input.mount),
1614
+ dismiss: input.dismiss,
1615
+ closeButton: input.closeButton,
1616
+ onClose
1617
+ })),
1618
+ rowsEntries(plugin, target) {
1619
+ return items.filter((item) => item.plugin === plugin).flatMap((item) => {
1620
+ if (item.target !== "rows") return [];
1621
+ try {
1622
+ if (item.when && item.when(target) === false) return [];
1623
+ if (!item.entries) return [{ label: item.label, run: () => item.run(target) }];
1624
+ return (item.entries(target) ?? []).filter((entry) => typeof entry?.label === "string" && (entry.disabled || typeof entry.run === "function"));
1625
+ } catch {
1626
+ return [];
1627
+ }
1628
+ });
1629
+ },
948
1630
  popover: (input) => show(input, (body, onClose) => {
949
1631
  const { anchor } = input;
950
1632
  let rect;
@@ -1078,119 +1760,6 @@ function scrollTo(element) {
1078
1760
  }
1079
1761
  }
1080
1762
 
1081
- // src/app/suggest.ts
1082
- function editDistance(a, b) {
1083
- const rows = a.length + 1;
1084
- const cols = b.length + 1;
1085
- let prev = Array.from({ length: cols }, (_, j) => j);
1086
- for (let i = 1; i < rows; i++) {
1087
- const curr = [i];
1088
- for (let j = 1; j < cols; j++) {
1089
- curr[j] = Math.min(
1090
- prev[j] + 1,
1091
- curr[j - 1] + 1,
1092
- prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1)
1093
- );
1094
- }
1095
- prev = curr;
1096
- }
1097
- return prev[cols - 1];
1098
- }
1099
- function suggest(value, candidates) {
1100
- let best;
1101
- let bestDistance = Infinity;
1102
- candidates.forEach((candidate) => {
1103
- const distance = editDistance(value.toLowerCase(), candidate.toLowerCase());
1104
- if (distance < bestDistance) {
1105
- bestDistance = distance;
1106
- best = candidate;
1107
- }
1108
- });
1109
- const threshold = Math.max(2, Math.floor(value.length / 3));
1110
- return bestDistance <= threshold ? best : void 0;
1111
- }
1112
- function withSuggestion(message, value, candidates) {
1113
- const hint = suggest(value, candidates);
1114
- return hint ? `${message} Did you mean '${hint}'?` : message;
1115
- }
1116
-
1117
- // src/app/validation.ts
1118
- var DatasetIndex = class {
1119
- constructor(descriptor) {
1120
- __publicField(this, "descriptor");
1121
- __publicField(this, "fields", /* @__PURE__ */ new Map());
1122
- __publicField(this, "references");
1123
- this.descriptor = descriptor;
1124
- descriptor.data_models.forEach((model) => {
1125
- model.fields.forEach((field) => {
1126
- const modelName = String(model.name);
1127
- this.fields.set(`${modelName}.${field.name}`, {
1128
- modelName,
1129
- fieldName: field.name,
1130
- isMetric: false,
1131
- type: field.type,
1132
- label: field.label ?? field.name
1133
- });
1134
- });
1135
- });
1136
- descriptor.metrics.forEach((metric) => {
1137
- this.fields.set(metric.name, {
1138
- fieldName: metric.name,
1139
- isMetric: true,
1140
- type: metric.type,
1141
- label: metric.label ?? metric.name
1142
- });
1143
- });
1144
- this.references = [...this.fields.keys()];
1145
- }
1146
- resolve(reference, entity) {
1147
- const field = this.fields.get(reference);
1148
- if (field) return field;
1149
- throw new ValidationError(
1150
- withSuggestion(
1151
- `Unknown field '${reference}' on dataset '${this.descriptor.name}'.`,
1152
- reference,
1153
- this.references
1154
- ),
1155
- entity
1156
- );
1157
- }
1158
- };
1159
- function resolveDataset(datasets, uname, entity) {
1160
- const dataset = datasets[uname];
1161
- if (dataset) return dataset;
1162
- throw new ValidationError(
1163
- withSuggestion(
1164
- `Unknown dataset '${uname}'.`,
1165
- uname,
1166
- Object.keys(datasets)
1167
- ),
1168
- entity
1169
- );
1170
- }
1171
- function assertValidFilterAggregation(aggregation, entity) {
1172
- if (!FILTER_AGGREGATIONS.includes(aggregation)) {
1173
- throw new ValidationError(
1174
- withSuggestion(
1175
- `Invalid filter aggregation '${aggregation}'.`,
1176
- aggregation,
1177
- [...FILTER_AGGREGATIONS]
1178
- ),
1179
- entity
1180
- );
1181
- }
1182
- }
1183
- function assertUniqueName(taken, name, kind) {
1184
- if (!name) {
1185
- throw new ValidationError(`A ${kind} needs a name.`);
1186
- }
1187
- for (const existing of taken) {
1188
- if (existing === name) {
1189
- throw new ValidationError(`'${name}' is already declared in this app.`, name);
1190
- }
1191
- }
1192
- }
1193
-
1194
1763
  // src/app/execution/submitQuery.ts
1195
1764
  function toFilter(mapping, condition) {
1196
1765
  if (!condition || condition.operator === "none" || condition.operator === "transform_date_drill") return void 0;
@@ -1229,7 +1798,8 @@ function toResult(query, data) {
1229
1798
  ...pageSize !== void 0 ? {
1230
1799
  page: data.meta?.page ?? query.page,
1231
1800
  pageSize: data.meta?.pageSize ?? pageSize,
1232
- ...data.meta?.hasMore !== void 0 ? { hasMore: data.meta.hasMore } : {}
1801
+ ...data.meta?.hasMore !== void 0 ? { hasMore: data.meta.hasMore } : {},
1802
+ ...data.meta?.pivot ? { pivot: data.meta.pivot } : {}
1233
1803
  } : {},
1234
1804
  numRows: data.meta?.numRows ?? rows.length
1235
1805
  },
@@ -1252,39 +1822,58 @@ function buildQuery(query, mappings, selection, context) {
1252
1822
  filters: [...mappedFilters, ...selectionFilters],
1253
1823
  conditions,
1254
1824
  sorts: query.sort.map((sort) => ({ field: sort.field, direction: sort.direction ?? "asc" })),
1255
- dateDrills
1825
+ dateDrills,
1826
+ // Omitted entirely when the app declares none, so the backend applies its own default rather
1827
+ // than the SDK guessing the browser's.
1828
+ ...context.timezone ? { timezone: context.timezone } : {},
1829
+ ...context.weekStartDay ? { weekStartDay: context.weekStartDay } : {}
1256
1830
  },
1257
- // Omitted entirely when the app declares none, so the backend applies its own default rather
1258
- // than the SDK guessing the browser's.
1259
- ...context.timezone ? { timezone: context.timezone } : {}
1831
+ ...query.cacheDuration ? { cacheDuration: query.cacheDuration } : {}
1260
1832
  };
1261
1833
  }
1262
1834
  function buildRequest(query, mappings, selection, context) {
1835
+ const { input, ...rest } = buildQuery(query, mappings, selection, context);
1263
1836
  return {
1264
- ...buildQuery(query, mappings, selection, context),
1265
- // Omitted for a query that declares no page size, so the backend returns every row.
1266
- ...query.pageSize !== void 0 ? { page: query.page, pageSize: query.pageSize } : {},
1837
+ ...rest,
1838
+ input: withPage(input, query),
1267
1839
  ...context.bustCache ? { bustCache: true } : {}
1268
1840
  };
1269
1841
  }
1842
+ function pageRequest(query, run) {
1843
+ return {
1844
+ dataset: query.dataset.descriptor.name,
1845
+ aql: query.declaration.aql,
1846
+ input: withPage(run.input, query),
1847
+ ...query.cacheDuration ? { cacheDuration: query.cacheDuration } : {},
1848
+ ...run.cachedAt ? { minCachedAt: run.cachedAt } : {}
1849
+ };
1850
+ }
1851
+ function withPage(input, query) {
1852
+ const { pagination: _, ...rest } = input;
1853
+ return query.pageSize !== void 0 ? { ...rest, pagination: { page: query.page, pageSize: query.pageSize } } : rest;
1854
+ }
1270
1855
  function defaultExportFilename(query, title) {
1271
1856
  const safeTitle = title?.replace(/[/\\]/g, "-").replace(/\p{Cc}/gu, "").trim();
1272
1857
  return safeTitle ? `${safeTitle} - ${query.name}` : query.name;
1273
1858
  }
1274
- function buildExportRequest(query, mappings, selection, context, options) {
1859
+ function buildExportRequest(query, mappings, selection, context, options, run) {
1275
1860
  const format2 = options.format ?? "csv";
1276
1861
  const formatOptions = format2 === "csv" ? { bom: true, ...options.formatOptions } : options.formatOptions;
1862
+ const built = buildQuery(query, mappings, selection, context);
1863
+ const { pagination: _, ...input } = run?.input ?? built.input;
1277
1864
  return {
1278
- ...buildQuery(query, mappings, selection, context),
1865
+ ...built,
1866
+ input,
1867
+ ...run?.cachedAt ? { minCachedAt: run.cachedAt } : {},
1279
1868
  format: format2,
1280
1869
  ...formatOptions ? { formatOptions } : {},
1281
1870
  filename: options.filename?.trim() || defaultExportFilename(query, context.title)
1282
1871
  };
1283
1872
  }
1284
- async function runQuery(query, mappings, selection, context, signal) {
1285
- const request = buildRequest(query, mappings, selection, context);
1286
- const data = await context.backend.submitQuery(request, signal);
1287
- return toResult(query, data);
1873
+ async function runQuery(query, request, backend, signal, stamp) {
1874
+ const data = await backend.submitQuery(request, signal, stamp);
1875
+ const cachedAt = data.debug?.cache?.cachedAt?.toISOString();
1876
+ return { result: toResult(query, data), run: { input: data.input ?? request.input, ...cachedAt ? { cachedAt } : {} } };
1288
1877
  }
1289
1878
 
1290
1879
  // src/app/aql.ts
@@ -1581,6 +2170,7 @@ function inspectError(error) {
1581
2170
  function inspectQuery(query) {
1582
2171
  const { result } = query;
1583
2172
  return {
2173
+ id: query.id,
1584
2174
  state: query.state,
1585
2175
  isDirty: query.isDirty,
1586
2176
  page: query.page,
@@ -1640,6 +2230,11 @@ var App = class extends Observable {
1640
2230
  __publicField(this, "extensions", extensions);
1641
2231
  __publicField(this, "title");
1642
2232
  __publicField(this, "_timezone");
2233
+ __publicField(this, "_weekStartDay");
2234
+ /** The app's `query.default.input`: what its queries use over its own timezone and week start day. */
2235
+ __publicField(this, "queryInput");
2236
+ /** The cache duration of each of the app's queries that declares none (`query.default.cache.duration`). */
2237
+ __publicField(this, "queryCacheDefaultDuration");
1643
2238
  __publicField(this, "datasets");
1644
2239
  __publicField(this, "backend");
1645
2240
  __publicField(this, "features");
@@ -1650,10 +2245,14 @@ var App = class extends Observable {
1650
2245
  __publicField(this, "_selection");
1651
2246
  __publicField(this, "_appliedSelection");
1652
2247
  /**
1653
- * Whether a run has ever committed the selection. Needed because `undefined` is a real applied
1654
- * value — "nothing selected" — unlike a control's condition, which is always present.
2248
+ * Whether a run has ever committed the selection, that is whether `execute()` has ever run. Needed
2249
+ * because `undefined` is a real applied value — "nothing selected" — unlike a control's condition,
2250
+ * which is always present.
1655
2251
  */
1656
2252
  __publicField(this, "selectionCommitted", false);
2253
+ /** The id the next query created gets. */
2254
+ __publicField(this, "nextQueryId", 1);
2255
+ __publicField(this, "removedListeners", /* @__PURE__ */ new Set());
1657
2256
  /**
1658
2257
  * @internal This app's index among the frame's apps, which is how a marked element names it
1659
2258
  * (`data-anfra-query="1/revenue"`); 0 unless set by the instance that created it.
@@ -1661,6 +2260,14 @@ var App = class extends Observable {
1661
2260
  __publicField(this, "index", 0);
1662
2261
  this.title = declaration.title;
1663
2262
  this._timezone = declaration.timezone;
2263
+ assertWeekStartDay(declaration.weekStartDay, "The app", "weekStartDay");
2264
+ this._weekStartDay = declaration.weekStartDay;
2265
+ const queryInput = declaration.query?.default?.input ?? {};
2266
+ assertWeekStartDay(queryInput.weekStartDay, "The app", "query.default.input.weekStartDay");
2267
+ this.queryInput = { ...queryInput };
2268
+ const duration = declaration.query?.default?.cache?.duration;
2269
+ assertCacheDuration(duration, "The app", "query.default.cache.duration");
2270
+ this.queryCacheDefaultDuration = duration;
1664
2271
  this.datasets = datasets;
1665
2272
  this.backend = backend;
1666
2273
  this.features = features;
@@ -1683,14 +2290,14 @@ var App = class extends Observable {
1683
2290
  }
1684
2291
  createQuery(name, declaration) {
1685
2292
  this.assertNameFree(name, "query");
1686
- const query = applyExtensions(new Query(name, this, declaration), this.extensions?.query);
2293
+ const query = applyExtensions(new Query(name, this, declaration, this.nextQueryId++), this.extensions?.query);
1687
2294
  this._queries.set(name, query);
1688
2295
  this.notify();
1689
2296
  return query;
1690
2297
  }
1691
2298
  createFilter(name, declaration) {
1692
2299
  this.assertNameFree(name, "filter");
1693
- const dataset = declaration.dataset ? this.datasetIndex(declaration.dataset, name) : this.soleDataset(name, declaration.field);
2300
+ const dataset = this.filterDataset(name, declaration);
1694
2301
  const filter = applyExtensions(new Filter(name, this, declaration, dataset, this.backend), this.extensions?.control);
1695
2302
  this._controls.set(name, filter);
1696
2303
  this.notify();
@@ -1714,7 +2321,7 @@ var App = class extends Observable {
1714
2321
  * because "the control happens to name a field this query also has" is exactly the coupling that
1715
2322
  * breaks silently when someone renames a dimension.
1716
2323
  *
1717
- * There is no `unmap`: a mapping you do not want is one you do not declare.
2324
+ * Edges never change: to change one, `remove()` it and map again.
1718
2325
  */
1719
2326
  mapControl(from, to, options) {
1720
2327
  if (!(from instanceof Control)) {
@@ -1722,6 +2329,8 @@ var App = class extends Observable {
1722
2329
  "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."
1723
2330
  );
1724
2331
  }
2332
+ from.assertLive();
2333
+ to.assertLive();
1725
2334
  if (this._controls.get(from.name) !== from) {
1726
2335
  throw new ValidationError(`Control '${from.name}' belongs to a different app.`, from.name);
1727
2336
  }
@@ -1731,7 +2340,7 @@ var App = class extends Observable {
1731
2340
  if (options.aggregation) {
1732
2341
  assertValidFilterAggregation(options.aggregation, from.name);
1733
2342
  }
1734
- const mapping = new Mapping(from, to, options.field, options.aggregation);
2343
+ const mapping = new Mapping(from, to, options.field, options.aggregation, this);
1735
2344
  if (this._mappings.some((existing) => existing.id === mapping.id)) {
1736
2345
  throw new ValidationError(`Mapping '${mapping.id}' is already declared.`, from.name);
1737
2346
  }
@@ -1756,6 +2365,8 @@ var App = class extends Observable {
1756
2365
  "mapCrossFilter expects two queries. To let a control condition a query, use app.mapControl(from, to, { field })."
1757
2366
  );
1758
2367
  }
2368
+ from.assertLive();
2369
+ to.assertLive();
1759
2370
  if (this._queries.get(from.name) !== from) {
1760
2371
  throw new ValidationError(`Query '${from.name}' belongs to a different app.`, from.name);
1761
2372
  }
@@ -1774,7 +2385,7 @@ var App = class extends Observable {
1774
2385
  from.name
1775
2386
  );
1776
2387
  }
1777
- const edge = new CrossFilter(from, to);
2388
+ const edge = new CrossFilter(from, to, this);
1778
2389
  if (this._crossFilters.some((existing) => existing.id === edge.id)) {
1779
2390
  throw new ValidationError(`Cross-filter '${edge.id}' is already declared.`, from.name);
1780
2391
  }
@@ -1782,6 +2393,86 @@ var App = class extends Observable {
1782
2393
  this.notify();
1783
2394
  return edge;
1784
2395
  }
2396
+ /** @internal Backs `query.update`: checks the change against the app, then swaps it in. */
2397
+ updateQuery(query, changes) {
2398
+ const previous = query.declaration;
2399
+ const declaration = withChanges(previous, changes, ["dataset", "aql", "pageSize", "cache"]);
2400
+ assertDeclaration(query.name, declaration, "sets");
2401
+ const dataset = this.datasetIndex(declaration.dataset, query.name);
2402
+ if (declaration.dataset !== previous.dataset) {
2403
+ const spanning = this._crossFilters.filter((edge) => {
2404
+ if (edge.from === query) return edge.to.declaration.dataset !== declaration.dataset;
2405
+ if (edge.to === query) return edge.from.declaration.dataset !== declaration.dataset;
2406
+ return false;
2407
+ });
2408
+ if (spanning.length) {
2409
+ throw new ValidationError(
2410
+ `Query '${query.name}' can't move to dataset '${declaration.dataset}': its cross-filters ${spanning.map((edge) => `'${edge.id}'`).join(", ")} would span two datasets. Remove them first.`,
2411
+ query.name
2412
+ );
2413
+ }
2414
+ }
2415
+ const reshaped = declaration.aql !== previous.aql || declaration.dataset !== previous.dataset;
2416
+ const sort = changes.sort ?? (reshaped ? [] : query.sort);
2417
+ if (reshaped) this.dropSelectionFrom(query.name);
2418
+ query.replaceDeclaration(declaration, dataset, sort);
2419
+ }
2420
+ /** @internal Backs `remove()` on a query or a control: takes it out, with its edges. */
2421
+ removeEntity(entity) {
2422
+ if (entity instanceof Query) {
2423
+ if (this._queries.get(entity.name) !== entity) {
2424
+ throw new ValidationError(`Query '${entity.name}' belongs to a different app.`, entity.name);
2425
+ }
2426
+ this._queries.delete(entity.name);
2427
+ this.dropEdges((edge) => edge.to === entity || edge.from === entity);
2428
+ this.dropSelectionFrom(entity.name);
2429
+ } else {
2430
+ if (this._controls.get(entity.name) !== entity) {
2431
+ throw new ValidationError(`Control '${entity.name}' belongs to a different app.`, entity.name);
2432
+ }
2433
+ this._controls.delete(entity.name);
2434
+ this.dropEdges((edge) => edge.from === entity);
2435
+ }
2436
+ entity.markRemoved();
2437
+ this.removedListeners.forEach((listener) => {
2438
+ try {
2439
+ listener(entity);
2440
+ } catch {
2441
+ }
2442
+ });
2443
+ this.notify();
2444
+ }
2445
+ /** @internal Backs `remove()` on an edge. */
2446
+ removeEdge(edge) {
2447
+ if (!this.dropEdges((candidate) => candidate === edge)) {
2448
+ throw new ValidationError(`Edge '${edge.id}' belongs to a different app.`, edge.from.name);
2449
+ }
2450
+ this.notify();
2451
+ }
2452
+ /** @internal Each query or control removed from this app, for what the kernel shows about one. */
2453
+ onRemoved(listener) {
2454
+ this.removedListeners.add(listener);
2455
+ return () => {
2456
+ this.removedListeners.delete(listener);
2457
+ };
2458
+ }
2459
+ /** Takes out the edges that match; whether any did. */
2460
+ dropEdges(matches) {
2461
+ const gone = this.mappings.filter(matches);
2462
+ gone.forEach((edge) => edge.markRemoved());
2463
+ const keep = (list) => {
2464
+ const kept = list.filter((edge) => !gone.includes(edge));
2465
+ list.splice(0, list.length, ...kept);
2466
+ };
2467
+ keep(this._mappings);
2468
+ keep(this._crossFilters);
2469
+ return gone.length > 0;
2470
+ }
2471
+ /** Clears the selection, the reader's and the applied one, when it was made in this query. */
2472
+ dropSelectionFrom(name) {
2473
+ if (this._selection?.source === name) this._selection = void 0;
2474
+ if (this._appliedSelection?.source === name) this._appliedSelection = void 0;
2475
+ }
1785
2476
  /* ----------------------------------------------------------------
1786
2477
  Selection
1787
2478
  ---------------------------------------------------------------- */
@@ -1812,12 +2503,37 @@ var App = class extends Observable {
1812
2503
  get timezone() {
1813
2504
  return this._timezone;
1814
2505
  }
2506
+ /**
2507
+ * The app's own, like `setTimezone`: for its UI, and for its queries unless
2508
+ * `query.default.input.weekStartDay` says otherwise. Changing it makes every query it reaches dirty.
2509
+ */
2510
+ setWeekStartDay(day) {
2511
+ assertWeekStartDay(day, "The app", "weekStartDay", "sets");
2512
+ this._weekStartDay = day;
2513
+ this.notify();
2514
+ }
2515
+ /** The app's own week start day, for its UI: undefined when it declares none. */
2516
+ get weekStartDay() {
2517
+ return this._weekStartDay;
2518
+ }
2519
+ /**
2520
+ * What the app's queries get in their input when they set none: its `query.default.input`, or else
2521
+ * its own timezone and week start day. A value absent from both is left to the backend's default.
2522
+ */
2523
+ get queryInputDefaults() {
2524
+ const timezone = this.queryInput.timezone ?? this._timezone;
2525
+ const weekStartDay = this.queryInput.weekStartDay ?? this._weekStartDay;
2526
+ return { ...timezone ? { timezone } : {}, ...weekStartDay ? { weekStartDay } : {} };
2527
+ }
1815
2528
  /* ----------------------------------------------------------------
1816
2529
  AppContext
1817
2530
  ---------------------------------------------------------------- */
1818
2531
  datasetIndex(uname, entity) {
1819
2532
  return resolveDataset(this.datasets, uname, entity);
1820
2533
  }
2534
+ filterDataset(entity, declaration) {
2535
+ return declaration.dataset ? this.datasetIndex(declaration.dataset, entity) : this.soleDataset(entity, declaration.field);
2536
+ }
1821
2537
  mappingsTo(queryName) {
1822
2538
  return this._mappings.filter((mapping) => mapping.to.name === queryName);
1823
2539
  }
@@ -1879,8 +2595,16 @@ var App = class extends Observable {
1879
2595
  );
1880
2596
  }
1881
2597
  }
2598
+ return openRowsMenu(event, this.rowsTarget(query, rows, fields, measure));
2599
+ }
2600
+ /**
2601
+ * @internal What a menu on these rows of the query is about: their conditions, derived as a
2602
+ * cross-filter's, and the annotations plugins set on them (on `measure`'s, when given).
2603
+ */
2604
+ rowsTarget(query, rows, fields, measure) {
1882
2605
  const derived = deriveSelection(query, rows, fields, this.drillTransformations(query));
1883
- return openRowsMenu(event, {
2606
+ const annotations = query.annotations.filter((annotation) => (annotation.kind === "mark" || annotation.kind === "focus") && (measure === void 0 || annotation.anchor.measure === void 0 || annotation.anchor.measure === measure) && annotation.anchor.rows.some((named) => rows.some((row) => rowMatches(named, row))));
2607
+ return {
1884
2608
  kind: "rows",
1885
2609
  app: this.index,
1886
2610
  query: query.name,
@@ -1888,8 +2612,9 @@ var App = class extends Observable {
1888
2612
  fields: derived?.fields ? [...derived.fields] : [],
1889
2613
  ...measure !== void 0 ? { measure } : {},
1890
2614
  conditions: derived?.conditions ? [...derived.conditions] : [],
1891
- ...derived?.expression ? { expression: derived.expression } : {}
1892
- });
2615
+ ...derived?.expression ? { expression: derived.expression } : {},
2616
+ ...annotations.length ? { annotations } : {}
2617
+ };
1893
2618
  }
1894
2619
  /**
1895
2620
  * @internal Backs the kernel's `queryRequest(query)`: what the query runs with now, from its applied
@@ -1906,7 +2631,7 @@ var App = class extends Observable {
1906
2631
  conditions: this.selectionConditionsFor(query.name, "applied"),
1907
2632
  expression: this.selectionExpressionFor(query.name, "applied")
1908
2633
  },
1909
- { timezone: this._timezone }
2634
+ this.queryInputDefaults
1910
2635
  );
1911
2636
  }
1912
2637
  select(query, rows, fields) {
@@ -1925,9 +2650,15 @@ var App = class extends Observable {
1925
2650
  /* ----------------------------------------------------------------
1926
2651
  Execution
1927
2652
  ---------------------------------------------------------------- */
1928
- /** True when a control or the selection has changed since the queries reading it last ran. */
2653
+ /**
2654
+ * True when the next `execute()` would apply something: a control or the selection changed since
2655
+ * the queries reading them last ran, a query changed since its last run (edited, or an edge or a
2656
+ * control taken from it), or, once the app has run, a query was created and never run. A run in
2657
+ * flight with the current inputs is not a change, and nor is a failed run: retrying it is
2658
+ * `execute()`'s, unasked.
2659
+ */
1929
2660
  get hasChanges() {
1930
- return [...this._controls.values()].some((control) => control.isDirty) || this.isSelectionDirty;
2661
+ return [...this._controls.values()].some((control) => control.isDirty) || this.isSelectionDirty || [...this._queries.values()].some((query) => query.hasUnappliedChange(this.selectionCommitted));
1931
2662
  }
1932
2663
  /**
1933
2664
  * False before the first execution, matching `Control.isDirty`: with nothing applied there is
@@ -1953,43 +2684,73 @@ var App = class extends Observable {
1953
2684
  });
1954
2685
  const context = {
1955
2686
  backend: this.backend,
1956
- timezone: this._timezone,
2687
+ ...this.queryInputDefaults,
1957
2688
  bustCache: options.bustCache
1958
2689
  };
1959
2690
  const succeeded = [];
1960
2691
  const failed = [];
1961
2692
  await Promise.all(targets.map(async (query) => {
1962
- const controller = new AbortController();
1963
- query.controller = controller;
1964
- const signature = query.signature();
1965
- query.markExecuting();
1966
- try {
1967
- const result = await runQuery(
1968
- query,
1969
- this.mappingsTo(query.name),
1970
- {
1971
- conditions: this.selectionConditionsFor(query.name, "applied"),
1972
- expression: this.selectionExpressionFor(query.name, "applied")
1973
- },
1974
- context,
1975
- controller.signal
1976
- );
1977
- if (superseded(query, controller)) return;
1978
- query.markSuccess(result, signature, false);
1979
- succeeded.push(query.name);
1980
- } catch (err) {
1981
- if (superseded(query, controller)) return;
1982
- if (isAbort(err)) return;
1983
- const error = toDataAppError(err, query.name);
1984
- query.markError(error);
1985
- reportError("call.query", error);
1986
- failed.push(query.name);
1987
- } finally {
1988
- if (query.controller === controller) query.controller = void 0;
1989
- }
2693
+ const outcome = await this.run(query, query.signature(), context);
2694
+ if (outcome === "succeeded") succeeded.push(query.name);
2695
+ else if (outcome === "failed") failed.push(query.name);
1990
2696
  }));
1991
2697
  return { succeeded, failed };
1992
2698
  }
2699
+ /**
2700
+ * @internal Backs `query.execute()`: that query alone, with what is applied, committing nothing.
2701
+ * Its signature is the applied one, so a query the reader has pending changes for stays dirty.
2702
+ */
2703
+ async executeQuery(query, options = {}) {
2704
+ if (!query.shouldRunAlone(options.force)) return { succeeded: [], failed: [] };
2705
+ query.controller?.abort();
2706
+ query.resetPage();
2707
+ const outcome = await this.run(query, query.signature("applied"), {
2708
+ backend: this.backend,
2709
+ ...this.queryInputDefaults,
2710
+ bustCache: options.bustCache
2711
+ });
2712
+ return {
2713
+ succeeded: outcome === "succeeded" ? [query.name] : [],
2714
+ failed: outcome === "failed" ? [query.name] : []
2715
+ };
2716
+ }
2717
+ /**
2718
+ * One query's run from its first page, with the applied inputs, recorded under `signature`.
2719
+ * Undefined when a newer run took the query over, or it was aborted.
2720
+ */
2721
+ async run(query, signature, context) {
2722
+ const controller = new AbortController();
2723
+ query.controller = controller;
2724
+ query.runningSignature = signature;
2725
+ query.markExecuting();
2726
+ try {
2727
+ const request = buildRequest(
2728
+ query,
2729
+ this.mappingsTo(query.name),
2730
+ {
2731
+ conditions: this.selectionConditionsFor(query.name, "applied"),
2732
+ expression: this.selectionExpressionFor(query.name, "applied")
2733
+ },
2734
+ context
2735
+ );
2736
+ const { result, run } = await runQuery(query, request, context.backend, controller.signal, this.stampOf(query));
2737
+ if (superseded(query, controller)) return void 0;
2738
+ query.markSuccess(result, signature, false, run);
2739
+ return "succeeded";
2740
+ } catch (err) {
2741
+ if (superseded(query, controller)) return void 0;
2742
+ if (isAbort(err)) return void 0;
2743
+ const error = toDataAppError(err, query.name);
2744
+ query.markError(error, false, signature);
2745
+ reportError("call.query", error);
2746
+ return "failed";
2747
+ } finally {
2748
+ if (query.controller === controller) {
2749
+ query.controller = void 0;
2750
+ query.runningSignature = void 0;
2751
+ }
2752
+ }
2753
+ }
1993
2754
  /** Re-runs everything and asks the server to skip its result cache. */
1994
2755
  async refresh() {
1995
2756
  return this.execute({ force: true, bustCache: true });
@@ -2000,32 +2761,30 @@ var App = class extends Observable {
2000
2761
  /** @internal Backs `query.fetchMore()`. Rejects, so an explicit page request reports its failure. */
2001
2762
  async fetchPage(query) {
2002
2763
  const controller = new AbortController();
2764
+ const signature = query.signature("applied");
2003
2765
  query.controller = controller;
2004
- const signature = query.signature();
2766
+ query.runningSignature = signature;
2005
2767
  query.markExecuting();
2006
2768
  try {
2007
- const result = await runQuery(
2008
- query,
2009
- this.mappingsTo(query.name),
2010
- {
2011
- conditions: this.selectionConditionsFor(query.name, "applied"),
2012
- expression: this.selectionExpressionFor(query.name, "applied")
2013
- },
2014
- {
2015
- backend: this.backend,
2016
- timezone: this._timezone
2017
- },
2018
- controller.signal
2019
- );
2769
+ const request = query.run ? pageRequest(query, query.run) : buildRequest(query, this.mappingsTo(query.name), {
2770
+ conditions: this.selectionConditionsFor(query.name, "applied"),
2771
+ expression: this.selectionExpressionFor(query.name, "applied")
2772
+ }, { backend: this.backend, ...this.queryInputDefaults });
2773
+ const { result } = await runQuery(query, request, this.backend, controller.signal, this.stampOf(query));
2774
+ if (superseded(query, controller)) return;
2020
2775
  query.markSuccess(result, signature, true);
2021
2776
  } catch (err) {
2777
+ if (superseded(query, controller)) return;
2022
2778
  query.rewindPage();
2023
2779
  if (isAbort(err)) return;
2024
2780
  const error = toDataAppError(err, query.name);
2025
2781
  query.markError(error, true);
2026
2782
  throw error;
2027
2783
  } finally {
2028
- if (query.controller === controller) query.controller = void 0;
2784
+ if (query.controller === controller) {
2785
+ query.controller = void 0;
2786
+ query.runningSignature = void 0;
2787
+ }
2029
2788
  }
2030
2789
  }
2031
2790
  /**
@@ -2041,11 +2800,13 @@ var App = class extends Observable {
2041
2800
  conditions: this.selectionConditionsFor(query.name, "applied"),
2042
2801
  expression: this.selectionExpressionFor(query.name, "applied")
2043
2802
  },
2044
- { backend: this.backend, timezone: this._timezone, title: this.title },
2045
- options
2803
+ { ...this.queryInputDefaults, title: this.title },
2804
+ options,
2805
+ // As the result on screen ran, so the file holds what the reader sees.
2806
+ query.run
2046
2807
  );
2047
2808
  try {
2048
- return await send(request, options.signal ?? new AbortController().signal);
2809
+ return await send(request, options.signal ?? new AbortController().signal, { app: this.index, query: query.name });
2049
2810
  } catch (err) {
2050
2811
  if (isAbort(err)) throw err;
2051
2812
  throw toDataAppError(err, query.name, "The export failed.");
@@ -2065,6 +2826,7 @@ var App = class extends Observable {
2065
2826
  return {
2066
2827
  ...this.title ? { title: this.title } : {},
2067
2828
  ...this._timezone ? { timezone: this._timezone } : {},
2829
+ ...this._weekStartDay ? { weekStartDay: this._weekStartDay } : {},
2068
2830
  queries: Object.fromEntries([...this._queries.entries()].map(([name, q]) => [name, q.toJSON()])),
2069
2831
  filters: byKind("filter"),
2070
2832
  dateDrills: byKind("dateDrill"),
@@ -2087,6 +2849,8 @@ var App = class extends Observable {
2087
2849
  return {
2088
2850
  ...this.title ? { title: this.title } : {},
2089
2851
  ...this._timezone ? { timezone: this._timezone } : {},
2852
+ ...this._weekStartDay ? { weekStartDay: this._weekStartDay } : {},
2853
+ ...Object.keys(this.queryInput).length > 0 ? { queryInput: { ...this.queryInput } } : {},
2090
2854
  hasChanges: this.hasChanges,
2091
2855
  declaration: this.toJSON(),
2092
2856
  queries: Object.fromEntries(
@@ -2121,6 +2885,10 @@ var App = class extends Observable {
2121
2885
  /* ----------------------------------------------------------------
2122
2886
  Internals
2123
2887
  ---------------------------------------------------------------- */
2888
+ /** What a query's calls are stamped with, so the host can show each under its query. */
2889
+ stampOf(query) {
2890
+ return { app: this.index, query: query.name, id: query.id };
2891
+ }
2124
2892
  assertNameFree(name, kind) {
2125
2893
  assertUniqueName([...this._queries.keys(), ...this._controls.keys()], name, kind);
2126
2894
  }
@@ -2376,6 +3144,16 @@ function namedMember(member, api) {
2376
3144
  }
2377
3145
  });
2378
3146
  }
3147
+ function withQueryId(sdk, { app, query, variant }) {
3148
+ const queries = sdk.apps[app]?.queries ?? {};
3149
+ const id = Object.hasOwn(queries, query) ? queries[query]?.id : void 0;
3150
+ return {
3151
+ app,
3152
+ query,
3153
+ ...id !== void 0 && { id },
3154
+ ...variant !== void 0 && { variant }
3155
+ };
3156
+ }
2379
3157
  function createKernel(plugin, shared, entities) {
2380
3158
  const { window: win, sdk, endpoint } = shared;
2381
3159
  let loading;
@@ -2394,7 +3172,7 @@ function createKernel(plugin, shared, entities) {
2394
3172
  if (!app) throw new ValidationError(`Query '${String(query?.name)}' belongs to no app.`, query?.name);
2395
3173
  return app.requestFor(query);
2396
3174
  },
2397
- call: (name, request, signal) => endpoint.call(name, request ?? null, signal),
3175
+ call: (name, request, signal, stamp) => endpoint.call(name, request ?? null, signal, stamp && withQueryId(sdk, stamp)),
2398
3176
  emit: (name, payload) => endpoint.emit(`${plugin}.${name}`, payload ?? null),
2399
3177
  handle(name, handler) {
2400
3178
  shared.handlers.set(`${plugin}.${name}`, handler);
@@ -2430,6 +3208,17 @@ function createKernel(plugin, shared, entities) {
2430
3208
  menuItem: (item) => shared.contentUi?.addItem(plugin, item),
2431
3209
  modal: (input) => shared.contentUi.modal(input),
2432
3210
  popover: (input) => shared.contentUi.popover(input),
3211
+ annotate(query, annotations, options) {
3212
+ if (query?.isRemoved) return false;
3213
+ const app = sdk.apps.find((candidate) => candidate.queries[query?.name] === query);
3214
+ if (!app) throw new ValidationError(`Plugin '${plugin}' annotated a query that belongs to no app.`, query?.name);
3215
+ if (!options || typeof options.result !== "object" || options.result === null) {
3216
+ throw new ValidationError(`Plugin '${plugin}' annotated query '${query.name}' without the result it computed them from ({ result: query.result }).`, query.name);
3217
+ }
3218
+ if (!query.isCurrentResult(options.result)) return false;
3219
+ query.setAnnotations(plugin, checkAnnotations(plugin, query.name, options.result, annotations));
3220
+ return true;
3221
+ },
2433
3222
  body() {
2434
3223
  loading ?? (loading = endpoint.call(BODY_CALL, { plugin }).then((code) => runBody(win, code)).catch((err) => {
2435
3224
  loading = void 0;
@@ -2440,6 +3229,17 @@ function createKernel(plugin, shared, entities) {
2440
3229
  };
2441
3230
  }
2442
3231
 
3232
+ // src/app/core.ts
3233
+ function installCore(kernel) {
3234
+ kernel.handle("execute", async () => {
3235
+ const summaries = await Promise.all(kernel.sdk.apps.map((app) => app.refresh()));
3236
+ return {
3237
+ succeeded: summaries.flatMap((summary) => summary.succeeded),
3238
+ failed: summaries.flatMap((summary) => summary.failed)
3239
+ };
3240
+ });
3241
+ }
3242
+
2443
3243
  // src/app/pick.ts
2444
3244
  function startPick(doc, handlers) {
2445
3245
  let current = null;
@@ -2586,6 +3386,139 @@ function installInspection(kernel) {
2586
3386
  });
2587
3387
  }
2588
3388
 
3389
+ // src/app/annotationBadges.ts
3390
+ var ANNOTATIONS_ATTRIBUTE = "data-anfra-annotations";
3391
+ function drawnBy(element) {
3392
+ const value = element.getAttribute(ANNOTATIONS_ATTRIBUTE);
3393
+ if (value?.trim() === "off") return "off";
3394
+ return new Set((value ?? "").split(/\s+/).filter((kind) => ANNOTATION_KINDS.includes(kind)));
3395
+ }
3396
+ function badgedAnnotations(element, annotations) {
3397
+ const drawn = drawnBy(element);
3398
+ return drawn === "off" ? [] : annotations.filter((annotation) => !drawn.has(annotation.kind));
3399
+ }
3400
+ function highest(annotations) {
3401
+ let top = -1;
3402
+ for (const { severity } of annotations) top = Math.max(top, severity ? SEVERITIES.indexOf(severity) : -1);
3403
+ return top < 0 ? void 0 : SEVERITIES[top];
3404
+ }
3405
+ var describe = (count, severity) => `${count} annotation${count === 1 ? "" : "s"}${severity ? `, highest: ${severity}` : ""}`;
3406
+ function installAnnotationBadges(kernel, contentUi) {
3407
+ const doc = kernel.window.document;
3408
+ const realm = kernel.window;
3409
+ const apps = [];
3410
+ let scheduled = false;
3411
+ let drawnAny = false;
3412
+ let observer;
3413
+ const lists = /* @__PURE__ */ new WeakMap();
3414
+ let listed = 0;
3415
+ const listId = (list) => {
3416
+ if (!lists.has(list)) lists.set(list, listed += 1);
3417
+ return lists.get(list);
3418
+ };
3419
+ const ui = () => kernel.body();
3420
+ function actionsFor(app, query, annotation, at) {
3421
+ const rows = query.result?.rows;
3422
+ if (annotation.kind !== "mark" && annotation.kind !== "focus" || !rows) return [];
3423
+ const target = app.rowsTarget(query, annotation.anchor.index.map((index) => rows[index]), void 0, annotation.anchor.measure);
3424
+ return contentUi.rowsEntries(annotation.plugin, { ...target, ...at ? { at } : {}, annotations: [annotation] });
3425
+ }
3426
+ async function open(app, query, covered, anchor) {
3427
+ const body = await ui();
3428
+ const badge = anchor();
3429
+ const at = badge ? { x: badge.x, y: badge.y + badge.height } : void 0;
3430
+ const opening = contentUi.popoverAt(anchor, {
3431
+ about: { app: app.index, query: query.name },
3432
+ side: "bottom",
3433
+ dismiss: "outside",
3434
+ mount: (root) => body.annotationList(
3435
+ root,
3436
+ covered.map((annotation) => ({ ...annotationNote(annotation), actions: actionsFor(app, query, annotation, at) })),
3437
+ (action) => {
3438
+ void opening.then((opened) => opened.close());
3439
+ Promise.resolve().then(action.run).catch((err) => {
3440
+ realm.console?.error("anfra: an annotation's action failed:", err);
3441
+ reportError("plugin.uncaught", err);
3442
+ });
3443
+ }
3444
+ )
3445
+ });
3446
+ await opening;
3447
+ }
3448
+ let shown = { signature: "", elements: [] };
3449
+ async function draw() {
3450
+ scheduled = false;
3451
+ const list = [];
3452
+ const parts = [];
3453
+ let annotated = false;
3454
+ for (const app of apps) {
3455
+ for (const query of Object.values(app.queries)) {
3456
+ const { annotations } = query;
3457
+ if (!annotations.length) continue;
3458
+ annotated = true;
3459
+ markersFor(doc, "query", app.index, query.name).forEach((element, position) => {
3460
+ const covered = badgedAnnotations(element, annotations);
3461
+ if (!covered.length) return;
3462
+ const severity = highest(covered);
3463
+ const id = `${app.index}/${query.name}#${position}`;
3464
+ parts.push(`${id}:${listId(annotations)}:${covered.length}`);
3465
+ list.push({
3466
+ id,
3467
+ element,
3468
+ count: covered.length,
3469
+ ...severity ? { severity } : {},
3470
+ label: describe(covered.length, severity),
3471
+ onOpen: (anchor) => {
3472
+ open(app, query, covered, anchor).catch((err) => {
3473
+ realm.console?.error("anfra: the annotations popover failed to open:", err);
3474
+ reportError("plugin.uncaught", err);
3475
+ });
3476
+ }
3477
+ });
3478
+ });
3479
+ }
3480
+ }
3481
+ watchPage(annotated);
3482
+ const elements = list.map((badge) => badge.element);
3483
+ const signature = parts.join("|");
3484
+ if (signature === shown.signature && elements.every((element, at) => element === shown.elements[at])) return;
3485
+ shown = { signature, elements };
3486
+ if (!list.length && !drawnAny) return;
3487
+ drawnAny = true;
3488
+ const body = await ui();
3489
+ body.badges(layerRoot(doc, "anfra-badges"), list);
3490
+ }
3491
+ const schedule = () => {
3492
+ if (scheduled) return;
3493
+ scheduled = true;
3494
+ queueMicrotask(() => {
3495
+ draw().catch((err) => {
3496
+ realm.console?.error("anfra: the annotations badge failed to draw:", err);
3497
+ reportError("plugin.uncaught", err);
3498
+ });
3499
+ });
3500
+ };
3501
+ function watchPage(on) {
3502
+ if (on && !observer && typeof realm.MutationObserver === "function") {
3503
+ observer = new realm.MutationObserver(schedule);
3504
+ observer.observe(doc.documentElement, {
3505
+ subtree: true,
3506
+ childList: true,
3507
+ attributes: true,
3508
+ attributeFilter: [ATTR.query, ANNOTATIONS_ATTRIBUTE]
3509
+ });
3510
+ } else if (!on && observer) {
3511
+ observer.disconnect();
3512
+ observer = void 0;
3513
+ }
3514
+ }
3515
+ kernel.onApp((app) => {
3516
+ apps.push(app);
3517
+ app.subscribe(schedule);
3518
+ app.onRemoved(schedule);
3519
+ });
3520
+ }
3521
+
2589
3522
  // src/app/bootstrap.ts
2590
3523
  function bootstrap(win, setups = []) {
2591
3524
  const element = win.document.getElementById(PROVISION_ELEMENT_ID);
@@ -2620,7 +3553,7 @@ function bootstrap(win, setups = []) {
2620
3553
  endpoint.receive(event.data);
2621
3554
  });
2622
3555
  const backend = {
2623
- submitQuery: (request, signal) => endpoint.call("core.submitQuery", request, signal).then((result) => {
3556
+ submitQuery: (request, signal, stamp) => endpoint.call("core.submitQuery", request, signal, stamp).then((result) => {
2624
3557
  if (result.debug?.executedAt) result.debug.executedAt = new Date(result.debug.executedAt);
2625
3558
  return result;
2626
3559
  }),
@@ -2655,7 +3588,9 @@ function bootstrap(win, setups = []) {
2655
3588
  const own = createKernel("anfra", shared, { Query, Control });
2656
3589
  installReporting(own, win, provision.captureConsole === true);
2657
3590
  installInspection(own);
3591
+ installCore(createKernel("core", shared, { Query, Control }));
2658
3592
  shared.contentUi = installContentUi(own);
3593
+ installAnnotationBadges(own, shared.contentUi);
2659
3594
  own.on("theme", (theme) => {
2660
3595
  const resolved = resolveTheme(theme);
2661
3596
  themeLayer(win.document, resolved);