@astrale-os/sdk 0.6.0-beta.66 → 0.6.0-beta.67

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.
@@ -135,10 +135,15 @@ export class Crossings {
135
135
  const edges = [...new Set(known.flatMap((c) => this.#concreteOf(c)))];
136
136
  const reached = this.model.reached(known, direction).flatMap((c) => this.#concreteOf(c));
137
137
  const nodes = this.#narrowed([...new Set(reached)], traversal.node);
138
- for (const c of [...edges, ...nodes])
138
+ // A walk also crosses the Nodes it passes through: those it reaches that meet `through`.
139
+ const reach = traversal.reachable;
140
+ const passed = reach === undefined ? [] : this.#narrowed([...new Set(reached)], reach.through);
141
+ for (const c of new Set([...edges, ...nodes, ...passed]))
139
142
  this.#require(query, relation, c);
140
143
  this.#where(query, traversal.edge, label, { relation, classes: edges });
141
144
  this.#where(query, traversal.node, label, { relation, classes: nodes });
145
+ if (reach !== undefined)
146
+ this.#where(query, reach.through, label, { relation, classes: passed });
142
147
  }
143
148
  /**
144
149
  * The concrete Classes a condition keeps: an `is` or `isExactly` conjunct, or an `or` of them,
@@ -52,9 +52,12 @@ export interface QueryErrorDetails {
52
52
  OUTDATED: {
53
53
  readonly kernelCode: 'QUERY_EXPECTATION_MISMATCH';
54
54
  };
55
- /** The Host does not serve v7, or does not give each row's Class. */
55
+ /**
56
+ * The Host does not serve v7, does not give each row's Class, or does not follow a relation
57
+ * more than one Edge (`.reachable()`).
58
+ */
56
59
  UNSUPPORTED: {
57
- readonly feature: 'v7' | 'classes';
60
+ readonly feature: 'v7' | 'classes' | 'reachable';
58
61
  };
59
62
  }
60
63
  export type QueryErrorCode = keyof QueryErrorDetails;
@@ -25,7 +25,9 @@ function sentence(code, details) {
25
25
  case 'UNSUPPORTED':
26
26
  return details.feature === 'v7'
27
27
  ? 'the Host does not serve Query v7'
28
- : 'the Host does not give the Class of each row';
28
+ : details.feature === 'reachable'
29
+ ? 'the Host does not follow a relation more than one Edge (.reachable())'
30
+ : 'the Host does not give the Class of each row';
29
31
  }
30
32
  }
31
33
  export class QueryError extends Error {
@@ -29,7 +29,10 @@ export declare class Renderer {
29
29
  readonly query: string;
30
30
  readonly model: Model;
31
31
  constructor(query: string, model: Model, answer: QueryListAnswer<unknown, unknown>);
32
- /** A Node row, or `undefined` when the reader may not read it and the read does not keep it. */
32
+ /**
33
+ * A Node row, or `undefined` when the reader may not read a fact it reads as values and the read
34
+ * does not keep it.
35
+ */
33
36
  node(item: Item, pattern: Pattern): Json | undefined;
34
37
  /** An Edge root row: its identity, its slug and values when read as values, and both ends. */
35
38
  edge(item: Item, plan: EdgeRootPlan): Json | undefined;
@@ -78,26 +78,31 @@ export class Renderer {
78
78
  return freeze(c === undefined ? [] : [...this.model.propertyNames(c)]);
79
79
  }
80
80
  /**
81
- * What a row may not show, the one rule of every render path and verb: the first fact it shows
82
- * that the reader may not read. A row shows its own fact, the Edge it reads as values, and an
83
- * Edge root's ends read as values; an end read as a reference shows no value.
81
+ * What a row may not show, the one rule of every render path and verb: the first fact it reads
82
+ * as values that the reader may not read. A row reads as values its own fact, the Edge
83
+ * `.withEdge()` reads and an Edge root's ends, each unless read as a reference. A reference shows
84
+ * no value, and the Kernel answers one for every fact the reader traverses: the table holds that
85
+ * fact only when another read of the answer renders it as values, which does not decide this row.
84
86
  */
85
87
  #unread(item, plan) {
88
+ const asValues = (select, shown) => select === 'value' ? shown : undefined;
89
+ const { edge } = plan;
86
90
  const shown = 'source' in plan
87
91
  ? [
88
- item,
89
- plan.source.select === 'value' ? item.source : undefined,
90
- plan.target.select === 'value' ? item.target : undefined,
92
+ asValues(plan.select, item),
93
+ asValues(plan.source.select, item.source),
94
+ asValues(plan.target.select, item.target),
91
95
  ]
92
96
  : [
93
- item,
94
- plan.edge === 'value' && item.edge !== undefined
95
- ? { fact: item.edge }
96
- : undefined,
97
+ asValues(plan.select, item),
98
+ asValues(edge, item.edge === undefined ? undefined : { fact: item.edge }),
97
99
  ];
98
100
  return shown.find((one) => one !== undefined && this.#withheld(one.fact));
99
101
  }
100
- /** A Node row, or `undefined` when the reader may not read it and the read does not keep it. */
102
+ /**
103
+ * A Node row, or `undefined` when the reader may not read a fact it reads as values and the read
104
+ * does not keep it.
105
+ */
101
106
  node(item, pattern) {
102
107
  const cls = this.#class(item);
103
108
  const id = item.fact;
@@ -112,20 +117,25 @@ export class Renderer {
112
117
  Object.assign(row, this.#values(id, layout, ROW_KEYS));
113
118
  for (const branch of pattern.branches)
114
119
  row[branch.key] = this.#relation(item, branch);
115
- const edge = pattern.edge;
120
+ const { edge, reachable } = pattern;
116
121
  if (edge !== undefined && item.edge !== undefined)
117
- row.$edge = this.#edgeValues(item.edge, edge);
122
+ row.$edge = this.#edgeValues(item.edge, edge, reachable === true);
118
123
  return freeze(row);
119
124
  }
120
125
  /**
121
126
  * What `.withEdge()` adds: the Edge's Class, and its slug with its values or, on a row
122
- * `.includeWithheld()` keeps, the names it withholds.
127
+ * `.includeWithheld()` keeps, the names it withholds. On a relation that follows one Edge or
128
+ * more (`ends`), the Edge leaves a Node its walk passed through: it names both its ends.
123
129
  */
124
- #edgeValues(edge, select) {
130
+ #edgeValues(edge, select, ends) {
131
+ const identity = {
132
+ $class: edge.class,
133
+ ...(ends ? { $source: edge.source, $target: edge.target } : {}),
134
+ };
125
135
  if (select === 'reference')
126
- return freeze({ $class: edge.class });
136
+ return freeze(identity);
127
137
  const c = this.#known(edge.class);
128
- const named = { $class: edge.class, ...this.#slug(edge) };
138
+ const named = { ...identity, ...this.#slug(edge) };
129
139
  if (this.#withheld(edge))
130
140
  return freeze({ ...named, $withheld: this.#names(c) });
131
141
  return freeze({ ...named, ...this.#values(edge, c, NO_TAKEN) });
@@ -162,8 +172,8 @@ export class Renderer {
162
172
  const row = { ...identity };
163
173
  if (plan.select === 'value')
164
174
  Object.assign(row, this.#values(key, c, roles));
165
- // `#unread` has ruled on the row: an end it let through that the reader may not read, one kept
166
- // or read as a reference, renders withheld.
175
+ // `#unread` has ruled on the row: an end it let through that the reader may not read, one
176
+ // `.includeWithheld()` keeps, renders withheld; an end read as a reference renders as one.
167
177
  const end = (rendered, { classes, select }) => {
168
178
  if (rendered === undefined)
169
179
  return undefined;
@@ -329,6 +339,7 @@ function documentRoot(plan) {
329
339
  verb: b.mode === 'count' ? 'count' : 'firstN',
330
340
  empty: false,
331
341
  edge: b.selectEdge,
342
+ ...(b.reachable === undefined ? {} : { reachable: true }),
332
343
  classes: [],
333
344
  select: b.select === 'value' ? 'value' : 'reference',
334
345
  withheld: false,
@@ -115,6 +115,9 @@ export class Run {
115
115
  if (isSnapshotStale(error))
116
116
  return new QueryError('REFUSED', this.query, { kernelCode, retryable: true }, cause);
117
117
  const refusals = refusalsOf(error);
118
+ // A Host that predates `.reachable()` refuses the member it does not know, at its pointer.
119
+ if (refusals?.some(unknownReach))
120
+ return new QueryError('UNSUPPORTED', this.query, { feature: 'reachable' }, cause);
118
121
  if (refusals !== undefined) {
119
122
  const path = refusals[0]?.path ?? (typeof details.path === 'string' ? details.path : undefined);
120
123
  return new QueryError('INPUT_INVALID', this.query, {
@@ -134,6 +137,12 @@ export class Run {
134
137
  return new QueryError('REFUSED', this.query, { kernelCode, retryable: false }, cause);
135
138
  }
136
139
  }
140
+ /** Whether a refusal says the Host does not know the `reachable` member of a Traversal. */
141
+ function unknownReach(refusal) {
142
+ return (refusal.phase === 'decode' &&
143
+ refusal.code === 'QUERY_SHAPE' &&
144
+ refusal.path.endsWith('/reachable'));
145
+ }
137
146
  /** A page document of `size` rows. */
138
147
  function withLimit(document, size) {
139
148
  const list = document.list;
@@ -9,8 +9,8 @@ import type { KernelDomain } from '../../../platform/schema/kernel.js';
9
9
  import type { SizedQuery } from '../language/query.js';
10
10
  import type { Cond, Conditions, HandleMembers, IsCond, Ordering, PropOf, PropsOf, Unordered } from './conditions.js';
11
11
  import type { Cls, Dom, KeyOf, LayoutOf, OriginOf, PropNamesOf, Satisfies, Single, Untyped, ValueOfEntry } from './domain.js';
12
- import type { Far, RelationsOf, SourceKeys, SourceRole, TargetKeys, TargetRole, ViaCheck, ViaOptions } from './relations.js';
13
- import type { Count, EdgeRootRef, EdgeRootRow, EdgeValues, Page, Ref, Row, RowKeys, WithheldEdgeRow, WithheldEdgeValues, WithheldRow } from './rows.js';
12
+ import type { CanWalk, Far, Followed, RelationsOf, SourceKeys, SourceRole, TargetKeys, TargetRole, ViaCheck, ViaFollowed, ViaOptions } from './relations.js';
13
+ import type { Count, EdgeEnds, EdgeRootRef, EdgeRootRow, EdgeValues, Page, Ref, Row, RowKeys, WithheldEdgeRow, WithheldEdgeValues, WithheldRow } from './rows.js';
14
14
  /** A read: what a verb returns, an opaque description the Query runs, typed by its answer `T`. */
15
15
  export interface Read<out T> {
16
16
  readonly '~read': T;
@@ -82,7 +82,7 @@ export interface NodeMethods<S, K extends string> {
82
82
  is<X extends string>(cls: ClassHandle<X> & IsCheck<S, K, X>, conditions: (node: NodeHandle<S, X>) => Conditions): Cond;
83
83
  isExactly<X extends string>(cls: ClassHandle<X> & IsCheck<S, K, X>): IsCond<X>;
84
84
  /** The Edges of one Class (or several) from this Node; the far end's Classes come from the Edge. */
85
- via<const X extends AnyEdgeSet | readonly [AnyEdgeSet, ...AnyEdgeSet[]], const O extends ViaOptions = {}>(edge: X & ViaCheck<S, K, EdgeKeysOf<X>, O>, options?: O): RelSet<S, Far<S, K, EdgeKeysOf<X>, O>, EdgeKeysOf<X>, {}, 'value', false>;
85
+ via<const X extends AnyEdgeSet | readonly [AnyEdgeSet, ...AnyEdgeSet[]], const O extends ViaOptions = {}>(edge: X & ViaCheck<S, K, EdgeKeysOf<X>, O>, options?: O): RelSet<S, Far<S, K, EdgeKeysOf<X>, O>, EdgeKeysOf<X>, {}, 'value', false, ViaFollowed<S, K, EdgeKeysOf<X>, O>>;
86
86
  }
87
87
  type IsUnion<K, All = K> = K extends unknown ? ([All] extends [K] ? false : true) : never;
88
88
  type FlatOf<S, K> = LayoutOf<Cls<S, K>, HandleMembers>['flat'];
@@ -118,9 +118,12 @@ export interface NodeSet<S, K extends string, W, M extends Rendering, H extends
118
118
  orderBy(keys: (node: NodeHandle<S, K>) => Ordering): NodeSet<S, K, W, M, H>;
119
119
  /** Rows gain each relation's answer under the name given. */
120
120
  with<const X extends Withs>(relations: (node: NodeHandle<S, K>) => X & WithCheck<S, K, W, X>): NodeSet<S, K, W & Answers<X>, M, H>;
121
- /** Rows of references: `{ id, $class }`. */
121
+ /** Rows of references, `{ id, $class }`: they read no values, so none is left out. */
122
122
  ref(): NodeSet<S, K, W, 'reference', H>;
123
- /** Rows the reader may not read stay, as `{ id, $class, $withheld }`. */
123
+ /**
124
+ * Rows read as values that the reader may not read stay, as `{ id, $class, $withheld }`. Rows
125
+ * of references are never left out, so they carry no `$withheld`.
126
+ */
124
127
  includeWithheld(): NodeSet<S, K, W, M, true>;
125
128
  union<K2 extends string>(other: ClassHandle<K2>): NodeSet<S, K | K2, W, M, H>;
126
129
  /**
@@ -157,29 +160,52 @@ export interface NodeSet<S, K extends string, W, M extends Rendering, H extends
157
160
  * Edge the reader may not read.
158
161
  */
159
162
  type RelRowOf<S, K, E, W, M extends Rendering, H extends boolean> = H extends true ? RowOf<S, K, W, M, true> | (W extends {
160
- readonly $edge: unknown;
163
+ readonly $edge: infer Edge;
161
164
  } ? RowOf<S, K, Omit<W, '$edge'> & {
162
- readonly $edge: WithheldEdgeValues<S, E>;
165
+ readonly $edge: WithheldEdgeValues<S, E> & (Edge extends EdgeEnds ? EdgeEnds : unknown);
163
166
  }, M, false> : never) : RowOf<S, K, W, M, false>;
167
+ /** What `.withEdge()` adds under `$edge`: on a relation that walks, both ends of the Edge too. */
168
+ type EdgeOf<S, E, F extends Followed> = F['reachable'] extends true ? EdgeValues<S, E> & EdgeEnds : EdgeValues<S, E>;
169
+ /** The rows of a relation once it walks: an `$edge` they already carry names both its ends. */
170
+ type Walked<W> = W extends {
171
+ readonly $edge: unknown;
172
+ } ? W & {
173
+ readonly $edge: EdgeEnds;
174
+ } : W;
164
175
  /** A relation from a Node: the Nodes at the far end of its Edges. */
165
- export interface RelSet<S, K extends string, E extends string, W, M extends Rendering, H extends boolean> {
176
+ export interface RelSet<S, K extends string, E extends string, W, M extends Rendering, H extends boolean, F extends Followed = Followed> {
166
177
  /** Its far Classes and Edges: a relation is not a Class handle, so `is` and `union` refuse it. */
167
- readonly '~via': readonly [K, E];
168
- where<const R extends Conditions>(conditions: (node: NodeHandle<S, K>, edge: EdgeHandle<S, E>) => R): RelSet<S, Narrow<K, R>, E, W, M, H>;
169
- orderBy(keys: (node: NodeHandle<S, K>, edge: EdgeHandle<S, E>) => Ordering): RelSet<S, K, E, W, M, H>;
170
- with<const X extends Withs>(relations: (node: NodeHandle<S, K>) => X & WithCheck<S, K, W, X>): RelSet<S, K, E, W & Answers<X>, M, H>;
178
+ readonly '~via': readonly [K, E, F];
179
+ where<const R extends Conditions>(conditions: (node: NodeHandle<S, K>, edge: EdgeHandle<S, E>) => R): RelSet<S, Narrow<K, R>, E, W, M, H, F>;
180
+ orderBy(keys: (node: NodeHandle<S, K>, edge: EdgeHandle<S, E>) => Ordering): RelSet<S, K, E, W, M, H, F>;
181
+ with<const X extends Withs>(relations: (node: NodeHandle<S, K>) => X & WithCheck<S, K, W, X>): RelSet<S, K, E, W & Answers<X>, M, H, F>;
171
182
  /**
172
183
  * Each row gains `$edge`: the Edge's Class, its slug when it has one, and its Properties. The
173
184
  * Edge is a fact the row reads: when the reader may not read it, the row is left out, `get` and
174
185
  * `find` raise `NOT_READABLE`, and `.includeWithheld()` keeps the row with `$withheld` in `$edge`.
186
+ * On a relation that walks (`.reachable()`), `$edge` also names both ends of the Edge.
175
187
  */
176
188
  withEdge(): RelSet<S, K, E, W & {
177
- readonly $edge: EdgeValues<S, E>;
178
- }, M, H>;
179
- /** Rows of references: `{ id, $class }`. */
180
- ref(): RelSet<S, K, E, W, 'reference', H>;
181
- includeWithheld(): RelSet<S, K, E, W, M, true>;
182
- distinct(): RelSet<S, K, E, W, M, H>;
189
+ readonly $edge: EdgeOf<S, E, F>;
190
+ }, M, H, F>;
191
+ /**
192
+ * Rows of references, `{ id, $class }`: they read no Node values, so only the Edge `.withEdge()`
193
+ * reads may leave one out.
194
+ */
195
+ ref(): RelSet<S, K, E, W, 'reference', H, F>;
196
+ includeWithheld(): RelSet<S, K, E, W, M, true, F>;
197
+ distinct(): RelSet<S, K, E, W, M, H, F>;
198
+ /**
199
+ * The relation followed one Edge or more: the Nodes it reaches however far, in one snapshot.
200
+ * Its rows are the Edges it follows, each once with the Node it reaches, or with `.distinct()`
201
+ * the Nodes it reaches, each once; the Node it starts from is among them only when a cycle
202
+ * returns to it. `where` holds on each Edge followed and each Node reached; `through` holds on
203
+ * every Node a walk passes through on its way. Followed `incident`, it needs `.distinct()`.
204
+ * It compiles only where a Class the relation reaches can start another of its Edges.
205
+ */
206
+ reachable(this: true extends CanWalk<S, E, F> ? unknown : `✗ no Class this relation reaches starts another of its Edges in this direction: it follows one Edge, so it is not reachable`, options?: {
207
+ readonly through?: (node: NodeHandle<S, K>) => Conditions;
208
+ }): RelSet<S, K, E, Walked<W>, M, H, Followed<F['direction'], F['reached'], true>>;
183
209
  /**
184
210
  * Exactly one per parent; none or a second is `INTEGRITY`, naming the relation; one the reader
185
211
  * may not read is `NOT_READABLE`.
@@ -224,9 +250,12 @@ export interface EdgeSet<S, E extends string, M extends Rendering, H extends boo
224
250
  readonly '~edge': E;
225
251
  where(conditions: (edge: EdgeRootHandle<S, E>) => Conditions): EdgeSet<S, E, M, H>;
226
252
  orderBy(keys: (edge: EdgeRootHandle<S, E>) => Ordering): EdgeSet<S, E, M, H>;
227
- /** Rows of `{ $class, $source, $target }`, with both ends as references. */
253
+ /** Rows of `{ $class, $source, $target }`, with both ends as references: none is left out. */
228
254
  ref(): EdgeSet<S, E, 'reference', H>;
229
- /** Keeps in a list a row the reader may not read: its Edge, or an end read as values, withheld. */
255
+ /**
256
+ * Keeps in a list a row the reader may not read: its Edge, or an end read as values, withheld.
257
+ * After `.ref()` no row is left out, so none is withheld.
258
+ */
230
259
  includeWithheld(): EdgeSet<S, E, M, true>;
231
260
  get(): Read<EdgeRowOf<S, E, M, false>>;
232
261
  find(): Read<EdgeRowOf<S, E, M, false> | undefined>;
@@ -85,6 +85,12 @@ export declare class Model {
85
85
  covers(end: End, classes: readonly string[]): boolean;
86
86
  /** Whether an end accepts one of `classes`, or one of their parents. */
87
87
  touches(classes: readonly AnyResolvedClass[], end: End): boolean;
88
+ /**
89
+ * Whether a Node of one of `classes` may be one `end` accepts: the end accepts the Class, one of
90
+ * its parents, or one of its subclasses. What a walk asks of the Classes it reaches before it
91
+ * follows another Edge from them.
92
+ */
93
+ meets(classes: readonly AnyResolvedClass[], end: End): boolean;
88
94
  /** The Classes a traversal of `edges` in `direction` reaches. */
89
95
  reached(edges: readonly AnyResolvedClass[], direction: Direction): readonly AnyResolvedClass[];
90
96
  /** Every Property name of a Class, flat or grouped: a relation or a `.with` name avoids them. */
@@ -137,6 +137,16 @@ export class Model {
137
137
  touches(classes, end) {
138
138
  return classes.some((c) => end.accepts.some((key) => this.satisfies(c).has(key)));
139
139
  }
140
+ /**
141
+ * Whether a Node of one of `classes` may be one `end` accepts: the end accepts the Class, one of
142
+ * its parents, or one of its subclasses. What a walk asks of the Classes it reaches before it
143
+ * follows another Edge from them.
144
+ */
145
+ meets(classes, end) {
146
+ if (this.touches(classes, end))
147
+ return true;
148
+ return this.far(end).some((accepted) => classes.some((c) => this.satisfies(accepted).has(c.key)));
149
+ }
140
150
  /** The Classes a traversal of `edges` in `direction` reaches. */
141
151
  reached(edges, direction) {
142
152
  const out = new Set();
@@ -17,7 +17,7 @@ export interface Pattern {
17
17
  /** The keys of the Classes its rows may be, after narrowing (S3): the layout of each row. */
18
18
  readonly classes: readonly string[];
19
19
  readonly select: Rendering;
20
- /** Rows the reader may not read stay, as `{ id, $class, $withheld }`. */
20
+ /** Rows read as values that the reader may not read stay, as `{ id, $class, $withheld }`. */
21
21
  readonly withheld: boolean;
22
22
  readonly branches: readonly BranchPlan[];
23
23
  }
@@ -36,6 +36,11 @@ export interface BranchPlan extends Pattern {
36
36
  readonly empty: boolean;
37
37
  /** Each row carries `$edge` (`.withEdge()`): the Edge's Class, and its values when selected. */
38
38
  readonly edge?: Rendering;
39
+ /**
40
+ * The relation follows one Edge or more (`.reachable()`): a row's Edge no longer leaves its
41
+ * parent, so `$edge` names both its ends.
42
+ */
43
+ readonly reachable?: true;
39
44
  }
40
45
  export interface NodeRootPlan extends Pattern {
41
46
  readonly kind: 'nodes';
@@ -38,6 +38,13 @@ export declare class Relation {
38
38
  ref(): Relation;
39
39
  includeWithheld(): Relation;
40
40
  distinct(): Relation;
41
+ /**
42
+ * The relation followed one Edge or more: the Nodes it reaches however far, each Edge followed
43
+ * once, or with `.distinct()` each Node once. `through` holds on every Node a walk passes
44
+ * through, between the Node it starts from and the Node it reaches; `where` still holds on each
45
+ * Edge followed and on each Node reached.
46
+ */
47
+ reachable(written?: unknown): Relation;
41
48
  /** Exactly one per parent: two rows, to see a second. */
42
49
  get(): RelationRead;
43
50
  find(): RelationRead;
@@ -16,15 +16,18 @@ const optional = (condition) => condition.always || condition.never ? undefined
16
16
  * A part of a document, from its conditions and its Branches: as sent, absent when a condition is
17
17
  * NEVER, and as written when the input folds one of them (absent when it is the part as sent).
18
18
  */
19
- function lowered(conditions, branches, write) {
20
- const part = (cs, withs) => cs.some((c) => c.never) ? undefined : write(cs, withs);
21
- const sent = part(conditions, branches.flatMap((b) => (b.branch === undefined ? [] : [b.branch])));
22
- if (!conditions.some((c) => c.folded) && branches.every((b) => b.written === undefined))
19
+ function lowered(conditions, branches, write,
20
+ /** Conditions the part writes that never empty it: the `through` of a walk. */
21
+ free = []) {
22
+ const part = (cs, withs, fs) => (cs.some((c) => c.never) ? undefined : write(cs, withs, fs));
23
+ const sent = part(conditions, branches.flatMap((b) => (b.branch === undefined ? [] : [b.branch])), free);
24
+ if (![...conditions, ...free].some((c) => c.folded) &&
25
+ branches.every((b) => b.written === undefined))
23
26
  return { sent };
24
27
  const written = part(conditions.map((c) => c.asWritten), branches.flatMap((b) => {
25
28
  const branch = b.written ?? b.branch;
26
29
  return branch === undefined ? [] : [branch];
27
- }));
30
+ }), free.map((c) => c.asWritten));
28
31
  return { sent, written };
29
32
  }
30
33
  /** A root read: its plan, and its document as `lowered` writes it from its condition. */
@@ -133,11 +136,39 @@ export function handleClass(value) {
133
136
  * is no set of roots; a set whose rows render (`with`, `ref`, `includeWithheld`) is refused.
134
137
  */
135
138
  export function rangeRead(value, ordered) {
136
- if (value instanceof NodeSet)
137
- return NodeSet.range(value, ordered);
138
- if (value instanceof EdgeSet)
139
- return EdgeSet.range(value, ordered);
140
- return undefined;
139
+ const read = value instanceof NodeSet
140
+ ? NodeSet.range(value, ordered)
141
+ : value instanceof EdgeSet
142
+ ? EdgeSet.range(value, ordered)
143
+ : undefined;
144
+ if (read !== undefined && (walks(read.plan.document) || walks(read.plan.written)))
145
+ throw new TypeError('A guard follows a relation one Edge at a time: the Kernel decides it inside the write, where it refuses `.reachable()`. Read the walk in a Query, and guard what it found.');
146
+ return read;
147
+ }
148
+ /**
149
+ * Whether a range holds a Traversal that follows one Edge or more: in its condition, at any depth.
150
+ * It reads the grammar's Traversals alone, never a value: a JSON literal may hold any key.
151
+ */
152
+ function walks(document) {
153
+ const walked = (value) => {
154
+ const where = value;
155
+ switch (where?.op) {
156
+ case 'and':
157
+ case 'or':
158
+ return where.operands.some(walked);
159
+ case 'not':
160
+ case 'source':
161
+ case 'target':
162
+ return walked(where.operand);
163
+ case 'exists':
164
+ return where.reachable !== undefined || walked(where.edge) || walked(where.node);
165
+ default:
166
+ return false;
167
+ }
168
+ };
169
+ const family = document;
170
+ const root = (family?.list ?? family?.exists ?? family?.count);
171
+ return walked(root?.where);
141
172
  }
142
173
  function renderedRange() {
143
174
  throw new TypeError("A guard reads its range's roots alone: `.with`, `.ref` and `.includeWithheld` render rows, which a guard never reads.");
@@ -372,6 +403,7 @@ export class Relation {
372
403
  edges,
373
404
  direction,
374
405
  far,
406
+ reached: far,
375
407
  role: farRole(model, from, edges, direction),
376
408
  context,
377
409
  node: Condition.ALWAYS,
@@ -382,6 +414,7 @@ export class Relation {
382
414
  withheld: false,
383
415
  selectEdge: false,
384
416
  distinct: false,
417
+ through: undefined,
385
418
  });
386
419
  }
387
420
  #next(patch) {
@@ -450,8 +483,54 @@ export class Relation {
450
483
  throw new TypeError(DISTINCT_EDGE);
451
484
  return this.#next({ distinct: true });
452
485
  }
486
+ /**
487
+ * The relation followed one Edge or more: the Nodes it reaches however far, each Edge followed
488
+ * once, or with `.distinct()` each Node once. `through` holds on every Node a walk passes
489
+ * through, between the Node it starts from and the Node it reaches; `where` still holds on each
490
+ * Edge followed and on each Node reached.
491
+ */
492
+ reachable(written) {
493
+ const s = this.#s;
494
+ if (s.through !== undefined)
495
+ throw new TypeError(`${s.name} is already reachable: write its \`through\` once.`);
496
+ const ends = s.edges.map((edge) => ({ edge, ...s.model.ends(edge) }));
497
+ if (s.role !== undefined)
498
+ throw new TypeError(`${s.name} follows an undirected Edge whose roles accept different Classes: the Node it reaches cannot start another Edge of it. Read it with { direction: 'incident' }.`);
499
+ if (s.direction !== 'incident' && new Set(ends.map((e) => e.undirected)).size > 1)
500
+ throw new TypeError(`${s.name} follows directed and undirected Edges: a walk of them has one direction only as { direction: 'incident' }.`);
501
+ // A reached Class starts another hop when an end the Edges leave from may accept its Nodes.
502
+ const leaves = (e) => s.direction === 'incident' || e.undirected
503
+ ? [e.source, e.target]
504
+ : [s.direction === 'outgoing' ? e.source : e.target];
505
+ if (!ends.some((e) => leaves(e).some((end) => s.model.meets(s.reached, end))))
506
+ throw new TypeError(`${s.name} reaches ${keysOf(s.reached).join(', ')}, none of which ${keysOf(s.edges).join(', ')} leaves from in this direction: it follows one Edge only, so it is not reachable.`);
507
+ if (written === undefined)
508
+ return this.#next({ through: Condition.ALWAYS });
509
+ const { through } = options(written, 'reachable');
510
+ if (through === undefined)
511
+ return this.#next({ through: Condition.ALWAYS });
512
+ const handleScope = scope(`the Nodes ${s.name} passes through`);
513
+ // Written on the Classes its rows are, as `where` is: the keys `through` may name.
514
+ const node = nodeHandle(s.model, s.far, { scope: handleScope, on: 'item' });
515
+ const listed = kept(callback(through, 'reachable({ through })')(node), 'through');
516
+ within(listed, [handleScope]);
517
+ return this.#next({ through: and(listed) });
518
+ }
519
+ /**
520
+ * The reach of its Traversal, as `through` is: none when the relation follows one Edge, or when
521
+ * no Node meets `through`, so that a walk never passes its first Edge.
522
+ */
523
+ #reach(through) {
524
+ if (through === undefined || through.never)
525
+ return undefined;
526
+ const s = this.#s;
527
+ const incident = s.direction === 'incident' || s.edges.every((edge) => s.model.ends(edge).undirected);
528
+ if (incident && !s.distinct)
529
+ throw new TypeError(`${s.name} is followed either way: a walk reaches an Edge from both its ends, so it has no single row. Add .distinct() to read the Nodes it reaches.`);
530
+ return defined({ through: optional(through) });
531
+ }
453
532
  /** Its Traversal: along an undirected Edge whose far role needs it, `incident` to that role. */
454
- #traversal(node, edge) {
533
+ #traversal(node, edge, through) {
455
534
  const { role } = this.#s;
456
535
  const conjuncts = [
457
536
  ...(role === undefined ? [] : [role]),
@@ -461,6 +540,7 @@ export class Relation {
461
540
  via: keysOf(this.#s.edges),
462
541
  direction: role === undefined ? this.#s.direction : 'incident',
463
542
  distinct: this.#s.distinct ? true : undefined,
543
+ reachable: this.#reach(through),
464
544
  edge: optional(edge),
465
545
  node: conjuncts.length === 0
466
546
  ? undefined
@@ -474,8 +554,8 @@ export class Relation {
474
554
  return new RelationRead(s.context.scope, (key, name) => {
475
555
  const counted = verb === 'count' || verb === 'exists';
476
556
  const branches = counted ? [] : lowerWiths(s.with);
477
- const { sent, written } = lowered([s.node, s.edge], branches, ([node, edge], withs) => {
478
- const traversal = this.#traversal(node, edge);
557
+ const { sent, written } = lowered([s.node, s.edge], branches, ([node, edge], withs, [through]) => {
558
+ const traversal = this.#traversal(node, edge, through);
479
559
  if (counted)
480
560
  return { name, ...traversal, mode: 'count', upTo: limit };
481
561
  const orderBy = s.orderBy.map((k) => keyJson(k, s.distinct));
@@ -489,7 +569,7 @@ export class Relation {
489
569
  with: nonEmpty(withs),
490
570
  limit,
491
571
  });
492
- });
572
+ }, s.through === undefined ? [] : [s.through]);
493
573
  const plan = {
494
574
  key,
495
575
  name,
@@ -498,6 +578,7 @@ export class Relation {
498
578
  ...(bound === undefined ? {} : { bound }),
499
579
  empty: sent === undefined,
500
580
  ...(s.selectEdge ? { edge: 'value' } : {}),
581
+ ...(s.through === undefined ? {} : { reachable: true }),
501
582
  classes: keysOf(s.far),
502
583
  select: s.select,
503
584
  withheld: s.withheld,
@@ -536,11 +617,12 @@ export class Relation {
536
617
  /** At least `atLeast` Edges of the relation meet the extra conditions. */
537
618
  #exists(extra, atLeast = 1) {
538
619
  const sides = [and([this.#s.node, extra.node]), and([this.#s.edge, extra.edge])];
539
- return folding(sides, ([node, edge]) => node.never || edge.never
620
+ const { through } = this.#s;
621
+ return folding(through === undefined ? sides : [...sides, through], ([node, edge, walked]) => node.never || edge.never
540
622
  ? Condition.NEVER
541
623
  : atom(this.#s.context, {
542
624
  op: 'exists',
543
- ...this.#traversal(node, edge),
625
+ ...this.#traversal(node, edge, walked),
544
626
  ...(atLeast > 1 ? { atLeast } : {}),
545
627
  }));
546
628
  }
@@ -4,6 +4,7 @@
4
4
  import type { HandleMembers } from './conditions.js';
5
5
  import type { Cls, EdgesOf, KeyOf, NodeClassKey, NodeRoot, OriginOf, PropNamesOf, Satisfies, Single } from './domain.js';
6
6
  import type { RelSet } from './handles.js';
7
+ import type { Direction } from './model.js';
7
8
  /**
8
9
  * An Edge's two ends. An undirected Edge's are its two roles in declared order, which name neither
9
10
  * stored end (`Model.ends`).
@@ -51,11 +52,21 @@ export type SourceKeys<S, E> = AcceptKeys<SourceOf<Cls<S, E>>> & NodeClassKey<S>
51
52
  export type TargetKeys<S, E> = AcceptKeys<TargetOf<Cls<S, E>>> & NodeClassKey<S>;
52
53
  export type SourceRole<S, E> = RoleOf<SourceOf<Cls<S, E>>>;
53
54
  export type TargetRole<S, E> = RoleOf<TargetOf<Cls<S, E>>>;
54
- interface Candidate<N extends string, E extends string, Own extends boolean, Far extends string> {
55
+ interface Candidate<N extends string, E extends string, Own extends boolean, Far extends string, D extends Direction> {
55
56
  readonly name: N;
56
57
  readonly edge: E;
57
58
  readonly own: Own;
58
59
  readonly far: Far;
60
+ readonly direction: D;
61
+ }
62
+ /**
63
+ * How a relation is followed: its direction, the Classes its Edges reach whatever `where` narrows
64
+ * its rows to, and whether it follows one Edge or more (`.reachable()`).
65
+ */
66
+ export interface Followed<D extends Direction = Direction, K extends string = string, R extends boolean = boolean> {
67
+ readonly direction: D;
68
+ readonly reached: K;
69
+ readonly reachable: R;
59
70
  }
60
71
  type IsOwn<S, E> = KeyOf<E> extends `${OriginOf<S>}:${string}` ? true : false;
61
72
  type ToOne = '0..1' | '1';
@@ -65,7 +76,7 @@ interface EndEntry<At extends string, C> {
65
76
  readonly candidate: C;
66
77
  }
67
78
  type EntriesAt<At, C> = At extends string ? EndEntry<At, C> : never;
68
- type ToOneEnds<S> = EdgesOf<S> extends infer E ? E extends unknown ? (CountOf<SourceOf<E>> extends ToOne ? Specific<TargetOf<E>> extends true ? EntriesAt<AcceptKeys<SourceOf<E>>, Candidate<RoleOf<TargetOf<E>>, KeyOf<E>, IsOwn<S, E>, AcceptKeys<TargetOf<E>>>> : never : never) | (CountOf<TargetOf<E>> extends ToOne ? Specific<SourceOf<E>> extends true ? EntriesAt<AcceptKeys<TargetOf<E>>, Candidate<RoleOf<SourceOf<E>>, KeyOf<E>, IsOwn<S, E>, AcceptKeys<SourceOf<E>>>> : never : never) : never : never;
79
+ type ToOneEnds<S> = EdgesOf<S> extends infer E ? E extends unknown ? (CountOf<SourceOf<E>> extends ToOne ? Specific<TargetOf<E>> extends true ? EntriesAt<AcceptKeys<SourceOf<E>>, Candidate<RoleOf<TargetOf<E>>, KeyOf<E>, IsOwn<S, E>, AcceptKeys<TargetOf<E>>, 'outgoing'>> : never : never) | (CountOf<TargetOf<E>> extends ToOne ? Specific<SourceOf<E>> extends true ? EntriesAt<AcceptKeys<TargetOf<E>>, Candidate<RoleOf<SourceOf<E>>, KeyOf<E>, IsOwn<S, E>, AcceptKeys<SourceOf<E>>, 'incoming'>> : never : never) : never : never;
69
80
  /** Every to-one end of the Domain, grouped by the Class key it accepts: computed once per Schema. */
70
81
  type EndsByClass<S> = {
71
82
  readonly [P in ToOneEnds<S> as P['at']]: P['candidate'];
@@ -90,7 +101,7 @@ type Shadowed<Cs> = Extract<Cs, {
90
101
  * ends claim names neither: its member is a message that says so.
91
102
  */
92
103
  export type RelationsOf<S, K> = Shadowed<CandidatesOf<S, Satisfies<S, K>>> extends infer Cs ? {
93
- readonly [C in Cs as Exclude<NameOf<C>, PropNamesOf<Cls<S, K>> | HandleMembers>]: Single<C> extends true ? C extends Candidate<string, infer E, boolean, infer Far> ? RelSet<S, Far & NodeClassKey<S>, E, {}, 'value', false> : never : `✗ "${NameOf<C>}" names several relations of this Class: use .via(d.<Edge>)`;
104
+ readonly [C in Cs as Exclude<NameOf<C>, PropNamesOf<Cls<S, K>> | HandleMembers>]: Single<C> extends true ? C extends Candidate<string, infer E, boolean, infer Far, infer D> ? RelSet<S, Far & NodeClassKey<S>, E, {}, 'value', false, Followed<D, Far & NodeClassKey<S>, false>> : never : `✗ "${NameOf<C>}" names several relations of this Class: use .via(d.<Edge>)`;
94
105
  } : never;
95
106
  export interface ViaOptions {
96
107
  readonly direction?: 'outgoing' | 'incoming' | 'incident';
@@ -101,6 +112,23 @@ type DirectionOf<S, K, E, O> = O extends {
101
112
  type FarKeys<S, E, Dir> = E extends unknown ? Dir extends 'outgoing' ? AcceptKeys<TargetOf<Cls<S, E>>> : Dir extends 'incoming' ? AcceptKeys<SourceOf<Cls<S, E>>> : AcceptKeys<TargetOf<Cls<S, E>>> | AcceptKeys<SourceOf<Cls<S, E>>> : never;
102
113
  /** The Class keys a `.via` reaches. */
103
114
  export type Far<S, K, E, O> = FarKeys<S, E, DirectionOf<S, K, E, O>> & NodeClassKey<S>;
115
+ /** How a `.via` is followed: one Edge, in its direction. */
116
+ export type ViaFollowed<S, K, E, O> = Followed<Extract<DirectionOf<S, K, E, O>, Direction>, Far<S, K, E, O>, false>;
117
+ type Undirected<C> = C extends {
118
+ readonly definition: {
119
+ readonly endpoints: readonly [unknown, unknown];
120
+ };
121
+ } ? true : false;
122
+ /** The ends an Edge followed in `D` leaves from: either, when undirected or followed `incident`. */
123
+ type LeftEnds<C, D> = Undirected<C> extends true ? SourceOf<C> | TargetOf<C> : D extends 'outgoing' ? SourceOf<C> : D extends 'incoming' ? TargetOf<C> : SourceOf<C> | TargetOf<C>;
124
+ /** Whether a Node of `K` may be one `End` accepts: the Class, one of its parents or subclasses. */
125
+ type Meets<S, K, End> = End extends unknown ? Touches<Satisfies<S, K>, End> extends true ? true : [Extract<Satisfies<S, AcceptKeys<End> & NodeClassKey<S>>, K>] extends [never] ? false : true : never;
126
+ /**
127
+ * Whether a relation can follow another Edge from a Node it reaches (D15): one of its Edges leaves
128
+ * from an end that may accept a Class it reaches. One member per Edge Class: a relation over
129
+ * several walks when `true` is among them.
130
+ */
131
+ export type CanWalk<S, E, F extends Followed> = E extends unknown ? true extends Meets<S, F['reached'], LeftEnds<Cls<S, E>, F['direction']>> ? true : false : never;
104
132
  /** A `.via` whose Edge has no end for this Class, or two, or reaches only foreign Classes. */
105
133
  export type ViaCheck<S, K, E, O> = E extends unknown ? DirectionOf<S, K, E, O> extends 'none' ? `✗ ${E & string} has no end that accepts this Class: read it from a Class one of its ends accepts` : DirectionOf<S, K, E, O> extends `not the ${infer End}` ? `✗ this Class is not the ${End} of ${E & string}: check the direction` : DirectionOf<S, K, E, O> extends 'ambiguous' ? `✗ both ends of ${E & string} accept this Class: pass { direction }` : [Far<S, K, E, O>] extends [never] ? `✗ ${E & string} reaches only Classes this Domain does not declare or depend on: depend on the Domain that declares them` : unknown : never;
106
134
  export {};