@astrale-os/kernel-client 1.0.0-beta.21 → 1.0.0-beta.23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/dist/client/client.d.ts +6 -2
  2. package/dist/client/client.js +32 -21
  3. package/dist/client/index.d.ts +1 -1
  4. package/dist/client/index.js +1 -1
  5. package/dist/client/request.d.ts +7 -2
  6. package/dist/client/request.js +11 -7
  7. package/dist/graph/domain/binding.d.ts +2 -2
  8. package/dist/graph/graph.d.ts +17 -3
  9. package/dist/graph/graph.js +4 -1
  10. package/dist/graph/index.d.ts +2 -2
  11. package/dist/graph/page-contract.d.ts +53 -1
  12. package/dist/graph/query.d.ts +10 -4
  13. package/dist/graph/query.js +125 -2
  14. package/dist/graph/query.typecheck.d.ts +77 -0
  15. package/dist/graph/query.typecheck.js +34 -0
  16. package/dist/session/bound.js +25 -31
  17. package/dist/session/content/api.d.ts +10 -2
  18. package/dist/session/content/api.js +13 -4
  19. package/dist/session/content/index.d.ts +1 -1
  20. package/dist/session/content/input.d.ts +6 -1
  21. package/dist/session/content/input.js +12 -4
  22. package/dist/session/content/retry.d.ts +5 -1
  23. package/dist/session/content/retry.js +21 -16
  24. package/dist/session/durable.js +13 -19
  25. package/dist/session/index.d.ts +1 -1
  26. package/dist/session/retry.d.ts +12 -0
  27. package/dist/session/retry.js +23 -0
  28. package/dist/session/routing/dispatch.d.ts +7 -3
  29. package/dist/session/routing/dispatch.js +23 -13
  30. package/dist/session/routing/request.d.ts +2 -1
  31. package/dist/session/routing/request.js +2 -1
  32. package/dist/session/session.typecheck.js +15 -2
  33. package/dist/store/store.d.ts +6 -6
  34. package/dist/transport/http/admission.js +7 -42
  35. package/dist/transport/http/binary-request.d.ts +44 -0
  36. package/dist/transport/http/binary-request.js +110 -0
  37. package/dist/transport/http/index.d.ts +1 -1
  38. package/dist/transport/http/index.js +1 -1
  39. package/dist/transport/http/response.d.ts +0 -1
  40. package/dist/transport/http/response.js +0 -6
  41. package/dist/transport/http/transport.d.ts +10 -0
  42. package/dist/transport/http/transport.js +71 -17
  43. package/dist/transport/unary.d.ts +7 -0
  44. package/dist/transport/unary.js +34 -0
  45. package/dist/transport/websocket/connection.js +1 -7
  46. package/dist/transport/websocket/exchange.d.ts +2 -0
  47. package/dist/transport/websocket/exchange.js +13 -43
  48. package/package.json +5 -5
@@ -1,4 +1,5 @@
1
1
  import type { invocation as protocol } from '@astrale-os/kernel-protocol';
2
+ import type { BinaryBody } from '../transport/http/binary-request.js';
2
3
  import type { Transport } from '../transport/index.js';
3
4
  import type { AuthenticatedClient, RemoteCredential } from './credential.js';
4
5
  import type { Call, ClientDispatchOptions, ClientDispatchOptionsWithBody } from './request.js';
@@ -7,8 +8,11 @@ import { type HttpTransportOptions } from '../transport/http/index.js';
7
8
  export type ClientOptions = HttpTransportOptions | {
8
9
  readonly transport: Transport;
9
10
  };
10
- /** Package-private redirect continuation path; intentionally absent from the public Client facade. */
11
- export declare function dispatchTrace(client: Client, credential: RemoteCredential | undefined, call: Call, options: ClientDispatchOptions | ClientDispatchOptionsWithBody | undefined, trace: protocol.Trace): Promise<Result>;
11
+ /**
12
+ * Package-private Session routing path: it presents a redirect continuation's Trace and sends an
13
+ * admitted body, which may be a one-shot stream. Intentionally absent from the public Client facade.
14
+ */
15
+ export declare function dispatchInternal(client: Client, credential: RemoteCredential | undefined, call: Call, options: ClientDispatchOptions | undefined, trace?: protocol.Trace, body?: BinaryBody): Promise<Result>;
12
16
  /** Pure client for the universal remote Function invocation boundary. */
13
17
  export declare class Client implements AuthenticatedClient {
14
18
  private readonly transport;
@@ -1,16 +1,20 @@
1
1
  import { ClientError } from '../errors/index.js';
2
- import { HttpTransport } from '../transport/http/index.js';
2
+ import { cancelUnsent } from '../transport/http/binary-request.js';
3
+ import { dispatchBinaryBody, HttpTransport, } from '../transport/http/index.js';
3
4
  import { authenticated, resolveCredential } from './credential.js';
4
5
  import { admitRequest, invocation } from './request.js';
5
6
  import { requireBinary, requireStream, requireValue } from './result.js';
6
7
  import { admittedDeploymentRetiredError, admittedMissError, admittedStaleRouteError, } from './routing-control.js';
7
8
  const controlledDispatch = new WeakMap();
8
- /** Package-private redirect continuation path; intentionally absent from the public Client facade. */
9
- export function dispatchTrace(client, credential, call, options, trace) {
9
+ /**
10
+ * Package-private Session routing path: it presents a redirect continuation's Trace and sends an
11
+ * admitted body, which may be a one-shot stream. Intentionally absent from the public Client facade.
12
+ */
13
+ export function dispatchInternal(client, credential, call, options, trace, body) {
10
14
  const dispatch = controlledDispatch.get(client);
11
15
  if (dispatch === undefined)
12
- throw new TypeError('Trace dispatch requires an owned Client.');
13
- return dispatch(credential, call, options, trace);
16
+ throw new TypeError('Internal dispatch requires an owned Client.');
17
+ return dispatch(credential, call, options, trace, body);
14
18
  }
15
19
  /** Pure client for the universal remote Function invocation boundary. */
16
20
  export class Client {
@@ -24,7 +28,7 @@ export class Client {
24
28
  this.transport = Object.hasOwn(options, 'transport')
25
29
  ? admitTransport(options.transport)
26
30
  : new HttpTransport(options);
27
- controlledDispatch.set(this, (credential, call, requestOptions, trace) => this.dispatchWith(credential, call, requestOptions, trace));
31
+ controlledDispatch.set(this, (credential, call, requestOptions, trace, body) => this.dispatchWith(credential, call, requestOptions, trace, body));
28
32
  }
29
33
  dispatch(call, options) {
30
34
  return this.dispatchWith(undefined, call, options);
@@ -49,25 +53,32 @@ export class Client {
49
53
  this.lifecycle.abort(failure);
50
54
  this.transport.close?.();
51
55
  }
52
- async dispatchWith(credential, input, options, trace) {
56
+ async dispatchWith(credential, input, options, trace, body) {
53
57
  if (this.closed)
54
58
  throw new ClientError('Client is closed.');
55
- const request = admitRequest(input, options, this.lifecycle.signal);
56
- const resolved = credential === undefined
57
- ? undefined
58
- : await resolveCredential(credential, request.options.signal);
59
- requireRequestLive(request.options.signal);
60
- const envelope = invocation(request, resolved, trace);
59
+ const request = admitRequest(input, options, this.lifecycle.signal, body);
61
60
  let result;
62
- if (request.body === undefined) {
63
- result = await this.transport.dispatch(envelope, request.options);
64
- }
65
- else {
66
- const transport = this.transport;
67
- if (!(transport instanceof HttpTransport)) {
68
- throw new TypeError('Binary dispatch requires HTTP transport.');
61
+ try {
62
+ const resolved = credential === undefined
63
+ ? undefined
64
+ : await resolveCredential(credential, request.options.signal);
65
+ requireRequestLive(request.options.signal);
66
+ const envelope = invocation(request, resolved, trace);
67
+ if (request.body === undefined) {
68
+ result = await this.transport.dispatch(envelope, request.options);
69
+ }
70
+ else {
71
+ const transport = this.transport;
72
+ if (!(transport instanceof HttpTransport)) {
73
+ throw new TypeError('Binary dispatch requires HTTP transport.');
74
+ }
75
+ result = await dispatchBinaryBody(transport, envelope, request.body, request.options);
69
76
  }
70
- result = await transport.dispatchBinary(envelope, request.body, request.options);
77
+ }
78
+ catch (cause) {
79
+ // A stream body this request never started to send is cancelled with it.
80
+ cancelUnsent(request.body);
81
+ throw cause;
71
82
  }
72
83
  if (result.kind === 'stale')
73
84
  throw admittedStaleRouteError(result.current, result.invocation);
@@ -1,4 +1,4 @@
1
- export { Client, dispatchTrace, type ClientOptions } from './client.js';
1
+ export { Client, dispatchInternal, type ClientOptions } from './client.js';
2
2
  export { acceptCall } from './admission.js';
3
3
  export type { AuthenticatedClient, RemoteCredential } from './credential.js';
4
4
  export { call, type Call, type ClientDispatchOptions, type ClientDispatchOptionsWithBody, } from './request.js';
@@ -1,4 +1,4 @@
1
- export { Client, dispatchTrace } from './client.js';
1
+ export { Client, dispatchInternal } from './client.js';
2
2
  export { acceptCall } from './admission.js';
3
3
  export { call, } from './request.js';
4
4
  export { isAdmittedDeploymentRetiredError, isAdmittedMissError, isAdmittedStaleRouteError, } from './routing-control.js';
@@ -1,6 +1,7 @@
1
1
  import type { Target } from '@astrale-os/kernel-core/callable';
2
2
  import type { PathLike } from '@astrale-os/kernel-core/path';
3
3
  import type * as protocol from '@astrale-os/kernel-protocol/invocation';
4
+ import type { BinaryBody } from '../transport/http/binary-request.js';
4
5
  import type { RequestOptions, TransportRequest } from '../transport/index.js';
5
6
  import type { Input } from './result.js';
6
7
  /** One portable call before Path canonicalization, correlation, and credential binding. */
@@ -27,8 +28,12 @@ export interface AdmittedRequest {
27
28
  readonly schema?: protocol.SchemaTarget;
28
29
  readonly maintenance?: protocol.Maintenance;
29
30
  readonly options: RequestOptions;
30
- readonly body?: Blob;
31
+ readonly body?: BinaryBody;
31
32
  }
32
33
  export declare function call(target: PathLike | Target, input: Input): Call;
33
- export declare function admitRequest(input: Call, options: ClientDispatchOptions | ClientDispatchOptionsWithBody | undefined, lifecycle: AbortSignal): AdmittedRequest;
34
+ /**
35
+ * Admit one request. A public caller's body is a Blob in its options; the package-private path
36
+ * passes a body its owner already admitted, which may be a stream that only Session routing sends.
37
+ */
38
+ export declare function admitRequest(input: Call, options: ClientDispatchOptions | ClientDispatchOptionsWithBody | undefined, lifecycle: AbortSignal, admittedBody?: BinaryBody): AdmittedRequest;
34
39
  export declare function invocation(request: AdmittedRequest, credential?: string, trace?: protocol.Trace): TransportRequest;
@@ -1,11 +1,17 @@
1
1
  import * as invocationProtocol from '@astrale-os/kernel-protocol/invocation';
2
+ import { replayableBody } from '../transport/http/binary-request.js';
2
3
  import { acceptCall } from './admission.js';
3
4
  export function call(target, input) {
4
5
  return Object.freeze({ target, input });
5
6
  }
6
- export function admitRequest(input, options, lifecycle) {
7
+ /**
8
+ * Admit one request. A public caller's body is a Blob in its options; the package-private path
9
+ * passes a body its owner already admitted, which may be a stream that only Session routing sends.
10
+ */
11
+ export function admitRequest(input, options, lifecycle, admittedBody) {
7
12
  const call = acceptCall(input);
8
13
  const admitted = admitRequestOptions(options);
14
+ const body = admittedBody ?? admitted.body;
9
15
  const admittedOptions = lifecycleOptions(admitted.options, lifecycle);
10
16
  const delegate = admitDelegate(options?.delegate);
11
17
  const routing = admitRouting(options?.routing);
@@ -17,7 +23,7 @@ export function admitRequest(input, options, lifecycle) {
17
23
  ...(routing === undefined ? {} : { routing }),
18
24
  ...(schema === undefined ? {} : { schema }),
19
25
  ...(maintenance === undefined ? {} : { maintenance }),
20
- ...(admitted.body === undefined ? {} : { body: admitted.body }),
26
+ ...(body === undefined ? {} : { body }),
21
27
  options: admittedOptions,
22
28
  });
23
29
  }
@@ -71,14 +77,12 @@ function admitRequestOptions(input) {
71
77
  input.timeoutMs > 2_147_483_647)) {
72
78
  throw new TypeError('Client request timeoutMs must be a positive safe platform integer.');
73
79
  }
74
- const hasBody = Object.hasOwn(input, 'body');
75
80
  let body;
76
- if (hasBody) {
81
+ if (Object.hasOwn(input, 'body')) {
77
82
  const candidate = input.body;
78
- if (!(candidate instanceof Blob)) {
83
+ if (!(candidate instanceof Blob))
79
84
  throw new TypeError('Binary input must be a Blob or File.');
80
- }
81
- body = candidate;
85
+ body = replayableBody(candidate);
82
86
  }
83
87
  if (body !== undefined && input.idempotencyKey !== undefined) {
84
88
  throw new TypeError('Binary requests cannot carry an idempotency key.');
@@ -3,11 +3,11 @@ import type { Node } from '@astrale-os/kernel-core/graph/node';
3
3
  import type { QueryAST, QuerySingleSourceClassOf } from '@astrale-os/kernel-core/graph/query';
4
4
  import type { Domain } from '@astrale-os/kernel-dsl/v1/domain';
5
5
  import type { AnyResolvedClass, ResolvedClass } from '@astrale-os/kernel-dsl/v1/language';
6
- import type { GraphApi, GraphQueryOptions } from '../graph.js';
6
+ import type { GraphApi, GraphQueryV6Options } from '../graph.js';
7
7
  import type { BoundEdge, BoundNode } from './model.js';
8
8
  import type { BoundQueryPage } from './page.js';
9
9
  import type { MethodCall } from './project.js';
10
- export type DomainQueryOptions = Omit<GraphQueryOptions, 'expected'>;
10
+ export type DomainQueryOptions = Omit<GraphQueryV6Options, 'expected'>;
11
11
  type AdmittedSourceClasses<Query extends QueryAST> = [QuerySingleSourceClassOf<Query>] extends [
12
12
  never
13
13
  ] ? never : QuerySingleSourceClassOf<Query> extends AnyResolvedClass ? unknown : never;
@@ -1,15 +1,27 @@
1
1
  import type { GraphSpec } from '@astrale-os/kernel-core/graph/graph';
2
2
  import type { MutationAST as MutationASTValue, MutationBuilder, MutationInput, MutationResult as MutationResultValue } from '@astrale-os/kernel-core/graph/mutate';
3
3
  import type { Node } from '@astrale-os/kernel-core/graph/node';
4
- import type { QueryAST as QueryASTValue, QueryEdgeClassInput, QueryResultFor } from '@astrale-os/kernel-core/graph/query';
4
+ import type { QueryAST as QueryASTValue, QueryEdgeClassInput, QueryResultFor, wire } from '@astrale-os/kernel-core/graph/query';
5
5
  import type { NodeTarget } from '@astrale-os/kernel-core/path';
6
6
  import type { DomainDependency } from '@astrale-os/kernel-dsl/v1/schema';
7
7
  import type { Call, Input } from '../client/index.js';
8
8
  import type { RequestOptions } from '../transport/index.js';
9
- import type { QueryPageRequest, QueryResponse } from './page-contract.js';
9
+ import type { QueryAnswerFor, QueryPageRequest, QueryResponse } from './page-contract.js';
10
10
  import type { NeighborsOptions, NodePage } from './page/index.js';
11
11
  export type GraphCall = (call: Call, options?: RequestOptions) => Promise<Input>;
12
+ /**
13
+ * The delivery of one Query: its page sizes and cursor (`paging`, never meaning, W1), the exact
14
+ * Domain revisions it is planned against, and its transport options.
15
+ */
12
16
  export interface GraphQueryOptions extends RequestOptions {
17
+ readonly paging?: wire.Paging;
18
+ readonly expected?: readonly DomainDependency[];
19
+ }
20
+ /**
21
+ * The options of a V6 QueryAST: its page and the exact Domain revisions it is planned against.
22
+ * @deprecated Query V6 is the legacy language: send a Query with `GraphQueryOptions`.
23
+ */
24
+ export interface GraphQueryV6Options extends RequestOptions {
13
25
  readonly expected?: readonly DomainDependency[];
14
26
  readonly page: QueryPageRequest;
15
27
  }
@@ -19,7 +31,9 @@ export interface GraphMutationOptions extends RequestOptions {
19
31
  }
20
32
  export type MutationAuthor = (mutation: MutationBuilder) => undefined;
21
33
  export interface GraphApi {
22
- query<Query extends QueryASTValue>(ast: Query, options: GraphQueryOptions): Promise<QueryResponse<QueryResultFor<Query>>>;
34
+ query<Query extends wire.Document>(query: Query, options?: GraphQueryOptions): Promise<QueryAnswerFor<Query>>;
35
+ /** The legacy V6 path; it stays the last overload, which `Parameters` and `ReturnType` read. */
36
+ query<Query extends QueryASTValue>(ast: Query, options: GraphQueryV6Options): Promise<QueryResponse<QueryResultFor<Query>>>;
23
37
  mutate(author: MutationAuthor, options?: GraphMutationOptions): Promise<MutationResultValue>;
24
38
  mutate(ast: MutationASTValue | MutationInput | GraphSpec, options?: GraphMutationOptions): Promise<MutationResultValue>;
25
39
  get(target: NodeTarget, options?: RequestOptions): Promise<Node | null>;
@@ -6,7 +6,10 @@ import { getNode, requireNode } from './read.js';
6
6
  export function createGraph(call) {
7
7
  if (typeof call !== 'function')
8
8
  throw new TypeError('Graph call capability is invalid.');
9
- const query = (ast, options) => queryGraph(call, ast, options);
9
+ function query(input, options) {
10
+ // The overloads above type the call; `queryGraph` dispatches on the input itself.
11
+ return queryGraph(call, input, options);
12
+ }
10
13
  const mutate = (input, options) => mutateGraph(call, input, options);
11
14
  return Object.freeze({
12
15
  query,
@@ -1,5 +1,5 @@
1
- export { createGraph, type GraphApi, type GraphCall, type GraphMutationOptions, type GraphQueryOptions, type MutationAuthor, } from './graph.js';
2
- export type { QueryPageRequest, QueryResponse } from './page-contract.js';
1
+ export { createGraph, type GraphApi, type GraphCall, type GraphQueryOptions, type GraphMutationOptions, type GraphQueryV6Options, type MutationAuthor, } from './graph.js';
2
+ export type { QueryAnswer, QueryAnswerFor, QueryItem, QueryPage, QueryPageRequest, QueryResponse, } from './page-contract.js';
3
3
  export { type BoundEdge, type BoundEdgePage, type BoundGraphValue, type BoundNode, type BoundNodeFor, type BoundNodePage, type BoundQueryPage, type DomainBinding, type DomainQueryOptions, definedClass, validateDefinedProperties, } from './domain/index.js';
4
4
  export { NodeUnavailableError } from './errors.js';
5
5
  export type { NeighborsOptions, NodePage } from './page/index.js';
@@ -1,4 +1,6 @@
1
- import type { QueryResult } from '@astrale-os/kernel-core/graph/query';
1
+ import type { EdgeKey } from '@astrale-os/kernel-core/graph/edge';
2
+ import type { FactId } from '@astrale-os/kernel-core/graph/formula';
3
+ import type { Answer, QueryResult, Undecided, wire } from '@astrale-os/kernel-core/graph/query';
2
4
  /** Caller-selected bounds and continuation for one graph query page. */
3
5
  export interface QueryPageRequest {
4
6
  readonly size: number;
@@ -17,3 +19,53 @@ export interface QueryResponse<Result extends QueryResult = QueryResult> {
17
19
  */
18
20
  readonly certification?: 'uncertified';
19
21
  }
22
+ /**
23
+ * One Page of a Query's answer (page "Fondations Query v7", § Résultats): the exact prefix of its
24
+ * list, and the opaque cursor that continues it when an item follows (W2, W3).
25
+ */
26
+ export type QueryPage = {
27
+ readonly items: readonly QueryItem[];
28
+ readonly undecided?: Undecided;
29
+ } & ({
30
+ readonly complete: true;
31
+ } | {
32
+ readonly complete: false;
33
+ readonly cursor: string;
34
+ });
35
+ /** One delivered item: its fact, the Edge its Branch followed, the ends it renders, its Branches. */
36
+ export interface QueryItem {
37
+ readonly fact: FactId;
38
+ readonly edge?: EdgeKey;
39
+ readonly source?: QueryItem;
40
+ readonly target?: QueryItem;
41
+ readonly branches: Readonly<Record<string, QueryPage | Exclude<Answer, {
42
+ readonly list: unknown;
43
+ }>>>;
44
+ }
45
+ /**
46
+ * What a Query answers, by the family of its root fold: a list's Page, the table of the facts it
47
+ * renders as values, the revision it was read at and whether its cursor came from another (W6);
48
+ * an `exists`; or a `count`.
49
+ */
50
+ export type QueryAnswer = {
51
+ readonly list: QueryPage;
52
+ readonly facts: Extract<Answer, {
53
+ readonly list: unknown;
54
+ }>['facts'];
55
+ readonly revision: string;
56
+ readonly revised?: true;
57
+ } | Exclude<Answer, {
58
+ readonly list: unknown;
59
+ }>;
60
+ /** The answer of the family a Query's root fold names. */
61
+ export type QueryAnswerFor<Query extends wire.Document> = Query extends {
62
+ readonly list: unknown;
63
+ } ? Extract<QueryAnswer, {
64
+ readonly list: unknown;
65
+ }> : Query extends {
66
+ readonly exists: unknown;
67
+ } ? Extract<QueryAnswer, {
68
+ readonly exists: unknown;
69
+ }> : Extract<QueryAnswer, {
70
+ readonly count: unknown;
71
+ }>;
@@ -1,7 +1,13 @@
1
- import type { QueryAST as QueryASTValue, QueryResultFor } from '@astrale-os/kernel-core/graph/query';
1
+ import type { QueryAST as QueryASTValue, QueryResultFor, wire } from '@astrale-os/kernel-core/graph/query';
2
2
  import { Path, type NodeTarget } from '@astrale-os/kernel-core/path';
3
- import type { GraphCall, GraphQueryOptions } from './graph.js';
4
- import type { QueryResponse } from './page-contract.js';
3
+ import type { GraphCall, GraphQueryOptions, GraphQueryV6Options } from './graph.js';
4
+ import type { QueryAnswerFor, QueryResponse } from './page-contract.js';
5
5
  /** Point/neighbor reads are exact targets, unlike Query's overloaded Class sources. */
6
6
  export declare function queryNodePath(target: NodeTarget): Path;
7
- export declare function queryGraph<Query extends QueryASTValue>(call: GraphCall, input: Query, options: GraphQueryOptions): Promise<QueryResponse<QueryResultFor<Query>>>;
7
+ /**
8
+ * Query the graph. A Query names its version in `query` (`"astrale.query/7"`); anything else
9
+ * takes the legacy V6 path, whose codec admits a QueryAST by its `format` and `version` and
10
+ * refuses the rest as it always has.
11
+ */
12
+ export declare function queryGraph<Query extends wire.Document>(call: GraphCall, query: Query, options?: GraphQueryOptions): Promise<QueryAnswerFor<Query>>;
13
+ export declare function queryGraph<Query extends QueryASTValue>(call: GraphCall, ast: Query, options: GraphQueryV6Options): Promise<QueryResponse<QueryResultFor<Query>>>;
@@ -1,6 +1,8 @@
1
- import { QueryAST, QueryASTDecodeError, QueryResult } from '@astrale-os/kernel-core/graph/query';
1
+ import { QUERY, QueryAST, QueryASTDecodeError, QueryResult, } from '@astrale-os/kernel-core/graph/query';
2
2
  import { Path, PathError } from '@astrale-os/kernel-core/path';
3
+ import { queryOutput } from '@astrale-os/kernel-core/schema/kernel/syscalls/contracts';
3
4
  import { query } from '@astrale-os/kernel-core/schema/kernel/syscalls/references';
5
+ import * as portable from '@astrale-os/kernel-dsl/value';
4
6
  import { call as invocation } from '../client/index.js';
5
7
  import { captureExpected } from './expectation.js';
6
8
  import { retainQueryProvenance } from './provenance.js';
@@ -17,7 +19,128 @@ export function queryNodePath(target) {
17
19
  throw new QueryASTDecodeError('/source/nodes/0', 'Invalid Node target', { cause });
18
20
  }
19
21
  }
20
- export async function queryGraph(call, input, options) {
22
+ export function queryGraph(call, input, options) {
23
+ return isQuery(input)
24
+ ? queryV7(call, input, options)
25
+ : queryLegacyAST(call, input, options);
26
+ }
27
+ /** A Query: an object naming `"query": "astrale.query/7"`. */
28
+ function isQuery(input) {
29
+ return isRecord(input) && input.query === QUERY;
30
+ }
31
+ // ─── Query v7 ───────────────────────────────────────────────────────────────────────────────
32
+ /**
33
+ * Send one Query (page "Fondations Query v7", § Wire v7) as the operation's request `{document,
34
+ * paging?, expected?}`, and admit the answer of its family. The Kernel decodes the Query against
35
+ * its Registry; the Client admits its structure only, before any I/O. A continuation is the same
36
+ * Query with `paging.after` set to a Page's cursor.
37
+ */
38
+ async function queryV7(call, input, options) {
39
+ const admitted = admitQuery(input);
40
+ const { expected, paging, ...request } = options ?? {};
41
+ const admittedPaging = admitPaging(paging);
42
+ const capturedExpected = captureExpected(expected);
43
+ const output = await call(invocation(KERNEL_QUERY_PATH, Object.freeze({
44
+ document: admitted,
45
+ ...(admittedPaging === undefined ? {} : { paging: admittedPaging }),
46
+ ...(capturedExpected === undefined ? {} : { expected: capturedExpected }),
47
+ })), options === undefined ? undefined : request);
48
+ return decodeAnswer(output, familyOf(admitted));
49
+ }
50
+ /** A detached, frozen Query of exactly one family; its names are the Kernel's to decode. */
51
+ function admitQuery(input) {
52
+ const query = snapshot(input, 'query');
53
+ if (!isRecord(query) || familyOf(query) === undefined) {
54
+ return invalid('query', 'it holds exactly one of list, exists, count');
55
+ }
56
+ return query;
57
+ }
58
+ /** A detached, frozen paging: sizes per list path, each at least 1, and a Page's cursor. */
59
+ function admitPaging(input) {
60
+ if (input === undefined)
61
+ return undefined;
62
+ const paging = snapshot(input, 'paging');
63
+ if (!isRecord(paging) || !hasOnlyKeys(paging, ['sizes', 'after'])) {
64
+ return invalid('paging', 'it is {sizes?, after?}');
65
+ }
66
+ const { sizes, after } = paging;
67
+ if (sizes !== undefined &&
68
+ (!Array.isArray(sizes) ||
69
+ !sizes.every((entry) => isRecord(entry) &&
70
+ hasExactKeys(entry, ['at', 'size']) &&
71
+ Array.isArray(entry.at) &&
72
+ entry.at.every((name) => typeof name === 'string') &&
73
+ Number.isSafeInteger(entry.size) &&
74
+ entry.size >= 1))) {
75
+ return invalid('paging', 'each size is {at: [Branch names], size: an integer of at least 1}');
76
+ }
77
+ if (after !== undefined && (typeof after !== 'string' || after.length === 0)) {
78
+ return invalid('paging', 'after is the cursor of a Page');
79
+ }
80
+ return paging;
81
+ }
82
+ /** A detached, frozen portable snapshot of one caller value. */
83
+ function snapshot(input, what) {
84
+ try {
85
+ return portable.acceptImmutable(input);
86
+ }
87
+ catch (cause) {
88
+ if (!(cause instanceof portable.BoundaryError))
89
+ throw cause;
90
+ return invalid(what, 'it is not a portable JSON value', cause);
91
+ }
92
+ }
93
+ function invalid(what, detail, cause) {
94
+ const subject = what === 'query' ? 'Graph query' : 'Graph query paging';
95
+ throw new TypeError(`${subject} is invalid: ${detail}.`, { cause });
96
+ }
97
+ /** The family a Query's root fold names; undefined unless it names exactly one. */
98
+ function familyOf(query) {
99
+ const families = ['list', 'exists', 'count'].filter((family) => family in query);
100
+ return families.length === 1 ? families[0] : undefined;
101
+ }
102
+ /**
103
+ * The Kernel's answer, admitted by the query operation's contract as a detached frozen value, of
104
+ * the family the Query asked for.
105
+ */
106
+ function decodeAnswer(input, family) {
107
+ const refuse = (cause) => {
108
+ throw new TypeError('Graph query answer is invalid.', { cause });
109
+ };
110
+ let value;
111
+ try {
112
+ value = portable.acceptImmutable(input);
113
+ }
114
+ catch (cause) {
115
+ if (!(cause instanceof portable.BoundaryError))
116
+ throw cause;
117
+ return refuse(cause);
118
+ }
119
+ if (!isRecord(value) || !(family in value) || !queryOutput.safeParse(value).success) {
120
+ return refuse();
121
+ }
122
+ const answer = value;
123
+ return 'list' in answer && !pagesClosed(answer.list) ? refuse() : answer;
124
+ }
125
+ /** Every Page, its Branches' included, carries a cursor exactly when an item follows it (W3). */
126
+ function pagesClosed(page) {
127
+ const continued = 'cursor' in page;
128
+ return page.complete !== continued && page.items.every(itemClosed);
129
+ }
130
+ function itemClosed(item) {
131
+ return ((item.source === undefined || itemClosed(item.source)) &&
132
+ (item.target === undefined || itemClosed(item.target)) &&
133
+ Object.values(item.branches).every((branch) => !('items' in branch) || pagesClosed(branch)));
134
+ }
135
+ function isRecord(input) {
136
+ return input !== null && typeof input === 'object' && !Array.isArray(input);
137
+ }
138
+ function hasOnlyKeys(input, allowed) {
139
+ return Object.keys(input).every((key) => allowed.includes(key));
140
+ }
141
+ // ─── Legacy: V6 QueryAST ────────────────────────────────────────────────────────────────────
142
+ /** The legacy path: one V6 QueryAST and its page, answered `{result, page}`. */
143
+ async function queryLegacyAST(call, input, options) {
21
144
  const ast = QueryAST.decode(input);
22
145
  const { expected, page, ...request } = options;
23
146
  const admittedPage = admitPage(page);
@@ -0,0 +1,77 @@
1
+ import type { QueryAST, QueryResultFor } from '@astrale-os/kernel-core/graph/query';
2
+ import type { GraphApi, GraphQueryV6Options } from './graph.js';
3
+ import type { QueryAnswer, QueryAnswerFor, QueryResponse } from './index.js';
4
+ type Equal<Left, Right> = (<Value>() => Value extends Left ? 1 : 2) extends <Value>() => (Value extends Right ? 1 : 2) ? true : false;
5
+ type Assert<Condition extends true> = Condition;
6
+ type ListAnswer = Extract<QueryAnswer, {
7
+ readonly list: unknown;
8
+ }>;
9
+ type ExistsAnswer = Extract<QueryAnswer, {
10
+ readonly exists: unknown;
11
+ }>;
12
+ type CountAnswer = Extract<QueryAnswer, {
13
+ readonly count: unknown;
14
+ }>;
15
+ declare const ast: QueryAST<import("@astrale-os/kernel-core/graph/query").QueryNodeSelect<{
16
+ kind: "value";
17
+ }>, never>;
18
+ declare const list: {
19
+ readonly query: "astrale.query/7";
20
+ readonly list: {
21
+ readonly nodes: readonly [`${string}:class.${string}`];
22
+ readonly orderBy: readonly [{
23
+ readonly property: `${string}:class.${string}.property.${string}`;
24
+ readonly direction: 'asc';
25
+ readonly missing: 'last';
26
+ }];
27
+ };
28
+ };
29
+ declare const exists: {
30
+ readonly query: "astrale.query/7";
31
+ readonly exists: {
32
+ readonly nodes: readonly [`${string}:class.${string}`];
33
+ };
34
+ };
35
+ declare const count: {
36
+ readonly query: "astrale.query/7";
37
+ readonly count: {
38
+ readonly nodes: readonly [`${string}:class.${string}`];
39
+ };
40
+ readonly upTo: 10;
41
+ };
42
+ declare function overloads(): Promise<readonly [QueryResponse<import("@astrale-os/kernel-core/graph/query").QueryNodeResult<{
43
+ kind: "value";
44
+ }>>, {
45
+ readonly list: import("./page-contract.js").QueryPage;
46
+ readonly facts: Extract<import("@astrale-os/kernel-core/graph/query").Answer, {
47
+ readonly list: unknown;
48
+ }>['facts'];
49
+ readonly revision: string;
50
+ readonly revised?: true;
51
+ }, {
52
+ readonly exists: boolean;
53
+ readonly undecided?: boolean;
54
+ }, {
55
+ readonly count: number;
56
+ readonly more: boolean;
57
+ readonly undecided?: import("@astrale-os/kernel-core/graph/query").Undecided;
58
+ }]>;
59
+ export type pickedByInput = Assert<Equal<Awaited<ReturnType<typeof overloads>>, readonly [QueryResponse<QueryResultFor<typeof ast>>, ListAnswer, ExistsAnswer, CountAnswer]>>;
60
+ export type answerByFamily = Assert<Equal<[
61
+ QueryAnswerFor<typeof list>,
62
+ QueryAnswerFor<typeof exists>,
63
+ QueryAnswerFor<typeof count>
64
+ ], [
65
+ ListAnswer,
66
+ ExistsAnswer,
67
+ CountAnswer
68
+ ]>>;
69
+ /** The legacy overload stays last: `Parameters` and `ReturnType` keep reading V6. */
70
+ export type legacyLast = Assert<Equal<[
71
+ Parameters<GraphApi['query']>,
72
+ Awaited<ReturnType<GraphApi['query']>>
73
+ ], [
74
+ [QueryAST, GraphQueryV6Options],
75
+ QueryResponse<QueryResultFor<QueryAST>>
76
+ ]>>;
77
+ export {};
@@ -0,0 +1,34 @@
1
+ import { Query, QUERY } from '@astrale-os/kernel-core/graph/query';
2
+ const ast = Query.from({ nodes: [task] }).select({ kind: 'nodes', projection: { kind: 'value' } });
3
+ const list = {
4
+ query: QUERY,
5
+ list: { nodes: [Task], orderBy: [{ property: title, direction: 'asc', missing: 'last' }] },
6
+ };
7
+ const exists = { query: QUERY, exists: { nodes: [Task] } };
8
+ const count = { query: QUERY, count: { nodes: [Task] }, upTo: 10 };
9
+ async function overloads() {
10
+ // A V6 QueryAST picks the legacy overload and its result; a Query the answer of its family.
11
+ const legacy = await graph.query(ast, { page: { size: 10 } });
12
+ const listed = await graph.query(list, { paging: { sizes: [{ at: [], size: 10 }] } });
13
+ const decided = await graph.query(exists);
14
+ const counted = await graph.query(count, { expected: [] });
15
+ return [legacy, listed, decided, counted];
16
+ }
17
+ async function refusals() {
18
+ // @ts-expect-error A Query takes its paging in `paging`, not V6's `page`.
19
+ await graph.query(list, { page: { size: 10 } });
20
+ // @ts-expect-error A V6 QueryAST needs its `page`; v7 `paging` is not one.
21
+ await graph.query(ast, { paging: { sizes: [{ at: [], size: 10 }] } });
22
+ // @ts-expect-error A V6 QueryAST has no default page.
23
+ await graph.query(ast);
24
+ // @ts-expect-error A Query names the v7 version.
25
+ await graph.query({ query: 'astrale.query/6', list: { nodes: [Task] } });
26
+ // @ts-expect-error A Query's root fold is list, exists or count.
27
+ await graph.query({ query: QUERY, nodes: [Task] });
28
+ // @ts-expect-error A count needs its bound.
29
+ await graph.query({ query: QUERY, count: { nodes: [Task] } });
30
+ // @ts-expect-error An input is a Query or a V6 QueryAST.
31
+ await graph.query({ ...ast, query: QUERY });
32
+ }
33
+ void overloads;
34
+ void refusals;