@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.
- package/CONTRIBUTING.md +3 -0
- package/REFERENCE.md +45 -37
- 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-CnlTr1U1.js → date-time-range-value-D-XfqVTT.js} +21 -24
- package/dist/chunks/date-time-range-value-D-XfqVTT.js.map +1 -0
- package/dist/chunks/{diagnostics-Dyj-rUsY.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 -101
- 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 +63 -11
- package/dist/internal.js.map +1 -1
- package/dist/types/chunks/contract.d.ts +254 -19
- 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 -80
- package/dist/types/client/index.d.ts +4 -3
- package/dist/types/core/config.d.ts +10 -4
- 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 +25 -6
- package/docs/app-authoring.md +13 -9
- package/docs/client.md +14 -53
- package/docs/contract.md +35 -15
- package/docs/data-context.md +5 -2
- package/docs/diagnostics.md +16 -23
- package/docs/embed.md +60 -25
- package/docs/filters.md +33 -57
- package/docs/hosted-apps.md +9 -9
- package/docs/layout.md +21 -0
- 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 +4 -4
- package/docs/styling.md +2 -1
- package/docs/ui.md +12 -3
- package/docs/views.md +12 -11
- package/docs/widgets.md +3 -3
- package/docs/worker.md +1 -1
- package/package.json +1 -5
- package/dist/chunks/contract-BQsFReRp.js +0 -780
- package/dist/chunks/contract-BQsFReRp.js.map +0 -1
- package/dist/chunks/contract-VhY9V9wd.js +0 -806
- package/dist/chunks/contract-VhY9V9wd.js.map +0 -1
- package/dist/chunks/date-time-range-value-CnlTr1U1.js.map +0 -1
- package/dist/chunks/diagnostics-Dyj-rUsY.js.map +0 -1
- package/dist/chunks/operation-BVRM-A5Y.js +0 -134
- package/dist/chunks/operation-BVRM-A5Y.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 -221
- 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
|
@@ -1,134 +0,0 @@
|
|
|
1
|
-
import { g as DimensionMembershipError } from "./contract-BQsFReRp.js";
|
|
2
|
-
import { t as DataSourceError } from "./contract-VhY9V9wd.js";
|
|
3
|
-
//#region src/core/operation.ts
|
|
4
|
-
/** Shared operation execution. Adapters own authorization, delivery, and public errors. */
|
|
5
|
-
async function executeDataOperation(operation, value, { operationName, lakehouse, signal: requestSignal, requestId, queryParams, onQuery }) {
|
|
6
|
-
requestSignal.throwIfAborted();
|
|
7
|
-
let input;
|
|
8
|
-
try {
|
|
9
|
-
input = operation.input(value);
|
|
10
|
-
} catch {
|
|
11
|
-
throw new OperationInputError();
|
|
12
|
-
}
|
|
13
|
-
const signal = AbortSignal.any([requestSignal, AbortSignal.timeout(operation.policy.maxDurationMs)]);
|
|
14
|
-
const execution = createOperationLakehouse(operation, lakehouse, signal, operationName, onQuery);
|
|
15
|
-
try {
|
|
16
|
-
const body = {
|
|
17
|
-
data: await runOperation(operation, input, {
|
|
18
|
-
lakehouse: execution.lakehouse,
|
|
19
|
-
signal,
|
|
20
|
-
queryParams
|
|
21
|
-
}),
|
|
22
|
-
requestId,
|
|
23
|
-
queriedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
24
|
-
queryIds: execution.queryIds,
|
|
25
|
-
queries: execution.queries
|
|
26
|
-
};
|
|
27
|
-
const serializedBody = JSON.stringify(body);
|
|
28
|
-
if (new TextEncoder().encode(serializedBody).byteLength > (operation.policy.maxResponseBytes ?? 1e6)) throw new Error("Response exceeds byte limit.");
|
|
29
|
-
return {
|
|
30
|
-
body,
|
|
31
|
-
serializedBody
|
|
32
|
-
};
|
|
33
|
-
} catch (error) {
|
|
34
|
-
if (signal.aborted && !(error instanceof DataSourceError)) throw new OperationTimeoutError();
|
|
35
|
-
throw error;
|
|
36
|
-
}
|
|
37
|
-
}
|
|
38
|
-
/** Query evidence follows statement invocation order; query IDs retain completion order. */
|
|
39
|
-
function createOperationLakehouse(operation, source, signal, operationName, onQuery) {
|
|
40
|
-
const queryIds = [];
|
|
41
|
-
const queries = [];
|
|
42
|
-
return {
|
|
43
|
-
lakehouse: { async queryAll(statement, options) {
|
|
44
|
-
signal.throwIfAborted();
|
|
45
|
-
if (!Number.isInteger(options.limit) || options.limit < 1) throw new Error("Query needs a positive row limit.");
|
|
46
|
-
if (operation.queryNames && !Object.values(operation.queryNames).includes(options.name ?? "")) throw new Error(`Query name is not registered for operation ${operationName}.`);
|
|
47
|
-
const query = {
|
|
48
|
-
name: options.name ?? `Query ${queries.length + 1}`,
|
|
49
|
-
statement,
|
|
50
|
-
...options.params === void 0 ? {} : { params: options.params }
|
|
51
|
-
};
|
|
52
|
-
queries.push(query);
|
|
53
|
-
const limit = Math.min(options.limit, operation.policy.maxQueryRows);
|
|
54
|
-
const querySignal = AbortSignal.any([signal, options.signal]);
|
|
55
|
-
let result;
|
|
56
|
-
try {
|
|
57
|
-
result = await source.queryAll(statement, {
|
|
58
|
-
limit,
|
|
59
|
-
...options.params === void 0 ? {} : { params: options.params },
|
|
60
|
-
signal: querySignal
|
|
61
|
-
});
|
|
62
|
-
} catch (error) {
|
|
63
|
-
if (!querySignal.aborted) onQuery?.(query.name, error);
|
|
64
|
-
if (error instanceof DataSourceError) error.queryName = query.name;
|
|
65
|
-
throw error;
|
|
66
|
-
}
|
|
67
|
-
onQuery?.(query.name);
|
|
68
|
-
if (result.rows.length > limit) throw new Error("Result exceeds row limit.");
|
|
69
|
-
if (result.queryId) {
|
|
70
|
-
query.queryId = result.queryId;
|
|
71
|
-
queryIds.push(result.queryId);
|
|
72
|
-
}
|
|
73
|
-
return result;
|
|
74
|
-
} },
|
|
75
|
-
queries,
|
|
76
|
-
queryIds
|
|
77
|
-
};
|
|
78
|
-
}
|
|
79
|
-
/** Settle cancellation even when operation code or its lakehouse ignores the signal. */
|
|
80
|
-
async function runOperation(operation, input, { lakehouse, signal, queryParams }) {
|
|
81
|
-
let abort;
|
|
82
|
-
try {
|
|
83
|
-
signal.throwIfAborted();
|
|
84
|
-
const cancelled = new Promise((_, reject) => {
|
|
85
|
-
function rejectAborted() {
|
|
86
|
-
reject(/* @__PURE__ */ new Error("Request aborted."));
|
|
87
|
-
}
|
|
88
|
-
abort = rejectAborted;
|
|
89
|
-
signal.addEventListener("abort", rejectAborted, { once: true });
|
|
90
|
-
if (signal.aborted) rejectAborted();
|
|
91
|
-
});
|
|
92
|
-
return await Promise.race([cancelled, Promise.resolve().then(() => {
|
|
93
|
-
signal.throwIfAborted();
|
|
94
|
-
return operation.run({
|
|
95
|
-
lakehouse,
|
|
96
|
-
signal,
|
|
97
|
-
queryParams
|
|
98
|
-
}, input);
|
|
99
|
-
})]);
|
|
100
|
-
} finally {
|
|
101
|
-
if (abort) signal.removeEventListener("abort", abort);
|
|
102
|
-
}
|
|
103
|
-
}
|
|
104
|
-
var OperationTimeoutError = class extends Error {};
|
|
105
|
-
var OperationInputError = class extends Error {};
|
|
106
|
-
const sourceErrorMessages = {
|
|
107
|
-
unauthorized: "This app could not authenticate its data connection. Contact the app owner.",
|
|
108
|
-
forbidden: "This app cannot access the requested data. Contact the app owner.",
|
|
109
|
-
rate_limited: "The lakehouse is busy. Wait a moment and retry.",
|
|
110
|
-
query_rejected: "A lakehouse query was rejected. Check the app's data operation.",
|
|
111
|
-
unavailable: "The lakehouse is unavailable. Check the connection and retry."
|
|
112
|
-
};
|
|
113
|
-
function toDataOperationFailure(error, aborted = false) {
|
|
114
|
-
if (error instanceof OperationInputError || error instanceof DimensionMembershipError) return {
|
|
115
|
-
status: 400,
|
|
116
|
-
code: "invalid_input",
|
|
117
|
-
message: "Check this operation's inputs."
|
|
118
|
-
};
|
|
119
|
-
if (error instanceof DataSourceError) return {
|
|
120
|
-
status: error.reason === "rate_limited" ? 429 : 502,
|
|
121
|
-
code: `source_${error.reason}`,
|
|
122
|
-
message: sourceErrorMessages[error.reason]
|
|
123
|
-
};
|
|
124
|
-
const timedOut = aborted || error instanceof OperationTimeoutError;
|
|
125
|
-
return {
|
|
126
|
-
status: timedOut ? 504 : 502,
|
|
127
|
-
code: timedOut ? "timeout" : "query_failed",
|
|
128
|
-
message: timedOut ? "The data request timed out." : "The data request failed."
|
|
129
|
-
};
|
|
130
|
-
}
|
|
131
|
-
//#endregion
|
|
132
|
-
export { toDataOperationFailure as n, executeDataOperation as t };
|
|
133
|
-
|
|
134
|
-
//# sourceMappingURL=operation-BVRM-A5Y.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"operation-BVRM-A5Y.js","names":[],"sources":["../../src/core/operation.ts"],"sourcesContent":["import { DataSourceError } from './contract.ts';\nimport { DimensionMembershipError } from './dimension-source.ts';\nimport type {\n DataOperations,\n DisclosedQuery,\n Lakehouse,\n OperationContext,\n DataQueryBody,\n} from './operation-types.ts';\n\ntype Operation = DataOperations[string];\ntype OperationExecutionOptions = {\n operationName: string;\n lakehouse: Lakehouse;\n signal: AbortSignal;\n requestId: string;\n queryParams?: OperationContext['queryParams'];\n onQuery?: (name: string, error?: unknown) => void;\n};\n\n/** Shared operation execution. Adapters own authorization, delivery, and public errors. */\nexport async function executeDataOperation(\n operation: Operation,\n value: unknown,\n {\n operationName,\n lakehouse,\n signal: requestSignal,\n requestId,\n queryParams,\n onQuery,\n }: OperationExecutionOptions\n) {\n requestSignal.throwIfAborted();\n let input: unknown;\n try {\n input = operation.input(value);\n } catch {\n throw new OperationInputError();\n }\n\n const signal = AbortSignal.any([\n requestSignal,\n AbortSignal.timeout(operation.policy.maxDurationMs),\n ]);\n const execution = createOperationLakehouse(\n operation,\n lakehouse,\n signal,\n operationName,\n onQuery\n );\n try {\n const output = await runOperation(operation, input, {\n lakehouse: execution.lakehouse,\n signal,\n queryParams,\n });\n const body: DataQueryBody<unknown> = {\n data: output,\n requestId,\n queriedAt: new Date().toISOString(),\n queryIds: execution.queryIds,\n queries: execution.queries,\n };\n const serializedBody = JSON.stringify(body);\n const responseBytes = new TextEncoder().encode(serializedBody).byteLength;\n if (responseBytes > (operation.policy.maxResponseBytes ?? 1_000_000))\n throw new Error('Response exceeds byte limit.');\n\n return { body, serializedBody };\n } catch (error) {\n if (signal.aborted && !(error instanceof DataSourceError))\n throw new OperationTimeoutError();\n throw error;\n }\n}\n\n/** Query evidence follows statement invocation order; query IDs retain completion order. */\nfunction createOperationLakehouse(\n operation: Operation,\n source: Lakehouse,\n signal: AbortSignal,\n operationName: string,\n onQuery?: (name: string, error?: unknown) => void\n) {\n const queryIds: string[] = [];\n const queries: DisclosedQuery[] = [];\n const lakehouse: Lakehouse = {\n async queryAll(statement, options) {\n signal.throwIfAborted();\n if (!Number.isInteger(options.limit) || options.limit < 1)\n throw new Error('Query needs a positive row limit.');\n if (\n operation.queryNames &&\n !Object.values(operation.queryNames).includes(options.name ?? '')\n )\n throw new Error(\n `Query name is not registered for operation ${operationName}.`\n );\n const query: DisclosedQuery = {\n name: options.name ?? `Query ${queries.length + 1}`,\n statement,\n ...(options.params === undefined ? {} : { params: options.params }),\n };\n queries.push(query);\n const limit = Math.min(options.limit, operation.policy.maxQueryRows);\n const querySignal = AbortSignal.any([signal, options.signal]);\n let result;\n try {\n result = await source.queryAll(statement, {\n limit,\n ...(options.params === undefined ? {} : { params: options.params }),\n signal: querySignal,\n });\n } catch (error) {\n if (!querySignal.aborted) onQuery?.(query.name, error);\n if (error instanceof DataSourceError) error.queryName = query.name;\n throw error;\n }\n onQuery?.(query.name);\n if (result.rows.length > limit)\n throw new Error('Result exceeds row limit.');\n if (result.queryId) {\n query.queryId = result.queryId;\n queryIds.push(result.queryId);\n }\n\n return result;\n },\n };\n\n return { lakehouse, queries, queryIds };\n}\n\n/** Settle cancellation even when operation code or its lakehouse ignores the signal. */\nasync function runOperation(\n operation: Operation,\n input: unknown,\n { lakehouse, signal, queryParams }: OperationContext\n) {\n let abort: (() => void) | undefined;\n try {\n signal.throwIfAborted();\n const cancelled = new Promise<never>((_, reject) => {\n function rejectAborted() {\n reject(new Error('Request aborted.'));\n }\n abort = rejectAborted;\n signal.addEventListener('abort', rejectAborted, { once: true });\n if (signal.aborted) rejectAborted();\n });\n\n return await Promise.race([\n cancelled,\n Promise.resolve().then(() => {\n signal.throwIfAborted();\n\n return operation.run(\n { lakehouse, signal, queryParams },\n input as never\n );\n }),\n ]);\n } finally {\n if (abort) signal.removeEventListener('abort', abort);\n }\n}\n\nclass OperationTimeoutError extends Error {}\n\nclass OperationInputError extends Error {}\n\nconst sourceErrorMessages = {\n unauthorized:\n 'This app could not authenticate its data connection. Contact the app owner.',\n forbidden:\n 'This app cannot access the requested data. Contact the app owner.',\n rate_limited: 'The lakehouse is busy. Wait a moment and retry.',\n query_rejected:\n \"A lakehouse query was rejected. Check the app's data operation.\",\n unavailable: 'The lakehouse is unavailable. Check the connection and retry.',\n};\n\nexport function toDataOperationFailure(error: unknown, aborted = false) {\n if (\n error instanceof OperationInputError ||\n error instanceof DimensionMembershipError\n )\n return {\n status: 400,\n code: 'invalid_input',\n message: \"Check this operation's inputs.\",\n };\n if (error instanceof DataSourceError)\n return {\n status: error.reason === 'rate_limited' ? 429 : 502,\n code: `source_${error.reason}`,\n message: sourceErrorMessages[error.reason],\n };\n const timedOut = aborted || error instanceof OperationTimeoutError;\n return {\n status: timedOut ? 504 : 502,\n code: timedOut ? 'timeout' : 'query_failed',\n message: timedOut\n ? 'The data request timed out.'\n : 'The data request failed.',\n };\n}\n"],"mappings":";;;;AAqBA,eAAsB,qBACpB,WACA,OACA,EACE,eACA,WACA,QAAQ,eACR,WACA,aACA,WAEF;CACA,cAAc,eAAe;CAC7B,IAAI;CACJ,IAAI;EACF,QAAQ,UAAU,MAAM,KAAK;CAC/B,QAAQ;EACN,MAAM,IAAI,oBAAoB;CAChC;CAEA,MAAM,SAAS,YAAY,IAAI,CAC7B,eACA,YAAY,QAAQ,UAAU,OAAO,aAAa,CACpD,CAAC;CACD,MAAM,YAAY,yBAChB,WACA,WACA,QACA,eACA,OACF;CACA,IAAI;EAMF,MAAM,OAA+B;GACnC,MAAM,MANa,aAAa,WAAW,OAAO;IAClD,WAAW,UAAU;IACrB;IACA;GACF,CAAC;GAGC;GACA,4BAAW,IAAI,KAAK,EAAA,CAAE,YAAY;GAClC,UAAU,UAAU;GACpB,SAAS,UAAU;EACrB;EACA,MAAM,iBAAiB,KAAK,UAAU,IAAI;EAE1C,IADsB,IAAI,YAAY,CAAC,CAAC,OAAO,cAAc,CAAC,CAAC,cAC1C,UAAU,OAAO,oBAAoB,MACxD,MAAM,IAAI,MAAM,8BAA8B;EAEhD,OAAO;GAAE;GAAM;EAAe;CAChC,SAAS,OAAO;EACd,IAAI,OAAO,WAAW,EAAE,iBAAiB,kBACvC,MAAM,IAAI,sBAAsB;EAClC,MAAM;CACR;AACF;;AAGA,SAAS,yBACP,WAC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,WAAW,QAAQ,eACrB;CACA,IAAI;CACJ,IAAI;EACF,OAAO,eAAe;EACtB,MAAM,YAAY,IAAI,SAAgB,GAAG,WAAW;GAClD,SAAS,gBAAgB;IACvB,uBAAO,IAAI,MAAM,kBAAkB,CAAC;GACtC;GACA,QAAQ;GACR,OAAO,iBAAiB,SAAS,eAAe,EAAE,MAAM,KAAK,CAAC;GAC9D,IAAI,OAAO,SAAS,cAAc;EACpC,CAAC;EAED,OAAO,MAAM,QAAQ,KAAK,CACxB,WACA,QAAQ,QAAQ,CAAC,CAAC,WAAW;GAC3B,OAAO,eAAe;GAEtB,OAAO,UAAU,IACf;IAAE;IAAW;IAAQ;GAAY,GACjC,KACF;EACF,CAAC,CACH,CAAC;CACH,UAAU;EACR,IAAI,OAAO,OAAO,oBAAoB,SAAS,KAAK;CACtD;AACF;AAEA,IAAM,wBAAN,cAAoC,MAAM,CAAC;AAE3C,IAAM,sBAAN,cAAkC,MAAM,CAAC;AAEzC,MAAM,sBAAsB;CAC1B,cACE;CACF,WACE;CACF,cAAc;CACd,gBACE;CACF,aAAa;AACf;AAEA,SAAgB,uBAAuB,OAAgB,UAAU,OAAO;CACtE,IACE,iBAAiB,uBACjB,iBAAiB,0BAEjB,OAAO;EACL,QAAQ;EACR,MAAM;EACN,SAAS;CACX;CACF,IAAI,iBAAiB,iBACnB,OAAO;EACL,QAAQ,MAAM,WAAW,iBAAiB,MAAM;EAChD,MAAM,UAAU,MAAM;EACtB,SAAS,oBAAoB,MAAM;CACrC;CACF,MAAM,WAAW,WAAW,iBAAiB;CAC7C,OAAO;EACL,QAAQ,WAAW,MAAM;EACzB,MAAM,WAAW,YAAY;EAC7B,SAAS,WACL,gCACA;CACN;AACF"}
|
|
@@ -1,50 +0,0 @@
|
|
|
1
|
-
//#region src/server/request-body.ts
|
|
2
|
-
var RequestBodyTooLargeError = class extends Error {};
|
|
3
|
-
/** Count encoded bytes before retaining chunks; cancellation also interrupts waiting reads. */
|
|
4
|
-
async function readRequestBody(request, maxBytes) {
|
|
5
|
-
const body = request.body;
|
|
6
|
-
if (!body) return "";
|
|
7
|
-
const reader = body.getReader();
|
|
8
|
-
const chunks = [];
|
|
9
|
-
let size = 0;
|
|
10
|
-
let abort;
|
|
11
|
-
function cancelReader() {
|
|
12
|
-
reader.cancel().catch(() => {});
|
|
13
|
-
}
|
|
14
|
-
try {
|
|
15
|
-
request.signal.throwIfAborted();
|
|
16
|
-
const cancelled = new Promise((_, reject) => {
|
|
17
|
-
function rejectAborted() {
|
|
18
|
-
reject(/* @__PURE__ */ new Error("Request aborted."));
|
|
19
|
-
cancelReader();
|
|
20
|
-
}
|
|
21
|
-
abort = rejectAborted;
|
|
22
|
-
request.signal.addEventListener("abort", rejectAborted, { once: true });
|
|
23
|
-
if (request.signal.aborted) rejectAborted();
|
|
24
|
-
});
|
|
25
|
-
while (true) {
|
|
26
|
-
const { done, value } = await Promise.race([reader.read(), cancelled]);
|
|
27
|
-
if (done) break;
|
|
28
|
-
size += value.byteLength;
|
|
29
|
-
if (size > maxBytes) {
|
|
30
|
-
cancelReader();
|
|
31
|
-
throw new RequestBodyTooLargeError();
|
|
32
|
-
}
|
|
33
|
-
chunks.push(value);
|
|
34
|
-
}
|
|
35
|
-
const bytes = new Uint8Array(size);
|
|
36
|
-
let offset = 0;
|
|
37
|
-
for (const chunk of chunks) {
|
|
38
|
-
bytes.set(chunk, offset);
|
|
39
|
-
offset += chunk.byteLength;
|
|
40
|
-
}
|
|
41
|
-
return new TextDecoder().decode(bytes);
|
|
42
|
-
} finally {
|
|
43
|
-
if (abort) request.signal.removeEventListener("abort", abort);
|
|
44
|
-
reader.releaseLock();
|
|
45
|
-
}
|
|
46
|
-
}
|
|
47
|
-
//#endregion
|
|
48
|
-
export { readRequestBody as n, RequestBodyTooLargeError as t };
|
|
49
|
-
|
|
50
|
-
//# sourceMappingURL=request-body-H1qPmmTN.js.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"request-body-H1qPmmTN.js","names":[],"sources":["../../src/server/request-body.ts"],"sourcesContent":["export class RequestBodyTooLargeError extends Error {}\n\n/** Count encoded bytes before retaining chunks; cancellation also interrupts waiting reads. */\nexport async function readRequestBody(\n request: Request,\n maxBytes: number\n): Promise<string> {\n const body = request.body;\n if (!body) return '';\n const reader = body.getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n let abort: (() => void) | undefined;\n\n function cancelReader() {\n // The source's cancel algorithm may never settle; the handler must still respond.\n void reader.cancel().catch(() => {});\n }\n\n try {\n request.signal.throwIfAborted();\n const cancelled = new Promise<never>((_, reject) => {\n function rejectAborted() {\n reject(new Error('Request aborted.'));\n cancelReader();\n }\n abort = rejectAborted;\n request.signal.addEventListener('abort', rejectAborted, { once: true });\n if (request.signal.aborted) rejectAborted();\n });\n while (true) {\n const { done, value } = await Promise.race([reader.read(), cancelled]);\n if (done) break;\n size += value.byteLength;\n if (size > maxBytes) {\n cancelReader();\n throw new RequestBodyTooLargeError();\n }\n chunks.push(value);\n }\n const bytes = new Uint8Array(size);\n let offset = 0;\n for (const chunk of chunks) {\n bytes.set(chunk, offset);\n offset += chunk.byteLength;\n }\n\n return new TextDecoder().decode(bytes);\n } finally {\n if (abort) request.signal.removeEventListener('abort', abort);\n reader.releaseLock();\n }\n}\n"],"mappings":";AAAA,IAAa,2BAAb,cAA8C,MAAM,CAAC;;AAGrD,eAAsB,gBACpB,SACA,UACiB;CACjB,MAAM,OAAO,QAAQ;CACrB,IAAI,CAAC,MAAM,OAAO;CAClB,MAAM,SAAS,KAAK,UAAU;CAC9B,MAAM,SAAuB,CAAC;CAC9B,IAAI,OAAO;CACX,IAAI;CAEJ,SAAS,eAAe;EAEtB,OAAY,OAAO,CAAC,CAAC,YAAY,CAAC,CAAC;CACrC;CAEA,IAAI;EACF,QAAQ,OAAO,eAAe;EAC9B,MAAM,YAAY,IAAI,SAAgB,GAAG,WAAW;GAClD,SAAS,gBAAgB;IACvB,uBAAO,IAAI,MAAM,kBAAkB,CAAC;IACpC,aAAa;GACf;GACA,QAAQ;GACR,QAAQ,OAAO,iBAAiB,SAAS,eAAe,EAAE,MAAM,KAAK,CAAC;GACtE,IAAI,QAAQ,OAAO,SAAS,cAAc;EAC5C,CAAC;EACD,OAAO,MAAM;GACX,MAAM,EAAE,MAAM,UAAU,MAAM,QAAQ,KAAK,CAAC,OAAO,KAAK,GAAG,SAAS,CAAC;GACrE,IAAI,MAAM;GACV,QAAQ,MAAM;GACd,IAAI,OAAO,UAAU;IACnB,aAAa;IACb,MAAM,IAAI,yBAAyB;GACrC;GACA,OAAO,KAAK,KAAK;EACnB;EACA,MAAM,QAAQ,IAAI,WAAW,IAAI;EACjC,IAAI,SAAS;EACb,KAAK,MAAM,SAAS,QAAQ;GAC1B,MAAM,IAAI,OAAO,MAAM;GACvB,UAAU,MAAM;EAClB;EAEA,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK;CACvC,UAAU;EACR,IAAI,OAAO,QAAQ,OAAO,oBAAoB,SAAS,KAAK;EAC5D,OAAO,YAAY;CACrB;AACF"}
|
package/dist/server/index.js
DELETED
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
import { y as withDimensionSelectors } from "../chunks/contract-BQsFReRp.js";
|
|
2
|
-
import { t as DataSourceError } from "../chunks/contract-VhY9V9wd.js";
|
|
3
|
-
import { n as toDataOperationFailure, t as executeDataOperation } from "../chunks/operation-BVRM-A5Y.js";
|
|
4
|
-
import { n as readRequestBody, t as RequestBodyTooLargeError } from "../chunks/request-body-H1qPmmTN.js";
|
|
5
|
-
//#region src/server/handler.ts
|
|
6
|
-
/**
|
|
7
|
-
* Execute named operations on the server. The app supplies operations and viewer authorization.
|
|
8
|
-
* JSON, Origin, and Fetch Metadata checks reject cross-site browser POSTs; they do not
|
|
9
|
-
* authenticate another local process. Query evidence accompanies every result.
|
|
10
|
-
*/
|
|
11
|
-
function createDataHandler(operations, authorize) {
|
|
12
|
-
operations = withDimensionSelectors(operations);
|
|
13
|
-
async function handleDataRequest(request) {
|
|
14
|
-
const requestId = crypto.randomUUID();
|
|
15
|
-
const url = new URL(request.url);
|
|
16
|
-
if (!url.pathname.startsWith("/api/data/")) return new Response("Not found", { status: 404 });
|
|
17
|
-
const encodedName = url.pathname.slice(10);
|
|
18
|
-
if (!encodedName || encodedName.includes("/")) return problem(404, "not_found", "Unknown data operation.", requestId);
|
|
19
|
-
let name;
|
|
20
|
-
try {
|
|
21
|
-
name = decodeURIComponent(encodedName);
|
|
22
|
-
} catch {
|
|
23
|
-
return problem(404, "not_found", "Unknown data operation.", requestId);
|
|
24
|
-
}
|
|
25
|
-
if (!Object.hasOwn(operations, name)) return problem(404, "not_found", "Unknown data operation.", requestId);
|
|
26
|
-
if (request.method !== "POST") return problem(405, "method_not_allowed", "Use POST.", requestId);
|
|
27
|
-
if (request.headers.get("content-type")?.split(";")[0]?.trim().toLowerCase() !== "application/json") return problem(415, "unsupported_media_type", "Use application/json.", requestId);
|
|
28
|
-
const origin = request.headers.get("origin");
|
|
29
|
-
const fetchSite = request.headers.get("sec-fetch-site");
|
|
30
|
-
const fetchMode = request.headers.get("sec-fetch-mode");
|
|
31
|
-
if (origin !== null && origin !== url.origin || fetchSite !== null && fetchSite !== "same-origin" || fetchSite !== null && origin === null || fetchMode !== null && fetchMode !== "cors" && fetchMode !== "same-origin") return problem(403, "cross_origin_request", "The data request must come from this app.", requestId);
|
|
32
|
-
let access;
|
|
33
|
-
try {
|
|
34
|
-
access = await authorize(request, name);
|
|
35
|
-
} catch {
|
|
36
|
-
return problem(403, "forbidden", "You cannot run this data operation.", requestId);
|
|
37
|
-
}
|
|
38
|
-
const operation = operations[name];
|
|
39
|
-
let input;
|
|
40
|
-
if (request.signal.aborted) return problem(504, "timeout", "The data request timed out.", requestId);
|
|
41
|
-
try {
|
|
42
|
-
const body = await readRequestBody(request, MAX_INPUT_BYTES);
|
|
43
|
-
input = JSON.parse(body);
|
|
44
|
-
} catch (error) {
|
|
45
|
-
if (error instanceof RequestBodyTooLargeError) return problem(413, "input_too_large", "Input is too large.", requestId);
|
|
46
|
-
return problem(400, "invalid_input", "Check this operation's inputs.", requestId);
|
|
47
|
-
}
|
|
48
|
-
const signal = request.signal;
|
|
49
|
-
try {
|
|
50
|
-
const { serializedBody } = await executeDataOperation(operation, input, {
|
|
51
|
-
lakehouse: access.lakehouse,
|
|
52
|
-
signal,
|
|
53
|
-
requestId,
|
|
54
|
-
operationName: name,
|
|
55
|
-
queryParams: access.queryParams
|
|
56
|
-
});
|
|
57
|
-
return new Response(serializedBody, { headers: {
|
|
58
|
-
"cache-control": "no-store",
|
|
59
|
-
"content-type": "application/json"
|
|
60
|
-
} });
|
|
61
|
-
} catch (error) {
|
|
62
|
-
let detail = error instanceof Error ? error.name : "unknown";
|
|
63
|
-
if (error instanceof DataSourceError) {
|
|
64
|
-
detail = error.reason;
|
|
65
|
-
if (error.status) detail += ` (${error.status})`;
|
|
66
|
-
if (error.queryName) detail += ` in ${error.queryName}`;
|
|
67
|
-
if (error.cause instanceof Error && error.cause.message) detail += `: ${error.cause.message}`;
|
|
68
|
-
}
|
|
69
|
-
console.error(`Data operation ${name} failed (${requestId}): ${detail}`);
|
|
70
|
-
const failure = toDataOperationFailure(error, signal.aborted);
|
|
71
|
-
return problem(failure.status, failure.code, failure.message, requestId);
|
|
72
|
-
}
|
|
73
|
-
}
|
|
74
|
-
return handleDataRequest;
|
|
75
|
-
}
|
|
76
|
-
function problem(status, code, message, requestId) {
|
|
77
|
-
return Response.json({ error: {
|
|
78
|
-
code,
|
|
79
|
-
message,
|
|
80
|
-
requestId
|
|
81
|
-
} }, {
|
|
82
|
-
status,
|
|
83
|
-
headers: { "cache-control": "no-store" }
|
|
84
|
-
});
|
|
85
|
-
}
|
|
86
|
-
const MAX_INPUT_BYTES = 16384;
|
|
87
|
-
//#endregion
|
|
88
|
-
export { createDataHandler };
|
|
89
|
-
|
|
90
|
-
//# sourceMappingURL=index.js.map
|
package/dist/server/index.js.map
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","names":[],"sources":["../../src/server/handler.ts"],"sourcesContent":["import {\n DataSourceError,\n type DataOperations,\n type Lakehouse,\n type QueryParameters,\n} from '../core/contract.ts';\nimport { withDimensionSelectors } from '../core/dimension-source.ts';\nimport {\n executeDataOperation,\n toDataOperationFailure,\n} from '../core/operation.ts';\nimport { readRequestBody, RequestBodyTooLargeError } from './request-body.ts';\n\n/** Authorization result for one viewer request. A hosted adapter must scope its lakehouse client. */\nexport type RequestAccess = {\n lakehouse: Lakehouse;\n /** Trusted values shared across queries; each query uses only its declared keys. Datetime ranges use serializeDateTimeRange(); they are decoded and validated before SQL binding. */\n queryParams?: QueryParameters;\n};\n\n/**\n * Execute named operations on the server. The app supplies operations and viewer authorization.\n * JSON, Origin, and Fetch Metadata checks reject cross-site browser POSTs; they do not\n * authenticate another local process. Query evidence accompanies every result.\n */\nexport function createDataHandler(\n operations: DataOperations,\n authorize: (request: Request, operation: string) => Promise<RequestAccess>\n) {\n operations = withDimensionSelectors(operations);\n async function handleDataRequest(request: Request): Promise<Response> {\n const requestId = crypto.randomUUID();\n const url = new URL(request.url);\n if (!url.pathname.startsWith('/api/data/'))\n return new Response('Not found', { status: 404 });\n const encodedName = url.pathname.slice('/api/data/'.length);\n if (!encodedName || encodedName.includes('/'))\n return problem(404, 'not_found', 'Unknown data operation.', requestId);\n let name: string;\n try {\n name = decodeURIComponent(encodedName);\n } catch {\n return problem(404, 'not_found', 'Unknown data operation.', requestId);\n }\n if (!Object.hasOwn(operations, name))\n return problem(404, 'not_found', 'Unknown data operation.', requestId);\n if (request.method !== 'POST')\n return problem(405, 'method_not_allowed', 'Use POST.', requestId);\n if (\n request.headers\n .get('content-type')\n ?.split(';')[0]\n ?.trim()\n .toLowerCase() !== 'application/json'\n )\n return problem(\n 415,\n 'unsupported_media_type',\n 'Use application/json.',\n requestId\n );\n const origin = request.headers.get('origin');\n const fetchSite = request.headers.get('sec-fetch-site');\n const fetchMode = request.headers.get('sec-fetch-mode');\n if (\n (origin !== null && origin !== url.origin) ||\n (fetchSite !== null && fetchSite !== 'same-origin') ||\n (fetchSite !== null && origin === null) ||\n (fetchMode !== null &&\n fetchMode !== 'cors' &&\n fetchMode !== 'same-origin')\n )\n return problem(\n 403,\n 'cross_origin_request',\n 'The data request must come from this app.',\n requestId\n );\n let access: RequestAccess;\n try {\n access = await authorize(request, name);\n } catch {\n return problem(\n 403,\n 'forbidden',\n 'You cannot run this data operation.',\n requestId\n );\n }\n const operation = operations[name]!;\n let input: unknown;\n if (request.signal.aborted)\n return problem(504, 'timeout', 'The data request timed out.', requestId);\n try {\n const body = await readRequestBody(request, MAX_INPUT_BYTES);\n input = JSON.parse(body);\n } catch (error) {\n if (error instanceof RequestBodyTooLargeError)\n return problem(\n 413,\n 'input_too_large',\n 'Input is too large.',\n requestId\n );\n\n return problem(\n 400,\n 'invalid_input',\n \"Check this operation's inputs.\",\n requestId\n );\n }\n const signal = request.signal;\n try {\n const { serializedBody } = await executeDataOperation(operation, input, {\n lakehouse: access.lakehouse,\n signal,\n requestId,\n operationName: name,\n queryParams: access.queryParams,\n });\n return new Response(serializedBody, {\n headers: {\n 'cache-control': 'no-store',\n 'content-type': 'application/json',\n },\n });\n } catch (error) {\n let detail = error instanceof Error ? error.name : 'unknown';\n if (error instanceof DataSourceError) {\n detail = error.reason;\n if (error.status) detail += ` (${error.status})`;\n if (error.queryName) detail += ` in ${error.queryName}`;\n if (error.cause instanceof Error && error.cause.message)\n detail += `: ${error.cause.message}`;\n }\n console.error(`Data operation ${name} failed (${requestId}): ${detail}`);\n const failure = toDataOperationFailure(error, signal.aborted);\n\n return problem(failure.status, failure.code, failure.message, requestId);\n }\n }\n\n return handleDataRequest;\n}\n\nfunction problem(\n status: number,\n code: string,\n message: string,\n requestId: string\n): Response {\n return Response.json(\n { error: { code, message, requestId } },\n { status, headers: { 'cache-control': 'no-store' } }\n );\n}\n\nconst MAX_INPUT_BYTES = 16_384;\n"],"mappings":";;;;;;;;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221 +0,0 @@
|
|
|
1
|
-
import { n as DateTimeRange } from "./date-time-range.js";
|
|
2
|
-
import { $ as DataQueryInput, Ct as DimensionFilterSettings, F as NavigationUpdate, Ft as FacetFilter, Ot as DimensionValue, Q as DataQueryBody, at as OutputOf, gt as QueryParameters, it as OperationContracts, ot as QueryResult, st as TransportResponse } from "./contract.js";
|
|
3
|
-
//#region src/core/facet-filter.d.ts
|
|
4
|
-
type FacetFilterOptions<Value extends DimensionValue, Operation extends string> = DimensionFilterSettings<Value> & {
|
|
5
|
-
/** The registered operation that returns this dimension's options. */
|
|
6
|
-
options: Operation;
|
|
7
|
-
};
|
|
8
|
-
/** Options load from `options`, an operation returning `DimensionOption[]`; the
|
|
9
|
-
* client checks that it is registered. Validate selections like any dimension. */
|
|
10
|
-
declare function facetFilter<const Operation extends string>(config: FacetFilterOptions<string, Operation> & {
|
|
11
|
-
valueType: 'string';
|
|
12
|
-
}): FacetFilter<string, Operation>;
|
|
13
|
-
declare function facetFilter<const Operation extends string>(config: FacetFilterOptions<number, Operation> & {
|
|
14
|
-
valueType: 'number';
|
|
15
|
-
}): FacetFilter<number, Operation>;
|
|
16
|
-
//#endregion
|
|
17
|
-
//#region src/core/date-time-range-sql.d.ts
|
|
18
|
-
/** DuckDB timestamp expressions using the query session's timezone for relative anchors.
|
|
19
|
-
* Absolute fields remain UTC-rebased TIMESTAMP values. Start is inclusive, end exclusive.
|
|
20
|
-
*/
|
|
21
|
-
declare function dateTimeRangeSql(range: DateTimeRange, parameter?: string): {
|
|
22
|
-
from: string;
|
|
23
|
-
to: string;
|
|
24
|
-
params: Record<string, string>;
|
|
25
|
-
};
|
|
26
|
-
//#endregion
|
|
27
|
-
//#region src/core/messages.d.ts
|
|
28
|
-
type MessageContext = {
|
|
29
|
-
signal: AbortSignal;
|
|
30
|
-
};
|
|
31
|
-
type RoutedMessage = {
|
|
32
|
-
route: string;
|
|
33
|
-
payload: unknown;
|
|
34
|
-
};
|
|
35
|
-
type MessageDispatcher = (message: unknown, context: MessageContext) => Promise<unknown>;
|
|
36
|
-
type MessageTransport = (message: RoutedMessage, signal?: AbortSignal) => Promise<unknown>;
|
|
37
|
-
type MessageRoute<Input, Output> = {
|
|
38
|
-
input: (value: unknown) => Input;
|
|
39
|
-
output: (value: unknown, input: Input) => Output;
|
|
40
|
-
};
|
|
41
|
-
type MessageRoutes = Record<string, {
|
|
42
|
-
input: (value: unknown) => unknown;
|
|
43
|
-
output: (value: unknown, input: never) => unknown;
|
|
44
|
-
}>;
|
|
45
|
-
type MessageInput<Route extends MessageRoutes[string]> = ReturnType<Route['input']>;
|
|
46
|
-
type MessageHandlers<Routes extends MessageRoutes> = { [Name in keyof Routes]: (payload: MessageInput<Routes[Name]>, context: MessageContext) => ReturnType<Routes[Name]['output']> | Promise<ReturnType<Routes[Name]['output']>>; };
|
|
47
|
-
declare const errorBrand: unique symbol;
|
|
48
|
-
/** Only these deliberate, public failures cross the message boundary. Other errors stay private. */
|
|
49
|
-
declare class MessageRoutingError extends Error {
|
|
50
|
-
readonly code: string;
|
|
51
|
-
readonly requestId?: string | undefined;
|
|
52
|
-
readonly [errorBrand] = true;
|
|
53
|
-
static [Symbol.hasInstance](value: unknown): boolean;
|
|
54
|
-
constructor(code: string, message: string, requestId?: string | undefined,
|
|
55
|
-
/** `cause` stays with the host for logs; the bridge sends only code, message, and request ID. */
|
|
56
|
-
options?: ErrorOptions);
|
|
57
|
-
}
|
|
58
|
-
declare function defineMessageRoute<Input, Output>(route: MessageRoute<Input, Output>): MessageRoute<Input, Output>;
|
|
59
|
-
/** Contracts are shared; handlers are supplied by the host and never belong in the app bundle. */
|
|
60
|
-
declare function createMessageRouter<const Routes extends MessageRoutes>(routes: Routes, handlers: MessageHandlers<NoInfer<Routes>>): {
|
|
61
|
-
dispatch: (value: unknown, context: MessageContext) => Promise<unknown>;
|
|
62
|
-
};
|
|
63
|
-
type DataQueryRoute<Operations extends OperationContracts> = MessageRoute<DataQueryInput<Operations>, TransportResponse> & {
|
|
64
|
-
operations: Operations | undefined;
|
|
65
|
-
};
|
|
66
|
-
type MessageOutput<Route extends MessageRoutes[string], Input> = Route extends DataQueryRoute<infer Operations> ? Input extends {
|
|
67
|
-
operation: infer Name extends keyof Operations;
|
|
68
|
-
} ? TransportResponse<DataQueryBody<OutputOf<Operations[Name]>>> : never : ReturnType<Route['output']>;
|
|
69
|
-
/** Omit contracts only in generic hosts such as the CLI shell, where Bun validates operations. */
|
|
70
|
-
declare function defineDataQueryRoute<Operations extends OperationContracts = OperationContracts>(operations?: Operations): DataQueryRoute<Operations>;
|
|
71
|
-
declare const navigationUpdateRoute: MessageRoute<NavigationUpdate, null>;
|
|
72
|
-
type SqlQueryInput = {
|
|
73
|
-
statement: string;
|
|
74
|
-
limit: number;
|
|
75
|
-
params?: QueryParameters;
|
|
76
|
-
};
|
|
77
|
-
/** SQL delivery for browser-owned operations. Hosts must enforce backend access and resource limits. */
|
|
78
|
-
declare const sqlQueryRoute: MessageRoute<SqlQueryInput, QueryResult>;
|
|
79
|
-
declare const dataAppRoutes: {
|
|
80
|
-
'data:query': DataQueryRoute<OperationContracts>;
|
|
81
|
-
'navigation:update': MessageRoute<NavigationUpdate, null>;
|
|
82
|
-
};
|
|
83
|
-
//#endregion
|
|
84
|
-
//#region src/core/annotations.d.ts
|
|
85
|
-
type DataAppAnnotationDraft = {
|
|
86
|
-
id: string;
|
|
87
|
-
target: {
|
|
88
|
-
id: string;
|
|
89
|
-
label: string;
|
|
90
|
-
kind: 'widget' | 'element' | 'app';
|
|
91
|
-
text: string;
|
|
92
|
-
queryNames: string[];
|
|
93
|
-
glossaryIds: string[];
|
|
94
|
-
};
|
|
95
|
-
context: {
|
|
96
|
-
search: string;
|
|
97
|
-
hash: string;
|
|
98
|
-
displayedInput?: unknown;
|
|
99
|
-
/** Normalized position within the selected target, stable across scrolling/resizing. */
|
|
100
|
-
anchor?: {
|
|
101
|
-
x: number;
|
|
102
|
-
y: number;
|
|
103
|
-
};
|
|
104
|
-
cursor?: {
|
|
105
|
-
x: number;
|
|
106
|
-
y: number;
|
|
107
|
-
};
|
|
108
|
-
/** Normalized custom selection rectangle within the iframe document. */
|
|
109
|
-
region?: {
|
|
110
|
-
x: number;
|
|
111
|
-
y: number;
|
|
112
|
-
width: number;
|
|
113
|
-
height: number;
|
|
114
|
-
};
|
|
115
|
-
screenshot?: {
|
|
116
|
-
mimeType: 'image/png';
|
|
117
|
-
dataUrl: string;
|
|
118
|
-
width: number;
|
|
119
|
-
height: number;
|
|
120
|
-
};
|
|
121
|
-
view?: string;
|
|
122
|
-
viewport: {
|
|
123
|
-
width: number;
|
|
124
|
-
height: number;
|
|
125
|
-
};
|
|
126
|
-
rect: {
|
|
127
|
-
x: number;
|
|
128
|
-
y: number;
|
|
129
|
-
width: number;
|
|
130
|
-
height: number;
|
|
131
|
-
};
|
|
132
|
-
};
|
|
133
|
-
comment: string;
|
|
134
|
-
};
|
|
135
|
-
type DataAppAnnotationPresentation = {
|
|
136
|
-
enabled: boolean;
|
|
137
|
-
/** When provided, the host owns the mode and renders the annotation trigger. */
|
|
138
|
-
active?: boolean;
|
|
139
|
-
pinsVisible?: boolean;
|
|
140
|
-
showHint?: boolean;
|
|
141
|
-
readOnly?: boolean;
|
|
142
|
-
targets?: {
|
|
143
|
-
id: string;
|
|
144
|
-
targetId: string;
|
|
145
|
-
number: number;
|
|
146
|
-
comment?: string;
|
|
147
|
-
anchor?: {
|
|
148
|
-
x: number;
|
|
149
|
-
y: number;
|
|
150
|
-
};
|
|
151
|
-
region?: {
|
|
152
|
-
x: number;
|
|
153
|
-
y: number;
|
|
154
|
-
width: number;
|
|
155
|
-
height: number;
|
|
156
|
-
};
|
|
157
|
-
}[];
|
|
158
|
-
selectedAnnotationId?: string;
|
|
159
|
-
selectedTargetId?: string;
|
|
160
|
-
selectionId?: string;
|
|
161
|
-
/** Confirmed host click outside the iframe; occurredAt is epoch milliseconds. */
|
|
162
|
-
dismissal?: {
|
|
163
|
-
id: string;
|
|
164
|
-
occurredAt: number;
|
|
165
|
-
};
|
|
166
|
-
};
|
|
167
|
-
/** Reconstruct at the boundary; discard extra fields and bound the entire JSON payload. */
|
|
168
|
-
declare function parseDataAppAnnotationDraft(value: unknown): DataAppAnnotationDraft;
|
|
169
|
-
declare const annotationDraftRoute: MessageRoute<DataAppAnnotationDraft, null>;
|
|
170
|
-
declare const annotationEditorStateRoute: MessageRoute<{
|
|
171
|
-
hasUnsavedChanges: boolean;
|
|
172
|
-
}, null>;
|
|
173
|
-
/** Request host-owned batch submission without transferring ownership of drafts. */
|
|
174
|
-
declare const annotationSendRoute: MessageRoute<null, null>;
|
|
175
|
-
declare const annotationUpdateRoute: MessageRoute<{
|
|
176
|
-
id: string;
|
|
177
|
-
comment: string;
|
|
178
|
-
}, null>;
|
|
179
|
-
/** A controlled shell acknowledges local exits (for example Escape). */
|
|
180
|
-
declare const annotationModeRoute: MessageRoute<{
|
|
181
|
-
active: boolean;
|
|
182
|
-
}, null>;
|
|
183
|
-
//#endregion
|
|
184
|
-
//#region src/core/external-link.d.ts
|
|
185
|
-
/** Absolute HTTPS destinations only; URLs must not contain embedded credentials. */
|
|
186
|
-
declare function parseExternalUrl(value: unknown): string;
|
|
187
|
-
type ExternalLinkTarget = 'tab' | 'window';
|
|
188
|
-
type ExternalLinkModifiers = {
|
|
189
|
-
shiftKey: boolean;
|
|
190
|
-
metaKey: boolean;
|
|
191
|
-
ctrlKey: boolean;
|
|
192
|
-
};
|
|
193
|
-
type OpenExternalLink = {
|
|
194
|
-
url: string;
|
|
195
|
-
} & ({
|
|
196
|
-
target?: ExternalLinkTarget;
|
|
197
|
-
} | {
|
|
198
|
-
target: 'event';
|
|
199
|
-
keys: ExternalLinkModifiers;
|
|
200
|
-
});
|
|
201
|
-
type ExternalLinkResult = 'opened' | 'cancelled' | 'ignored';
|
|
202
|
-
/** Shift takes precedence over Ctrl/Cmd; an unmodified event requests no navigation. */
|
|
203
|
-
declare function resolveExternalLinkTarget(input: OpenExternalLink): ExternalLinkTarget | null;
|
|
204
|
-
/** Opt-in host route. Validation does not replace the host's destination policy. */
|
|
205
|
-
declare const openExternalLinkRoute: MessageRoute<OpenExternalLink, ExternalLinkResult>;
|
|
206
|
-
//#endregion
|
|
207
|
-
//#region src/core/contract.d.ts
|
|
208
|
-
declare const sourceErrorBrand: unique symbol;
|
|
209
|
-
declare class DataSourceError extends Error {
|
|
210
|
-
readonly reason: 'unauthorized' | 'forbidden' | 'rate_limited' | 'query_rejected' | 'unavailable';
|
|
211
|
-
readonly status?: number | undefined;
|
|
212
|
-
readonly [sourceErrorBrand] = true;
|
|
213
|
-
queryName?: string;
|
|
214
|
-
static [Symbol.hasInstance](value: unknown): boolean;
|
|
215
|
-
constructor(reason: 'unauthorized' | 'forbidden' | 'rate_limited' | 'query_rejected' | 'unavailable', status?: number | undefined,
|
|
216
|
-
/** `cause` stays on the server or host for logs; responses carry only the reason. */
|
|
217
|
-
options?: ErrorOptions);
|
|
218
|
-
}
|
|
219
|
-
//#endregion
|
|
220
|
-
export { dataAppRoutes as A, MessageRoute as C, RoutedMessage as D, MessageTransport as E, dateTimeRangeSql as F, facetFilter as I, defineMessageRoute as M, navigationUpdateRoute as N, SqlQueryInput as O, sqlQueryRoute as P, MessageOutput as S, MessageRoutingError as T, DataQueryRoute as _, OpenExternalLink as a, MessageHandlers as b, resolveExternalLinkTarget as c, annotationDraftRoute as d, annotationEditorStateRoute as f, parseDataAppAnnotationDraft as g, annotationUpdateRoute as h, ExternalLinkTarget as i, defineDataQueryRoute as j, createMessageRouter as k, DataAppAnnotationDraft as l, annotationSendRoute as m, ExternalLinkModifiers as n, openExternalLinkRoute as o, annotationModeRoute as p, ExternalLinkResult as r, parseExternalUrl as s, DataSourceError as t, DataAppAnnotationPresentation as u, MessageContext as v, MessageRoutes as w, MessageInput as x, MessageDispatcher as y };
|
|
221
|
-
//# sourceMappingURL=contract2.d.ts.map
|
|
@@ -1,29 +0,0 @@
|
|
|
1
|
-
//#region src/core/date-time-range.d.ts
|
|
2
|
-
/** Frontend-compatible range values. Absolute dates encode wall-clock fields as UTC,
|
|
3
|
-
* not instants converted from a reporting timezone. The backend interprets that zone.
|
|
4
|
-
*/
|
|
5
|
-
type AbsoluteOrRelativeDateTime = Date | RelativeDateTime;
|
|
6
|
-
type DateTimeRange = {
|
|
7
|
-
/** Inclusive start; null or omitted means unbounded. */
|
|
8
|
-
from?: AbsoluteOrRelativeDateTime | null;
|
|
9
|
-
/** Exclusive end; null or omitted means now. */
|
|
10
|
-
to?: AbsoluteOrRelativeDateTime | null;
|
|
11
|
-
};
|
|
12
|
-
type RelativeDateTime = {
|
|
13
|
-
anchor: RelativeAnchor;
|
|
14
|
-
offset: RelativeOffset[];
|
|
15
|
-
};
|
|
16
|
-
type RelativeOffset = {
|
|
17
|
-
amount: number;
|
|
18
|
-
unit: RelativeUnit;
|
|
19
|
-
};
|
|
20
|
-
type RelativeAnchor = 'RELATIVE_ANCHOR_NOW' | 'RELATIVE_ANCHOR_START_OF_TODAY' | 'RELATIVE_ANCHOR_START_OF_YESTERDAY' | 'RELATIVE_ANCHOR_START_OF_TOMORROW' | 'RELATIVE_ANCHOR_START_OF_WEEK' | 'RELATIVE_ANCHOR_START_OF_MONTH' | 'RELATIVE_ANCHOR_START_OF_YEAR';
|
|
21
|
-
type RelativeUnit = 'SECOND' | 'MINUTE' | 'HOUR' | 'DAY' | 'WEEK' | 'MONTH' | 'YEAR';
|
|
22
|
-
/** Bounded, resolved wall-clock dates encoded in UTC, with an exclusive end. */
|
|
23
|
-
type ResolvedDateTimeRange = {
|
|
24
|
-
from: Date;
|
|
25
|
-
to: Date;
|
|
26
|
-
};
|
|
27
|
-
//#endregion
|
|
28
|
-
export { RelativeOffset as a, RelativeDateTime as i, DateTimeRange as n, RelativeUnit as o, RelativeAnchor as r, ResolvedDateTimeRange as s, AbsoluteOrRelativeDateTime as t };
|
|
29
|
-
//# sourceMappingURL=date-time-range.d.ts.map
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
import { Z as DataOperations, gt as QueryParameters, nt as Lakehouse } from "../chunks/contract.js";
|
|
2
|
-
//#region src/server/handler.d.ts
|
|
3
|
-
/** Authorization result for one viewer request. A hosted adapter must scope its lakehouse client. */
|
|
4
|
-
type RequestAccess = {
|
|
5
|
-
lakehouse: Lakehouse;
|
|
6
|
-
/** Trusted values shared across queries; each query uses only its declared keys. Datetime ranges use serializeDateTimeRange(); they are decoded and validated before SQL binding. */
|
|
7
|
-
queryParams?: QueryParameters;
|
|
8
|
-
};
|
|
9
|
-
/**
|
|
10
|
-
* Execute named operations on the server. The app supplies operations and viewer authorization.
|
|
11
|
-
* JSON, Origin, and Fetch Metadata checks reject cross-site browser POSTs; they do not
|
|
12
|
-
* authenticate another local process. Query evidence accompanies every result.
|
|
13
|
-
*/
|
|
14
|
-
export declare function createDataHandler(operations: DataOperations, authorize: (request: Request, operation: string) => Promise<RequestAccess>): (request: Request) => Promise<Response>;
|
|
15
|
-
//#endregion
|
|
16
|
-
export type { RequestAccess };
|
|
17
|
-
//# sourceMappingURL=index.d.ts.map
|
package/docs/server.md
DELETED
|
@@ -1,41 +0,0 @@
|
|
|
1
|
-
# Server
|
|
2
|
-
|
|
3
|
-
Import `createDataHandler()` and the `RequestAccess` type from
|
|
4
|
-
`@altertable/data-app/server`. The handler accepts a Web `Request` and returns a
|
|
5
|
-
`Promise<Response>` in Node or Bun.
|
|
6
|
-
|
|
7
|
-
```ts
|
|
8
|
-
import { createDataHandler } from '@altertable/data-app/server';
|
|
9
|
-
import { operations } from './operations.ts';
|
|
10
|
-
|
|
11
|
-
export const handleDataRequest = createDataHandler(
|
|
12
|
-
operations,
|
|
13
|
-
async (request, operation) => {
|
|
14
|
-
const viewer = await authenticate(request);
|
|
15
|
-
return {
|
|
16
|
-
lakehouse: await lakehouseFor(viewer, operation),
|
|
17
|
-
queryParams: { orgId: viewer.organizationId },
|
|
18
|
-
};
|
|
19
|
-
}
|
|
20
|
-
);
|
|
21
|
-
```
|
|
22
|
-
|
|
23
|
-
The app supplies `authenticate()` and `lakehouseFor()`, then routes `/api/data/*`
|
|
24
|
-
requests to the handler. Authorize every viewer and operation, and scope the
|
|
25
|
-
returned lakehouse to the viewer's permitted data. Supply trusted registry
|
|
26
|
-
parameters through `queryParams`; query callers cannot override them. Origin and Fetch Metadata
|
|
27
|
-
checks reject cross-site browser requests; they do not authenticate viewers.
|
|
28
|
-
|
|
29
|
-
The handler validates operation input, enforces query row and duration
|
|
30
|
-
bounds, propagates cancellation, and returns query evidence and request IDs.
|
|
31
|
-
Keep credentials and operation implementations on the server.
|
|
32
|
-
|
|
33
|
-
See [operation contracts](contract.md), the [client](client.md), and the
|
|
34
|
-
[local Bun adapter](server-bun.md).
|
|
35
|
-
|
|
36
|
-
## Request input limits
|
|
37
|
-
|
|
38
|
-
JSON request bodies are limited to 16,384 encoded bytes. Oversized bodies return
|
|
39
|
-
`413/input_too_large`; invalid or interrupted bodies return `400/invalid_input`.
|
|
40
|
-
`maxDurationMs` bounds execution after parsing; configure body-read deadlines in
|
|
41
|
-
the hosting runtime.
|