@hypequery/serve 0.24.4 → 0.26.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/dist/adapters/fetch.d.ts.map +1 -1
- package/dist/adapters/fetch.js +19 -6
- package/dist/adapters/node.d.ts +1 -1
- package/dist/adapters/node.d.ts.map +1 -1
- package/dist/adapters/node.js +110 -11
- package/dist/adapters/standalone.d.ts +1 -1
- package/dist/adapters/standalone.d.ts.map +1 -1
- package/dist/adapters/utils.d.ts +5 -0
- package/dist/adapters/utils.d.ts.map +1 -1
- package/dist/adapters/utils.js +8 -0
- package/dist/auth.d.ts +1 -1
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +9 -1
- package/dist/client-config.d.ts +8 -7
- package/dist/client-config.d.ts.map +1 -1
- package/dist/client-config.js +16 -7
- package/dist/cors.d.ts.map +1 -1
- package/dist/cors.js +2 -1
- package/dist/dev.d.ts +1 -1
- package/dist/index.d.ts +5 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/pipeline.d.ts +2 -0
- package/dist/pipeline.d.ts.map +1 -1
- package/dist/pipeline.js +81 -10
- package/dist/query-logger.d.ts +6 -0
- package/dist/query-logger.d.ts.map +1 -1
- package/dist/query-logger.js +6 -0
- package/dist/semantic/datasets/contract-endpoint.d.ts.map +1 -1
- package/dist/semantic/datasets/contract-endpoint.js +1 -0
- package/dist/semantic/datasets/dataset-endpoint.d.ts.map +1 -1
- package/dist/semantic/datasets/dataset-endpoint.js +40 -13
- package/dist/semantic/datasets/index.d.ts +1 -1
- package/dist/semantic/datasets/index.d.ts.map +1 -1
- package/dist/semantic/datasets/metric-endpoint.d.ts.map +1 -1
- package/dist/semantic/datasets/metric-endpoint.js +2 -1
- package/dist/semantic/datasets/utils/client-endpoint-binding.d.ts +22 -0
- package/dist/semantic/datasets/utils/client-endpoint-binding.d.ts.map +1 -0
- package/dist/semantic/datasets/utils/client-endpoint-binding.js +20 -0
- package/dist/semantic/datasets/utils/client-endpoint-profile.d.ts +10 -0
- package/dist/semantic/datasets/utils/client-endpoint-profile.d.ts.map +1 -0
- package/dist/semantic/datasets/utils/client-endpoint-profile.js +15 -0
- package/dist/semantic/datasets/utils/client-response-meta.d.ts +8 -0
- package/dist/semantic/datasets/utils/client-response-meta.d.ts.map +1 -0
- package/dist/semantic/datasets/utils/client-response-meta.js +28 -0
- package/dist/semantic/datasets/utils/dataset-entry.d.ts +23 -0
- package/dist/semantic/datasets/utils/dataset-entry.d.ts.map +1 -1
- package/dist/semantic/datasets/utils/dataset-entry.js +20 -0
- package/dist/semantic/datasets/utils/mcp-restrictions.d.ts +16 -0
- package/dist/semantic/datasets/utils/mcp-restrictions.d.ts.map +1 -0
- package/dist/semantic/datasets/utils/mcp-restrictions.js +33 -0
- package/dist/semantic/datasets/utils/ndjson-frames.d.ts +18 -0
- package/dist/semantic/datasets/utils/ndjson-frames.d.ts.map +1 -0
- package/dist/semantic/datasets/utils/ndjson-frames.js +56 -0
- package/dist/semantic/datasets/utils/semantic-fixture-builder.d.ts +9 -1
- package/dist/semantic/datasets/utils/semantic-fixture-builder.d.ts.map +1 -1
- package/dist/semantic/datasets/utils/semantic-fixture-builder.js +33 -5
- package/dist/semantic/datasets/utils/stream-format.d.ts +14 -0
- package/dist/semantic/datasets/utils/stream-format.d.ts.map +1 -0
- package/dist/semantic/datasets/utils/stream-format.js +50 -0
- package/dist/server/api-builder.d.ts +2 -1
- package/dist/server/api-builder.d.ts.map +1 -1
- package/dist/server/api-builder.js +3 -1
- package/dist/server/builder.d.ts +2 -1
- package/dist/server/builder.d.ts.map +1 -1
- package/dist/server/builder.js +3 -1
- package/dist/server/client-contract.d.ts +7 -0
- package/dist/server/client-contract.d.ts.map +1 -0
- package/dist/server/client-contract.js +17 -0
- package/dist/server/context-query-builder.d.ts +25 -0
- package/dist/server/context-query-builder.d.ts.map +1 -0
- package/dist/server/context-query-builder.js +51 -0
- package/dist/server/create-api.d.ts.map +1 -1
- package/dist/server/create-api.js +88 -3
- package/dist/server/mcp-source.d.ts +28 -0
- package/dist/server/mcp-source.d.ts.map +1 -1
- package/dist/server/mcp-source.js +5 -0
- package/dist/tenant.d.ts +9 -0
- package/dist/tenant.d.ts.map +1 -1
- package/dist/tenant.js +8 -0
- package/dist/type-tests/client-contract.test-d.d.ts +13 -0
- package/dist/type-tests/client-contract.test-d.d.ts.map +1 -0
- package/dist/type-tests/client-contract.test-d.js +14 -0
- package/dist/type-tests/streaming.test-d.d.ts +45 -0
- package/dist/type-tests/streaming.test-d.d.ts.map +1 -0
- package/dist/type-tests/streaming.test-d.js +59 -0
- package/dist/types.d.ts +86 -2
- package/dist/types.d.ts.map +1 -1
- package/dist/utils/client-schema-precondition.d.ts +31 -0
- package/dist/utils/client-schema-precondition.d.ts.map +1 -0
- package/dist/utils/client-schema-precondition.js +57 -0
- package/dist/utils/jwt-audience.d.ts +9 -0
- package/dist/utils/jwt-audience.d.ts.map +1 -0
- package/dist/utils/jwt-audience.js +27 -0
- package/dist/utils/observe-stream-body.d.ts +20 -0
- package/dist/utils/observe-stream-body.d.ts.map +1 -0
- package/dist/utils/observe-stream-body.js +83 -0
- package/dist/utils/response-drain.d.ts +4 -0
- package/dist/utils/response-drain.d.ts.map +1 -0
- package/dist/utils/response-drain.js +10 -0
- package/dist/utils/response-headers.d.ts +13 -0
- package/dist/utils/response-headers.d.ts.map +1 -0
- package/dist/utils/response-headers.js +40 -0
- package/dist/utils/stream-body.d.ts +37 -0
- package/dist/utils/stream-body.d.ts.map +1 -0
- package/dist/utils/stream-body.js +13 -0
- package/dist/utils/stream-timeout.d.ts +15 -0
- package/dist/utils/stream-timeout.d.ts.map +1 -0
- package/dist/utils/stream-timeout.js +20 -0
- package/package.json +8 -7
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { resolveMetricEntry } from '../metric-endpoint.js';
|
|
2
|
+
import { resolveDatasetEntry } from './dataset-entry.js';
|
|
3
|
+
function rulesOf(entry) {
|
|
4
|
+
const rules = [];
|
|
5
|
+
// `requiresAuth: false` is not listed: MCP over HTTP always authenticates, which is stricter.
|
|
6
|
+
if (entry.auth != null)
|
|
7
|
+
rules.push('auth');
|
|
8
|
+
if ((entry.requiredRoles?.length ?? 0) > 0)
|
|
9
|
+
rules.push('requiredRoles');
|
|
10
|
+
if ((entry.requiredScopes?.length ?? 0) > 0)
|
|
11
|
+
rules.push('requiredScopes');
|
|
12
|
+
if ((entry.middlewares?.length ?? 0) > 0)
|
|
13
|
+
rules.push('middlewares');
|
|
14
|
+
// A per-dataset tenant override can resolve a different tenant than the global one.
|
|
15
|
+
if (entry.tenant !== undefined)
|
|
16
|
+
rules.push('tenant');
|
|
17
|
+
return rules;
|
|
18
|
+
}
|
|
19
|
+
/** Every registered dataset and metric that carries endpoint-level access rules. */
|
|
20
|
+
export function collectMcpRestrictions(datasets, metrics) {
|
|
21
|
+
const restricted = [];
|
|
22
|
+
for (const [name, entry] of Object.entries(datasets ?? {})) {
|
|
23
|
+
const rules = rulesOf(resolveDatasetEntry(entry));
|
|
24
|
+
if (rules.length > 0)
|
|
25
|
+
restricted.push({ kind: 'dataset', name, rules });
|
|
26
|
+
}
|
|
27
|
+
for (const [name, entry] of Object.entries(metrics ?? {})) {
|
|
28
|
+
const rules = rulesOf(resolveMetricEntry(entry));
|
|
29
|
+
if (rules.length > 0)
|
|
30
|
+
restricted.push({ kind: 'metric', name, rules });
|
|
31
|
+
}
|
|
32
|
+
return restricted;
|
|
33
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A streamed dataset response as NDJSON frames, one JSON object per line:
|
|
3
|
+
*
|
|
4
|
+
* {"type":"start","meta":{...}} meta only when requested
|
|
5
|
+
* {"type":"rows","data":[...]} one per batch, as `execute` returns rows
|
|
6
|
+
* {"type":"end","rowCount":N} the result is complete
|
|
7
|
+
* {"type":"error","error":{...}} the query failed after the response began
|
|
8
|
+
*
|
|
9
|
+
* The HTTP status is sent before the first row, so a failure partway is a
|
|
10
|
+
* final `error` frame; a response without an `end` frame is incomplete. The
|
|
11
|
+
* client only sees a sanitized message: `failure()` returns the error itself,
|
|
12
|
+
* once the stream has ended, for hooks and logs.
|
|
13
|
+
*/
|
|
14
|
+
export declare function datasetNdjsonStream(rows: ReadableStream<Record<string, unknown>[]>, meta?: unknown): {
|
|
15
|
+
stream: ReadableStream<Uint8Array>;
|
|
16
|
+
failure: () => unknown;
|
|
17
|
+
};
|
|
18
|
+
//# sourceMappingURL=ndjson-frames.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"ndjson-frames.d.ts","sourceRoot":"","sources":["../../../../src/semantic/datasets/utils/ndjson-frames.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,wBAAgB,mBAAmB,CACjC,IAAI,EAAE,cAAc,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAAE,CAAC,EAC/C,IAAI,CAAC,EAAE,OAAO,GACb;IAAE,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,CAAC;IAAC,OAAO,EAAE,MAAM,OAAO,CAAA;CAAE,CAyChE"}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* A streamed dataset response as NDJSON frames, one JSON object per line:
|
|
3
|
+
*
|
|
4
|
+
* {"type":"start","meta":{...}} meta only when requested
|
|
5
|
+
* {"type":"rows","data":[...]} one per batch, as `execute` returns rows
|
|
6
|
+
* {"type":"end","rowCount":N} the result is complete
|
|
7
|
+
* {"type":"error","error":{...}} the query failed after the response began
|
|
8
|
+
*
|
|
9
|
+
* The HTTP status is sent before the first row, so a failure partway is a
|
|
10
|
+
* final `error` frame; a response without an `end` frame is incomplete. The
|
|
11
|
+
* client only sees a sanitized message: `failure()` returns the error itself,
|
|
12
|
+
* once the stream has ended, for hooks and logs.
|
|
13
|
+
*/
|
|
14
|
+
export function datasetNdjsonStream(rows, meta) {
|
|
15
|
+
const encoder = new TextEncoder();
|
|
16
|
+
const frame = (value) => encoder.encode(`${JSON.stringify(value)}\n`);
|
|
17
|
+
const reader = rows.getReader();
|
|
18
|
+
let rowCount = 0;
|
|
19
|
+
let failure;
|
|
20
|
+
const stream = new ReadableStream({
|
|
21
|
+
start(controller) {
|
|
22
|
+
controller.enqueue(frame(meta === undefined ? { type: 'start' } : { type: 'start', meta }));
|
|
23
|
+
},
|
|
24
|
+
async pull(controller) {
|
|
25
|
+
try {
|
|
26
|
+
// A pull that enqueues nothing is not called again: skip empty batches here.
|
|
27
|
+
for (;;) {
|
|
28
|
+
const { done, value } = await reader.read();
|
|
29
|
+
if (done) {
|
|
30
|
+
controller.enqueue(frame({ type: 'end', rowCount }));
|
|
31
|
+
controller.close();
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
if (value.length === 0)
|
|
35
|
+
continue;
|
|
36
|
+
rowCount += value.length;
|
|
37
|
+
controller.enqueue(frame({ type: 'rows', data: value }));
|
|
38
|
+
return;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
catch (error) {
|
|
42
|
+
failure = error ?? new Error('The row stream failed without an error.');
|
|
43
|
+
// Never the thrown message: it can carry SQL or a driver detail.
|
|
44
|
+
controller.enqueue(frame({
|
|
45
|
+
type: 'error',
|
|
46
|
+
error: { type: 'QUERY_FAILURE', message: 'The query failed after the response began.' },
|
|
47
|
+
}));
|
|
48
|
+
controller.close();
|
|
49
|
+
}
|
|
50
|
+
},
|
|
51
|
+
cancel(reason) {
|
|
52
|
+
return reader.cancel(reason);
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
return { stream, failure: () => failure };
|
|
56
|
+
}
|
|
@@ -1,4 +1,12 @@
|
|
|
1
1
|
import type { QueryBuilderFactoryLike } from '@hypequery/datasets';
|
|
2
|
+
export interface SemanticFixtureStreamOptions {
|
|
3
|
+
/** Rows per streamed batch. */
|
|
4
|
+
batchSize?: number;
|
|
5
|
+
/** Fail a row stream after this many batches. */
|
|
6
|
+
failAfterBatches?: number;
|
|
7
|
+
/** The bytes an Arrow stream returns. */
|
|
8
|
+
arrowBytes?: Uint8Array;
|
|
9
|
+
}
|
|
2
10
|
/** Deterministic recording backend for HTTP fixtures; actually applies LIMIT/OFFSET. */
|
|
3
|
-
export declare function semanticFixtureBuilder(rows: Array<Record<string, unknown
|
|
11
|
+
export declare function semanticFixtureBuilder(rows: Array<Record<string, unknown>>, streams?: SemanticFixtureStreamOptions): QueryBuilderFactoryLike;
|
|
4
12
|
//# sourceMappingURL=semantic-fixture-builder.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"semantic-fixture-builder.d.ts","sourceRoot":"","sources":["../../../../src/semantic/datasets/utils/semantic-fixture-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAoB,MAAM,qBAAqB,CAAC;AAErF,wFAAwF;AACxF,wBAAgB,sBAAsB,
|
|
1
|
+
{"version":3,"file":"semantic-fixture-builder.d.ts","sourceRoot":"","sources":["../../../../src/semantic/datasets/utils/semantic-fixture-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAoB,MAAM,qBAAqB,CAAC;AAErF,MAAM,WAAW,4BAA4B;IAC3C,+BAA+B;IAC/B,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,iDAAiD;IACjD,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,yCAAyC;IACzC,UAAU,CAAC,EAAE,UAAU,CAAC;CACzB;AAED,wFAAwF;AACxF,wBAAgB,sBAAsB,CACpC,IAAI,EAAE,KAAK,CAAC,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC,EACpC,OAAO,GAAE,4BAAiC,GACzC,uBAAuB,CAsDzB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
/** Deterministic recording backend for HTTP fixtures; actually applies LIMIT/OFFSET. */
|
|
2
|
-
export function semanticFixtureBuilder(rows) {
|
|
2
|
+
export function semanticFixtureBuilder(rows, streams = {}) {
|
|
3
3
|
return {
|
|
4
4
|
rawQuery: async () => rows,
|
|
5
5
|
table: () => {
|
|
@@ -18,11 +18,39 @@ export function semanticFixtureBuilder(rows) {
|
|
|
18
18
|
limit: (value) => { limit = value; return builder; },
|
|
19
19
|
offset: (value) => { offset = value; return builder; },
|
|
20
20
|
toSQLWithParams: () => ({ sql: 'SELECT private_columns FROM private_orders', parameters: [] }),
|
|
21
|
-
execute: async () =>
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
21
|
+
execute: async () => project(),
|
|
22
|
+
stream: async () => {
|
|
23
|
+
const projected = project();
|
|
24
|
+
const size = streams.batchSize ?? projected.length;
|
|
25
|
+
let batches = 0;
|
|
26
|
+
let at = 0;
|
|
27
|
+
return new ReadableStream({
|
|
28
|
+
pull(controller) {
|
|
29
|
+
if (streams.failAfterBatches !== undefined && batches >= streams.failAfterBatches) {
|
|
30
|
+
controller.error(new Error('Code: 396. DB::Exception: private detail. (TOO_MANY_ROWS_OR_BYTES)'));
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
if (at >= projected.length) {
|
|
34
|
+
controller.close();
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
controller.enqueue(projected.slice(at, at + size));
|
|
38
|
+
at += size;
|
|
39
|
+
batches += 1;
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
},
|
|
43
|
+
streamArrow: async () => new ReadableStream({
|
|
44
|
+
start(controller) {
|
|
45
|
+
controller.enqueue(streams.arrowBytes ?? new Uint8Array());
|
|
46
|
+
controller.close();
|
|
47
|
+
},
|
|
48
|
+
}),
|
|
25
49
|
};
|
|
50
|
+
const project = () => rows.slice(offset, offset + limit).map(row => Object.fromEntries(fields.map(field => {
|
|
51
|
+
const name = field.match(/\bAS\s+[`"]?([^`"\s]+)[`"]?$/i)?.[1] ?? field.replaceAll('`', '');
|
|
52
|
+
return [name, row[name]];
|
|
53
|
+
})));
|
|
26
54
|
return builder;
|
|
27
55
|
},
|
|
28
56
|
};
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
/** Media type of a streamed dataset response of row batches, one JSON frame per line. */
|
|
2
|
+
export declare const NDJSON_MEDIA_TYPE = "application/x-ndjson";
|
|
3
|
+
/** Media type of a streamed dataset response as an Arrow IPC stream. */
|
|
4
|
+
export declare const ARROW_STREAM_MEDIA_TYPE = "application/vnd.apache.arrow.stream";
|
|
5
|
+
export type DatasetStreamFormat = 'ndjson' | 'arrow';
|
|
6
|
+
/**
|
|
7
|
+
* The stream an `Accept` header asks for, or `undefined` for a JSON page.
|
|
8
|
+
* Streams are matched only by their exact media type, never by a wildcard.
|
|
9
|
+
* The acceptable stream type with the highest `q` wins (the first listed on a
|
|
10
|
+
* tie); a JSON page is preferred only when `application/json` (or the most
|
|
11
|
+
* specific wildcard covering it) has a strictly higher `q`. `q=0` refuses a type.
|
|
12
|
+
*/
|
|
13
|
+
export declare function requestedStreamFormat(accept: string | undefined): DatasetStreamFormat | undefined;
|
|
14
|
+
//# sourceMappingURL=stream-format.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"stream-format.d.ts","sourceRoot":"","sources":["../../../../src/semantic/datasets/utils/stream-format.ts"],"names":[],"mappings":"AAAA,yFAAyF;AACzF,eAAO,MAAM,iBAAiB,yBAAyB,CAAC;AACxD,wEAAwE;AACxE,eAAO,MAAM,uBAAuB,wCAAwC,CAAC;AAE7E,MAAM,MAAM,mBAAmB,GAAG,QAAQ,GAAG,OAAO,CAAC;AAgCrD;;;;;;GAMG;AACH,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,MAAM,GAAG,SAAS,GAAG,mBAAmB,GAAG,SAAS,CAWjG"}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/** Media type of a streamed dataset response of row batches, one JSON frame per line. */
|
|
2
|
+
export const NDJSON_MEDIA_TYPE = 'application/x-ndjson';
|
|
3
|
+
/** Media type of a streamed dataset response as an Arrow IPC stream. */
|
|
4
|
+
export const ARROW_STREAM_MEDIA_TYPE = 'application/vnd.apache.arrow.stream';
|
|
5
|
+
// A Map, not an object literal: a media type such as `constructor` must not
|
|
6
|
+
// match an inherited property.
|
|
7
|
+
const FORMATS = new Map([
|
|
8
|
+
[NDJSON_MEDIA_TYPE, 'ndjson'],
|
|
9
|
+
[ARROW_STREAM_MEDIA_TYPE, 'arrow'],
|
|
10
|
+
]);
|
|
11
|
+
const parseAccept = (accept) => accept.split(',').flatMap((range) => {
|
|
12
|
+
const [type, ...params] = range.trim().toLowerCase().split(';').map(part => part.trim());
|
|
13
|
+
if (!type)
|
|
14
|
+
return [];
|
|
15
|
+
const q = params.find(param => param.startsWith('q='));
|
|
16
|
+
const quality = q === undefined ? 1 : Number(q.slice(2));
|
|
17
|
+
return [{ type, quality: Number.isFinite(quality) ? quality : 0 }];
|
|
18
|
+
});
|
|
19
|
+
/** The quality of the most specific range matching `application/json`, or 0 when none does. */
|
|
20
|
+
const jsonQuality = (ranges) => {
|
|
21
|
+
for (const type of ['application/json', 'application/*', '*/*']) {
|
|
22
|
+
const range = ranges.find(candidate => candidate.type === type);
|
|
23
|
+
if (range)
|
|
24
|
+
return range.quality;
|
|
25
|
+
}
|
|
26
|
+
return 0;
|
|
27
|
+
};
|
|
28
|
+
/**
|
|
29
|
+
* The stream an `Accept` header asks for, or `undefined` for a JSON page.
|
|
30
|
+
* Streams are matched only by their exact media type, never by a wildcard.
|
|
31
|
+
* The acceptable stream type with the highest `q` wins (the first listed on a
|
|
32
|
+
* tie); a JSON page is preferred only when `application/json` (or the most
|
|
33
|
+
* specific wildcard covering it) has a strictly higher `q`. `q=0` refuses a type.
|
|
34
|
+
*/
|
|
35
|
+
export function requestedStreamFormat(accept) {
|
|
36
|
+
if (!accept)
|
|
37
|
+
return undefined;
|
|
38
|
+
const ranges = parseAccept(accept);
|
|
39
|
+
let best;
|
|
40
|
+
for (const range of ranges) {
|
|
41
|
+
const format = FORMATS.get(range.type);
|
|
42
|
+
if (!format || range.quality <= 0)
|
|
43
|
+
continue;
|
|
44
|
+
if (!best || range.quality > best.quality)
|
|
45
|
+
best = { format, quality: range.quality };
|
|
46
|
+
}
|
|
47
|
+
if (!best || jsonQuality(ranges) > best.quality)
|
|
48
|
+
return undefined;
|
|
49
|
+
return best.format;
|
|
50
|
+
}
|
|
@@ -2,5 +2,6 @@ import type { AuthContext, AuthStrategy, HypeQueryAPI, ServeEndpointMap, ServeMi
|
|
|
2
2
|
import type { ServeRouter } from "../router.js";
|
|
3
3
|
import type { CacheObservability } from "../cache-observability.js";
|
|
4
4
|
import { ServeQueryLogger } from "../query-logger.js";
|
|
5
|
-
|
|
5
|
+
import type { PreparedProtocolClientContract } from "@hypequery/protocol";
|
|
6
|
+
export declare const createAPImethods: <TQueries extends ServeQueriesMap<TContext, TAuth>, TContext extends Record<string, unknown>, TAuth extends AuthContext>(queryEntries: ServeEndpointMap<TQueries, TContext, TAuth>, queryLogger: ServeQueryLogger, router: ServeRouter, authStrategies: AuthStrategy<TAuth>[], globalMiddlewares: ServeMiddleware<any, any, TContext, TAuth>[], executeQuery: ExecuteQueryFunction<ServeEndpointMap<TQueries, TContext, TAuth>, TContext, TAuth>, handler: ServeHandler, basePath: string, cacheObservability: CacheObservability, clientContract?: () => PreparedProtocolClientContract) => HypeQueryAPI<ServeEndpointMap<TQueries, TContext, TAuth>, TContext, TAuth>;
|
|
6
7
|
//# sourceMappingURL=api-builder.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"api-builder.d.ts","sourceRoot":"","sources":["../../src/server/api-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,YAAY,EACZ,YAAY,EAIZ,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,YAAY,EACZ,oBAAoB,EAErB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"api-builder.d.ts","sourceRoot":"","sources":["../../src/server/api-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,YAAY,EACZ,YAAY,EAIZ,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,YAAY,EACZ,oBAAoB,EAErB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AACpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAItD,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,qBAAqB,CAAC;AAG1E,eAAO,MAAM,gBAAgB,GAC3B,QAAQ,SAAS,eAAe,CAAC,QAAQ,EAAE,KAAK,CAAC,EACjD,QAAQ,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACxC,KAAK,SAAS,WAAW,EAEzB,cAAc,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,CAAC,EACzD,aAAa,gBAAgB,EAC7B,QAAQ,WAAW,EACnB,gBAAgB,YAAY,CAAC,KAAK,CAAC,EAAE,EACrC,mBAAmB,eAAe,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,EAAE,KAAK,CAAC,EAAE,EAC/D,cAAc,oBAAoB,CAChC,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,CAAC,EAC3C,QAAQ,EACR,KAAK,CACN,EACD,SAAS,YAAY,EACrB,UAAU,MAAM,EAChB,oBAAoB,kBAAkB,EACtC,iBAAgB,MAAM,8BAAmE,KACxF,YAAY,CAAC,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,CAAC,EAAE,QAAQ,EAAE,KAAK,CAqH3E,CAAC"}
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { mergeTags } from "../utils.js";
|
|
2
2
|
import { applyBasePath, normalizeRoutePath } from "../router.js";
|
|
3
3
|
import { mapEndpointToToolkit } from "./mapper.js";
|
|
4
|
-
|
|
4
|
+
import { exportClientContract } from "./client-contract.js";
|
|
5
|
+
export const createAPImethods = (queryEntries, queryLogger, router, authStrategies, globalMiddlewares, executeQuery, handler, basePath, cacheObservability, clientContract = () => exportClientContract([], '')) => {
|
|
5
6
|
/**
|
|
6
7
|
* Routes registered through `api.route()`, keyed by endpoint identity.
|
|
7
8
|
*
|
|
@@ -30,6 +31,7 @@ export const createAPImethods = (queryEntries, queryLogger, router, authStrategi
|
|
|
30
31
|
}
|
|
31
32
|
return manifest;
|
|
32
33
|
},
|
|
34
|
+
clientContract,
|
|
33
35
|
route: (path, endpoint, options = {}) => {
|
|
34
36
|
if (!endpoint) {
|
|
35
37
|
throw new Error("Endpoint definition is required when registering a route");
|
package/dist/server/builder.d.ts
CHANGED
|
@@ -2,7 +2,8 @@ import type { AuthContext, AuthStrategy, HttpMethod, ServeBuilder, ServeEndpoint
|
|
|
2
2
|
import type { ServeRouter } from "../router.js";
|
|
3
3
|
import type { CacheObservability } from "../cache-observability.js";
|
|
4
4
|
import { ServeQueryLogger } from "../query-logger.js";
|
|
5
|
+
import type { PreparedProtocolClientContract } from "@hypequery/protocol";
|
|
5
6
|
export declare const createBuilderMethods: <TQueries extends ServeQueriesMap<TContext, TAuth>, TContext extends Record<string, unknown>, TAuth extends AuthContext>(queryEntries: ServeEndpointMap<TQueries, TContext, TAuth>, queryLogger: ServeQueryLogger, routeConfig: Record<string, {
|
|
6
7
|
method: HttpMethod;
|
|
7
|
-
}>, router: ServeRouter, authStrategies: AuthStrategy<TAuth>[], globalMiddlewares: ServeMiddleware<any, any, TContext, TAuth>[], executeQuery: ExecuteQueryFunction<ServeEndpointMap<TQueries, TContext, TAuth>, TContext, TAuth>, handler: ServeHandler, basePath: string, cacheObservability?: CacheObservability) => ServeBuilder<ServeEndpointMap<TQueries, TContext, TAuth>, TContext, TAuth>;
|
|
8
|
+
}>, router: ServeRouter, authStrategies: AuthStrategy<TAuth>[], globalMiddlewares: ServeMiddleware<any, any, TContext, TAuth>[], executeQuery: ExecuteQueryFunction<ServeEndpointMap<TQueries, TContext, TAuth>, TContext, TAuth>, handler: ServeHandler, basePath: string, cacheObservability?: CacheObservability, clientContract?: () => PreparedProtocolClientContract) => ServeBuilder<ServeEndpointMap<TQueries, TContext, TAuth>, TContext, TAuth>;
|
|
8
9
|
//# sourceMappingURL=builder.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"builder.d.ts","sourceRoot":"","sources":["../../src/server/builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,YAAY,EACZ,UAAU,EAEV,YAAY,EAEZ,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,YAAY,EACZ,oBAAoB,EAGrB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAEpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;
|
|
1
|
+
{"version":3,"file":"builder.d.ts","sourceRoot":"","sources":["../../src/server/builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,WAAW,EACX,YAAY,EACZ,UAAU,EAEV,YAAY,EAEZ,gBAAgB,EAChB,eAAe,EACf,eAAe,EACf,YAAY,EACZ,oBAAoB,EAGrB,MAAM,aAAa,CAAC;AACrB,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,cAAc,CAAC;AAChD,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,2BAA2B,CAAC;AAEpE,OAAO,EAAE,gBAAgB,EAAE,MAAM,oBAAoB,CAAC;AAItD,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,qBAAqB,CAAC;AAU1E,eAAO,MAAM,oBAAoB,GAC/B,QAAQ,SAAS,eAAe,CAAC,QAAQ,EAAE,KAAK,CAAC,EACjD,QAAQ,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EACxC,KAAK,SAAS,WAAW,EAEzB,cAAc,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,CAAC,EACzD,aAAa,gBAAgB,EAC7B,aAAa,MAAM,CAAC,MAAM,EAAE;IAAE,MAAM,EAAE,UAAU,CAAA;CAAE,CAAC,EACnD,QAAQ,WAAW,EACnB,gBAAgB,YAAY,CAAC,KAAK,CAAC,EAAE,EACrC,mBAAmB,eAAe,CAAC,GAAG,EAAE,GAAG,EAAE,QAAQ,EAAE,KAAK,CAAC,EAAE,EAC/D,cAAc,oBAAoB,CAChC,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,CAAC,EAC3C,QAAQ,EACR,KAAK,CACN,EACD,SAAS,YAAY,EACrB,UAAU,MAAM,EAChB,qBAAoB,kBAAiD,EACrE,iBAAgB,MAAM,8BAAmE,KACxF,YAAY,CAAC,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,CAAC,EAAE,QAAQ,EAAE,KAAK,CAuG3E,CAAC"}
|
package/dist/server/builder.js
CHANGED
|
@@ -2,13 +2,14 @@ import { createCacheObservability } from "../cache-observability.js";
|
|
|
2
2
|
import { mergeTags } from "../utils.js";
|
|
3
3
|
import { applyBasePath, normalizeRoutePath } from "../router.js";
|
|
4
4
|
import { mapEndpointToToolkit } from "./mapper.js";
|
|
5
|
+
import { exportClientContract } from "./client-contract.js";
|
|
5
6
|
const loadNodeAdapter = async () => {
|
|
6
7
|
if (typeof require !== "undefined") {
|
|
7
8
|
return require("../adapters/node.js");
|
|
8
9
|
}
|
|
9
10
|
return import("../adapters/node.js");
|
|
10
11
|
};
|
|
11
|
-
export const createBuilderMethods = (queryEntries, queryLogger, routeConfig, router, authStrategies, globalMiddlewares, executeQuery, handler, basePath, cacheObservability = createCacheObservability({})) => {
|
|
12
|
+
export const createBuilderMethods = (queryEntries, queryLogger, routeConfig, router, authStrategies, globalMiddlewares, executeQuery, handler, basePath, cacheObservability = createCacheObservability({}), clientContract = () => exportClientContract([], '')) => {
|
|
12
13
|
const builder = {
|
|
13
14
|
queries: queryEntries,
|
|
14
15
|
basePath: basePath || undefined,
|
|
@@ -25,6 +26,7 @@ export const createBuilderMethods = (queryEntries, queryLogger, routeConfig, rou
|
|
|
25
26
|
}
|
|
26
27
|
return manifest;
|
|
27
28
|
},
|
|
29
|
+
clientContract,
|
|
28
30
|
route: (path, endpoint, options = {}) => {
|
|
29
31
|
if (!endpoint) {
|
|
30
32
|
throw new Error("Endpoint definition is required when registering a route");
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { PreparedProtocolClientContract } from '@hypequery/protocol';
|
|
2
|
+
import type { ClientEndpointBinding } from '../semantic/datasets/utils/client-endpoint-binding.js';
|
|
3
|
+
/** Validate the trusted mount path every client contract path starts with. */
|
|
4
|
+
export declare function resolveClientMountPath(mountPath: string | undefined): string;
|
|
5
|
+
/** The build view of every describable endpoint, in registration order. */
|
|
6
|
+
export declare function exportClientContract(bindings: readonly ClientEndpointBinding[], mountPath: string): PreparedProtocolClientContract;
|
|
7
|
+
//# sourceMappingURL=client-contract.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-contract.d.ts","sourceRoot":"","sources":["../../src/server/client-contract.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,qBAAqB,CAAC;AAC1E,OAAO,KAAK,EAAE,qBAAqB,EAAE,MAAM,uDAAuD,CAAC;AAEnG,8EAA8E;AAC9E,wBAAgB,sBAAsB,CAAC,SAAS,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAM5E;AAED,2EAA2E;AAC3E,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,SAAS,qBAAqB,EAAE,EAC1C,SAAS,EAAE,MAAM,GAChB,8BAA8B,CAKhC"}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { buildDatasetClientContract } from '@hypequery/datasets';
|
|
2
|
+
/** Validate the trusted mount path every client contract path starts with. */
|
|
3
|
+
export function resolveClientMountPath(mountPath) {
|
|
4
|
+
if (mountPath === undefined || mountPath === '')
|
|
5
|
+
return '';
|
|
6
|
+
if (!mountPath.startsWith('/') || mountPath.endsWith('/')) {
|
|
7
|
+
throw new Error('createAPI: clientContract.mountPath must be empty or an absolute path without a trailing slash.');
|
|
8
|
+
}
|
|
9
|
+
return mountPath;
|
|
10
|
+
}
|
|
11
|
+
/** The build view of every describable endpoint, in registration order. */
|
|
12
|
+
export function exportClientContract(bindings, mountPath) {
|
|
13
|
+
const definitions = bindings
|
|
14
|
+
.map(binding => binding.definition())
|
|
15
|
+
.filter((definition) => definition !== undefined);
|
|
16
|
+
return buildDatasetClientContract(definitions, { mountPath });
|
|
17
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { QueryBuilderFactoryLike } from "@hypequery/datasets";
|
|
2
|
+
export interface ContextQueryBuilder {
|
|
3
|
+
/** Stand-in builder for construction-time wiring; delegates to the bound builder. */
|
|
4
|
+
readonly builder: QueryBuilderFactoryLike;
|
|
5
|
+
/** The builder bound from the first request's context, if any. */
|
|
6
|
+
current(): QueryBuilderFactoryLike | undefined;
|
|
7
|
+
/**
|
|
8
|
+
* Binds the first builder a request's context returns, and maps later
|
|
9
|
+
* requests that return the same builder back to the stand-in, so they share
|
|
10
|
+
* the stand-in's identity (and with it the dataset client's result cache).
|
|
11
|
+
* A different builder is returned as-is and runs as a per-call override.
|
|
12
|
+
*/
|
|
13
|
+
resolve(fromContext: QueryBuilderFactoryLike): QueryBuilderFactoryLike;
|
|
14
|
+
/**
|
|
15
|
+
* Builder for a request whose context returned no `db`. It always throws,
|
|
16
|
+
* so the request never falls back to a builder another request supplied.
|
|
17
|
+
*/
|
|
18
|
+
readonly missing: QueryBuilderFactoryLike;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Lets semantic endpoints be built when the query builder only exists per
|
|
22
|
+
* request, as with `context: () => ({ db })`.
|
|
23
|
+
*/
|
|
24
|
+
export declare function createContextQueryBuilder(): ContextQueryBuilder;
|
|
25
|
+
//# sourceMappingURL=context-query-builder.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"context-query-builder.d.ts","sourceRoot":"","sources":["../../src/server/context-query-builder.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,uBAAuB,EAAE,MAAM,qBAAqB,CAAC;AAOnE,MAAM,WAAW,mBAAmB;IAClC,qFAAqF;IACrF,QAAQ,CAAC,OAAO,EAAE,uBAAuB,CAAC;IAC1C,kEAAkE;IAClE,OAAO,IAAI,uBAAuB,GAAG,SAAS,CAAC;IAC/C;;;;;OAKG;IACH,OAAO,CAAC,WAAW,EAAE,uBAAuB,GAAG,uBAAuB,CAAC;IACvE;;;OAGG;IACH,QAAQ,CAAC,OAAO,EAAE,uBAAuB,CAAC;CAC3C;AAWD;;;GAGG;AACH,wBAAgB,yBAAyB,IAAI,mBAAmB,CA0C/D"}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
const UNBOUND_MESSAGE = "createAPI: no query builder is available yet. `context` is a function, so the builder " +
|
|
2
|
+
"is read from `ctx.db` on each request, and no request has supplied one. Return the " +
|
|
3
|
+
"createQueryBuilder(config) result as `db` from `context`, or pass it to serve() as `queryBuilder`.";
|
|
4
|
+
const throwingBuilder = (message) => ({
|
|
5
|
+
table() {
|
|
6
|
+
throw new Error(message);
|
|
7
|
+
},
|
|
8
|
+
async rawQuery() {
|
|
9
|
+
throw new Error(message);
|
|
10
|
+
},
|
|
11
|
+
});
|
|
12
|
+
/**
|
|
13
|
+
* Lets semantic endpoints be built when the query builder only exists per
|
|
14
|
+
* request, as with `context: () => ({ db })`.
|
|
15
|
+
*/
|
|
16
|
+
export function createContextQueryBuilder() {
|
|
17
|
+
let bound;
|
|
18
|
+
const target = () => {
|
|
19
|
+
if (!bound)
|
|
20
|
+
throw new Error(UNBOUND_MESSAGE);
|
|
21
|
+
return bound;
|
|
22
|
+
};
|
|
23
|
+
const builder = {
|
|
24
|
+
get datasetSqlDialect() {
|
|
25
|
+
return bound?.datasetSqlDialect;
|
|
26
|
+
},
|
|
27
|
+
table: (name) => target().table(name),
|
|
28
|
+
rawQuery(sql, params, options) {
|
|
29
|
+
return target().rawQuery(sql, params, options);
|
|
30
|
+
},
|
|
31
|
+
// Optional on the protocol: present only when the bound builder can
|
|
32
|
+
// stream, so a builder that cannot still gets its clear error.
|
|
33
|
+
get rawStream() {
|
|
34
|
+
return bound?.rawStream?.bind(bound);
|
|
35
|
+
},
|
|
36
|
+
get rawArrowStream() {
|
|
37
|
+
return bound?.rawArrowStream?.bind(bound);
|
|
38
|
+
},
|
|
39
|
+
};
|
|
40
|
+
return {
|
|
41
|
+
builder,
|
|
42
|
+
current: () => bound,
|
|
43
|
+
resolve(fromContext) {
|
|
44
|
+
bound ??= fromContext;
|
|
45
|
+
return fromContext === bound ? builder : fromContext;
|
|
46
|
+
},
|
|
47
|
+
missing: throwingBuilder("createAPI: this request's context returned no query builder as `db`, which semantic " +
|
|
48
|
+
"endpoints need. Return the createQueryBuilder(config) result as `db` from `context`, " +
|
|
49
|
+
"or pass it to serve() as `queryBuilder`."),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"create-api.d.ts","sourceRoot":"","sources":["../../src/server/create-api.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,WAAW,EAEX,YAAY,EAEZ,gBAAgB,EAIhB,eAAe,EACf,WAAW,EACX,aAAa,EACb,cAAc,EACd,wBAAwB,EACzB,MAAM,aAAa,CAAC;
|
|
1
|
+
{"version":3,"file":"create-api.d.ts","sourceRoot":"","sources":["../../src/server/create-api.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EACV,WAAW,EAEX,YAAY,EAEZ,gBAAgB,EAIhB,eAAe,EACf,WAAW,EACX,aAAa,EACb,cAAc,EACd,wBAAwB,EACzB,MAAM,aAAa,CAAC;AAyCrB;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4BG;AACH,eAAO,MAAM,SAAS,GACpB,QAAQ,SAAS,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,EAClE,KAAK,SAAS,WAAW,GAAG,WAAW,EACvC,QAAQ,SAAS,eAAe,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EACxE,QAAQ,SAAS,aAAa,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EAC5D,SAAS,SAAS,cAAc,CAAC,KAAK,CAAC,GAAG,MAAM,CAAC,KAAK,EAAE,KAAK,CAAC,EAE9D,QAAQ,WAAW,CAAC,QAAQ,EAAE,KAAK,EAAE,QAAQ,EAAE,QAAQ,EAAE,SAAS,CAAC,KAClE,YAAY,CACb,gBAAgB,CAAC,QAAQ,EAAE,QAAQ,EAAE,KAAK,CAAC,GACvC,wBAAwB,CAAC,QAAQ,EAAE,SAAS,EAAE,QAAQ,EAAE,KAAK,CAAC,EAClE,QAAQ,EACR,KAAK,CA0YN,CAAC"}
|
|
@@ -14,7 +14,14 @@ import { createCacheObservability, detectBuilderCache } from "../cache-observabi
|
|
|
14
14
|
import { createDatasetClient, serializeSemanticContract, toQueryBuilderFactory } from "@hypequery/datasets";
|
|
15
15
|
import { createMetricEndpoint, createDatasetEndpoint, createSemanticContractEndpoint, buildSemanticContractSource, } from "../semantic/datasets/index.js";
|
|
16
16
|
import { attachServeMcpSource } from "./mcp-source.js";
|
|
17
|
+
import { collectMcpRestrictions } from "../semantic/datasets/utils/mcp-restrictions.js";
|
|
18
|
+
import { exportClientContract, resolveClientMountPath } from "./client-contract.js";
|
|
19
|
+
import { createClientEndpointBinding } from "../semantic/datasets/utils/client-endpoint-binding.js";
|
|
20
|
+
import { endpointClientProfile } from "../semantic/datasets/utils/client-endpoint-profile.js";
|
|
21
|
+
import { resolveDatasetEntry } from "../semantic/datasets/utils/dataset-entry.js";
|
|
22
|
+
import { resolveMetricEntry } from "../semantic/datasets/metric-endpoint.js";
|
|
17
23
|
import { attachSemanticQueryBuilder, extractQueryBuilderFromContext } from "../semantic/query-builder-context.js";
|
|
24
|
+
import { createContextQueryBuilder } from "./context-query-builder.js";
|
|
18
25
|
const assertSemanticKeyAvailable = (queryEntries, key, kind) => {
|
|
19
26
|
if (key in queryEntries) {
|
|
20
27
|
throw new Error(`createAPI: ${kind} "${key}" collides with an existing query key. ` +
|
|
@@ -53,6 +60,16 @@ const assertSemanticKeyAvailable = (queryEntries, key, kind) => {
|
|
|
53
60
|
export const createAPI = (config) => {
|
|
54
61
|
const basePath = config.basePath ?? "/api/analytics";
|
|
55
62
|
const router = new ServeRouter(basePath);
|
|
63
|
+
const clientMountPath = resolveClientMountPath(config.clientContract?.mountPath);
|
|
64
|
+
// Dataset and metric endpoints in registration order; each is exported at the
|
|
65
|
+
// path the manifest names, so it resolves through `api` once that exists.
|
|
66
|
+
const clientBindings = [];
|
|
67
|
+
// Client contract routes are POST. An `api.route()` override with another
|
|
68
|
+
// method can't be advertised, but the endpoint's own POST route stays live.
|
|
69
|
+
const clientPath = (key, routePath) => {
|
|
70
|
+
const entry = api.manifest()[key];
|
|
71
|
+
return entry?.method === 'POST' && entry.path ? entry.path : applyBasePath(basePath, routePath);
|
|
72
|
+
};
|
|
56
73
|
const globalMiddlewares = [
|
|
57
74
|
...(config.middlewares ?? []),
|
|
58
75
|
];
|
|
@@ -66,6 +83,9 @@ export const createAPI = (config) => {
|
|
|
66
83
|
: undefined;
|
|
67
84
|
let resolvedQueryBuilder = explicitQueryBuilder;
|
|
68
85
|
let extractedFromContext = false;
|
|
86
|
+
// With a context function the builder only exists per request; semantic
|
|
87
|
+
// endpoints wire up against a stand-in bound to the first request's `ctx.db`.
|
|
88
|
+
let contextQueryBuilder;
|
|
69
89
|
if (!resolvedQueryBuilder && baseContextFactory && (config.metrics || config.datasets)) {
|
|
70
90
|
// If context is a static object (not a function), we can extract queryBuilder synchronously
|
|
71
91
|
if (typeof baseContextFactory !== "function") {
|
|
@@ -74,6 +94,10 @@ export const createAPI = (config) => {
|
|
|
74
94
|
extractedFromContext = true;
|
|
75
95
|
}
|
|
76
96
|
}
|
|
97
|
+
else {
|
|
98
|
+
contextQueryBuilder = createContextQueryBuilder();
|
|
99
|
+
resolvedQueryBuilder = contextQueryBuilder.builder;
|
|
100
|
+
}
|
|
77
101
|
}
|
|
78
102
|
const contextFactory = baseContextFactory || resolvedQueryBuilder
|
|
79
103
|
? async ({ request, auth }) => {
|
|
@@ -92,7 +116,10 @@ export const createAPI = (config) => {
|
|
|
92
116
|
if (!extractedFromContext && typeof baseContextFactory === "function") {
|
|
93
117
|
const maybeQueryBuilder = extractQueryBuilderFromContext(baseContext);
|
|
94
118
|
if (maybeQueryBuilder) {
|
|
95
|
-
return attachSemanticQueryBuilder({ ...baseContext }, maybeQueryBuilder);
|
|
119
|
+
return attachSemanticQueryBuilder({ ...baseContext }, contextQueryBuilder ? contextQueryBuilder.resolve(maybeQueryBuilder) : maybeQueryBuilder);
|
|
120
|
+
}
|
|
121
|
+
if (contextQueryBuilder) {
|
|
122
|
+
return attachSemanticQueryBuilder({ ...baseContext }, contextQueryBuilder.missing);
|
|
96
123
|
}
|
|
97
124
|
}
|
|
98
125
|
return baseContext;
|
|
@@ -175,9 +202,30 @@ export const createAPI = (config) => {
|
|
|
175
202
|
const metricEndpoint = createMetricEndpoint(name, entry, analytics, builderFactory, relatedPolicies);
|
|
176
203
|
const metricsPath = config.semanticPaths?.metrics ?? '/metrics';
|
|
177
204
|
const routePath = normalizeRoutePath(`${metricsPath}/${name}`);
|
|
205
|
+
const { metric, maxLimit } = resolveMetricEntry(entry);
|
|
206
|
+
const clientEndpoint = createClientEndpointBinding(clientMountPath, () => {
|
|
207
|
+
// A fixed grain always returns a period, which the contract cannot say.
|
|
208
|
+
if (metric.__type === 'grained_metric_ref')
|
|
209
|
+
return undefined;
|
|
210
|
+
// Rows carry the value under the metric's name and React keys the hook
|
|
211
|
+
// by the entry's key; as in Python's create_api, the two are one name.
|
|
212
|
+
if (metric.name !== name) {
|
|
213
|
+
throw new Error(`Client export: metrics entry "${name}" serves metric "${metric.name}". `
|
|
214
|
+
+ `Register it under its own name to export a client contract.`);
|
|
215
|
+
}
|
|
216
|
+
return {
|
|
217
|
+
dataset: metric.dataset,
|
|
218
|
+
metric,
|
|
219
|
+
name,
|
|
220
|
+
path: clientPath(name, routePath),
|
|
221
|
+
profile: endpointClientProfile(metric.dataset, maxLimit),
|
|
222
|
+
};
|
|
223
|
+
});
|
|
224
|
+
clientBindings.push(clientEndpoint);
|
|
178
225
|
const registeredEndpoint = {
|
|
179
226
|
...metricEndpoint,
|
|
180
227
|
metadata: { ...metricEndpoint.metadata, path: routePath },
|
|
228
|
+
clientEndpoint,
|
|
181
229
|
};
|
|
182
230
|
queryEntries[name] = registeredEndpoint;
|
|
183
231
|
router.register(registeredEndpoint);
|
|
@@ -197,9 +245,25 @@ export const createAPI = (config) => {
|
|
|
197
245
|
const datasetEndpoint = createDatasetEndpoint(name, entry, getAnalytics(builderFactory), builderFactory, relatedPolicies);
|
|
198
246
|
const datasetsPath = config.semanticPaths?.datasets ?? '/datasets';
|
|
199
247
|
const routePath = normalizeRoutePath(`${datasetsPath}/${name}/query`);
|
|
248
|
+
const { dataset: served, maxLimit } = resolveDatasetEntry(entry);
|
|
249
|
+
const clientEndpoint = createClientEndpointBinding(clientMountPath, () => {
|
|
250
|
+
// React keys a dataset hook `dataset:<id>`, and a dataset endpoint's
|
|
251
|
+
// contract ID is its dataset's name, so the two must agree.
|
|
252
|
+
if (served.name !== name) {
|
|
253
|
+
throw new Error(`Client export: datasets entry "${name}" serves dataset "${served.name}". `
|
|
254
|
+
+ `Register it under its own name to export a client contract.`);
|
|
255
|
+
}
|
|
256
|
+
return {
|
|
257
|
+
dataset: served,
|
|
258
|
+
path: clientPath(`dataset:${name}`, routePath),
|
|
259
|
+
profile: endpointClientProfile(served, maxLimit),
|
|
260
|
+
};
|
|
261
|
+
});
|
|
262
|
+
clientBindings.push(clientEndpoint);
|
|
200
263
|
const registeredEndpoint = {
|
|
201
264
|
...datasetEndpoint,
|
|
202
265
|
metadata: { ...datasetEndpoint.metadata, path: routePath },
|
|
266
|
+
clientEndpoint,
|
|
203
267
|
};
|
|
204
268
|
queryEntries[`dataset:${name}`] = registeredEndpoint;
|
|
205
269
|
router.register(registeredEndpoint);
|
|
@@ -240,20 +304,41 @@ export const createAPI = (config) => {
|
|
|
240
304
|
// do; bare factories report no builder layer).
|
|
241
305
|
const cacheObservability = createCacheObservability({
|
|
242
306
|
getSemanticClient: () => sharedAnalytics,
|
|
243
|
-
getBuilderCache: () => detectBuilderCache(resolvedQueryBuilder),
|
|
307
|
+
getBuilderCache: () => detectBuilderCache(contextQueryBuilder?.current() ?? resolvedQueryBuilder),
|
|
244
308
|
});
|
|
245
|
-
const api = createAPImethods(queryEntries, queryLogger, router, authStrategies, globalMiddlewares, executeQuery, handler, basePath, cacheObservability);
|
|
309
|
+
const api = createAPImethods(queryEntries, queryLogger, router, authStrategies, globalMiddlewares, executeQuery, handler, basePath, cacheObservability, () => exportClientContract(clientBindings, clientMountPath));
|
|
246
310
|
// Expose the registered datasets to `hypequery mcp`, so the CLI serves the
|
|
247
311
|
// same semantic model as this entrypoint rather than a second MCP config.
|
|
248
312
|
if (config.datasets) {
|
|
249
313
|
const mcpDatasets = buildSemanticContractSource(config.datasets, config.metrics);
|
|
314
|
+
const restricted = collectMcpRestrictions(config.datasets, config.metrics);
|
|
250
315
|
attachServeMcpSource(api, {
|
|
251
316
|
datasets: mcpDatasets,
|
|
317
|
+
...(restricted.length > 0 ? { restricted } : {}),
|
|
318
|
+
// Read when MCP starts: `api.use()` may add global middlewares after defineServe.
|
|
319
|
+
globalMiddlewareCount: () => globalMiddlewares.length,
|
|
320
|
+
...(authStrategies.length > 0
|
|
321
|
+
? {
|
|
322
|
+
auth: {
|
|
323
|
+
strategies: authStrategies,
|
|
324
|
+
...(globalTenantConfig
|
|
325
|
+
? { tenant: { extract: globalTenantConfig.extract } }
|
|
326
|
+
: {}),
|
|
327
|
+
},
|
|
328
|
+
}
|
|
329
|
+
: {}),
|
|
252
330
|
resolveAnalytics: () => {
|
|
253
331
|
if (!resolvedQueryBuilder) {
|
|
254
332
|
throw new Error('A query builder is required to execute datasets over MCP. Pass `queryBuilder` '
|
|
255
333
|
+ 'to defineServe, or expose it as `context.db`.');
|
|
256
334
|
}
|
|
335
|
+
// MCP never runs the context factory, so a builder that only exists
|
|
336
|
+
// per request is unavailable there. Fail at startup, not on first query.
|
|
337
|
+
if (contextQueryBuilder && !contextQueryBuilder.current()) {
|
|
338
|
+
throw new Error('A query builder is required to execute datasets over MCP, and `context` is a '
|
|
339
|
+
+ 'function, so its `db` only exists per HTTP request. Pass `queryBuilder` to serve(), '
|
|
340
|
+
+ 'or use a static `context: { db }`.');
|
|
341
|
+
}
|
|
257
342
|
return getAnalytics(resolvedQueryBuilder);
|
|
258
343
|
},
|
|
259
344
|
});
|