@astrale-os/sdk 0.6.0-beta.47 → 0.6.0-beta.49

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.
@@ -27,10 +27,15 @@ export interface End {
27
27
  readonly accepts: readonly string[];
28
28
  readonly count: string;
29
29
  }
30
- /** An Edge's two ends; an undirected Edge's are its two incident ends, in declared order. */
30
+ /**
31
+ * An Edge's two ends. An undirected Edge's are its two roles in declared order, which its stored
32
+ * ends do not keep: the Kernel stores the end with the smaller NodeId as `source`, whatever its
33
+ * role (ED-IDENTITY), so a role names neither stored end.
34
+ */
31
35
  export interface Ends {
32
36
  readonly source: End;
33
37
  readonly target: End;
38
+ readonly undirected: boolean;
34
39
  }
35
40
  /** A named to-one relation of a Class (S2). */
36
41
  export interface Relation {
@@ -72,6 +77,11 @@ export declare class Model {
72
77
  ends(edge: AnyResolvedClass): Ends;
73
78
  /** The Classes an end accepts that the Domain can name. */
74
79
  far(end: End): readonly AnyResolvedClass[];
80
+ /**
81
+ * Whether every Node of `classes` is one `end` accepts: each Class is one of `end`'s, or
82
+ * satisfies one. A Class the Domain cannot name is covered only by itself or the graph root.
83
+ */
84
+ covers(end: End, classes: readonly string[]): boolean;
75
85
  /** Whether an end accepts one of `classes`, or one of their parents. */
76
86
  touches(classes: readonly AnyResolvedClass[], end: End): boolean;
77
87
  /** The Classes a traversal of `edges` in `direction` reaches. */
@@ -101,7 +101,8 @@ export class Model {
101
101
  accepts: e.accepts.map((a) => `${a.origin}:class.${a.name}`),
102
102
  count: e.outgoing ?? e.incoming ?? e.incident ?? '',
103
103
  });
104
- const ends = { source: end(source), target: end(target) };
104
+ const undirected = edge.definition.orientation === 'undirected';
105
+ const ends = { source: end(source), target: end(target), undirected };
105
106
  this.#ends.set(edge.key, ends);
106
107
  return ends;
107
108
  }
@@ -109,6 +110,20 @@ export class Model {
109
110
  far(end) {
110
111
  return end.accepts.flatMap((key) => this.#byKey.get(key) ?? []);
111
112
  }
113
+ /**
114
+ * Whether every Node of `classes` is one `end` accepts: each Class is one of `end`'s, or
115
+ * satisfies one. A Class the Domain cannot name is covered only by itself or the graph root.
116
+ */
117
+ covers(end, classes) {
118
+ if (end.accepts.includes(NODE_ROOT))
119
+ return true;
120
+ return classes.every((key) => {
121
+ if (end.accepts.includes(key))
122
+ return true;
123
+ const c = this.#byKey.get(key);
124
+ return c !== undefined && end.accepts.some((accepted) => this.satisfies(c).has(accepted));
125
+ });
126
+ }
112
127
  /** Whether an end accepts one of `classes`, or one of their parents. */
113
128
  touches(classes, end) {
114
129
  return classes.some((c) => end.accepts.some((key) => this.satisfies(c).has(key)));
@@ -30,7 +30,7 @@ declare class Exists extends Condition {
30
30
  export declare class Relation {
31
31
  #private;
32
32
  private constructor();
33
- static of(model: Model, name: string, edges: readonly AnyResolvedClass[], direction: Direction, far: readonly AnyResolvedClass[], context: Context): Relation;
33
+ static of(model: Model, name: string, from: readonly AnyResolvedClass[], edges: readonly AnyResolvedClass[], direction: Direction, far: readonly AnyResolvedClass[], context: Context): Relation;
34
34
  where(conditions: unknown): Relation;
35
35
  orderBy(keys: unknown): Relation;
36
36
  with(relations: unknown): Relation;
@@ -207,7 +207,8 @@ export function nodeHandle(model, classes, context) {
207
207
  const far = model.reached(edges, direction);
208
208
  if (far.length === 0)
209
209
  throw new TypeError(`${keysOf(edges).join(', ')} reaches only Classes this Domain does not declare or depend on: depend on the Domain that declares them.`);
210
- return Relation.of(model, `via(${keysOf(edges).join(', ')})`, edges, direction, far, context);
210
+ const name = `via(${keysOf(edges).join(', ')})`;
211
+ return Relation.of(model, name, classes, edges, direction, far, context);
211
212
  },
212
213
  };
213
214
  return handle(fixed, (name) => {
@@ -238,7 +239,7 @@ function relationNamed(model, classes, name, context) {
238
239
  return undefined;
239
240
  const edges = [...new Set(relations.map((r) => r.edge))];
240
241
  const far = [...new Set(relations.flatMap((r) => r.far))];
241
- return Relation.of(model, name, edges, relations[0].direction, far, context);
242
+ return Relation.of(model, name, classes, edges, relations[0].direction, far, context);
242
243
  }
243
244
  /** An Edge handle in a `(node, edge) =>` callback: the Properties its Edges share. */
244
245
  function edgeHandle(model, edges, context) {
@@ -318,19 +319,56 @@ class Exists extends Condition {
318
319
  this.read = read;
319
320
  }
320
321
  }
322
+ /** A Node one of `end`'s Classes accepts: an `is` of each. */
323
+ function acceptedBy(end) {
324
+ const atoms = end.accepts.map((key) => ({ op: 'is', class: key }));
325
+ return atoms.length === 1 ? atoms[0] : { op: 'or', operands: atoms };
326
+ }
327
+ /**
328
+ * The far role a relation along an undirected Edge Class sends, in `direction` from `from`. Its
329
+ * ends have no order: the Kernel follows it both ways, whatever direction is written, and a
330
+ * direction names a role, never a stored end. From a Node its near role accepts, the far Node
331
+ * takes the far role when that role accepts it, so the relation follows the Edge `incident` to a
332
+ * Node of the far role's Classes; when the far role accepts every Node the near one does, every
333
+ * far Node takes it and nothing is sent. A relation from Nodes its near role may not accept, or
334
+ * along several Edge Classes one of which needs that condition, is refused: one condition on the
335
+ * far Node cannot say it.
336
+ */
337
+ function farRole(model, from, edges, direction) {
338
+ if (direction === 'incident')
339
+ return undefined;
340
+ let needed;
341
+ for (const edge of edges) {
342
+ const { source, target, undirected } = model.ends(edge);
343
+ if (!undirected)
344
+ continue;
345
+ const [near, far] = direction === 'outgoing' ? [source, target] : [target, source];
346
+ const stray = from.find((c) => !model.covers(near, [c.key]));
347
+ if (stray !== undefined)
348
+ throw new TypeError(`An undirected Edge's ends have no order: this relation reads ${edge.key} from its ${near.role} role, which does not accept ${stray.key}. Read it from a Class that role accepts, or with { direction: 'incident' }.`);
349
+ if (!model.covers(far, near.accepts))
350
+ needed = { edge, far };
351
+ }
352
+ if (needed === undefined)
353
+ return undefined;
354
+ if (edges.length > 1)
355
+ throw new TypeError(`An undirected Edge's ends have no order: a far Node of ${needed.edge.key} takes its ${needed.far.role} role only when that role accepts it, which one condition over several Edge Classes cannot say. Read ${needed.edge.key} with its own .via().`);
356
+ return acceptedBy(needed.far);
357
+ }
321
358
  /** A relation from a Node: the Nodes at the far end of its Edges. */
322
359
  export class Relation {
323
360
  #s;
324
361
  constructor(state) {
325
362
  this.#s = state;
326
363
  }
327
- static of(model, name, edges, direction, far, context) {
364
+ static of(model, name, from, edges, direction, far, context) {
328
365
  return new _a({
329
366
  model,
330
367
  name,
331
368
  edges,
332
369
  direction,
333
370
  far,
371
+ role: farRole(model, from, edges, direction),
334
372
  context,
335
373
  node: Condition.ALWAYS,
336
374
  edge: Condition.ALWAYS,
@@ -408,13 +446,23 @@ export class Relation {
408
446
  throw new TypeError(DISTINCT_EDGE);
409
447
  return this.#next({ distinct: true });
410
448
  }
449
+ /** Its Traversal: along an undirected Edge whose far role needs it, `incident` to that role. */
411
450
  #traversal(node, edge) {
451
+ const { role } = this.#s;
452
+ const conjuncts = [
453
+ ...(role === undefined ? [] : [role]),
454
+ ...(node.always || node.never ? [] : node.conjuncts.map((c) => c.where)),
455
+ ];
412
456
  return defined({
413
457
  via: keysOf(this.#s.edges),
414
- direction: this.#s.direction,
458
+ direction: role === undefined ? this.#s.direction : 'incident',
415
459
  distinct: this.#s.distinct ? true : undefined,
416
460
  edge: optional(edge),
417
- node: optional(node),
461
+ node: conjuncts.length === 0
462
+ ? undefined
463
+ : conjuncts.length === 1
464
+ ? conjuncts[0]
465
+ : { op: 'and', operands: conjuncts },
418
466
  });
419
467
  }
420
468
  #read(verb, limit, bound) {
@@ -708,6 +756,64 @@ export class NodeSet {
708
756
  }
709
757
  }
710
758
  _b = NodeSet;
759
+ /** Whether an Edge root's condition reads one of its ends. */
760
+ function readsEnd(where) {
761
+ switch (where.op) {
762
+ case 'source':
763
+ case 'target':
764
+ return true;
765
+ case 'and':
766
+ case 'or':
767
+ return where.operands.some(readsEnd);
768
+ case 'not':
769
+ return readsEnd(where.operand);
770
+ }
771
+ return false;
772
+ }
773
+ /**
774
+ * An Edge root's condition with its ends exchanged. At an Edge root a condition is a connective, a
775
+ * condition on the Edge's Properties, or a condition on one end, whose operand is the end Node's
776
+ * and is kept as it is.
777
+ */
778
+ function swapped(where) {
779
+ switch (where.op) {
780
+ case 'source':
781
+ return { ...where, op: 'target' };
782
+ case 'target':
783
+ return { ...where, op: 'source' };
784
+ case 'and':
785
+ case 'or':
786
+ return { ...where, operands: where.operands.map(swapped) };
787
+ case 'not':
788
+ return { ...where, operand: swapped(where.operand) };
789
+ }
790
+ return where;
791
+ }
792
+ /**
793
+ * The condition an undirected Edge root sends, from the one its roles are written in. Its ends
794
+ * have no order: the stored `source` is the end with the smaller NodeId, whatever its role. An
795
+ * Edge meets a condition on its roles when one pairing of its two ends with its two roles does,
796
+ * each role's Classes accepted at the end it takes: `or(W[roles→(source, target)],
797
+ * W[roles→(target, source)])`. The conjuncts that read no end are the same in both pairings and
798
+ * stay outside the `or`; an end's acceptance that every stored Edge meets is not written.
799
+ */
800
+ function paired(model, ends, condition) {
801
+ const read = (condition.conjuncts ?? []).filter((c) => readsEnd(c.where));
802
+ if (read.length === 0)
803
+ return condition;
804
+ const accepted = (end, on, other) => model.covers(end, other.accepts) ? [] : [{ op: on, operand: acceptedBy(end) }];
805
+ const { source, target } = ends;
806
+ const atoms = [
807
+ ...accepted(source, 'source', target),
808
+ ...accepted(target, 'target', source),
809
+ ...read.map((c) => c.where),
810
+ ];
811
+ const pairing = atoms.length === 1 ? atoms[0] : { op: 'and', operands: atoms };
812
+ return new Condition([
813
+ ...condition.conjuncts.filter((c) => !readsEnd(c.where)),
814
+ { scope: read[0].scope, where: { op: 'or', operands: [pairing, swapped(pairing)] } },
815
+ ], condition.narrows);
816
+ }
711
817
  /** The Edges of a Class at the root of a read: its Properties, and both ends by role. */
712
818
  export class EdgeSet {
713
819
  #s;
@@ -764,7 +870,12 @@ export class EdgeSet {
764
870
  orderBy(keys) {
765
871
  const { edge, scope: handleScope } = this.#handle();
766
872
  const ordering = callback(keys, 'orderBy')(edge);
767
- return this.#next({ orderBy: [...this.#s.orderBy, ...orderKeys(ordering, [handleScope])] });
873
+ const listed = orderKeys(ordering, [handleScope]);
874
+ const ends = this.#s.model.ends(this.#s.edge);
875
+ const role = listed.find((key) => key.target === 'source' || key.target === 'target')?.target;
876
+ if (ends.undirected && role !== undefined)
877
+ throw new TypeError(`An undirected Edge's ends have no order: ${this.#s.edge.key} orders by its own Properties, not by its ${ends[role].role}'s.`);
878
+ return this.#next({ orderBy: [...this.#s.orderBy, ...listed] });
768
879
  }
769
880
  pick() {
770
881
  return this.#next({ select: 'reference' });
@@ -784,10 +895,31 @@ export class EdgeSet {
784
895
  target: { role: target.role, classes: keysOf(model.far(target)), select: this.#s.select },
785
896
  };
786
897
  }
898
+ /** The condition the read sends: an undirected Edge's, over both pairings of its ends. */
899
+ #where() {
900
+ const { model, edge, where } = this.#s;
901
+ const ends = model.ends(edge);
902
+ return ends.undirected ? folding([where], ([c]) => paired(model, ends, c)) : where;
903
+ }
904
+ /**
905
+ * The rows of a list, each end under its role. An undirected Edge's ends render in their stored
906
+ * order, which is one pairing of its roles that the read meets only when its roles accept the
907
+ * same Classes and its condition reads no end; any other list of it is refused.
908
+ */
909
+ #rows(verb, limit, bound) {
910
+ const { model, edge, where } = this.#s;
911
+ const { source, target, undirected } = model.ends(edge);
912
+ if (undirected &&
913
+ !(model.covers(source, target.accepts) && model.covers(target, source.accepts)))
914
+ throw new TypeError(`An undirected Edge's ends have no order: a row of ${edge.key} cannot say which end is its ${source.role} and which its ${target.role}. Read the Edge from a Node with .via(), or ask exists() or count().`);
915
+ if (undirected && (where.written ?? []).some((c) => readsEnd(c.where)))
916
+ throw new TypeError(`An undirected Edge's ends have no order: a row of ${edge.key} read by a condition on its ${source.role} or ${target.role} cannot say which end meets it. Read the Edge from a Node with .via(), or ask exists() or count().`);
917
+ return this.#list(verb, limit, bound);
918
+ }
787
919
  #list(verb, limit, bound) {
788
920
  const s = this.#s;
789
921
  const plan = { verb, ...(bound === undefined ? {} : { bound }), root: this.#root() };
790
- return rootRead(plan, s.where, [], (where) => documentOf({
922
+ return rootRead(plan, this.#where(), [], (where) => documentOf({
791
923
  list: defined({
792
924
  edges: [s.edge.key],
793
925
  where: optional(where),
@@ -803,30 +935,30 @@ export class EdgeSet {
803
935
  #range(verb, upTo) {
804
936
  const s = this.#s;
805
937
  const plan = { verb, ...(upTo === undefined ? {} : { bound: upTo }), root: this.#root() };
806
- return rootRead(plan, s.where, [], (where) => {
938
+ return rootRead(plan, this.#where(), [], (where) => {
807
939
  const range = defined({ edges: [s.edge.key], where: optional(where) });
808
940
  return documentOf(verb === 'exists' ? { exists: range } : { count: range, upTo });
809
941
  });
810
942
  }
811
943
  get() {
812
- return this.#list('get', 2);
944
+ return this.#rows('get', 2);
813
945
  }
814
946
  find() {
815
- return this.#list('find', 2);
947
+ return this.#rows('find', 2);
816
948
  }
817
949
  first(n) {
818
950
  if (n === undefined)
819
- return this.#list('first', 1);
951
+ return this.#rows('first', 1);
820
952
  const bound = integer(n, 'first', 1);
821
- return this.#list('firstN', bound, bound);
953
+ return this.#rows('firstN', bound, bound);
822
954
  }
823
955
  page(written) {
824
956
  const max = integer(options(written, 'page').max, 'page({ max })', 1);
825
- return this.#list('page', max, max);
957
+ return this.#rows('page', max, max);
826
958
  }
827
959
  all(written) {
828
960
  const max = integer(options(written, 'all').max, 'all({ max })', 1);
829
- return this.#list('all', max + 1, max);
961
+ return this.#rows('all', max + 1, max);
830
962
  }
831
963
  exists() {
832
964
  return this.#range('exists');
@@ -4,7 +4,10 @@
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
- /** An Edge's two ends; an undirected Edge's are its two incident ends, in declared order. */
7
+ /**
8
+ * An Edge's two ends. An undirected Edge's are its two roles in declared order, which name neither
9
+ * stored end (`Model.ends`).
10
+ */
8
11
  type EndsOf<E> = E extends {
9
12
  readonly definition: {
10
13
  readonly endpoints: infer P;
@@ -1,4 +1,5 @@
1
1
  import * as errors from '@astrale-os/kernel-protocol/errors';
2
+ import { QueryError } from '../../../application/query/execution/error.js';
2
3
  import { ClientError, MissError, ProtocolError as ClientProtocolError, ResponseError, SessionError, StaleRouteError, TransportError, } from '../../../platform/client/index.js';
3
4
  const PUBLIC_DIAGNOSTICS = new Set(['VALUE_SCHEMA_INSTANCE_INVALID', 'VS_NUMBER_DOMAIN']);
4
5
  const PUBLIC_ERROR_CODES = new Set(Object.values(errors.CODES));
@@ -48,6 +49,10 @@ export function projectError(input) {
48
49
  ? input
49
50
  : protocolError('INTERNAL_ERROR', 'Internal application error.');
50
51
  }
52
+ // A v7 read the Kernel refused reaches the caller as that refusal, as a V6 read's did.
53
+ if (input instanceof QueryError && input.cause instanceof ResponseError) {
54
+ return projectError(input.cause);
55
+ }
51
56
  if (input instanceof ResponseError) {
52
57
  if (!PUBLIC_ERROR_CODES.has(input.code)) {
53
58
  return protocolError('BACKEND_UNAVAILABLE', 'Dependency Kernel returned invalid error evidence.');
package/docs/queries.md CHANGED
@@ -183,6 +183,23 @@ and both ends' rows under their roles. `edgeKey(row)` gives the `{ source, targe
183
183
  Mutation or a guard names an Edge by. An Edge root's `get()`, `find()` and `exists()` take no id,
184
184
  and its `first(n)` takes no `{ more }`.
185
185
 
186
+ An undirected Edge's ends have no order: neither of its roles is kept at a fixed end. A condition
187
+ on its roles holds when one pairing of the Edge's two ends with its two roles meets the whole
188
+ condition, each end a Node its role accepts:
189
+ `d.involves.where((e) => e.person.id.eq(ada)).count({ upTo: 100 })` counts the Edges that involve
190
+ Ada, at either end. An undirected Edge root answers `exists()` and `count()` under any condition.
191
+ It lists rows only when its two roles accept the same Nodes and its condition reads neither role;
192
+ any other list of it, and an order key on a role's Property, throws a `TypeError`. Read those
193
+ Edges from a Node with `.via()`.
194
+
195
+ From a Node, a direction along an undirected Edge names a role, never a stored end:
196
+ `{ direction: 'outgoing' }` reads the Edges where the Node takes the first declared role and
197
+ answers the Nodes that take the second, `'incoming'` the reverse, and `'incident'` every Node at
198
+ the other end. A named relation reads its roles the same way. A relation throws a `TypeError`
199
+ when the role its direction names does not accept every Class it is read from, or when it reads
200
+ several Edge Classes and one of them can reach Nodes its far role does not accept: read that Edge
201
+ Class with its own `.via()`.
202
+
186
203
  ## Defining a Query
187
204
 
188
205
  `defineQuery<Schema>()(id, { build, output?, errors? })` defines a Query. Its id is unique in the
@@ -268,6 +285,14 @@ of that code:
268
285
 
269
286
  `isQueryError(error, code?)` recognizes one.
270
287
 
288
+ A `QueryError` an Action or an inline Workflow does not catch reaches its caller as follows:
289
+
290
+ - One the Kernel refused (`REFUSED`, `OUTDATED`, `UNSUPPORTED` for `v7`, `INPUT_INVALID` with a
291
+ `kernelCode`, `TOO_MANY` past the Host's bytes) reaches it as that refusal: the Kernel's public
292
+ code, message and data. A Kernel code outside the public codes reaches it as
293
+ `BACKEND_UNAVAILABLE`.
294
+ - One the SDK raised itself, the client's bytes included, reaches it as an internal error.
295
+
271
296
  A refusal the caller handles by code is declared in `errors`, as on Actions, and raised by
272
297
  `output`:
273
298
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@astrale-os/sdk",
3
- "version": "0.6.0-beta.47",
3
+ "version": "0.6.0-beta.49",
4
4
  "description": "Schema-first SDK for defining, composing, and deploying Astrale domains",
5
5
  "keywords": [
6
6
  "astrale",