@altertable/data-app 0.77.0 → 0.78.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 (68) hide show
  1. package/CONTRIBUTING.md +3 -0
  2. package/REFERENCE.md +45 -37
  3. package/dist/chunks/contract-gu1rDsV0.js +1588 -0
  4. package/dist/chunks/contract-gu1rDsV0.js.map +1 -0
  5. package/dist/chunks/data-client-BMdL73Ab.js +122 -0
  6. package/dist/chunks/data-client-BMdL73Ab.js.map +1 -0
  7. package/dist/chunks/{date-time-range-value-CnlTr1U1.js → date-time-range-value-D-XfqVTT.js} +21 -24
  8. package/dist/chunks/date-time-range-value-D-XfqVTT.js.map +1 -0
  9. package/dist/chunks/{diagnostics-Dyj-rUsY.js → diagnostics-CX9SsU79.js} +240 -63
  10. package/dist/chunks/diagnostics-CX9SsU79.js.map +1 -0
  11. package/dist/chunks/record-Cr4Uk1K3.js +9 -0
  12. package/dist/chunks/record-Cr4Uk1K3.js.map +1 -0
  13. package/dist/client/index.js +4 -101
  14. package/dist/client/index.js.map +1 -1
  15. package/dist/core/appearance.js +3 -5
  16. package/dist/core/appearance.js.map +1 -1
  17. package/dist/core/config.js +11 -3
  18. package/dist/core/config.js.map +1 -1
  19. package/dist/core/contract.js +3 -4
  20. package/dist/core/format.js +1 -1
  21. package/dist/internal.js +63 -11
  22. package/dist/internal.js.map +1 -1
  23. package/dist/types/chunks/contract.d.ts +254 -19
  24. package/dist/types/chunks/data-client.d.ts +46 -0
  25. package/dist/types/chunks/date-time-range-value.d.ts +28 -2
  26. package/dist/types/chunks/index.d.ts +65 -80
  27. package/dist/types/client/index.d.ts +4 -3
  28. package/dist/types/core/config.d.ts +10 -4
  29. package/dist/types/core/contract.d.ts +3 -5
  30. package/dist/types/core/format.d.ts +1 -2
  31. package/dist/types/index.d.ts +4 -4
  32. package/dist/types/internal.d.ts +25 -6
  33. package/docs/app-authoring.md +13 -9
  34. package/docs/client.md +14 -53
  35. package/docs/contract.md +35 -15
  36. package/docs/data-context.md +5 -2
  37. package/docs/diagnostics.md +16 -23
  38. package/docs/embed.md +60 -25
  39. package/docs/filters.md +33 -57
  40. package/docs/hosted-apps.md +9 -9
  41. package/docs/layout.md +21 -0
  42. package/docs/local-data-apps.md +5 -6
  43. package/docs/react-embed.md +44 -2
  44. package/docs/react.md +1 -2
  45. package/docs/server-bun.md +8 -5
  46. package/docs/stories-and-export.md +4 -4
  47. package/docs/styling.md +2 -1
  48. package/docs/ui.md +12 -3
  49. package/docs/views.md +12 -11
  50. package/docs/widgets.md +3 -3
  51. package/docs/worker.md +1 -1
  52. package/package.json +1 -5
  53. package/dist/chunks/contract-BQsFReRp.js +0 -780
  54. package/dist/chunks/contract-BQsFReRp.js.map +0 -1
  55. package/dist/chunks/contract-VhY9V9wd.js +0 -806
  56. package/dist/chunks/contract-VhY9V9wd.js.map +0 -1
  57. package/dist/chunks/date-time-range-value-CnlTr1U1.js.map +0 -1
  58. package/dist/chunks/diagnostics-Dyj-rUsY.js.map +0 -1
  59. package/dist/chunks/operation-BVRM-A5Y.js +0 -134
  60. package/dist/chunks/operation-BVRM-A5Y.js.map +0 -1
  61. package/dist/chunks/request-body-H1qPmmTN.js +0 -50
  62. package/dist/chunks/request-body-H1qPmmTN.js.map +0 -1
  63. package/dist/server/index.js +0 -90
  64. package/dist/server/index.js.map +0 -1
  65. package/dist/types/chunks/contract2.d.ts +0 -221
  66. package/dist/types/chunks/date-time-range.d.ts +0 -29
  67. package/dist/types/server/index.d.ts +0 -17
  68. package/docs/server.md +0 -41
@@ -1,806 +0,0 @@
1
- import { a as resolveDateTimeRange, c as parseDateTimeRangeInput, i as parseDateTimeRange, l as invariant, n as formatDateTimeRange, o as serializeDateTimeRange, s as fixedUnitMilliseconds } from "./date-time-range-value-CnlTr1U1.js";
2
- import { w as createDimensionFilter, x as isQueryParameters } from "./contract-BQsFReRp.js";
3
- import { fromDate, parseDate, toCalendarDateTime, today } from "@internationalized/date";
4
- //#region src/core/filters.ts
5
- const all = { kind: "all" };
6
- const numberOperatorLabels = {
7
- eq: "Equals",
8
- ne: "Does not equal",
9
- gt: "Greater than",
10
- gte: "At least",
11
- lt: "Less than",
12
- lte: "At most"
13
- };
14
- /** Exact numeric predicates; range bounds are inclusive and may be open-ended. */
15
- function numberFilter({ key, label, min, max, defaultValue = all, history = "push", presentation }) {
16
- invariant(!!key.trim(), "Numeric filter requires a URL key.");
17
- invariant((min === void 0 || Number.isFinite(min)) && (max === void 0 || Number.isFinite(max)) && (min === void 0 || max === void 0 || min <= max), "Invalid numeric filter bounds.");
18
- function validNumber(value) {
19
- return typeof value === "number" && Number.isFinite(value) && (min === void 0 || value >= min) && (max === void 0 || value <= max);
20
- }
21
- function valid(value) {
22
- if (!value || typeof value !== "object") return false;
23
- if (value.kind === "all") return true;
24
- if (value.kind === "comparison") return typeof value.operator === "string" && Object.hasOwn(numberOperatorLabels, value.operator) && validNumber(value.value);
25
- return value.kind === "range" && (value.min !== void 0 || value.max !== void 0) && (value.min === void 0 || validNumber(value.min)) && (value.max === void 0 || validNumber(value.max)) && (value.min === void 0 || value.max === void 0 || value.min <= value.max);
26
- }
27
- function encode(value) {
28
- return value.kind === "all" ? null : value.kind === "range" ? JSON.stringify({
29
- kind: "range",
30
- min: value.min,
31
- max: value.max
32
- }) : JSON.stringify({
33
- kind: "comparison",
34
- operator: value.operator,
35
- value: value.value
36
- });
37
- }
38
- invariant(valid(defaultValue), `Invalid default for ${label}.`);
39
- return {
40
- kind: "numberFilter",
41
- presentation,
42
- label,
43
- min,
44
- max,
45
- defaultValue,
46
- clearValue: all,
47
- urlKeys: [key],
48
- history,
49
- valid,
50
- same: (left, right) => encode(left) === encode(right),
51
- describe(value) {
52
- return value.kind === "all" ? "Any" : value.kind === "comparison" ? `${numberOperatorLabels[value.operator]} ${value.value}` : value.min === void 0 ? `At most ${value.max}` : value.max === void 0 ? `At least ${value.min}` : `${value.min}–${value.max}`;
53
- },
54
- read(params) {
55
- const raw = params.get(key);
56
- if (raw === null) return defaultValue;
57
- if (raw.length > 512) return defaultValue;
58
- try {
59
- const value = raw === "all" ? all : JSON.parse(raw);
60
- return valid(value) ? value : defaultValue;
61
- } catch {
62
- return defaultValue;
63
- }
64
- },
65
- write(value) {
66
- return { [key]: encode(value) === encode(defaultValue) ? null : value.kind === "all" ? "all" : encode(value) };
67
- }
68
- };
69
- }
70
- /** Boolean predicate with a distinct unrestricted state. */
71
- function booleanFilter({ key, label, defaultValue = all, history = "push", presentation }) {
72
- invariant(!!key.trim(), "Boolean filter requires a URL key.");
73
- function valid(value) {
74
- return !!value && typeof value === "object" && (value.kind === "all" || value.kind === "is" && typeof value.value === "boolean");
75
- }
76
- function encode(value) {
77
- return value.kind === "all" ? "all" : String(value.value);
78
- }
79
- invariant(valid(defaultValue), `Invalid default for ${label}.`);
80
- return {
81
- kind: "booleanFilter",
82
- presentation,
83
- label,
84
- defaultValue,
85
- clearValue: all,
86
- urlKeys: [key],
87
- history,
88
- valid,
89
- describe: (value) => value.kind === "all" ? "Any" : value.value ? "Yes" : "No",
90
- same: (left, right) => encode(left) === encode(right),
91
- read(params) {
92
- const raw = params.get(key);
93
- return raw === "all" ? all : raw === "true" || raw === "false" ? {
94
- kind: "is",
95
- value: raw === "true"
96
- } : defaultValue;
97
- },
98
- write(value) {
99
- return { [key]: encode(value) === encode(defaultValue) ? null : encode(value) };
100
- }
101
- };
102
- }
103
- function parseNumberSelection(value, filter) {
104
- invariant(filter.valid(value), `Invalid ${filter.label} selection.`);
105
- return value;
106
- }
107
- function parseBooleanSelection(value, filter) {
108
- invariant(filter.valid(value), `Invalid ${filter.label} selection.`);
109
- return value;
110
- }
111
- //#endregion
112
- //#region src/core/facets.ts
113
- const facetSource = Symbol("data-app.facetSource");
114
- //#endregion
115
- //#region src/core/facet-filter.ts
116
- function facetFilter({ options: operation, ...settings }) {
117
- return Object.assign(createDimensionFilter({
118
- ...settings,
119
- options: []
120
- }, true), {
121
- optionsSource: "query",
122
- [facetSource]: Object.freeze({ operation })
123
- });
124
- }
125
- //#endregion
126
- //#region src/core/date-time-range-contract.ts
127
- function createDateTimeRangePolicy({ minDate, maxDate: sourceMaxDate, maxRangeDays, timeZone, completeDays = false }) {
128
- invariant(maxRangeDays === void 0 || Number.isInteger(maxRangeDays) && maxRangeDays > 0, "maxRangeDays must be a positive integer.");
129
- if (minDate) parseDate(minDate);
130
- if (typeof sourceMaxDate === "string") parseDate(sourceMaxDate);
131
- today(timeZone);
132
- function reference(now) {
133
- invariant(Number.isFinite(now.getTime()), "Invalid reference date.");
134
- return toCalendarDateTime(fromDate(now, timeZone)).toDate("UTC");
135
- }
136
- function bounds(now = /* @__PURE__ */ new Date()) {
137
- const date = reference(now).toISOString().slice(0, 10);
138
- const latest = parseDate(date).subtract({ days: completeDays ? 1 : 0 }).toString();
139
- const sourceMax = typeof sourceMaxDate === "function" ? sourceMaxDate() : sourceMaxDate;
140
- if (sourceMax) parseDate(sourceMax);
141
- return {
142
- minDate,
143
- maxDate: sourceMax && sourceMax < latest ? sourceMax : latest,
144
- maxRangeDays,
145
- timeZone
146
- };
147
- }
148
- function resolve(value, now = /* @__PURE__ */ new Date()) {
149
- const range = resolveDateTimeRange(parseDateTimeRange(value), reference(now));
150
- const limits = bounds(now);
151
- invariant(range.from, "Choose a bounded datetime range.");
152
- invariant(maxRangeDays === void 0 || range.to.getTime() - range.from.getTime() <= maxRangeDays * fixedUnitMilliseconds.DAY, `Choose a range of at most ${maxRangeDays} days.`);
153
- invariant(!minDate || range.from >= parseDate(minDate).toDate("UTC"), "Range starts before available source coverage.");
154
- invariant(range.to <= parseDate(limits.maxDate).add({ days: 1 }).toDate("UTC"), "Range ends after available source coverage.");
155
- return {
156
- from: range.from,
157
- to: range.to
158
- };
159
- }
160
- function parse(value, now = /* @__PURE__ */ new Date()) {
161
- const range = parseDateTimeRange(value);
162
- resolve(range, now);
163
- return range;
164
- }
165
- /** Hours that have not happened yet hold no data; ending there keeps comparisons equal. */
166
- function endAtNow(range, now = /* @__PURE__ */ new Date()) {
167
- const current = reference(now);
168
- if (range.to <= current) return range;
169
- return {
170
- from: range.from,
171
- to: range.from > current ? range.from : current
172
- };
173
- }
174
- /** The same window one selected length earlier, ending as far before now as the range does. */
175
- function comparison(value, now = /* @__PURE__ */ new Date()) {
176
- const selected = resolve(value, now);
177
- const length = selected.to.getTime() - selected.from.getTime();
178
- const range = endAtNow(selected, now);
179
- const previous = {
180
- from: new Date(range.from.getTime() - length),
181
- to: new Date(range.to.getTime() - length)
182
- };
183
- try {
184
- return resolve(previous, now);
185
- } catch {
186
- return null;
187
- }
188
- }
189
- return {
190
- timeZone,
191
- bounds,
192
- /** Validate coverage and duration while preserving symbolic relative bounds. */
193
- parse,
194
- /** Resolve to UTC-rebased bounds using reporting-zone wall-clock fields, then validate policy. */
195
- resolve,
196
- /** Return the comparison window, or null when source coverage excludes it. */
197
- comparison,
198
- /** End a resolved range at the reference time when it runs past it. */
199
- endAtNow,
200
- /** Resolve both periods against one reference instant, ending the range at now. */
201
- request(value, compare = false, now = /* @__PURE__ */ new Date()) {
202
- const range = endAtNow(resolve(value, now), now);
203
- const previous = compare ? comparison(value, now) : null;
204
- invariant(!compare || previous, "Comparison is outside available source coverage.");
205
- return {
206
- range,
207
- comparison: previous
208
- };
209
- }
210
- };
211
- }
212
- //#endregion
213
- //#region src/core/date-time-filter.ts
214
- /** Monitoring offers minute/hour windows; analytics offers longer periods and to-date windows. Spread either menu to add custom presets. */
215
- const dateTimeRangePresets = {
216
- monitoring: [
217
- {
218
- label: "Past 5 minutes",
219
- range: "5m",
220
- shortcut: "5m"
221
- },
222
- {
223
- label: "Past 15 minutes",
224
- range: "15m",
225
- shortcut: "15m"
226
- },
227
- {
228
- label: "Past hour",
229
- range: "1h",
230
- shortcut: "1h"
231
- },
232
- {
233
- label: "Past 4 hours",
234
- range: "4h",
235
- shortcut: "4h"
236
- },
237
- {
238
- label: "Past 24 hours",
239
- range: "1d",
240
- shortcut: "1d"
241
- }
242
- ],
243
- analytics: [
244
- {
245
- label: "Past 7 days",
246
- range: "7d",
247
- shortcut: "7d"
248
- },
249
- {
250
- label: "Past 30 days",
251
- range: "30d",
252
- shortcut: "30d"
253
- },
254
- {
255
- label: "Past 90 days",
256
- range: "90d",
257
- shortcut: "90d"
258
- },
259
- {
260
- label: "Month to date",
261
- range: "MTD",
262
- shortcut: "MTD"
263
- },
264
- {
265
- label: "Year to date",
266
- range: "YTD",
267
- shortcut: "YTD"
268
- },
269
- {
270
- label: "Past year",
271
- range: "1y",
272
- shortcut: "1y"
273
- }
274
- ]
275
- };
276
- /** One declaration drives the picker, URL state, and the input of operations that list it.
277
- * Operations receive `{ range, comparison }`: `from` inclusive, `to` exclusive.
278
- */
279
- function dateTimeRangeFilter(options) {
280
- const { key, label = "Date range", defaultValue, timeZone = "UTC", maxRangeDays, minDate, maxDate, completeDays, comparison, presets, history = "push", presentation } = options;
281
- const policy = createDateTimeRangePolicy({
282
- minDate,
283
- maxDate,
284
- maxRangeDays,
285
- timeZone,
286
- completeDays
287
- });
288
- const comparable = comparison !== void 0;
289
- const compareKey = key === "period" ? "compare" : `${key}-compare`;
290
- function parseRange(value, now) {
291
- return policy.parse(parseDateTimeRange(value, { maxRangeDays }), now);
292
- }
293
- const parsed = typeof defaultValue === "string" ? parseDateTimeRangeInput(defaultValue) : null;
294
- invariant(!parsed || parsed.ok, `Invalid default range for ${key}.`);
295
- const initial = {
296
- range: parseRange(parsed?.ok ? parsed.range : defaultValue),
297
- ...comparison === "on" ? { comparison: "previous" } : {}
298
- };
299
- function sameRange(left, right) {
300
- return serializeDateTimeRange(left) === serializeDateTimeRange(right);
301
- }
302
- function parseSelection(value, now = /* @__PURE__ */ new Date()) {
303
- invariant(!!value && typeof value === "object" && !Array.isArray(value), "Choose a datetime range.");
304
- const selection = value;
305
- invariant(Object.keys(selection).every((name) => name === "range" || name === "comparison") && (selection.comparison === void 0 || comparable && selection.comparison === "previous"), "Invalid comparison selection.");
306
- const range = parseRange(selection.range, now);
307
- invariant(!selection.comparison || policy.comparison(range, now), "Comparison is outside available source coverage.");
308
- return {
309
- range,
310
- ...selection.comparison ? { comparison: "previous" } : {}
311
- };
312
- }
313
- function request(value, now = /* @__PURE__ */ new Date()) {
314
- const selection = parseSelection(value, now);
315
- return {
316
- ...policy.request(selection.range, selection.comparison === "previous", now),
317
- selection,
318
- reference: now.toISOString()
319
- };
320
- }
321
- function same(left, right) {
322
- return left.comparison === right.comparison && sameRange(left.range, right.range);
323
- }
324
- function valid(value) {
325
- try {
326
- parseSelection(value);
327
- return true;
328
- } catch {
329
- return false;
330
- }
331
- }
332
- invariant(valid(initial), `Date filter ${key} has a default outside its source coverage.`);
333
- /** The URL records the comparison only when it differs from the default. */
334
- function comparisonParam(selection) {
335
- if (!comparable) return {};
336
- const state = selection.comparison ?? "off";
337
- return { [compareKey]: state === (initial.comparison ?? "off") ? null : state };
338
- }
339
- function readRange(params) {
340
- const text = params.get(key);
341
- if (!text || text.length > 8192) return initial.range;
342
- try {
343
- return parseRange(JSON.parse(text));
344
- } catch {
345
- return initial.range;
346
- }
347
- }
348
- return {
349
- kind: "dateTimeRange",
350
- label,
351
- presentation,
352
- history,
353
- urlKeys: comparable ? [key, compareKey] : [key],
354
- defaultValue: initial,
355
- clearValue: initial,
356
- comparable,
357
- policy,
358
- maxRangeDays,
359
- presets,
360
- request,
361
- parseInput(value) {
362
- invariant(!!value && typeof value === "object" && !Array.isArray(value), "Invalid datetime request.");
363
- const supplied = value;
364
- invariant(Object.keys(supplied).every((name) => [
365
- "range",
366
- "comparison",
367
- "selection",
368
- "reference"
369
- ].includes(name)), "Invalid datetime request.");
370
- const range = policy.endAtNow(policy.resolve(parseRange(supplied.range)));
371
- if (supplied.comparison === null || supplied.comparison === void 0) return {
372
- range,
373
- comparison: null
374
- };
375
- invariant(comparable, `${label} has no comparison.`);
376
- const comparison = policy.resolve(parseDateTimeRange(supplied.comparison));
377
- invariant(comparison.to <= range.from && comparison.to.getTime() - comparison.from.getTime() === range.to.getTime() - range.from.getTime(), "Comparison must be an earlier range of equal length.");
378
- return {
379
- range,
380
- comparison
381
- };
382
- },
383
- previous(selection) {
384
- return comparable ? policy.comparison(selection.range) : null;
385
- },
386
- valid,
387
- same,
388
- describe: (selection) => `${formatDateTimeRange(selection.range)}${selection.comparison ? " vs previous period" : ""}`,
389
- read(params) {
390
- const range = readRange(params);
391
- if (!comparable) return { range };
392
- const state = params.get(compareKey);
393
- const compared = {
394
- range,
395
- comparison: "previous"
396
- };
397
- return (state === "previous" || state === null && !!initial.comparison) && valid(compared) ? compared : { range };
398
- },
399
- write(value) {
400
- const selection = parseSelection(value);
401
- return {
402
- [key]: sameRange(selection.range, initial.range) ? null : serializeDateTimeRange(selection.range),
403
- ...comparisonParam(selection)
404
- };
405
- }
406
- };
407
- }
408
- //#endregion
409
- //#region src/core/navigation.ts
410
- function validLocation(value) {
411
- if (!value || typeof value !== "object") return false;
412
- const message = value;
413
- return typeof message.search === "string" && message.search.length <= 16384 && (message.search === "" || message.search.startsWith("?")) && typeof message.hash === "string" && message.hash.length <= 4096 && (message.hash === "" || message.hash.startsWith("#"));
414
- }
415
- //#endregion
416
- //#region src/core/messages.ts
417
- const errorBrand = Symbol.for("@altertable/data-app/MessageRoutingError");
418
- /** Only these deliberate, public failures cross the message boundary. Other errors stay private. */
419
- var MessageRoutingError = class extends Error {
420
- code;
421
- requestId;
422
- [errorBrand] = true;
423
- static [Symbol.hasInstance](value) {
424
- return value instanceof Error && value[errorBrand] === true;
425
- }
426
- constructor(code, message, requestId, options) {
427
- super(message, options);
428
- this.code = code;
429
- this.requestId = requestId;
430
- this.name = "MessageRoutingError";
431
- }
432
- };
433
- function defineMessageRoute(route) {
434
- return route;
435
- }
436
- /** Contracts are shared; handlers are supplied by the host and never belong in the app bundle. */
437
- function createMessageRouter(routes, handlers) {
438
- const registered = new Map(Object.entries(routes).map(([name, contract]) => {
439
- const handler = handlers[name];
440
- if (!name || name.length > 256 || typeof handler !== "function") throw new Error("Each message route requires a handler and a bounded name.");
441
- return [name, {
442
- contract,
443
- handler
444
- }];
445
- }));
446
- async function dispatch(value, context) {
447
- if (!value || typeof value !== "object" || typeof value.route !== "string") throw new MessageRoutingError("invalid_message", "Invalid routed message.");
448
- const message = value;
449
- const entry = registered.get(message.route);
450
- if (!entry) throw new MessageRoutingError("unknown_route", "Unknown message route.");
451
- let payload;
452
- try {
453
- payload = entry.contract.input(message.payload);
454
- } catch (error) {
455
- if (error instanceof MessageRoutingError) throw error;
456
- throw new MessageRoutingError("invalid_payload", "Invalid message payload.");
457
- }
458
- context.signal.throwIfAborted();
459
- let result;
460
- try {
461
- result = await entry.handler(payload, context);
462
- } catch (error) {
463
- if (context.signal.aborted) throw context.signal.reason;
464
- if (error instanceof MessageRoutingError) throw error;
465
- throw new MessageRoutingError("request_failed", "The message request failed. Retry the request.");
466
- }
467
- context.signal.throwIfAborted();
468
- try {
469
- return entry.contract.output(result, payload);
470
- } catch (error) {
471
- if (error instanceof MessageRoutingError) throw error;
472
- throw new MessageRoutingError("invalid_response", "Invalid message response.");
473
- }
474
- }
475
- return { dispatch };
476
- }
477
- /** Omit contracts only in generic hosts such as the CLI shell, where Bun validates operations. */
478
- function defineDataQueryRoute(operations) {
479
- return {
480
- operations,
481
- input(value) {
482
- if (!value || typeof value !== "object") throw new Error("Invalid query.");
483
- const request = value;
484
- if (typeof request.operation !== "string" || !request.operation || request.operation.length > 256 || request.operation.includes("/")) throw new Error("Invalid operation.");
485
- const operation = operations && Object.hasOwn(operations, request.operation) ? operations[request.operation] : void 0;
486
- if (operations && !operation) throw new Error("Unknown operation.");
487
- return {
488
- operation: request.operation,
489
- input: operation ? operation.input(request.input) : request.input
490
- };
491
- },
492
- output(value) {
493
- if (!value || typeof value !== "object") throw new Error("Invalid data response.");
494
- const response = value;
495
- if (!Number.isInteger(response.status) || response.status < 100 || response.status > 599 || !response.body || typeof response.body !== "object" || Array.isArray(response.body)) throw new Error("Invalid data response.");
496
- const body = response.body;
497
- if (response.status < 200 || response.status >= 300) {
498
- const failure = body.error;
499
- throw new MessageRoutingError(typeof failure?.code === "string" ? failure.code : "request_failed", typeof failure?.message === "string" ? failure.message : "Could not load data.", typeof failure?.requestId === "string" ? failure.requestId : void 0);
500
- }
501
- if (!("data" in body) || typeof body.requestId !== "string" || typeof body.queriedAt !== "string" || !Array.isArray(body.queryIds) || !body.queryIds.every((id) => typeof id === "string")) throw new Error("Invalid data envelope.");
502
- if (body.queries !== void 0 && (!Array.isArray(body.queries) || !body.queries.every((query) => query && typeof query === "object" && typeof query.name === "string" && typeof query.statement === "string" && (query.params === void 0 || isQueryParameters(query.params)) && (query.queryId === void 0 || typeof query.queryId === "string")))) throw new Error("Invalid query evidence.");
503
- return {
504
- status: response.status,
505
- body
506
- };
507
- }
508
- };
509
- }
510
- const navigationUpdateRoute = /* @__PURE__ */ defineMessageRoute({
511
- input(value) {
512
- if (!value || typeof value !== "object") throw new Error("Invalid navigation.");
513
- const input = value;
514
- if (!validLocation(input) || input.mode !== "push" && input.mode !== "replace" || input.title !== void 0 && (typeof input.title !== "string" || input.title.length > 512)) throw new Error("Invalid navigation.");
515
- return {
516
- search: input.search,
517
- hash: input.hash,
518
- mode: input.mode,
519
- ...input.title === void 0 ? {} : { title: input.title }
520
- };
521
- },
522
- output(value) {
523
- if (value !== null) throw new Error("Invalid navigation response.");
524
- return null;
525
- }
526
- });
527
- /** SQL delivery for browser-owned operations. Hosts must enforce backend access and resource limits. */
528
- const sqlQueryRoute = defineMessageRoute({
529
- input(value) {
530
- if (!value || typeof value !== "object") throw new Error("Invalid SQL query.");
531
- const query = value;
532
- if (typeof query.statement !== "string" || !query.statement.trim() || typeof query.limit !== "number" || !Number.isSafeInteger(query.limit) || query.limit < 1 || query.params !== void 0 && !isQueryParameters(query.params)) throw new Error("Invalid SQL query.");
533
- return {
534
- statement: query.statement,
535
- limit: query.limit,
536
- ...query.params === void 0 ? {} : { params: query.params }
537
- };
538
- },
539
- output(value, input) {
540
- if (!value || typeof value !== "object") throw new Error("Invalid query result.");
541
- const result = value;
542
- if (!Array.isArray(result.columns) || !result.columns.every((column) => column && typeof column.name === "string" && (column.type === void 0 || typeof column.type === "string")) || !Array.isArray(result.rows) || result.rows.length > input.limit || !result.rows.every((row) => Array.isArray(row) && row.length === result.columns.length) || result.queryId !== void 0 && typeof result.queryId !== "string") throw new Error("Invalid query result.");
543
- return {
544
- columns: result.columns,
545
- rows: result.rows,
546
- ...result.queryId === void 0 ? {} : { queryId: result.queryId }
547
- };
548
- }
549
- });
550
- const dataAppRoutes = {
551
- "data:query": /* @__PURE__ */ defineDataQueryRoute(),
552
- "navigation:update": navigationUpdateRoute
553
- };
554
- //#endregion
555
- //#region src/core/annotations.ts
556
- function object(value) {
557
- if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid annotation.");
558
- return value;
559
- }
560
- function text(value, limit, required = false) {
561
- if (typeof value !== "string" || value.length > limit || required && !value.trim()) throw new Error("Invalid annotation text.");
562
- return value;
563
- }
564
- function names(value) {
565
- if (!Array.isArray(value) || value.length > 20) throw new Error("Invalid annotation references.");
566
- return value.map((name) => text(name, 128, true));
567
- }
568
- function number(value, positive = false) {
569
- if (typeof value !== "number" || !Number.isFinite(value) || Math.abs(value) > 1e6 || positive && value < 0) throw new Error("Invalid annotation geometry.");
570
- return value;
571
- }
572
- /** Reconstruct at the boundary; discard extra fields and bound the entire JSON payload. */
573
- function parseDataAppAnnotationDraft(value) {
574
- const input = object(value);
575
- const target = object(input.target);
576
- const context = object(input.context);
577
- const viewport = object(context.viewport);
578
- const rect = object(context.rect);
579
- if (target.kind !== "widget" && target.kind !== "element" && target.kind !== "app") throw new Error("Invalid annotation target.");
580
- let screenshot;
581
- if (context.screenshot !== void 0) {
582
- const image = object(context.screenshot);
583
- const dataUrl = text(image.dataUrl, 35e4, true);
584
- if (image.mimeType !== "image/png" || !/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(dataUrl)) throw new Error("Invalid annotation screenshot.");
585
- const width = number(image.width, true);
586
- const height = number(image.height, true);
587
- if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 1024 || height > 1024) throw new Error("Invalid screenshot dimensions.");
588
- const encoded = dataUrl.slice(22);
589
- if (encoded.length % 4 !== 0 || encoded.length / 4 * 3 - (encoded.endsWith("==") ? 2 : encoded.endsWith("=") ? 1 : 0) > 262144) throw new Error("Screenshot is too large.");
590
- const header = atob(encoded.slice(0, 44));
591
- if (header.length < 24 || header.slice(12, 16) !== "IHDR") throw new Error("Invalid PNG header.");
592
- const bytes = Uint8Array.from(header, (character) => character.charCodeAt(0));
593
- const dimensions = new DataView(bytes.buffer);
594
- if (dimensions.getUint32(16) !== width || dimensions.getUint32(20) !== height) throw new Error("Screenshot dimensions do not match the image.");
595
- screenshot = {
596
- mimeType: "image/png",
597
- dataUrl,
598
- width,
599
- height
600
- };
601
- }
602
- let anchor;
603
- if (context.anchor !== void 0) {
604
- const point = object(context.anchor);
605
- const x = number(point.x, true);
606
- const y = number(point.y, true);
607
- if (x > 1 || y > 1) throw new Error("Invalid annotation anchor.");
608
- anchor = {
609
- x,
610
- y
611
- };
612
- }
613
- let cursor;
614
- if (context.cursor !== void 0) {
615
- const point = object(context.cursor);
616
- cursor = {
617
- x: number(point.x),
618
- y: number(point.y)
619
- };
620
- }
621
- let region;
622
- if (context.region !== void 0) {
623
- const area = object(context.region);
624
- region = {
625
- x: number(area.x, true),
626
- y: number(area.y, true),
627
- width: number(area.width, true),
628
- height: number(area.height, true)
629
- };
630
- if (target.kind !== "app" || region.width <= 0 || region.height <= 0 || region.x + region.width > 1.000001 || region.y + region.height > 1.000001) throw new Error("Invalid annotation selection.");
631
- }
632
- const draft = {
633
- id: text(input.id, 128, true),
634
- target: {
635
- id: text(target.id, 128, true),
636
- label: text(target.label, 256, true),
637
- kind: target.kind,
638
- text: text(target.text, 1024),
639
- queryNames: names(target.queryNames),
640
- glossaryIds: names(target.glossaryIds)
641
- },
642
- context: {
643
- ...anchor ? { anchor } : {},
644
- ...region ? { region } : {},
645
- ...cursor ? { cursor } : {},
646
- ...screenshot ? { screenshot } : {},
647
- search: text(context.search, 2048),
648
- hash: text(context.hash, 1024),
649
- viewport: {
650
- width: number(viewport.width, true),
651
- height: number(viewport.height, true)
652
- },
653
- rect: {
654
- x: number(rect.x),
655
- y: number(rect.y),
656
- width: number(rect.width, true),
657
- height: number(rect.height, true)
658
- },
659
- ...context.view === void 0 ? {} : { view: text(context.view, 128) },
660
- ...context.displayedInput === void 0 ? {} : { displayedInput: context.displayedInput }
661
- },
662
- comment: text(input.comment, 2e3, true).trim()
663
- };
664
- const json = JSON.stringify({
665
- ...draft,
666
- context: {
667
- ...draft.context,
668
- screenshot: void 0
669
- }
670
- });
671
- if (new TextEncoder().encode(json).byteLength > 12e3) throw new Error("Annotation is too large.");
672
- return JSON.parse(JSON.stringify(draft));
673
- }
674
- const annotationDraftRoute = /* @__PURE__ */ defineMessageRoute({
675
- input: parseDataAppAnnotationDraft,
676
- output(value) {
677
- if (value !== null) throw new Error("Invalid annotation response.");
678
- return null;
679
- }
680
- });
681
- const annotationEditorStateRoute = /* @__PURE__ */ defineMessageRoute({
682
- input(value) {
683
- const input = object(value);
684
- if (typeof input.hasUnsavedChanges !== "boolean") throw new Error("Invalid annotation editor state.");
685
- return { hasUnsavedChanges: input.hasUnsavedChanges };
686
- },
687
- output(value) {
688
- if (value !== null) throw new Error("Invalid annotation response.");
689
- return null;
690
- }
691
- });
692
- /** Request host-owned batch submission without transferring ownership of drafts. */
693
- const annotationSendRoute = /* @__PURE__ */ defineMessageRoute({
694
- input(value) {
695
- if (value !== null) throw new Error("Invalid annotation send request.");
696
- return null;
697
- },
698
- output(value) {
699
- if (value !== null) throw new Error("Invalid annotation response.");
700
- return null;
701
- }
702
- });
703
- const annotationUpdateRoute = /* @__PURE__ */ defineMessageRoute({
704
- input(value) {
705
- const input = object(value);
706
- return {
707
- id: text(input.id, 128, true),
708
- comment: text(input.comment, 2e3, true).trim()
709
- };
710
- },
711
- output(value) {
712
- if (value !== null) throw new Error("Invalid annotation response.");
713
- return null;
714
- }
715
- });
716
- /** A controlled shell acknowledges local exits (for example Escape). */
717
- const annotationModeRoute = /* @__PURE__ */ defineMessageRoute({
718
- input(value) {
719
- const input = object(value);
720
- if (typeof input.active !== "boolean") throw new Error("Invalid annotation mode.");
721
- return { active: input.active };
722
- },
723
- output(value) {
724
- if (value !== null) throw new Error("Invalid annotation response.");
725
- return null;
726
- }
727
- });
728
- function isAnnotationPresentation(value) {
729
- if (!value || typeof value !== "object") return false;
730
- const input = value;
731
- return typeof input.enabled === "boolean" && (input.active === void 0 || typeof input.active === "boolean") && (input.pinsVisible === void 0 || typeof input.pinsVisible === "boolean") && (input.showHint === void 0 || typeof input.showHint === "boolean") && (input.readOnly === void 0 || typeof input.readOnly === "boolean") && (input.selectedAnnotationId === void 0 || typeof input.selectedAnnotationId === "string" && input.selectedAnnotationId.length <= 128) && (input.dismissal === void 0 || input.dismissal !== null && typeof input.dismissal === "object" && typeof input.dismissal.id === "string" && input.dismissal.id.length <= 128 && typeof input.dismissal.occurredAt === "number" && Number.isFinite(input.dismissal.occurredAt)) && (input.selectionId === void 0 || typeof input.selectionId === "string" && input.selectionId.length <= 128) && (input.selectedTargetId === void 0 || typeof input.selectedTargetId === "string" && input.selectedTargetId.length <= 128) && (input.targets === void 0 || Array.isArray(input.targets) && input.targets.length <= 50 && input.targets.every((target) => target && typeof target.id === "string" && target.id.length <= 128 && typeof target.targetId === "string" && target.targetId.length <= 128 && Number.isSafeInteger(target.number) && target.number > 0 && (target.anchor === void 0 || typeof target.anchor.x === "number" && Number.isFinite(target.anchor.x) && target.anchor.x >= 0 && target.anchor.x <= 1 && typeof target.anchor.y === "number" && Number.isFinite(target.anchor.y) && target.anchor.y >= 0 && target.anchor.y <= 1) && (target.region === void 0 || typeof target.region === "object" && target.region !== null && [
732
- "x",
733
- "y",
734
- "width",
735
- "height"
736
- ].every((key) => {
737
- const value = target.region[key];
738
- return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
739
- }) && target.region.width > 0 && target.region.height > 0 && target.region.x + target.region.width <= 1.000001 && target.region.y + target.region.height <= 1.000001) && (target.comment === void 0 || typeof target.comment === "string" && target.comment.length <= 2e3)));
740
- }
741
- //#endregion
742
- //#region src/core/external-link.ts
743
- /** Absolute HTTPS destinations only; URLs must not contain embedded credentials. */
744
- function parseExternalUrl(value) {
745
- if (typeof value !== "string" || value.length > 8192 || /[\s\\\p{Cc}\p{Cf}]/u.test(value)) throw new Error("Expected an absolute HTTPS URL.");
746
- const url = new URL(value);
747
- if (!/^https:\/\//i.test(value) || url.protocol !== "https:" || url.username || url.password) throw new Error("Expected an HTTPS URL without credentials.");
748
- return url.href;
749
- }
750
- /** Shift takes precedence over Ctrl/Cmd; an unmodified event requests no navigation. */
751
- function resolveExternalLinkTarget(input) {
752
- if (input.target !== "event") return input.target ?? "tab";
753
- return input.keys.shiftKey ? "window" : input.keys.metaKey || input.keys.ctrlKey ? "tab" : null;
754
- }
755
- /** Opt-in host route. Validation does not replace the host's destination policy. */
756
- const openExternalLinkRoute = /* @__PURE__ */ defineMessageRoute({
757
- input(value) {
758
- if (!value || typeof value !== "object") throw new Error("Invalid external link.");
759
- const input = value;
760
- const url = parseExternalUrl(input.url);
761
- if (input.target === void 0) return { url };
762
- if (input.target === "tab" || input.target === "window") return {
763
- url,
764
- target: input.target
765
- };
766
- if (input.target === "event" && input.keys && typeof input.keys === "object") {
767
- const keys = input.keys;
768
- if (typeof keys.shiftKey === "boolean" && typeof keys.metaKey === "boolean" && typeof keys.ctrlKey === "boolean") return {
769
- url,
770
- target: "event",
771
- keys: {
772
- shiftKey: keys.shiftKey,
773
- metaKey: keys.metaKey,
774
- ctrlKey: keys.ctrlKey
775
- }
776
- };
777
- }
778
- throw new Error("Invalid external navigation target.");
779
- },
780
- output(value) {
781
- if (value !== "opened" && value !== "cancelled" && value !== "ignored") throw new Error("Invalid external link response.");
782
- return value;
783
- }
784
- });
785
- //#endregion
786
- //#region src/core/contract.ts
787
- const sourceErrorBrand = Symbol.for("@altertable/data-app/DataSourceError");
788
- var DataSourceError = class extends Error {
789
- reason;
790
- status;
791
- [sourceErrorBrand] = true;
792
- queryName;
793
- static [Symbol.hasInstance](value) {
794
- return value instanceof Error && value[sourceErrorBrand] === true;
795
- }
796
- constructor(reason, status, options) {
797
- super(`Data source ${reason}${status ? ` (${status})` : ""}.`, options);
798
- this.reason = reason;
799
- this.status = status;
800
- this.name = "DataSourceError";
801
- }
802
- };
803
- //#endregion
804
- export { facetSource as C, parseBooleanSelection as D, numberOperatorLabels as E, parseNumberSelection as O, facetFilter as S, numberFilter as T, navigationUpdateRoute as _, annotationDraftRoute as a, dateTimeRangeFilter as b, annotationSendRoute as c, parseDataAppAnnotationDraft as d, MessageRoutingError as f, defineMessageRoute as g, defineDataQueryRoute as h, resolveExternalLinkTarget as i, annotationUpdateRoute as l, dataAppRoutes as m, openExternalLinkRoute as n, annotationEditorStateRoute as o, createMessageRouter as p, parseExternalUrl as r, annotationModeRoute as s, DataSourceError as t, isAnnotationPresentation as u, sqlQueryRoute as v, booleanFilter as w, dateTimeRangePresets as x, validLocation as y };
805
-
806
- //# sourceMappingURL=contract-VhY9V9wd.js.map