@altertable/data-app 0.76.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.
- package/CONTRIBUTING.md +3 -0
- package/REFERENCE.md +392 -276
- package/dist/chunks/contract-gu1rDsV0.js +1588 -0
- package/dist/chunks/contract-gu1rDsV0.js.map +1 -0
- package/dist/chunks/data-client-BMdL73Ab.js +122 -0
- package/dist/chunks/data-client-BMdL73Ab.js.map +1 -0
- package/dist/chunks/{date-time-range-value-TE8KCsfV.js → date-time-range-value-D-XfqVTT.js} +28 -31
- package/dist/chunks/date-time-range-value-D-XfqVTT.js.map +1 -0
- package/dist/chunks/{diagnostics-DhCqGklq.js → diagnostics-CX9SsU79.js} +240 -63
- package/dist/chunks/diagnostics-CX9SsU79.js.map +1 -0
- package/dist/chunks/record-Cr4Uk1K3.js +9 -0
- package/dist/chunks/record-Cr4Uk1K3.js.map +1 -0
- package/dist/client/index.js +4 -86
- package/dist/client/index.js.map +1 -1
- package/dist/core/appearance.js +3 -5
- package/dist/core/appearance.js.map +1 -1
- package/dist/core/config.js +11 -3
- package/dist/core/config.js.map +1 -1
- package/dist/core/contract.js +3 -4
- package/dist/core/format.js +1 -1
- package/dist/internal.js +58 -124
- package/dist/internal.js.map +1 -1
- package/dist/types/chunks/contract.d.ts +592 -308
- package/dist/types/chunks/data-client.d.ts +46 -0
- package/dist/types/chunks/date-time-range-value.d.ts +28 -2
- package/dist/types/chunks/index.d.ts +65 -53
- package/dist/types/client/index.d.ts +4 -3
- package/dist/types/core/config.d.ts +16 -6
- package/dist/types/core/contract.d.ts +3 -5
- package/dist/types/core/format.d.ts +1 -2
- package/dist/types/index.d.ts +4 -4
- package/dist/types/internal.d.ts +26 -7
- package/docs/app-authoring.md +23 -14
- package/docs/client.md +14 -48
- package/docs/contract.md +58 -56
- package/docs/data-context.md +13 -6
- package/docs/diagnostics.md +16 -23
- package/docs/embed.md +60 -25
- package/docs/filters.md +271 -0
- package/docs/hosted-apps.md +11 -10
- package/docs/layout.md +45 -18
- package/docs/local-data-apps.md +5 -6
- package/docs/react-embed.md +44 -2
- package/docs/react.md +1 -2
- package/docs/server-bun.md +8 -5
- package/docs/stories-and-export.md +23 -14
- package/docs/styling.md +2 -1
- package/docs/ui.md +18 -8
- package/docs/views.md +63 -26
- package/docs/widgets.md +40 -16
- package/docs/worker.md +1 -1
- package/package.json +1 -5
- package/dist/chunks/contract-DsyRYgN_.js +0 -626
- package/dist/chunks/contract-DsyRYgN_.js.map +0 -1
- package/dist/chunks/contract-kNFYPHRK.js +0 -713
- package/dist/chunks/contract-kNFYPHRK.js.map +0 -1
- package/dist/chunks/date-time-range-value-TE8KCsfV.js.map +0 -1
- package/dist/chunks/diagnostics-DhCqGklq.js.map +0 -1
- package/dist/chunks/operation-7tiT4cpJ.js +0 -134
- package/dist/chunks/operation-7tiT4cpJ.js.map +0 -1
- package/dist/chunks/request-body-H1qPmmTN.js +0 -50
- package/dist/chunks/request-body-H1qPmmTN.js.map +0 -1
- package/dist/server/index.js +0 -90
- package/dist/server/index.js.map +0 -1
- package/dist/types/chunks/contract2.d.ts +0 -207
- package/dist/types/chunks/date-time-range.d.ts +0 -29
- package/dist/types/server/index.d.ts +0 -17
- package/docs/server.md +0 -41
- package/docs/variables.md +0 -280
|
@@ -0,0 +1,1588 @@
|
|
|
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-D-XfqVTT.js";
|
|
2
|
+
import { t as isRecord } from "./record-Cr4Uk1K3.js";
|
|
3
|
+
import { fromDate, parseDate, toCalendarDateTime, today } from "@internationalized/date";
|
|
4
|
+
//#region src/core/keys.ts
|
|
5
|
+
/** Separator for opaque composite keys, independent of URL and DOM ID formats. */
|
|
6
|
+
const KEY_SEPARATOR = ":";
|
|
7
|
+
//#endregion
|
|
8
|
+
//#region src/core/dimension.ts
|
|
9
|
+
const allSelection = { kind: "all" };
|
|
10
|
+
/** Selections are equal when they keep the same members, in any order. */
|
|
11
|
+
function selectionKey(value) {
|
|
12
|
+
return value.kind === "all" ? "all" : [value.kind, ...value.members.map(dimensionMemberKey).sort()].join(":");
|
|
13
|
+
}
|
|
14
|
+
function dimensionMemberKey(member) {
|
|
15
|
+
return member.kind === "missing" ? "missing" : [
|
|
16
|
+
"value",
|
|
17
|
+
typeof member.value,
|
|
18
|
+
member.value
|
|
19
|
+
].join(":");
|
|
20
|
+
}
|
|
21
|
+
function dimensionFilter(config) {
|
|
22
|
+
return {
|
|
23
|
+
...createDimensionFilter(config),
|
|
24
|
+
optionsSource: "fixed"
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
/** Shared fixed-option and query-backed selection behavior. */
|
|
28
|
+
function createDimensionFilter(config, dynamic = false) {
|
|
29
|
+
const { key, label, selectionMode, valueType } = config;
|
|
30
|
+
const options = config.options ?? [];
|
|
31
|
+
const optionKeys = options.map((option) => dimensionMemberKey({
|
|
32
|
+
kind: "value",
|
|
33
|
+
value: option.value
|
|
34
|
+
}));
|
|
35
|
+
invariant(!!key && options.length <= 200 && new Set(optionKeys).size === options.length, "Dimension options need a key, at most 200 distinct values.");
|
|
36
|
+
invariant(options.every((option) => typeof option.value === valueType && !!option.label.trim() && (option.count === void 0 || Number.isSafeInteger(option.count) && option.count >= 0)), "Dimension options need typed values, labels, and nonnegative counts.");
|
|
37
|
+
const allowed = new Set(optionKeys);
|
|
38
|
+
const maxSelected = config.maxSelected ?? (selectionMode === "single" ? 1 : 20);
|
|
39
|
+
invariant(Number.isInteger(maxSelected) && maxSelected >= 1 && maxSelected <= 50 && (selectionMode !== "single" || maxSelected === 1), "Dimension selection limit is invalid.");
|
|
40
|
+
const allowMissing = config.allowMissing ?? false;
|
|
41
|
+
const defaultValue = config.defaultValue ?? allSelection;
|
|
42
|
+
function validMember(member) {
|
|
43
|
+
if (!member || typeof member !== "object") return false;
|
|
44
|
+
if (member.kind === "missing") return allowMissing;
|
|
45
|
+
if (member.kind !== "value" || typeof member.value !== valueType) return false;
|
|
46
|
+
if (!dynamic) return allowed.has(dimensionMemberKey(member));
|
|
47
|
+
return typeof member.value === "number" ? Number.isFinite(member.value) : member.value.length <= 100;
|
|
48
|
+
}
|
|
49
|
+
function valid(value) {
|
|
50
|
+
if (!value || typeof value !== "object") return false;
|
|
51
|
+
if (value.kind === "all") return true;
|
|
52
|
+
if (value.kind !== "include" && !(config.allowExclusion && value.kind === "exclude") || !Array.isArray(value.members) || !value.members.length || value.members.length > maxSelected) return false;
|
|
53
|
+
if (!value.members.every(validMember)) return false;
|
|
54
|
+
const ids = value.members.map(dimensionMemberKey);
|
|
55
|
+
return new Set(ids).size === ids.length;
|
|
56
|
+
}
|
|
57
|
+
invariant(valid(defaultValue), `Invalid default selection for ${label}.`);
|
|
58
|
+
/** The default selection has no URL value; every member is explicit when it differs. */
|
|
59
|
+
function encode(value) {
|
|
60
|
+
if (same(value, defaultValue)) return null;
|
|
61
|
+
return value.kind === "all" ? JSON.stringify({ kind: "all" }) : JSON.stringify({
|
|
62
|
+
kind: value.kind,
|
|
63
|
+
members: value.members.map((member) => member.kind === "missing" ? ["m"] : ["v", member.value])
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
function same(left, right) {
|
|
67
|
+
return selectionKey(left) === selectionKey(right);
|
|
68
|
+
}
|
|
69
|
+
function parse(raw) {
|
|
70
|
+
if (raw === null) return defaultValue;
|
|
71
|
+
if (raw.length > 4096) return defaultValue;
|
|
72
|
+
try {
|
|
73
|
+
const parsed = JSON.parse(raw);
|
|
74
|
+
const tokens = Array.isArray(parsed) ? {
|
|
75
|
+
kind: "include",
|
|
76
|
+
members: parsed
|
|
77
|
+
} : parsed;
|
|
78
|
+
if (tokens?.kind === "all") return allSelection;
|
|
79
|
+
if (!tokens || !Array.isArray(tokens.members)) return defaultValue;
|
|
80
|
+
const value = {
|
|
81
|
+
kind: tokens.kind,
|
|
82
|
+
members: tokens.members.map((token) => Array.isArray(token) && token.length === 1 && token[0] === "m" ? { kind: "missing" } : Array.isArray(token) && token.length === 2 && token[0] === "v" ? {
|
|
83
|
+
kind: "value",
|
|
84
|
+
value: token[1]
|
|
85
|
+
} : { kind: "invalid" })
|
|
86
|
+
};
|
|
87
|
+
return valid(value) ? value : defaultValue;
|
|
88
|
+
} catch {
|
|
89
|
+
return defaultValue;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
kind: "dimension",
|
|
94
|
+
optionsSource: dynamic ? "query" : "fixed",
|
|
95
|
+
presentation: config.presentation,
|
|
96
|
+
label,
|
|
97
|
+
valueType,
|
|
98
|
+
selectionMode,
|
|
99
|
+
options,
|
|
100
|
+
allowMissing,
|
|
101
|
+
allowExclusion: config.allowExclusion ?? false,
|
|
102
|
+
maxSelected,
|
|
103
|
+
urlKeys: [key],
|
|
104
|
+
defaultValue,
|
|
105
|
+
clearValue: allSelection,
|
|
106
|
+
history: config.history ?? "push",
|
|
107
|
+
valid,
|
|
108
|
+
same,
|
|
109
|
+
read(params) {
|
|
110
|
+
return parse(params.get(key));
|
|
111
|
+
},
|
|
112
|
+
write(value) {
|
|
113
|
+
return { [key]: encode(value) };
|
|
114
|
+
},
|
|
115
|
+
describe(value, suppliedOptions = options) {
|
|
116
|
+
return value.kind === "all" ? `All ${label.toLocaleLowerCase()}` : `${value.kind === "exclude" ? "Exclude: " : ""}${value.members.map((member) => member.kind === "missing" ? "Missing" : suppliedOptions.find((option) => option.value === member.value)?.label ?? String(member.value)).join(", ")}`;
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
/** Server-side parser; call from the operation input parser before building SQL. */
|
|
121
|
+
function parseDimensionSelection(value, filter) {
|
|
122
|
+
invariant(filter.valid(value), `Invalid ${filter.label} selection.`);
|
|
123
|
+
return value;
|
|
124
|
+
}
|
|
125
|
+
/** Validate bounded facet results before showing them in a picker. */
|
|
126
|
+
function parseFacetOptions(value, filter) {
|
|
127
|
+
invariant(Array.isArray(value) && value.length <= 200, "Facet options exceed their bound.");
|
|
128
|
+
const options = [];
|
|
129
|
+
const seen = /* @__PURE__ */ new Set();
|
|
130
|
+
for (const item of value) {
|
|
131
|
+
invariant(isRecord(item), "Invalid facet option.");
|
|
132
|
+
const option = item;
|
|
133
|
+
invariant(typeof option.value === filter.valueType && filter.valid({
|
|
134
|
+
kind: "include",
|
|
135
|
+
members: [{
|
|
136
|
+
kind: "value",
|
|
137
|
+
value: option.value
|
|
138
|
+
}]
|
|
139
|
+
}) && typeof option.label === "string" && !!option.label.trim() && option.label.length <= 100 && (option.count === void 0 || Number.isSafeInteger(option.count) && option.count >= 0), "Invalid facet option.");
|
|
140
|
+
const id = dimensionMemberKey({
|
|
141
|
+
kind: "value",
|
|
142
|
+
value: option.value
|
|
143
|
+
});
|
|
144
|
+
invariant(!seen.has(id), "Duplicate facet option.");
|
|
145
|
+
seen.add(id);
|
|
146
|
+
options.push(option);
|
|
147
|
+
}
|
|
148
|
+
return options;
|
|
149
|
+
}
|
|
150
|
+
/** Central SQL literal encoding for transports without bound parameters. Column is an allowlisted identifier. */
|
|
151
|
+
function dimensionPredicate(column, selection, allowedColumns) {
|
|
152
|
+
invariant(allowedColumns.includes(column) && /^[A-Za-z_][A-Za-z_0-9]*(?:\.[A-Za-z_][A-Za-z_0-9]*)*$/.test(column), "Invalid dimension column.");
|
|
153
|
+
if (selection.kind === "all") return "";
|
|
154
|
+
invariant(selection.members.length > 0, "Empty dimension inclusion is invalid.");
|
|
155
|
+
const values = selection.members.filter((member) => member.kind === "value");
|
|
156
|
+
const missing = selection.members.some((member) => member.kind === "missing");
|
|
157
|
+
const literals = values.map(({ value }) => {
|
|
158
|
+
if (typeof value === "number") {
|
|
159
|
+
invariant(Number.isFinite(value), "Invalid numeric dimension value.");
|
|
160
|
+
return String(value);
|
|
161
|
+
}
|
|
162
|
+
const text = value;
|
|
163
|
+
for (let index = 0; index < text.length; index++) invariant(text.charCodeAt(index) >= 32 && text.charCodeAt(index) !== 127, "Invalid control character in dimension value.");
|
|
164
|
+
return `'${text.replaceAll("'", "''")}'`;
|
|
165
|
+
});
|
|
166
|
+
const predicate = `(${[...literals.length ? [`${column} IN (${literals.join(", ")})`] : [], ...missing ? [`${column} IS NULL`] : []].join(" OR ")})`;
|
|
167
|
+
return selection.kind === "exclude" ? missing ? `NOT ${predicate}` : `(${column} IS NULL OR NOT ${predicate})` : predicate;
|
|
168
|
+
}
|
|
169
|
+
//#endregion
|
|
170
|
+
//#region src/core/parameter-sql.ts
|
|
171
|
+
/** Find SDK-only parameter syntax in SQL code, ignoring strings and comments. */
|
|
172
|
+
function unsupportedParameterReference(statement) {
|
|
173
|
+
const token = /[eE]'(?:\\.|''|[^'\\])*'|'(?:''|[^'])*'|"(?:""|[^"])*"|\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$|--[^\n]*(?:\n|$)|\/\*|\$([A-Za-z_][A-Za-z0-9_]*)(?:\.(from|to)\b|\.matches\(\s*([A-Za-z_][A-Za-z0-9_]*(?:\.[A-Za-z_][A-Za-z0-9_]*)*)\s*\))?/g;
|
|
174
|
+
for (let match = token.exec(statement); match; match = token.exec(statement)) {
|
|
175
|
+
const text = match[0];
|
|
176
|
+
if (text === "/*") {
|
|
177
|
+
let depth = 1;
|
|
178
|
+
let end = token.lastIndex;
|
|
179
|
+
while (depth && end < statement.length) if (statement.slice(end, end + 2) === "/*") {
|
|
180
|
+
depth++;
|
|
181
|
+
end += 2;
|
|
182
|
+
} else if (statement.slice(end, end + 2) === "*/") {
|
|
183
|
+
depth--;
|
|
184
|
+
end += 2;
|
|
185
|
+
} else end++;
|
|
186
|
+
token.lastIndex = end;
|
|
187
|
+
} else if (/^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$$/.test(text)) {
|
|
188
|
+
const closing = statement.indexOf(text, token.lastIndex);
|
|
189
|
+
token.lastIndex = closing < 0 ? statement.length : closing + text.length;
|
|
190
|
+
} else if (match[1] && (match[2] || match[3])) return text;
|
|
191
|
+
}
|
|
192
|
+
return null;
|
|
193
|
+
}
|
|
194
|
+
//#endregion
|
|
195
|
+
//#region src/core/queries.ts
|
|
196
|
+
const MAX_QUERY_ROWS = 1e4;
|
|
197
|
+
const REGISTERED_QUERY_ID_PATTERN = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
|
|
198
|
+
const QUERY_CAST_ERROR = "##ERROR##";
|
|
199
|
+
/** Bind a selection as JSON the expanded predicate reads: kind, listed values, and
|
|
200
|
+
* whether missing values are listed. */
|
|
201
|
+
function serializeSelection(key, valueType, value) {
|
|
202
|
+
const selection = typeof value === "string" ? JSON.parse(value) : value;
|
|
203
|
+
if (!(isRecord(selection) && (selection.kind === "all" || (selection.kind === "include" || selection.kind === "exclude") && Array.isArray(selection.members) && selection.members.length > 0 && selection.members.every((member) => member?.kind === "missing" || member?.kind === "value" && (valueType === "number" ? typeof member.value === "number" && Number.isFinite(member.value) : typeof member.value === "string"))))) throw new Error(`Parameter ${key} is not a ${valueType} dimension selection.`);
|
|
204
|
+
if (selection.kind === "all") return JSON.stringify({ kind: "all" });
|
|
205
|
+
return JSON.stringify({
|
|
206
|
+
kind: selection.kind,
|
|
207
|
+
values: selection.members.flatMap((member) => member.kind === "value" ? [member.value] : []),
|
|
208
|
+
missing: selection.members.some((member) => member.kind === "missing")
|
|
209
|
+
});
|
|
210
|
+
}
|
|
211
|
+
function isQueryParameterValue(value) {
|
|
212
|
+
return value === null || typeof value === "string" || typeof value === "boolean" || typeof value === "number" && Number.isFinite(value);
|
|
213
|
+
}
|
|
214
|
+
function isQueryParameters(value) {
|
|
215
|
+
return isRecord(value) && Object.values(value).every(isQueryParameterValue);
|
|
216
|
+
}
|
|
217
|
+
function snapshotField(field) {
|
|
218
|
+
invariant(isRecord(field) && (field.type === "string" || field.type === "number" || field.type === "boolean" || field.type === "null") && (field.nullable === void 0 || typeof field.nullable === "boolean"), "Query fields need a supported type and a boolean nullable flag.");
|
|
219
|
+
return Object.freeze({ ...field });
|
|
220
|
+
}
|
|
221
|
+
/** Snapshot the query's SQL, parameter defaults, and decoded result contract. */
|
|
222
|
+
function snapshotQueries(definitions) {
|
|
223
|
+
return Object.freeze(Object.fromEntries(Object.entries(definitions).map(([name, query]) => {
|
|
224
|
+
invariant(REGISTERED_QUERY_ID_PATTERN.test(name), `Invalid query name ${name}. Use 1–64 letters, digits, underscores, or hyphens, starting with a letter or digit.`);
|
|
225
|
+
invariant(!!query.statement.trim(), "Queries need a SQL statement.");
|
|
226
|
+
const unsupported = unsupportedParameterReference(query.statement);
|
|
227
|
+
invariant(!unsupported, `Query ${name} uses SDK-only SQL syntax ${unsupported}. Write DuckDB SQL with bound parameters instead.`);
|
|
228
|
+
const params = Object.freeze(Object.fromEntries(Object.entries(query.params).map(([key, declaration]) => {
|
|
229
|
+
if (declaration.type === "dateTimeRange" || declaration.type === "dimension") invariant(/^[A-Za-z_][A-Za-z0-9_]*$/.test(key) && declaration.nullable !== true, "Range and dimension parameters require a SQL parameter name and cannot be nullable.");
|
|
230
|
+
if (declaration.type === "dimension") {
|
|
231
|
+
invariant((declaration.valueType === "string" || declaration.valueType === "number") && !Object.hasOwn(declaration, "defaultValue"), `Dimension parameter ${key} in query ${name} needs a string or number valueType and no default.`);
|
|
232
|
+
return [key, Object.freeze({ ...declaration })];
|
|
233
|
+
}
|
|
234
|
+
invariant(!Object.hasOwn(declaration, "defaultValue") || (declaration.type === "dateTimeRange" ? !!parseDateTimeRange(declaration.defaultValue) : isQueryParameterValue(declaration.defaultValue)), `Invalid default for parameter ${key} in query ${name}.`);
|
|
235
|
+
return [key, declaration.type === "dateTimeRange" ? Object.freeze({
|
|
236
|
+
...declaration,
|
|
237
|
+
...declaration.defaultValue === void 0 ? {} : { defaultValue: parseDateTimeRange(declaration.defaultValue) }
|
|
238
|
+
}) : snapshotField(declaration)];
|
|
239
|
+
})));
|
|
240
|
+
const projectionEntries = Object.entries(query.projections);
|
|
241
|
+
invariant(projectionEntries.length > 0 && projectionEntries.every(([alias]) => !!alias.trim()), "Queries need at least one named projection.");
|
|
242
|
+
return [name, Object.freeze({
|
|
243
|
+
statement: query.statement,
|
|
244
|
+
params,
|
|
245
|
+
projections: Object.freeze(Object.fromEntries(projectionEntries.map(([alias, field]) => [alias, snapshotField(field)])))
|
|
246
|
+
})];
|
|
247
|
+
})));
|
|
248
|
+
}
|
|
249
|
+
/** Decode each returned cell once, matching aliases independently of result order. */
|
|
250
|
+
function decodeQueryResult(result, projections) {
|
|
251
|
+
if (!result || !Array.isArray(result.columns) || !Array.isArray(result.rows) || result.queryId !== void 0 && typeof result.queryId !== "string") throw new Error("Query result must contain columns and rows.");
|
|
252
|
+
const returnedColumns = Array.from(result.columns, (column) => {
|
|
253
|
+
if (!column || typeof column !== "object" || Array.isArray(column) || typeof column.name !== "string" || column.type !== void 0 && typeof column.type !== "string") throw new Error("Query result columns must have names and optional type strings.");
|
|
254
|
+
return {
|
|
255
|
+
name: column.name,
|
|
256
|
+
...column.type === void 0 ? {} : { type: column.type }
|
|
257
|
+
};
|
|
258
|
+
});
|
|
259
|
+
const names = returnedColumns.map((column) => column.name);
|
|
260
|
+
return {
|
|
261
|
+
columns: returnedColumns,
|
|
262
|
+
rows: Array.from(result.rows, (row) => {
|
|
263
|
+
if (!Array.isArray(row) || row.length !== names.length) throw new Error("Query result row has the wrong width.");
|
|
264
|
+
return Object.fromEntries(names.map((name, index) => [name, castQueryCell(row[index], projections[name])]));
|
|
265
|
+
}),
|
|
266
|
+
...result.queryId === void 0 ? {} : { queryId: result.queryId }
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
function castQueryCell(value, field) {
|
|
270
|
+
if (field === void 0) {
|
|
271
|
+
if (typeof value === "string" || typeof value === "boolean" || typeof value === "number") return value;
|
|
272
|
+
if (value === null) return null;
|
|
273
|
+
return JSON.stringify(value);
|
|
274
|
+
}
|
|
275
|
+
if (value === null && field.nullable !== false) return null;
|
|
276
|
+
switch (field.type) {
|
|
277
|
+
case "string": return String(value);
|
|
278
|
+
case "number": {
|
|
279
|
+
const number = Number(value);
|
|
280
|
+
return Number.isFinite(number) ? number : QUERY_CAST_ERROR;
|
|
281
|
+
}
|
|
282
|
+
case "boolean": return Boolean(value);
|
|
283
|
+
case "null": return null;
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
/** Host context supplies protected values; callers and defaults fill the remaining parameters. */
|
|
287
|
+
function resolveQueryParameters(declarations, values, context) {
|
|
288
|
+
if (!values || typeof values !== "object" || Array.isArray(values)) throw new Error("Supply query parameter values as an object.");
|
|
289
|
+
for (const key of Object.keys(values)) {
|
|
290
|
+
if (!Object.hasOwn(declarations, key)) throw new Error(`Unknown parameter ${key}.`);
|
|
291
|
+
if (Object.hasOwn(context, key)) throw new Error(`Cannot override context parameter ${key}.`);
|
|
292
|
+
}
|
|
293
|
+
return Object.fromEntries(Object.entries(declarations).map(([key, declaration]) => {
|
|
294
|
+
const value = Object.hasOwn(context, key) ? context[key] : Object.hasOwn(values, key) && values[key] !== void 0 ? values[key] : declaration.defaultValue;
|
|
295
|
+
if (value === void 0) throw new Error(`Missing parameter ${key}.`);
|
|
296
|
+
if (declaration.type === "dimension") return [key, serializeSelection(key, declaration.valueType, value)];
|
|
297
|
+
if (declaration.type === "dateTimeRange") return [key, serializeDateTimeRange(parseDateTimeRange(typeof value === "string" ? JSON.parse(value) : value))];
|
|
298
|
+
const nullable = declaration.type === "null" || declaration.nullable === true;
|
|
299
|
+
if (!(value === null ? nullable : typeof value === declaration.type && isQueryParameterValue(value))) throw new Error(`Parameter ${key} does not match ${declaration.type}.`);
|
|
300
|
+
return [key, value];
|
|
301
|
+
}));
|
|
302
|
+
}
|
|
303
|
+
//#endregion
|
|
304
|
+
//#region src/core/dimension-source.ts
|
|
305
|
+
const dimensionSource = Symbol("data-app.dimensionSource");
|
|
306
|
+
const sources = /* @__PURE__ */ new WeakMap();
|
|
307
|
+
const selectorsKey = Symbol.for("@altertable/data-app/dimension-selectors");
|
|
308
|
+
const ownerKey = Symbol.for("@altertable/data-app/dimension-selector-owner");
|
|
309
|
+
const invalidMemberKey = Symbol.for("@altertable/data-app/dimension-member-error");
|
|
310
|
+
var DimensionMembershipError = class extends Error {
|
|
311
|
+
[invalidMemberKey] = true;
|
|
312
|
+
static [Symbol.hasInstance](value) {
|
|
313
|
+
return value instanceof Error && value[invalidMemberKey] === true;
|
|
314
|
+
}
|
|
315
|
+
};
|
|
316
|
+
/** A query supplies independent options and exact member lookup; it declares a nullable `member` parameter. */
|
|
317
|
+
function bindDimensionSource(config, queries) {
|
|
318
|
+
invariant(!config.allowMissing, "Source dimensions require concrete members.");
|
|
319
|
+
const query = queries[config.source.query];
|
|
320
|
+
invariant(query && Object.hasOwn(query.params, "member"), "Dimension sources must declare member.");
|
|
321
|
+
const member = query.params.member;
|
|
322
|
+
const { value, label, count } = query.projections;
|
|
323
|
+
invariant(member.type === config.valueType && member.nullable === true && value?.type === config.valueType && value.nullable !== true && label?.type === "string" && label.nullable !== true && (!count || count.type === "number" && count.nullable !== true), "Dimension sources require a matching nullable member and concrete value, label, and count projections.");
|
|
324
|
+
const operation = `__dimension:${config.key}`;
|
|
325
|
+
const filter = Object.assign(createDimensionFilter({
|
|
326
|
+
...config,
|
|
327
|
+
valueType: config.valueType,
|
|
328
|
+
options: []
|
|
329
|
+
}, true), {
|
|
330
|
+
optionsSource: "query",
|
|
331
|
+
[dimensionSource]: Object.freeze({ operation })
|
|
332
|
+
});
|
|
333
|
+
sources.set(filter, {
|
|
334
|
+
query: config.source.query,
|
|
335
|
+
queries
|
|
336
|
+
});
|
|
337
|
+
return filter;
|
|
338
|
+
}
|
|
339
|
+
async function loadOptions(filter, member, query) {
|
|
340
|
+
const result = await query(sources.get(filter).query, { member }, { limit: member === null ? 200 : 2 });
|
|
341
|
+
const names = result.columns.map((column) => column.name);
|
|
342
|
+
invariant(new Set(names).size === names.length && names.includes("value") && names.includes("label"), "Dimension source must return value and label.");
|
|
343
|
+
const options = parseFacetOptions(result.rows, filter);
|
|
344
|
+
if (member !== null && (options.length !== 1 || options[0].value !== member)) throw new DimensionMembershipError(`Invalid ${filter.label} member.`);
|
|
345
|
+
return options;
|
|
346
|
+
}
|
|
347
|
+
/** Source dimension selections must name members the source query returns. */
|
|
348
|
+
async function validateSourceMembers(filters, input, query) {
|
|
349
|
+
for (const [name, filter] of Object.entries(filters)) {
|
|
350
|
+
if (filter.kind !== "dimension" || !sources.has(filter)) continue;
|
|
351
|
+
const selection = input[name];
|
|
352
|
+
if (selection.kind === "all") continue;
|
|
353
|
+
for (const member of selection.members) if (member.kind === "value") await loadOptions(filter, member.value, query);
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
function attachDimensionSelectors(operation, queries) {
|
|
357
|
+
const selectors = {};
|
|
358
|
+
for (const filter of Object.values(operation.filters ?? {})) {
|
|
359
|
+
if (filter.kind !== "dimension" || !(dimensionSource in filter)) continue;
|
|
360
|
+
const source = sources.get(filter);
|
|
361
|
+
if (!source) continue;
|
|
362
|
+
invariant(JSON.stringify(source.queries[source.query]) === JSON.stringify(queries[source.query]), "Dimension sources must belong to the operation query registry.");
|
|
363
|
+
const name = filter[dimensionSource].operation;
|
|
364
|
+
invariant(!selectors[name] || selectors[name][ownerKey] === filter, "Dimension source keys must be unique across the app.");
|
|
365
|
+
selectors[name] = {
|
|
366
|
+
input(value) {
|
|
367
|
+
invariant(isRecord(value), "Invalid dimension request.");
|
|
368
|
+
const member = value.member;
|
|
369
|
+
invariant(member === null || filter.valid({
|
|
370
|
+
kind: "include",
|
|
371
|
+
members: [{
|
|
372
|
+
kind: "value",
|
|
373
|
+
value: member
|
|
374
|
+
}]
|
|
375
|
+
}), "Invalid requested member.");
|
|
376
|
+
return { member };
|
|
377
|
+
},
|
|
378
|
+
checks: [{ member: null }],
|
|
379
|
+
policy: {
|
|
380
|
+
maxDurationMs: 15e3,
|
|
381
|
+
maxQueryRows: 200,
|
|
382
|
+
maxResponseBytes: 1e6
|
|
383
|
+
},
|
|
384
|
+
queryNames: { [source.query]: source.query },
|
|
385
|
+
async run(context, input) {
|
|
386
|
+
return loadOptions(filter, input.member, async (name, params, options) => {
|
|
387
|
+
const definition = queries[name];
|
|
388
|
+
return decodeQueryResult(await context.lakehouse.queryAll(definition.statement, {
|
|
389
|
+
name,
|
|
390
|
+
params: resolveQueryParameters(definition.params, params, context.queryParams ?? {}),
|
|
391
|
+
limit: options.limit,
|
|
392
|
+
signal: context.signal
|
|
393
|
+
}), definition.projections);
|
|
394
|
+
});
|
|
395
|
+
}
|
|
396
|
+
};
|
|
397
|
+
Object.defineProperty(selectors[name], ownerKey, { value: filter });
|
|
398
|
+
}
|
|
399
|
+
Object.defineProperty(operation, selectorsKey, { value: selectors });
|
|
400
|
+
}
|
|
401
|
+
function withDimensionSelectors(operations) {
|
|
402
|
+
const expanded = { ...operations };
|
|
403
|
+
for (const operation of Object.values(operations)) for (const [name, selector] of Object.entries(operation[selectorsKey] ?? {})) {
|
|
404
|
+
invariant(!Object.hasOwn(operations, name), "Reserved dimension operation name.");
|
|
405
|
+
invariant(!expanded[name] || expanded[name][ownerKey] === selector[ownerKey], "Dimension source keys must be unique across the app.");
|
|
406
|
+
expanded[name] ??= selector;
|
|
407
|
+
}
|
|
408
|
+
return expanded;
|
|
409
|
+
}
|
|
410
|
+
//#endregion
|
|
411
|
+
//#region src/core/app-filters.ts
|
|
412
|
+
/** Name filters once in the app. URL keys must be unique across its controls. */
|
|
413
|
+
function defineAppFilters(filters) {
|
|
414
|
+
const owners = /* @__PURE__ */ new Map();
|
|
415
|
+
for (const [name, filter] of Object.entries(filters)) {
|
|
416
|
+
const presentation = filter.presentation;
|
|
417
|
+
invariant(presentation === void 0 || isRecord(presentation) && (presentation.control === void 0 || presentation.control === "toolbar" || presentation.control === "widget") && (presentation.group === void 0 || presentation.group === "scope" || presentation.group === "display") && (presentation.prominence === void 0 || presentation.prominence === "primary" || presentation.prominence === "secondary"), `Filter ${name} has invalid presentation.`);
|
|
418
|
+
for (const key of filter.urlKeys) {
|
|
419
|
+
invariant(![
|
|
420
|
+
"view",
|
|
421
|
+
"about",
|
|
422
|
+
"tab",
|
|
423
|
+
"present",
|
|
424
|
+
"step",
|
|
425
|
+
"details"
|
|
426
|
+
].includes(key), `Filter ${name} uses reserved URL key: ${key}.`);
|
|
427
|
+
invariant(!!key && !owners.has(key), `Filter ${name} has an empty or duplicate URL key: ${key}.`);
|
|
428
|
+
owners.set(key, name);
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return filters;
|
|
432
|
+
}
|
|
433
|
+
/** Search query state; typing replaces history by default. Operations reject text
|
|
434
|
+
* longer than `maxLength` (200 by default). */
|
|
435
|
+
function searchFilter({ key, label, defaultValue = "", history = "replace", maxLength = 200 }) {
|
|
436
|
+
invariant(Number.isSafeInteger(maxLength) && maxLength > 0, `Search ${key} needs a positive maxLength.`);
|
|
437
|
+
function valid(value) {
|
|
438
|
+
return typeof value === "string" && value.length <= maxLength;
|
|
439
|
+
}
|
|
440
|
+
invariant(valid(defaultValue), `Search ${key} default exceeds maxLength.`);
|
|
441
|
+
return {
|
|
442
|
+
kind: "search",
|
|
443
|
+
label: label ?? key,
|
|
444
|
+
urlKeys: [key],
|
|
445
|
+
defaultValue,
|
|
446
|
+
clearValue: "",
|
|
447
|
+
describe: (value) => value,
|
|
448
|
+
history,
|
|
449
|
+
read(params) {
|
|
450
|
+
const value = params.get(key);
|
|
451
|
+
return value !== null && valid(value) ? value : defaultValue;
|
|
452
|
+
},
|
|
453
|
+
write(value) {
|
|
454
|
+
return { [key]: value === defaultValue ? null : value };
|
|
455
|
+
},
|
|
456
|
+
valid,
|
|
457
|
+
same(left, right) {
|
|
458
|
+
return left === right;
|
|
459
|
+
}
|
|
460
|
+
};
|
|
461
|
+
}
|
|
462
|
+
/** Validate labeled choices before controls or URL state consume them. */
|
|
463
|
+
function validateChoiceOptions(options) {
|
|
464
|
+
invariant(options.length > 0 && options.every((option) => !!option.id.trim() && !!option.label.trim()) && new Set(options.map((option) => option.id)).size === options.length, "Choices require nonempty, unique IDs and labels.");
|
|
465
|
+
}
|
|
466
|
+
/** One choice that narrows the included data. */
|
|
467
|
+
function choiceFilter(options) {
|
|
468
|
+
return createChoice(options);
|
|
469
|
+
}
|
|
470
|
+
/** One choice that changes how results are shown, such as a chart breakdown or sort order.
|
|
471
|
+
* Clearing filters keeps it; pass `view.breakdown(name)` to render it beside its chart. */
|
|
472
|
+
function displayChoice(options) {
|
|
473
|
+
const presentation = {
|
|
474
|
+
...options.presentation,
|
|
475
|
+
group: "display"
|
|
476
|
+
};
|
|
477
|
+
return {
|
|
478
|
+
...createChoice(options),
|
|
479
|
+
presentation
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
function createChoice({ key, label, defaultValue, options, history = "push", presentation }) {
|
|
483
|
+
validateChoiceOptions(options);
|
|
484
|
+
function valid(value) {
|
|
485
|
+
return typeof value === "string" && options.some((option) => option.id === value);
|
|
486
|
+
}
|
|
487
|
+
invariant(valid(defaultValue), `Choice ${key} must include its default value.`);
|
|
488
|
+
return {
|
|
489
|
+
kind: "choice",
|
|
490
|
+
presentation,
|
|
491
|
+
label: label ?? key,
|
|
492
|
+
options,
|
|
493
|
+
urlKeys: [key],
|
|
494
|
+
defaultValue,
|
|
495
|
+
history,
|
|
496
|
+
describe: (value) => options.find((option) => option.id === value).label,
|
|
497
|
+
read(params) {
|
|
498
|
+
const value = params.get(key);
|
|
499
|
+
return value !== null && valid(value) ? value : defaultValue;
|
|
500
|
+
},
|
|
501
|
+
write(value) {
|
|
502
|
+
return { [key]: value === defaultValue ? null : value };
|
|
503
|
+
},
|
|
504
|
+
valid,
|
|
505
|
+
same: (left, right) => left === right
|
|
506
|
+
};
|
|
507
|
+
}
|
|
508
|
+
function multiChoiceFilter({ key, label, defaultValue = [], options, maxSelected = options.length, history = "push", presentation }) {
|
|
509
|
+
validateChoiceOptions(options);
|
|
510
|
+
invariant(Number.isSafeInteger(maxSelected) && maxSelected >= 1 && maxSelected <= options.length, "Invalid choice selection limit.");
|
|
511
|
+
function valid(value) {
|
|
512
|
+
return Array.isArray(value) && value.length <= maxSelected && new Set(value).size === value.length && value.every((id) => options.some((option) => option.id === id));
|
|
513
|
+
}
|
|
514
|
+
function same(left, right) {
|
|
515
|
+
return left.length === right.length && left.every((id) => right.includes(id));
|
|
516
|
+
}
|
|
517
|
+
invariant(valid(defaultValue), `Invalid default choices for ${key}.`);
|
|
518
|
+
return {
|
|
519
|
+
kind: "multiChoice",
|
|
520
|
+
presentation,
|
|
521
|
+
label: label ?? key,
|
|
522
|
+
options,
|
|
523
|
+
maxSelected,
|
|
524
|
+
urlKeys: [key],
|
|
525
|
+
defaultValue,
|
|
526
|
+
history,
|
|
527
|
+
describe: (values) => values.map((id) => options.find((option) => option.id === id).label).join(", ") || "None",
|
|
528
|
+
read(params) {
|
|
529
|
+
const raw = params.get(key);
|
|
530
|
+
if (raw === null || raw.length > 4096) return defaultValue;
|
|
531
|
+
try {
|
|
532
|
+
const values = JSON.parse(raw);
|
|
533
|
+
return valid(values) ? values : defaultValue;
|
|
534
|
+
} catch {
|
|
535
|
+
return defaultValue;
|
|
536
|
+
}
|
|
537
|
+
},
|
|
538
|
+
write(value) {
|
|
539
|
+
return { [key]: same(value, defaultValue) ? null : JSON.stringify(options.filter((option) => value.includes(option.id)).map((option) => option.id)) };
|
|
540
|
+
},
|
|
541
|
+
valid,
|
|
542
|
+
same
|
|
543
|
+
};
|
|
544
|
+
}
|
|
545
|
+
//#endregion
|
|
546
|
+
//#region src/core/operation-filters.ts
|
|
547
|
+
function isDateFilter(filter) {
|
|
548
|
+
return filter.kind === "dateTimeRange";
|
|
549
|
+
}
|
|
550
|
+
/** Validate an operation's filters once: unique URL keys and at most one date filter. */
|
|
551
|
+
function defineOperationFilters(filters) {
|
|
552
|
+
defineAppFilters(filters);
|
|
553
|
+
invariant(Object.values(filters).filter(isDateFilter).length <= 1, "An operation reads at most one date filter.");
|
|
554
|
+
return Object.freeze({ ...filters });
|
|
555
|
+
}
|
|
556
|
+
/** The name of the operation's date filter, which sets its reporting period. */
|
|
557
|
+
function dateFilterName(filters) {
|
|
558
|
+
return Object.keys(filters).find((name) => isDateFilter(filters[name]));
|
|
559
|
+
}
|
|
560
|
+
/** Resolve URL selections to the request the browser sends. Relative date ranges
|
|
561
|
+
* resolve against one reference time so the range and its comparison agree. */
|
|
562
|
+
function resolveFilterInput(filters, values, reference = /* @__PURE__ */ new Date()) {
|
|
563
|
+
const input = {};
|
|
564
|
+
for (const [name, filter] of Object.entries(filters)) {
|
|
565
|
+
const value = values[name];
|
|
566
|
+
input[name] = filter.kind === "dateTimeRange" ? filter.request(value, reference) : value;
|
|
567
|
+
}
|
|
568
|
+
return input;
|
|
569
|
+
}
|
|
570
|
+
/** Validate untrusted operation input against the declared filters. */
|
|
571
|
+
function parseFilterInput(filters, value) {
|
|
572
|
+
invariant(value && typeof value === "object" && !Array.isArray(value), "Expected filter input.");
|
|
573
|
+
const fields = value;
|
|
574
|
+
for (const name of Object.keys(fields)) invariant(Object.hasOwn(filters, name), `Unknown filter input: ${name}.`);
|
|
575
|
+
const input = {};
|
|
576
|
+
for (const [name, filter] of Object.entries(filters)) {
|
|
577
|
+
const selected = Object.hasOwn(fields, name) ? fields[name] : void 0;
|
|
578
|
+
if (filter.kind === "dateTimeRange") input[name] = filter.parseInput(selected);
|
|
579
|
+
else {
|
|
580
|
+
invariant(filter.valid(selected), `Invalid ${filter.label ?? name}.`);
|
|
581
|
+
input[name] = selected;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
return input;
|
|
585
|
+
}
|
|
586
|
+
/** The default selections, resolved: every filter operation can run with them. */
|
|
587
|
+
function defaultFilterInput(filters) {
|
|
588
|
+
return Object.fromEntries(Object.entries(filters).map(([name, filter]) => {
|
|
589
|
+
if (filter.kind !== "dateTimeRange") return [name, filter.defaultValue];
|
|
590
|
+
const { range, comparison, selection } = filter.request(filter.defaultValue);
|
|
591
|
+
return [name, {
|
|
592
|
+
range,
|
|
593
|
+
comparison,
|
|
594
|
+
selection
|
|
595
|
+
}];
|
|
596
|
+
}));
|
|
597
|
+
}
|
|
598
|
+
/** Every operation in an app shares one filter per name and one owner per URL key. */
|
|
599
|
+
function combineOperationFilters(operations) {
|
|
600
|
+
const combined = {};
|
|
601
|
+
for (const [operation, filters] of Object.entries(operations)) for (const [name, filter] of Object.entries(filters)) {
|
|
602
|
+
invariant(!Object.hasOwn(combined, name) || combined[name] === filter, `Operations read different filters named ${name}; declare it once and share it (${operation}).`);
|
|
603
|
+
combined[name] = filter;
|
|
604
|
+
}
|
|
605
|
+
return defineAppFilters(combined);
|
|
606
|
+
}
|
|
607
|
+
//#endregion
|
|
608
|
+
//#region src/core/filters.ts
|
|
609
|
+
const all = { kind: "all" };
|
|
610
|
+
const numberOperatorLabels = {
|
|
611
|
+
eq: "Equals",
|
|
612
|
+
ne: "Does not equal",
|
|
613
|
+
gt: "Greater than",
|
|
614
|
+
gte: "At least",
|
|
615
|
+
lt: "Less than",
|
|
616
|
+
lte: "At most"
|
|
617
|
+
};
|
|
618
|
+
/** Exact numeric predicates; range bounds are inclusive and may be open-ended. */
|
|
619
|
+
function numberFilter({ key, label, min, max, defaultValue = all, history = "push", presentation }) {
|
|
620
|
+
invariant(!!key.trim(), "Numeric filter requires a URL key.");
|
|
621
|
+
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.");
|
|
622
|
+
function validNumber(value) {
|
|
623
|
+
return typeof value === "number" && Number.isFinite(value) && (min === void 0 || value >= min) && (max === void 0 || value <= max);
|
|
624
|
+
}
|
|
625
|
+
function valid(value) {
|
|
626
|
+
if (!value || typeof value !== "object") return false;
|
|
627
|
+
if (value.kind === "all") return true;
|
|
628
|
+
if (value.kind === "comparison") return typeof value.operator === "string" && Object.hasOwn(numberOperatorLabels, value.operator) && validNumber(value.value);
|
|
629
|
+
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);
|
|
630
|
+
}
|
|
631
|
+
function encode(value) {
|
|
632
|
+
return value.kind === "all" ? null : value.kind === "range" ? JSON.stringify({
|
|
633
|
+
kind: "range",
|
|
634
|
+
min: value.min,
|
|
635
|
+
max: value.max
|
|
636
|
+
}) : JSON.stringify({
|
|
637
|
+
kind: "comparison",
|
|
638
|
+
operator: value.operator,
|
|
639
|
+
value: value.value
|
|
640
|
+
});
|
|
641
|
+
}
|
|
642
|
+
invariant(valid(defaultValue), `Invalid default for ${label}.`);
|
|
643
|
+
return {
|
|
644
|
+
kind: "numberFilter",
|
|
645
|
+
presentation,
|
|
646
|
+
label,
|
|
647
|
+
min,
|
|
648
|
+
max,
|
|
649
|
+
defaultValue,
|
|
650
|
+
clearValue: all,
|
|
651
|
+
urlKeys: [key],
|
|
652
|
+
history,
|
|
653
|
+
valid,
|
|
654
|
+
same: (left, right) => encode(left) === encode(right),
|
|
655
|
+
describe(value) {
|
|
656
|
+
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}`;
|
|
657
|
+
},
|
|
658
|
+
read(params) {
|
|
659
|
+
const raw = params.get(key);
|
|
660
|
+
if (raw === null) return defaultValue;
|
|
661
|
+
if (raw.length > 512) return defaultValue;
|
|
662
|
+
try {
|
|
663
|
+
const value = raw === "all" ? all : JSON.parse(raw);
|
|
664
|
+
return valid(value) ? value : defaultValue;
|
|
665
|
+
} catch {
|
|
666
|
+
return defaultValue;
|
|
667
|
+
}
|
|
668
|
+
},
|
|
669
|
+
write(value) {
|
|
670
|
+
return { [key]: encode(value) === encode(defaultValue) ? null : value.kind === "all" ? "all" : encode(value) };
|
|
671
|
+
}
|
|
672
|
+
};
|
|
673
|
+
}
|
|
674
|
+
/** Boolean predicate with a distinct unrestricted state. */
|
|
675
|
+
function booleanFilter({ key, label, defaultValue = all, history = "push", presentation }) {
|
|
676
|
+
invariant(!!key.trim(), "Boolean filter requires a URL key.");
|
|
677
|
+
function valid(value) {
|
|
678
|
+
return isRecord(value) && (value.kind === "all" || value.kind === "is" && typeof value.value === "boolean");
|
|
679
|
+
}
|
|
680
|
+
function encode(value) {
|
|
681
|
+
return value.kind === "all" ? "all" : String(value.value);
|
|
682
|
+
}
|
|
683
|
+
invariant(valid(defaultValue), `Invalid default for ${label}.`);
|
|
684
|
+
return {
|
|
685
|
+
kind: "booleanFilter",
|
|
686
|
+
presentation,
|
|
687
|
+
label,
|
|
688
|
+
defaultValue,
|
|
689
|
+
clearValue: all,
|
|
690
|
+
urlKeys: [key],
|
|
691
|
+
history,
|
|
692
|
+
valid,
|
|
693
|
+
describe: (value) => value.kind === "all" ? "Any" : value.value ? "Yes" : "No",
|
|
694
|
+
same: (left, right) => encode(left) === encode(right),
|
|
695
|
+
read(params) {
|
|
696
|
+
const raw = params.get(key);
|
|
697
|
+
return raw === "all" ? all : raw === "true" || raw === "false" ? {
|
|
698
|
+
kind: "is",
|
|
699
|
+
value: raw === "true"
|
|
700
|
+
} : defaultValue;
|
|
701
|
+
},
|
|
702
|
+
write(value) {
|
|
703
|
+
return { [key]: encode(value) === encode(defaultValue) ? null : encode(value) };
|
|
704
|
+
}
|
|
705
|
+
};
|
|
706
|
+
}
|
|
707
|
+
function parseNumberSelection(value, filter) {
|
|
708
|
+
invariant(filter.valid(value), `Invalid ${filter.label} selection.`);
|
|
709
|
+
return value;
|
|
710
|
+
}
|
|
711
|
+
function parseBooleanSelection(value, filter) {
|
|
712
|
+
invariant(filter.valid(value), `Invalid ${filter.label} selection.`);
|
|
713
|
+
return value;
|
|
714
|
+
}
|
|
715
|
+
//#endregion
|
|
716
|
+
//#region src/core/facets.ts
|
|
717
|
+
const facetSource = Symbol("data-app.facetSource");
|
|
718
|
+
//#endregion
|
|
719
|
+
//#region src/core/facet-filter.ts
|
|
720
|
+
function facetFilter({ options: operation, ...settings }) {
|
|
721
|
+
return Object.assign(createDimensionFilter({
|
|
722
|
+
...settings,
|
|
723
|
+
options: []
|
|
724
|
+
}, true), {
|
|
725
|
+
optionsSource: "query",
|
|
726
|
+
[facetSource]: Object.freeze({ operation })
|
|
727
|
+
});
|
|
728
|
+
}
|
|
729
|
+
//#endregion
|
|
730
|
+
//#region src/core/date-time-range-contract.ts
|
|
731
|
+
function createDateTimeRangePolicy({ minDate, maxDate: sourceMaxDate, maxRangeDays, timeZone, completeDays = false }) {
|
|
732
|
+
invariant(maxRangeDays === void 0 || Number.isInteger(maxRangeDays) && maxRangeDays > 0, "maxRangeDays must be a positive integer.");
|
|
733
|
+
if (minDate) parseDate(minDate);
|
|
734
|
+
if (typeof sourceMaxDate === "string") parseDate(sourceMaxDate);
|
|
735
|
+
today(timeZone);
|
|
736
|
+
function reference(now) {
|
|
737
|
+
invariant(Number.isFinite(now.getTime()), "Invalid reference date.");
|
|
738
|
+
return toCalendarDateTime(fromDate(now, timeZone)).toDate("UTC");
|
|
739
|
+
}
|
|
740
|
+
function bounds(now = /* @__PURE__ */ new Date()) {
|
|
741
|
+
const date = reference(now).toISOString().slice(0, 10);
|
|
742
|
+
const latest = parseDate(date).subtract({ days: completeDays ? 1 : 0 }).toString();
|
|
743
|
+
const sourceMax = typeof sourceMaxDate === "function" ? sourceMaxDate() : sourceMaxDate;
|
|
744
|
+
if (sourceMax) parseDate(sourceMax);
|
|
745
|
+
return {
|
|
746
|
+
minDate,
|
|
747
|
+
maxDate: sourceMax && sourceMax < latest ? sourceMax : latest,
|
|
748
|
+
maxRangeDays,
|
|
749
|
+
timeZone
|
|
750
|
+
};
|
|
751
|
+
}
|
|
752
|
+
function resolve(value, now = /* @__PURE__ */ new Date()) {
|
|
753
|
+
const range = resolveDateTimeRange(parseDateTimeRange(value), reference(now));
|
|
754
|
+
const limits = bounds(now);
|
|
755
|
+
invariant(range.from, "Choose a bounded datetime range.");
|
|
756
|
+
invariant(maxRangeDays === void 0 || range.to.getTime() - range.from.getTime() <= maxRangeDays * fixedUnitMilliseconds.DAY, `Choose a range of at most ${maxRangeDays} days.`);
|
|
757
|
+
invariant(!minDate || range.from >= parseDate(minDate).toDate("UTC"), "Range starts before available source coverage.");
|
|
758
|
+
invariant(range.to <= parseDate(limits.maxDate).add({ days: 1 }).toDate("UTC"), "Range ends after available source coverage.");
|
|
759
|
+
return {
|
|
760
|
+
from: range.from,
|
|
761
|
+
to: range.to
|
|
762
|
+
};
|
|
763
|
+
}
|
|
764
|
+
function parse(value, now = /* @__PURE__ */ new Date()) {
|
|
765
|
+
const range = parseDateTimeRange(value);
|
|
766
|
+
resolve(range, now);
|
|
767
|
+
return range;
|
|
768
|
+
}
|
|
769
|
+
/** Hours that have not happened yet hold no data; ending there keeps comparisons equal. */
|
|
770
|
+
function endAtNow(range, now = /* @__PURE__ */ new Date()) {
|
|
771
|
+
const current = reference(now);
|
|
772
|
+
if (range.to <= current) return range;
|
|
773
|
+
return {
|
|
774
|
+
from: range.from,
|
|
775
|
+
to: range.from > current ? range.from : current
|
|
776
|
+
};
|
|
777
|
+
}
|
|
778
|
+
/** The same window one selected length earlier, ending as far before now as the range does. */
|
|
779
|
+
function comparison(value, now = /* @__PURE__ */ new Date()) {
|
|
780
|
+
const selected = resolve(value, now);
|
|
781
|
+
const length = selected.to.getTime() - selected.from.getTime();
|
|
782
|
+
const range = endAtNow(selected, now);
|
|
783
|
+
const previous = {
|
|
784
|
+
from: new Date(range.from.getTime() - length),
|
|
785
|
+
to: new Date(range.to.getTime() - length)
|
|
786
|
+
};
|
|
787
|
+
try {
|
|
788
|
+
return resolve(previous, now);
|
|
789
|
+
} catch {
|
|
790
|
+
return null;
|
|
791
|
+
}
|
|
792
|
+
}
|
|
793
|
+
return {
|
|
794
|
+
timeZone,
|
|
795
|
+
bounds,
|
|
796
|
+
/** Validate coverage and duration while preserving symbolic relative bounds. */
|
|
797
|
+
parse,
|
|
798
|
+
/** Resolve to UTC-rebased bounds using reporting-zone wall-clock fields, then validate policy. */
|
|
799
|
+
resolve,
|
|
800
|
+
/** Return the comparison window, or null when source coverage excludes it. */
|
|
801
|
+
comparison,
|
|
802
|
+
/** End a resolved range at the reference time when it runs past it. */
|
|
803
|
+
endAtNow,
|
|
804
|
+
/** Resolve both periods against one reference instant, ending the range at now. */
|
|
805
|
+
request(value, compare = false, now = /* @__PURE__ */ new Date()) {
|
|
806
|
+
const range = endAtNow(resolve(value, now), now);
|
|
807
|
+
const previous = compare ? comparison(value, now) : null;
|
|
808
|
+
invariant(!compare || previous, "Comparison is outside available source coverage.");
|
|
809
|
+
return {
|
|
810
|
+
range,
|
|
811
|
+
comparison: previous
|
|
812
|
+
};
|
|
813
|
+
}
|
|
814
|
+
};
|
|
815
|
+
}
|
|
816
|
+
//#endregion
|
|
817
|
+
//#region src/core/date-time-range-sql.ts
|
|
818
|
+
const SQL_PARAMETER_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
819
|
+
/** Bind a resolved filter range as timestamp strings for literal DuckDB SQL.
|
|
820
|
+
* Dates carry reporting-zone wall-clock fields in UTC; omit `Z` for TIMESTAMP casts. */
|
|
821
|
+
function resolvedDateTimeRangeParams(range, prefix) {
|
|
822
|
+
invariant(SQL_PARAMETER_NAME.test(prefix), "Use a SQL parameter name.");
|
|
823
|
+
return {
|
|
824
|
+
[`${prefix}_from`]: range.from.toISOString().slice(0, -1),
|
|
825
|
+
[`${prefix}_to`]: range.to.toISOString().slice(0, -1)
|
|
826
|
+
};
|
|
827
|
+
}
|
|
828
|
+
/** DuckDB timestamp expressions using the query session's timezone for relative anchors.
|
|
829
|
+
* Absolute fields remain UTC-rebased TIMESTAMP values. Start is inclusive, end exclusive.
|
|
830
|
+
*/
|
|
831
|
+
function dateTimeRangeSql(range, parameter = "period") {
|
|
832
|
+
invariant(SQL_PARAMETER_NAME.test(parameter), "Use a SQL parameter name.");
|
|
833
|
+
return {
|
|
834
|
+
from: boundExpression(parameter, "from"),
|
|
835
|
+
to: boundExpression(parameter, "to"),
|
|
836
|
+
params: { [parameter]: serializeDateTimeRange(range) }
|
|
837
|
+
};
|
|
838
|
+
}
|
|
839
|
+
function boundExpression(parameter, bound) {
|
|
840
|
+
const json = `$${parameter}`;
|
|
841
|
+
const path = `$.${bound}`;
|
|
842
|
+
const anchor = `json_extract_string(${json}, '${path}.anchor')`;
|
|
843
|
+
const base = `CASE WHEN json_type(${json}, '${path}') = 'VARCHAR' THEN CAST(json_extract_string(${json}, '${path}') AS TIMESTAMP)
|
|
844
|
+
WHEN ${anchor} = 'RELATIVE_ANCHOR_START_OF_TODAY' THEN date_trunc('day', localtimestamp)
|
|
845
|
+
WHEN ${anchor} = 'RELATIVE_ANCHOR_START_OF_YESTERDAY' THEN date_trunc('day', localtimestamp) - INTERVAL '1 day'
|
|
846
|
+
WHEN ${anchor} = 'RELATIVE_ANCHOR_START_OF_TOMORROW' THEN date_trunc('day', localtimestamp) + INTERVAL '1 day'
|
|
847
|
+
WHEN ${anchor} = 'RELATIVE_ANCHOR_START_OF_WEEK' THEN date_trunc('week', localtimestamp)
|
|
848
|
+
WHEN ${anchor} = 'RELATIVE_ANCHOR_START_OF_MONTH' THEN date_trunc('month', localtimestamp)
|
|
849
|
+
WHEN ${anchor} = 'RELATIVE_ANCHOR_START_OF_YEAR' THEN date_trunc('year', localtimestamp)
|
|
850
|
+
WHEN ${anchor} = 'RELATIVE_ANCHOR_NOW' THEN localtimestamp
|
|
851
|
+
ELSE ${bound === "from" ? "TIMESTAMP '-infinity'" : "localtimestamp"} END`;
|
|
852
|
+
const item = `json_extract(${json}, '${path}.offset[' || i::VARCHAR || ']')`;
|
|
853
|
+
const amount = `CAST(json_extract_string(${item}, '$.amount') AS INTEGER)`;
|
|
854
|
+
return `(WITH RECURSIVE bounds(i, value) AS (
|
|
855
|
+
SELECT 0, ${base}
|
|
856
|
+
UNION ALL SELECT i + 1, value + ${`CASE json_extract_string(${item}, '$.unit') ${[
|
|
857
|
+
"SECOND",
|
|
858
|
+
"MINUTE",
|
|
859
|
+
"HOUR",
|
|
860
|
+
"DAY",
|
|
861
|
+
"WEEK",
|
|
862
|
+
"MONTH",
|
|
863
|
+
"YEAR"
|
|
864
|
+
].map((unit) => `WHEN '${unit}' THEN ${amount} * INTERVAL '1 ${unit}'`).join(" ")} ELSE INTERVAL '0 seconds' END`} FROM bounds
|
|
865
|
+
WHERE i < COALESCE(json_array_length(${json}, '${path}.offset'), 0)
|
|
866
|
+
) SELECT value FROM bounds ORDER BY i DESC LIMIT 1)`;
|
|
867
|
+
}
|
|
868
|
+
//#endregion
|
|
869
|
+
//#region src/core/date-time-filter.ts
|
|
870
|
+
/** Monitoring offers minute/hour windows; analytics offers longer periods and to-date windows. Spread either menu to add custom presets. */
|
|
871
|
+
const dateTimeRangePresets = {
|
|
872
|
+
monitoring: [
|
|
873
|
+
{
|
|
874
|
+
label: "Past 5 minutes",
|
|
875
|
+
range: "5m",
|
|
876
|
+
shortcut: "5m"
|
|
877
|
+
},
|
|
878
|
+
{
|
|
879
|
+
label: "Past 15 minutes",
|
|
880
|
+
range: "15m",
|
|
881
|
+
shortcut: "15m"
|
|
882
|
+
},
|
|
883
|
+
{
|
|
884
|
+
label: "Past hour",
|
|
885
|
+
range: "1h",
|
|
886
|
+
shortcut: "1h"
|
|
887
|
+
},
|
|
888
|
+
{
|
|
889
|
+
label: "Past 4 hours",
|
|
890
|
+
range: "4h",
|
|
891
|
+
shortcut: "4h"
|
|
892
|
+
},
|
|
893
|
+
{
|
|
894
|
+
label: "Past 24 hours",
|
|
895
|
+
range: "1d",
|
|
896
|
+
shortcut: "1d"
|
|
897
|
+
}
|
|
898
|
+
],
|
|
899
|
+
analytics: [
|
|
900
|
+
{
|
|
901
|
+
label: "Past 7 days",
|
|
902
|
+
range: "7d",
|
|
903
|
+
shortcut: "7d"
|
|
904
|
+
},
|
|
905
|
+
{
|
|
906
|
+
label: "Past 30 days",
|
|
907
|
+
range: "30d",
|
|
908
|
+
shortcut: "30d"
|
|
909
|
+
},
|
|
910
|
+
{
|
|
911
|
+
label: "Past 90 days",
|
|
912
|
+
range: "90d",
|
|
913
|
+
shortcut: "90d"
|
|
914
|
+
},
|
|
915
|
+
{
|
|
916
|
+
label: "Month to date",
|
|
917
|
+
range: "MTD",
|
|
918
|
+
shortcut: "MTD"
|
|
919
|
+
},
|
|
920
|
+
{
|
|
921
|
+
label: "Year to date",
|
|
922
|
+
range: "YTD",
|
|
923
|
+
shortcut: "YTD"
|
|
924
|
+
},
|
|
925
|
+
{
|
|
926
|
+
label: "Past year",
|
|
927
|
+
range: "1y",
|
|
928
|
+
shortcut: "1y"
|
|
929
|
+
}
|
|
930
|
+
]
|
|
931
|
+
};
|
|
932
|
+
/** One declaration drives the picker, URL state, and the input of operations that list it.
|
|
933
|
+
* Operations receive resolved bounds and the original selection: `from` inclusive, `to` exclusive.
|
|
934
|
+
*/
|
|
935
|
+
function dateTimeRangeFilter(options) {
|
|
936
|
+
const { key, label = "Date range", defaultValue, timeZone = "UTC", maxRangeDays, minDate, maxDate, completeDays, comparison, presets, history = "push", presentation } = options;
|
|
937
|
+
const policy = createDateTimeRangePolicy({
|
|
938
|
+
minDate,
|
|
939
|
+
maxDate,
|
|
940
|
+
maxRangeDays,
|
|
941
|
+
timeZone,
|
|
942
|
+
completeDays
|
|
943
|
+
});
|
|
944
|
+
const comparable = comparison !== void 0;
|
|
945
|
+
const compareKey = key === "period" ? "compare" : `${key}-compare`;
|
|
946
|
+
function parseRange(value, now) {
|
|
947
|
+
return policy.parse(parseDateTimeRange(value, { maxRangeDays }), now);
|
|
948
|
+
}
|
|
949
|
+
const parsed = typeof defaultValue === "string" ? parseDateTimeRangeInput(defaultValue) : null;
|
|
950
|
+
invariant(!parsed || parsed.ok, `Invalid default range for ${key}.`);
|
|
951
|
+
const initial = {
|
|
952
|
+
range: parseRange(parsed?.ok ? parsed.range : defaultValue),
|
|
953
|
+
...comparison === "on" ? { comparison: "previous" } : {}
|
|
954
|
+
};
|
|
955
|
+
function sameRange(left, right) {
|
|
956
|
+
return serializeDateTimeRange(left) === serializeDateTimeRange(right);
|
|
957
|
+
}
|
|
958
|
+
function parseSelection(value, now = /* @__PURE__ */ new Date()) {
|
|
959
|
+
invariant(isRecord(value), "Choose a datetime range.");
|
|
960
|
+
const selection = value;
|
|
961
|
+
invariant(Object.keys(selection).every((name) => name === "range" || name === "comparison") && (selection.comparison === void 0 || comparable && selection.comparison === "previous"), "Invalid comparison selection.");
|
|
962
|
+
const range = parseRange(selection.range, now);
|
|
963
|
+
invariant(!selection.comparison || policy.comparison(range, now), "Comparison is outside available source coverage.");
|
|
964
|
+
return {
|
|
965
|
+
range,
|
|
966
|
+
...selection.comparison ? { comparison: "previous" } : {}
|
|
967
|
+
};
|
|
968
|
+
}
|
|
969
|
+
function request(value, now = /* @__PURE__ */ new Date()) {
|
|
970
|
+
const selection = parseSelection(value, now);
|
|
971
|
+
return {
|
|
972
|
+
...policy.request(selection.range, selection.comparison === "previous", now),
|
|
973
|
+
selection,
|
|
974
|
+
reference: now.toISOString()
|
|
975
|
+
};
|
|
976
|
+
}
|
|
977
|
+
function same(left, right) {
|
|
978
|
+
return left.comparison === right.comparison && sameRange(left.range, right.range);
|
|
979
|
+
}
|
|
980
|
+
function valid(value) {
|
|
981
|
+
try {
|
|
982
|
+
parseSelection(value);
|
|
983
|
+
return true;
|
|
984
|
+
} catch {
|
|
985
|
+
return false;
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
invariant(valid(initial), `Date filter ${key} has a default outside its source coverage.`);
|
|
989
|
+
/** The URL records the comparison only when it differs from the default. */
|
|
990
|
+
function comparisonParam(selection) {
|
|
991
|
+
if (!comparable) return {};
|
|
992
|
+
const state = selection.comparison ?? "off";
|
|
993
|
+
return { [compareKey]: state === (initial.comparison ?? "off") ? null : state };
|
|
994
|
+
}
|
|
995
|
+
function readRange(params) {
|
|
996
|
+
const text = params.get(key);
|
|
997
|
+
if (!text || text.length > 8192) return initial.range;
|
|
998
|
+
try {
|
|
999
|
+
return parseRange(JSON.parse(text));
|
|
1000
|
+
} catch {
|
|
1001
|
+
return initial.range;
|
|
1002
|
+
}
|
|
1003
|
+
}
|
|
1004
|
+
return {
|
|
1005
|
+
kind: "dateTimeRange",
|
|
1006
|
+
label,
|
|
1007
|
+
presentation,
|
|
1008
|
+
history,
|
|
1009
|
+
urlKeys: comparable ? [key, compareKey] : [key],
|
|
1010
|
+
defaultValue: initial,
|
|
1011
|
+
clearValue: initial,
|
|
1012
|
+
comparable,
|
|
1013
|
+
policy,
|
|
1014
|
+
maxRangeDays,
|
|
1015
|
+
presets,
|
|
1016
|
+
request,
|
|
1017
|
+
parseInput(value) {
|
|
1018
|
+
invariant(isRecord(value), "Invalid datetime request.");
|
|
1019
|
+
const supplied = value;
|
|
1020
|
+
invariant(Object.keys(supplied).every((name) => [
|
|
1021
|
+
"range",
|
|
1022
|
+
"comparison",
|
|
1023
|
+
"selection",
|
|
1024
|
+
"reference"
|
|
1025
|
+
].includes(name)), "Invalid datetime request.");
|
|
1026
|
+
const range = policy.endAtNow(policy.resolve(parseRange(supplied.range)));
|
|
1027
|
+
const selection = supplied.selection === void 0 ? void 0 : parseSelection(supplied.selection);
|
|
1028
|
+
if (supplied.comparison === null || supplied.comparison === void 0) return {
|
|
1029
|
+
range,
|
|
1030
|
+
comparison: null,
|
|
1031
|
+
...selection ? { selection } : {}
|
|
1032
|
+
};
|
|
1033
|
+
invariant(comparable, `${label} has no comparison.`);
|
|
1034
|
+
const comparison = policy.resolve(parseDateTimeRange(supplied.comparison));
|
|
1035
|
+
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.");
|
|
1036
|
+
return {
|
|
1037
|
+
range,
|
|
1038
|
+
comparison,
|
|
1039
|
+
...selection ? { selection } : {}
|
|
1040
|
+
};
|
|
1041
|
+
},
|
|
1042
|
+
previous(selection) {
|
|
1043
|
+
return comparable ? policy.comparison(selection.range) : null;
|
|
1044
|
+
},
|
|
1045
|
+
valid,
|
|
1046
|
+
same,
|
|
1047
|
+
describe: (selection) => `${formatDateTimeRange(selection.range)}${selection.comparison ? " vs previous period" : ""}`,
|
|
1048
|
+
read(params) {
|
|
1049
|
+
const range = readRange(params);
|
|
1050
|
+
if (!comparable) return { range };
|
|
1051
|
+
const state = params.get(compareKey);
|
|
1052
|
+
const compared = {
|
|
1053
|
+
range,
|
|
1054
|
+
comparison: "previous"
|
|
1055
|
+
};
|
|
1056
|
+
return (state === "previous" || state === null && !!initial.comparison) && valid(compared) ? compared : { range };
|
|
1057
|
+
},
|
|
1058
|
+
write(value) {
|
|
1059
|
+
const selection = parseSelection(value);
|
|
1060
|
+
return {
|
|
1061
|
+
[key]: sameRange(selection.range, initial.range) ? null : serializeDateTimeRange(selection.range),
|
|
1062
|
+
...comparisonParam(selection)
|
|
1063
|
+
};
|
|
1064
|
+
}
|
|
1065
|
+
};
|
|
1066
|
+
}
|
|
1067
|
+
/** Bind one date selection immediately before dispatching a query. Both periods share one clock. */
|
|
1068
|
+
function queryDateTimeRangeParams(filter, input, prefix, now = /* @__PURE__ */ new Date()) {
|
|
1069
|
+
const { range, comparison } = input.selection ? filter.request(input.selection, now) : input;
|
|
1070
|
+
return {
|
|
1071
|
+
current: resolvedDateTimeRangeParams(range, prefix),
|
|
1072
|
+
comparison: comparison ? resolvedDateTimeRangeParams(comparison, prefix) : null,
|
|
1073
|
+
combined: resolvedDateTimeRangeParams({
|
|
1074
|
+
from: comparison?.from ?? range.from,
|
|
1075
|
+
to: range.to
|
|
1076
|
+
}, prefix)
|
|
1077
|
+
};
|
|
1078
|
+
}
|
|
1079
|
+
//#endregion
|
|
1080
|
+
//#region src/authoring/contract.ts
|
|
1081
|
+
function parseTrue(value) {
|
|
1082
|
+
invariant(value === true, "Expected a successful check.");
|
|
1083
|
+
return true;
|
|
1084
|
+
}
|
|
1085
|
+
/** Accepts numeric strings from DuckDB; rejects negative, fractional, and unsafe integers. */
|
|
1086
|
+
function parseCount(value) {
|
|
1087
|
+
const number = typeof value === "number" || typeof value === "string" ? Number(value) : NaN;
|
|
1088
|
+
invariant(Number.isSafeInteger(number) && number >= 0 && (typeof value !== "string" || !!value.trim()), "Invalid count in query result.");
|
|
1089
|
+
return number;
|
|
1090
|
+
}
|
|
1091
|
+
function parseLabel(value, maxLength = 100) {
|
|
1092
|
+
invariant(typeof value === "string" && !!value && value.length <= maxLength, "Invalid label in query result.");
|
|
1093
|
+
return value;
|
|
1094
|
+
}
|
|
1095
|
+
function defineQueryNames(names) {
|
|
1096
|
+
const values = Object.values(names);
|
|
1097
|
+
invariant(values.every((name) => !!name.trim()) && new Set(values).size === values.length, "Query names must be nonempty and unique.");
|
|
1098
|
+
return names;
|
|
1099
|
+
}
|
|
1100
|
+
function defineOperation(operation) {
|
|
1101
|
+
const { policy } = operation;
|
|
1102
|
+
invariant(Number.isInteger(policy.maxQueryRows) && policy.maxQueryRows > 0 && policy.maxQueryRows <= 1e4 && Number.isInteger(policy.maxDurationMs) && policy.maxDurationMs > 0 && (policy.maxResponseBytes === void 0 || Number.isInteger(policy.maxResponseBytes) && policy.maxResponseBytes > 0), `Each data operation needs positive row and duration limits, with at most ${MAX_QUERY_ROWS.toLocaleString("en-US")} rows.`);
|
|
1103
|
+
const contract = operationInputContract(operation);
|
|
1104
|
+
const queries = snapshotQueries(operation.queries);
|
|
1105
|
+
const queryNames = Object.fromEntries(Object.keys(queries).map((name) => [name, name]));
|
|
1106
|
+
const defined = {
|
|
1107
|
+
...contract,
|
|
1108
|
+
policy,
|
|
1109
|
+
queryNames,
|
|
1110
|
+
async run(context, input) {
|
|
1111
|
+
async function query(name, values = {}, options) {
|
|
1112
|
+
invariant(Object.hasOwn(queries, name), `Unknown query name: ${name}.`);
|
|
1113
|
+
const definition = queries[name];
|
|
1114
|
+
const params = resolveQueryParameters(definition.params, values, context.queryParams ?? {});
|
|
1115
|
+
return decodeQueryResult(await context.lakehouse.queryAll(definition.statement, {
|
|
1116
|
+
name,
|
|
1117
|
+
params,
|
|
1118
|
+
limit: options?.limit ?? policy.maxQueryRows,
|
|
1119
|
+
signal: context.signal
|
|
1120
|
+
}), definition.projections);
|
|
1121
|
+
}
|
|
1122
|
+
if (contract.filters) await validateSourceMembers(contract.filters, input, query);
|
|
1123
|
+
context.signal.throwIfAborted();
|
|
1124
|
+
return operation.run({
|
|
1125
|
+
signal: context.signal,
|
|
1126
|
+
query
|
|
1127
|
+
}, input);
|
|
1128
|
+
}
|
|
1129
|
+
};
|
|
1130
|
+
attachDimensionSelectors(defined, queries);
|
|
1131
|
+
return defined;
|
|
1132
|
+
}
|
|
1133
|
+
/** Filters parse themselves; an operation's own `input` parses only its other fields. */
|
|
1134
|
+
function operationInputContract(operation) {
|
|
1135
|
+
const filters = defineOperationFilters(operation.filters ?? {});
|
|
1136
|
+
const defaults = defaultFilterInput(filters);
|
|
1137
|
+
if (!operation.input) return {
|
|
1138
|
+
filters,
|
|
1139
|
+
input: (value) => parseFilterInput(filters, value),
|
|
1140
|
+
checks: [defaults]
|
|
1141
|
+
};
|
|
1142
|
+
const parseOwn = operation.input;
|
|
1143
|
+
invariant(Array.isArray(operation.checks) && operation.checks.length > 0, "An operation with its own input needs check inputs.");
|
|
1144
|
+
if (!Object.keys(filters).length) {
|
|
1145
|
+
for (const check of operation.checks) parseOwn(check);
|
|
1146
|
+
return {
|
|
1147
|
+
input: parseOwn,
|
|
1148
|
+
checks: operation.checks
|
|
1149
|
+
};
|
|
1150
|
+
}
|
|
1151
|
+
function input(value) {
|
|
1152
|
+
invariant(isRecord(value), "Expected operation input.");
|
|
1153
|
+
const own = {};
|
|
1154
|
+
const selected = {};
|
|
1155
|
+
for (const [name, field] of Object.entries(value)) (Object.hasOwn(filters, name) ? selected : own)[name] = field;
|
|
1156
|
+
const parsed = parseOwn(own);
|
|
1157
|
+
invariant(isRecord(parsed), "Expected parsed input object.");
|
|
1158
|
+
for (const name of Object.keys(parsed)) invariant(!Object.hasOwn(filters, name), `Input field ${name} is also a filter; the filter parses it.`);
|
|
1159
|
+
return {
|
|
1160
|
+
...parseFilterInput(filters, selected),
|
|
1161
|
+
...parsed
|
|
1162
|
+
};
|
|
1163
|
+
}
|
|
1164
|
+
const checks = operation.checks.map((check) => ({
|
|
1165
|
+
...defaults,
|
|
1166
|
+
...check
|
|
1167
|
+
}));
|
|
1168
|
+
for (const check of checks) input(check);
|
|
1169
|
+
return {
|
|
1170
|
+
filters,
|
|
1171
|
+
input,
|
|
1172
|
+
checks
|
|
1173
|
+
};
|
|
1174
|
+
}
|
|
1175
|
+
/** A connectivity probe uses the app's registered connection query. */
|
|
1176
|
+
function connectionCheck(queries) {
|
|
1177
|
+
const connection = queries.connection;
|
|
1178
|
+
return defineOperation({
|
|
1179
|
+
queries: { connection },
|
|
1180
|
+
policy: {
|
|
1181
|
+
maxQueryRows: 1,
|
|
1182
|
+
maxDurationMs: 15e3
|
|
1183
|
+
},
|
|
1184
|
+
async run({ query }) {
|
|
1185
|
+
await query("connection");
|
|
1186
|
+
return true;
|
|
1187
|
+
}
|
|
1188
|
+
});
|
|
1189
|
+
}
|
|
1190
|
+
//#endregion
|
|
1191
|
+
//#region src/core/navigation.ts
|
|
1192
|
+
function validLocation(value) {
|
|
1193
|
+
if (!value || typeof value !== "object") return false;
|
|
1194
|
+
const message = value;
|
|
1195
|
+
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("#"));
|
|
1196
|
+
}
|
|
1197
|
+
//#endregion
|
|
1198
|
+
//#region src/core/messages.ts
|
|
1199
|
+
const errorBrand = Symbol.for("@altertable/data-app/MessageRoutingError");
|
|
1200
|
+
/** Only these deliberate, public failures cross the message boundary. Other errors stay private. */
|
|
1201
|
+
var MessageRoutingError = class extends Error {
|
|
1202
|
+
code;
|
|
1203
|
+
requestId;
|
|
1204
|
+
[errorBrand] = true;
|
|
1205
|
+
static [Symbol.hasInstance](value) {
|
|
1206
|
+
return value instanceof Error && value[errorBrand] === true;
|
|
1207
|
+
}
|
|
1208
|
+
constructor(code, message, requestId, options) {
|
|
1209
|
+
super(message, options);
|
|
1210
|
+
this.code = code;
|
|
1211
|
+
this.requestId = requestId;
|
|
1212
|
+
this.name = "MessageRoutingError";
|
|
1213
|
+
}
|
|
1214
|
+
};
|
|
1215
|
+
function defineMessageRoute(route) {
|
|
1216
|
+
return route;
|
|
1217
|
+
}
|
|
1218
|
+
/** Contracts are shared; handlers are supplied by the host and never belong in the app bundle. */
|
|
1219
|
+
function createMessageRouter(routes, handlers) {
|
|
1220
|
+
const registered = new Map(Object.entries(routes).map(([name, contract]) => {
|
|
1221
|
+
const handler = handlers[name];
|
|
1222
|
+
if (!name || name.length > 256 || typeof handler !== "function") throw new Error("Each message route requires a handler and a bounded name.");
|
|
1223
|
+
return [name, {
|
|
1224
|
+
contract,
|
|
1225
|
+
handler
|
|
1226
|
+
}];
|
|
1227
|
+
}));
|
|
1228
|
+
async function dispatch(value, context) {
|
|
1229
|
+
if (!value || typeof value !== "object" || typeof value.route !== "string") throw new MessageRoutingError("invalid_message", "Invalid routed message.");
|
|
1230
|
+
const message = value;
|
|
1231
|
+
const entry = registered.get(message.route);
|
|
1232
|
+
if (!entry) throw new MessageRoutingError("unknown_route", "Unknown message route.");
|
|
1233
|
+
let payload;
|
|
1234
|
+
try {
|
|
1235
|
+
payload = entry.contract.input(message.payload);
|
|
1236
|
+
} catch (error) {
|
|
1237
|
+
if (error instanceof MessageRoutingError) throw error;
|
|
1238
|
+
throw new MessageRoutingError("invalid_payload", "Invalid message payload.");
|
|
1239
|
+
}
|
|
1240
|
+
context.signal.throwIfAborted();
|
|
1241
|
+
let result;
|
|
1242
|
+
try {
|
|
1243
|
+
result = await entry.handler(payload, context);
|
|
1244
|
+
} catch (error) {
|
|
1245
|
+
if (context.signal.aborted) throw context.signal.reason;
|
|
1246
|
+
if (error instanceof MessageRoutingError) throw error;
|
|
1247
|
+
throw new MessageRoutingError("request_failed", "The message request failed. Retry the request.");
|
|
1248
|
+
}
|
|
1249
|
+
context.signal.throwIfAborted();
|
|
1250
|
+
try {
|
|
1251
|
+
return entry.contract.output(result, payload);
|
|
1252
|
+
} catch (error) {
|
|
1253
|
+
if (error instanceof MessageRoutingError) throw error;
|
|
1254
|
+
throw new MessageRoutingError("invalid_response", "Invalid message response.");
|
|
1255
|
+
}
|
|
1256
|
+
}
|
|
1257
|
+
return { dispatch };
|
|
1258
|
+
}
|
|
1259
|
+
/** Omit contracts only in generic hosts such as the CLI shell, where Bun validates operations. */
|
|
1260
|
+
function defineDataOperationRoute(operations) {
|
|
1261
|
+
return {
|
|
1262
|
+
operations,
|
|
1263
|
+
input(value) {
|
|
1264
|
+
if (!value || typeof value !== "object") throw new Error("Invalid query.");
|
|
1265
|
+
const request = value;
|
|
1266
|
+
if (typeof request.operation !== "string" || !request.operation || request.operation.length > 256 || request.operation.includes("/")) throw new Error("Invalid operation.");
|
|
1267
|
+
const operation = operations && Object.hasOwn(operations, request.operation) ? operations[request.operation] : void 0;
|
|
1268
|
+
if (operations && !operation) throw new Error("Unknown operation.");
|
|
1269
|
+
return {
|
|
1270
|
+
operation: request.operation,
|
|
1271
|
+
input: operation ? operation.input(request.input) : request.input
|
|
1272
|
+
};
|
|
1273
|
+
},
|
|
1274
|
+
output(value) {
|
|
1275
|
+
if (!value || typeof value !== "object") throw new Error("Invalid data response.");
|
|
1276
|
+
const response = value;
|
|
1277
|
+
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.");
|
|
1278
|
+
const body = response.body;
|
|
1279
|
+
if (response.status < 200 || response.status >= 300) {
|
|
1280
|
+
const failure = body.error;
|
|
1281
|
+
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);
|
|
1282
|
+
}
|
|
1283
|
+
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.");
|
|
1284
|
+
if (body.queries !== void 0 && (!Array.isArray(body.queries) || !body.queries.every((query) => isRecord(query) && 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.");
|
|
1285
|
+
return {
|
|
1286
|
+
status: response.status,
|
|
1287
|
+
body
|
|
1288
|
+
};
|
|
1289
|
+
}
|
|
1290
|
+
};
|
|
1291
|
+
}
|
|
1292
|
+
const navigationUpdateRoute = /* @__PURE__ */ defineMessageRoute({
|
|
1293
|
+
input(value) {
|
|
1294
|
+
if (!value || typeof value !== "object") throw new Error("Invalid navigation.");
|
|
1295
|
+
const input = value;
|
|
1296
|
+
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.");
|
|
1297
|
+
return {
|
|
1298
|
+
search: input.search,
|
|
1299
|
+
hash: input.hash,
|
|
1300
|
+
mode: input.mode,
|
|
1301
|
+
...input.title === void 0 ? {} : { title: input.title }
|
|
1302
|
+
};
|
|
1303
|
+
},
|
|
1304
|
+
output(value) {
|
|
1305
|
+
if (value !== null) throw new Error("Invalid navigation response.");
|
|
1306
|
+
return null;
|
|
1307
|
+
}
|
|
1308
|
+
});
|
|
1309
|
+
/** Run a SQL query already registered by the app's defineDataApp manifest. */
|
|
1310
|
+
const registeredQueryRoute = /* @__PURE__ */ defineMessageRoute({
|
|
1311
|
+
input(value) {
|
|
1312
|
+
if (!value || typeof value !== "object") throw new Error("Invalid registered query.");
|
|
1313
|
+
const query = value;
|
|
1314
|
+
if (typeof query.queryId !== "string" || !REGISTERED_QUERY_ID_PATTERN.test(query.queryId) || typeof query.limit !== "number" || !Number.isSafeInteger(query.limit) || query.limit < 1 || query.limit > 1e4 || query.params !== void 0 && !isQueryParameters(query.params)) throw new Error("Invalid registered query.");
|
|
1315
|
+
return {
|
|
1316
|
+
queryId: query.queryId,
|
|
1317
|
+
limit: query.limit,
|
|
1318
|
+
...query.params === void 0 ? {} : { params: query.params }
|
|
1319
|
+
};
|
|
1320
|
+
},
|
|
1321
|
+
output(value, input) {
|
|
1322
|
+
if (!value || typeof value !== "object") throw new Error("Invalid query result.");
|
|
1323
|
+
const result = value;
|
|
1324
|
+
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.");
|
|
1325
|
+
return {
|
|
1326
|
+
columns: result.columns,
|
|
1327
|
+
rows: result.rows,
|
|
1328
|
+
...result.queryId === void 0 ? {} : { queryId: result.queryId }
|
|
1329
|
+
};
|
|
1330
|
+
}
|
|
1331
|
+
});
|
|
1332
|
+
const dataAppRoutes = {
|
|
1333
|
+
"data:query": registeredQueryRoute,
|
|
1334
|
+
"navigation:update": navigationUpdateRoute
|
|
1335
|
+
};
|
|
1336
|
+
//#endregion
|
|
1337
|
+
//#region src/core/annotations.ts
|
|
1338
|
+
function object(value) {
|
|
1339
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid annotation.");
|
|
1340
|
+
return value;
|
|
1341
|
+
}
|
|
1342
|
+
function text(value, limit, required = false) {
|
|
1343
|
+
if (typeof value !== "string" || value.length > limit || required && !value.trim()) throw new Error("Invalid annotation text.");
|
|
1344
|
+
return value;
|
|
1345
|
+
}
|
|
1346
|
+
function names(value) {
|
|
1347
|
+
if (!Array.isArray(value) || value.length > 20) throw new Error("Invalid annotation references.");
|
|
1348
|
+
return value.map((name) => text(name, 128, true));
|
|
1349
|
+
}
|
|
1350
|
+
function number(value, positive = false) {
|
|
1351
|
+
if (typeof value !== "number" || !Number.isFinite(value) || Math.abs(value) > 1e6 || positive && value < 0) throw new Error("Invalid annotation geometry.");
|
|
1352
|
+
return value;
|
|
1353
|
+
}
|
|
1354
|
+
/** Reconstruct at the boundary; discard extra fields and bound the entire JSON payload. */
|
|
1355
|
+
function parseDataAppAnnotationDraft(value) {
|
|
1356
|
+
const input = object(value);
|
|
1357
|
+
const target = object(input.target);
|
|
1358
|
+
const context = object(input.context);
|
|
1359
|
+
const viewport = object(context.viewport);
|
|
1360
|
+
const rect = object(context.rect);
|
|
1361
|
+
if (target.kind !== "widget" && target.kind !== "element" && target.kind !== "app") throw new Error("Invalid annotation target.");
|
|
1362
|
+
let screenshot;
|
|
1363
|
+
if (context.screenshot !== void 0) {
|
|
1364
|
+
const image = object(context.screenshot);
|
|
1365
|
+
const dataUrl = text(image.dataUrl, 35e4, true);
|
|
1366
|
+
if (image.mimeType !== "image/png" || !/^data:image\/png;base64,iVBORw0KGgo[A-Za-z0-9+/]*={0,2}$/.test(dataUrl)) throw new Error("Invalid annotation screenshot.");
|
|
1367
|
+
const width = number(image.width, true);
|
|
1368
|
+
const height = number(image.height, true);
|
|
1369
|
+
if (!Number.isInteger(width) || !Number.isInteger(height) || width < 1 || height < 1 || width > 1024 || height > 1024) throw new Error("Invalid screenshot dimensions.");
|
|
1370
|
+
const encoded = dataUrl.slice(22);
|
|
1371
|
+
if (encoded.length % 4 !== 0 || encoded.length / 4 * 3 - (encoded.endsWith("==") ? 2 : encoded.endsWith("=") ? 1 : 0) > 262144) throw new Error("Screenshot is too large.");
|
|
1372
|
+
const header = atob(encoded.slice(0, 44));
|
|
1373
|
+
if (header.length < 24 || header.slice(12, 16) !== "IHDR") throw new Error("Invalid PNG header.");
|
|
1374
|
+
const bytes = Uint8Array.from(header, (character) => character.charCodeAt(0));
|
|
1375
|
+
const dimensions = new DataView(bytes.buffer);
|
|
1376
|
+
if (dimensions.getUint32(16) !== width || dimensions.getUint32(20) !== height) throw new Error("Screenshot dimensions do not match the image.");
|
|
1377
|
+
screenshot = {
|
|
1378
|
+
mimeType: "image/png",
|
|
1379
|
+
dataUrl,
|
|
1380
|
+
width,
|
|
1381
|
+
height
|
|
1382
|
+
};
|
|
1383
|
+
}
|
|
1384
|
+
let anchor;
|
|
1385
|
+
if (context.anchor !== void 0) {
|
|
1386
|
+
const point = object(context.anchor);
|
|
1387
|
+
const x = number(point.x, true);
|
|
1388
|
+
const y = number(point.y, true);
|
|
1389
|
+
if (x > 1 || y > 1) throw new Error("Invalid annotation anchor.");
|
|
1390
|
+
anchor = {
|
|
1391
|
+
x,
|
|
1392
|
+
y
|
|
1393
|
+
};
|
|
1394
|
+
}
|
|
1395
|
+
let cursor;
|
|
1396
|
+
if (context.cursor !== void 0) {
|
|
1397
|
+
const point = object(context.cursor);
|
|
1398
|
+
cursor = {
|
|
1399
|
+
x: number(point.x),
|
|
1400
|
+
y: number(point.y)
|
|
1401
|
+
};
|
|
1402
|
+
}
|
|
1403
|
+
let region;
|
|
1404
|
+
if (context.region !== void 0) {
|
|
1405
|
+
const area = object(context.region);
|
|
1406
|
+
region = {
|
|
1407
|
+
x: number(area.x, true),
|
|
1408
|
+
y: number(area.y, true),
|
|
1409
|
+
width: number(area.width, true),
|
|
1410
|
+
height: number(area.height, true)
|
|
1411
|
+
};
|
|
1412
|
+
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.");
|
|
1413
|
+
}
|
|
1414
|
+
const draft = {
|
|
1415
|
+
id: text(input.id, 128, true),
|
|
1416
|
+
target: {
|
|
1417
|
+
id: text(target.id, 128, true),
|
|
1418
|
+
label: text(target.label, 256, true),
|
|
1419
|
+
kind: target.kind,
|
|
1420
|
+
text: text(target.text, 1024),
|
|
1421
|
+
queryNames: names(target.queryNames),
|
|
1422
|
+
glossaryIds: names(target.glossaryIds)
|
|
1423
|
+
},
|
|
1424
|
+
context: {
|
|
1425
|
+
...anchor ? { anchor } : {},
|
|
1426
|
+
...region ? { region } : {},
|
|
1427
|
+
...cursor ? { cursor } : {},
|
|
1428
|
+
...screenshot ? { screenshot } : {},
|
|
1429
|
+
search: text(context.search, 2048),
|
|
1430
|
+
hash: text(context.hash, 1024),
|
|
1431
|
+
viewport: {
|
|
1432
|
+
width: number(viewport.width, true),
|
|
1433
|
+
height: number(viewport.height, true)
|
|
1434
|
+
},
|
|
1435
|
+
rect: {
|
|
1436
|
+
x: number(rect.x),
|
|
1437
|
+
y: number(rect.y),
|
|
1438
|
+
width: number(rect.width, true),
|
|
1439
|
+
height: number(rect.height, true)
|
|
1440
|
+
},
|
|
1441
|
+
...context.view === void 0 ? {} : { view: text(context.view, 128) },
|
|
1442
|
+
...context.displayedInput === void 0 ? {} : { displayedInput: context.displayedInput }
|
|
1443
|
+
},
|
|
1444
|
+
comment: text(input.comment, 2e3, true).trim()
|
|
1445
|
+
};
|
|
1446
|
+
const json = JSON.stringify({
|
|
1447
|
+
...draft,
|
|
1448
|
+
context: {
|
|
1449
|
+
...draft.context,
|
|
1450
|
+
screenshot: void 0
|
|
1451
|
+
}
|
|
1452
|
+
});
|
|
1453
|
+
if (new TextEncoder().encode(json).byteLength > 12e3) throw new Error("Annotation is too large.");
|
|
1454
|
+
return JSON.parse(JSON.stringify(draft));
|
|
1455
|
+
}
|
|
1456
|
+
const annotationDraftRoute = /* @__PURE__ */ defineMessageRoute({
|
|
1457
|
+
input: parseDataAppAnnotationDraft,
|
|
1458
|
+
output(value) {
|
|
1459
|
+
if (value !== null) throw new Error("Invalid annotation response.");
|
|
1460
|
+
return null;
|
|
1461
|
+
}
|
|
1462
|
+
});
|
|
1463
|
+
const annotationEditorStateRoute = /* @__PURE__ */ defineMessageRoute({
|
|
1464
|
+
input(value) {
|
|
1465
|
+
const input = object(value);
|
|
1466
|
+
if (typeof input.hasUnsavedChanges !== "boolean") throw new Error("Invalid annotation editor state.");
|
|
1467
|
+
return { hasUnsavedChanges: input.hasUnsavedChanges };
|
|
1468
|
+
},
|
|
1469
|
+
output(value) {
|
|
1470
|
+
if (value !== null) throw new Error("Invalid annotation response.");
|
|
1471
|
+
return null;
|
|
1472
|
+
}
|
|
1473
|
+
});
|
|
1474
|
+
/** Request host-owned batch submission without transferring ownership of drafts. */
|
|
1475
|
+
const annotationSendRoute = /* @__PURE__ */ defineMessageRoute({
|
|
1476
|
+
input(value) {
|
|
1477
|
+
if (value !== null) throw new Error("Invalid annotation send request.");
|
|
1478
|
+
return null;
|
|
1479
|
+
},
|
|
1480
|
+
output(value) {
|
|
1481
|
+
if (value !== null) throw new Error("Invalid annotation response.");
|
|
1482
|
+
return null;
|
|
1483
|
+
}
|
|
1484
|
+
});
|
|
1485
|
+
const annotationUpdateRoute = /* @__PURE__ */ defineMessageRoute({
|
|
1486
|
+
input(value) {
|
|
1487
|
+
const input = object(value);
|
|
1488
|
+
return {
|
|
1489
|
+
id: text(input.id, 128, true),
|
|
1490
|
+
comment: text(input.comment, 2e3, true).trim()
|
|
1491
|
+
};
|
|
1492
|
+
},
|
|
1493
|
+
output(value) {
|
|
1494
|
+
if (value !== null) throw new Error("Invalid annotation response.");
|
|
1495
|
+
return null;
|
|
1496
|
+
}
|
|
1497
|
+
});
|
|
1498
|
+
/** A controlled shell acknowledges local exits (for example Escape). */
|
|
1499
|
+
const annotationModeRoute = /* @__PURE__ */ defineMessageRoute({
|
|
1500
|
+
input(value) {
|
|
1501
|
+
const input = object(value);
|
|
1502
|
+
if (typeof input.active !== "boolean") throw new Error("Invalid annotation mode.");
|
|
1503
|
+
return { active: input.active };
|
|
1504
|
+
},
|
|
1505
|
+
output(value) {
|
|
1506
|
+
if (value !== null) throw new Error("Invalid annotation response.");
|
|
1507
|
+
return null;
|
|
1508
|
+
}
|
|
1509
|
+
});
|
|
1510
|
+
function isAnnotationPresentation(value) {
|
|
1511
|
+
if (!value || typeof value !== "object") return false;
|
|
1512
|
+
const input = value;
|
|
1513
|
+
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 || isRecord(input.dismissal) && 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 === "object" && target.anchor !== null && 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 || isRecord(target.region) && [
|
|
1514
|
+
"x",
|
|
1515
|
+
"y",
|
|
1516
|
+
"width",
|
|
1517
|
+
"height"
|
|
1518
|
+
].every((key) => {
|
|
1519
|
+
const value = target.region[key];
|
|
1520
|
+
return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= 1;
|
|
1521
|
+
}) && 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)));
|
|
1522
|
+
}
|
|
1523
|
+
//#endregion
|
|
1524
|
+
//#region src/core/external-link.ts
|
|
1525
|
+
/** Absolute HTTPS destinations only; URLs must not contain embedded credentials. */
|
|
1526
|
+
function parseExternalUrl(value) {
|
|
1527
|
+
if (typeof value !== "string" || value.length > 8192 || /[\s\\\p{Cc}\p{Cf}]/u.test(value)) throw new Error("Expected an absolute HTTPS URL.");
|
|
1528
|
+
const url = new URL(value);
|
|
1529
|
+
if (!/^https:\/\//i.test(value) || url.protocol !== "https:" || url.username || url.password) throw new Error("Expected an HTTPS URL without credentials.");
|
|
1530
|
+
return url.href;
|
|
1531
|
+
}
|
|
1532
|
+
/** Shift takes precedence over Ctrl/Cmd; an unmodified event requests no navigation. */
|
|
1533
|
+
function resolveExternalLinkTarget(input) {
|
|
1534
|
+
if (input.target !== "event") return input.target ?? "tab";
|
|
1535
|
+
return input.keys.shiftKey ? "window" : input.keys.metaKey || input.keys.ctrlKey ? "tab" : null;
|
|
1536
|
+
}
|
|
1537
|
+
/** Opt-in host route. Validation does not replace the host's destination policy. */
|
|
1538
|
+
const openExternalLinkRoute = /* @__PURE__ */ defineMessageRoute({
|
|
1539
|
+
input(value) {
|
|
1540
|
+
if (!value || typeof value !== "object") throw new Error("Invalid external link.");
|
|
1541
|
+
const input = value;
|
|
1542
|
+
const url = parseExternalUrl(input.url);
|
|
1543
|
+
if (input.target === void 0) return { url };
|
|
1544
|
+
if (input.target === "tab" || input.target === "window") return {
|
|
1545
|
+
url,
|
|
1546
|
+
target: input.target
|
|
1547
|
+
};
|
|
1548
|
+
if (input.target === "event" && isRecord(input.keys)) {
|
|
1549
|
+
const keys = input.keys;
|
|
1550
|
+
if (typeof keys.shiftKey === "boolean" && typeof keys.metaKey === "boolean" && typeof keys.ctrlKey === "boolean") return {
|
|
1551
|
+
url,
|
|
1552
|
+
target: "event",
|
|
1553
|
+
keys: {
|
|
1554
|
+
shiftKey: keys.shiftKey,
|
|
1555
|
+
metaKey: keys.metaKey,
|
|
1556
|
+
ctrlKey: keys.ctrlKey
|
|
1557
|
+
}
|
|
1558
|
+
};
|
|
1559
|
+
}
|
|
1560
|
+
throw new Error("Invalid external navigation target.");
|
|
1561
|
+
},
|
|
1562
|
+
output(value) {
|
|
1563
|
+
if (value !== "opened" && value !== "cancelled" && value !== "ignored") throw new Error("Invalid external link response.");
|
|
1564
|
+
return value;
|
|
1565
|
+
}
|
|
1566
|
+
});
|
|
1567
|
+
//#endregion
|
|
1568
|
+
//#region src/core/contract.ts
|
|
1569
|
+
const sourceErrorBrand = Symbol.for("@altertable/data-app/DataSourceError");
|
|
1570
|
+
var DataSourceError = class extends Error {
|
|
1571
|
+
reason;
|
|
1572
|
+
status;
|
|
1573
|
+
[sourceErrorBrand] = true;
|
|
1574
|
+
queryName;
|
|
1575
|
+
static [Symbol.hasInstance](value) {
|
|
1576
|
+
return value instanceof Error && value[sourceErrorBrand] === true;
|
|
1577
|
+
}
|
|
1578
|
+
constructor(reason, status, options) {
|
|
1579
|
+
super(`Data source ${reason}${status ? ` (${status})` : ""}.`, options);
|
|
1580
|
+
this.reason = reason;
|
|
1581
|
+
this.status = status;
|
|
1582
|
+
this.name = "DataSourceError";
|
|
1583
|
+
}
|
|
1584
|
+
};
|
|
1585
|
+
//#endregion
|
|
1586
|
+
export { snapshotQueries as $, resolvedDateTimeRangeParams as A, resolveFilterInput as B, parseCount as C, dateTimeRangePresets as D, dateTimeRangeFilter as E, numberOperatorLabels as F, searchFilter as G, defineAppFilters as H, parseBooleanSelection as I, bindDimensionSource as J, validateChoiceOptions as K, parseNumberSelection as L, facetSource as M, booleanFilter as N, queryDateTimeRangeParams as O, numberFilter as P, REGISTERED_QUERY_ID_PATTERN as Q, combineOperationFilters as R, defineQueryNames as S, parseTrue as T, displayChoice as U, choiceFilter as V, multiChoiceFilter as W, withDimensionSelectors as X, dimensionSource as Y, MAX_QUERY_ROWS as Z, navigationUpdateRoute as _, annotationDraftRoute as a, parseDimensionSelection as at, connectionCheck as b, annotationSendRoute as c, parseDataAppAnnotationDraft as d, unsupportedParameterReference as et, MessageRoutingError as f, defineMessageRoute as g, defineDataOperationRoute as h, resolveExternalLinkTarget as i, dimensionPredicate as it, facetFilter as j, dateTimeRangeSql as k, annotationUpdateRoute as l, dataAppRoutes as m, openExternalLinkRoute as n, dimensionFilter as nt, annotationEditorStateRoute as o, parseFacetOptions as ot, createMessageRouter as p, DimensionMembershipError as q, parseExternalUrl as r, dimensionMemberKey as rt, annotationModeRoute as s, KEY_SEPARATOR as st, DataSourceError as t, createDimensionFilter as tt, isAnnotationPresentation as u, registeredQueryRoute as v, parseLabel as w, defineOperation as x, validLocation as y, dateFilterName as z };
|
|
1587
|
+
|
|
1588
|
+
//# sourceMappingURL=contract-gu1rDsV0.js.map
|