@astrale-os/kernel-dsl 1.0.0-beta.34 → 1.0.0-beta.35

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 (34) hide show
  1. package/dist/v1/builder/lowering/schema/lifetime.js +3 -5
  2. package/dist/v1/compiled/admission/semantics/policy/callable.js +7 -29
  3. package/dist/v1/compiled/admission/semantics/policy/parity.js +4 -11
  4. package/dist/v1/compiled/admission/wire/core.js +2 -6
  5. package/dist/v1/compiled/admission/wire/property.js +6 -19
  6. package/dist/v1/domain/projection/classes.js +5 -7
  7. package/dist/v1/language/class/inheritance.d.ts +26 -2
  8. package/dist/v1/language/class/inheritance.js +63 -40
  9. package/dist/v1/language/class/lifetime.d.ts +7 -15
  10. package/dist/v1/language/class/lifetime.js +19 -40
  11. package/dist/v1/language/class/property-values.d.ts +13 -0
  12. package/dist/v1/language/class/property-values.js +35 -4
  13. package/dist/v1/language/class/unique.js +2 -12
  14. package/dist/v1/language/limits.d.ts +3 -1
  15. package/dist/v1/language/limits.js +3 -1
  16. package/dist/v1/language/policy/analysis/branches.d.ts +5 -1
  17. package/dist/v1/language/policy/analysis/branches.js +21 -5
  18. package/dist/v1/language/policy/analysis/budgets.d.ts +2 -0
  19. package/dist/v1/language/policy/analysis/budgets.js +7 -1
  20. package/dist/v1/language/policy/analysis/typing.d.ts +9 -1
  21. package/dist/v1/language/policy/analysis/typing.js +44 -49
  22. package/dist/v1/language/state/topology.d.ts +24 -0
  23. package/dist/v1/language/state/topology.js +60 -19
  24. package/dist/v1/language/value/syntax/node-path/schema.d.ts +7 -0
  25. package/dist/v1/language/value/syntax/node-path/schema.js +32 -0
  26. package/dist/v1/schema/compatibility/comparators/classes.js +10 -21
  27. package/dist/v1/schema/enforcement/derived.js +1 -1
  28. package/dist/v1/schema/resolution/origins.js +3 -5
  29. package/dist/v1/schema/rule.js +2 -1
  30. package/dist/v1/schema/validation/class.js +38 -46
  31. package/dist/v1/schema/validation/policy/budgets.js +1 -0
  32. package/dist/v1/schema/validation/policy/typing.js +7 -20
  33. package/dist/v1/schema/validation/policy/uses.js +5 -25
  34. package/package.json +1 -1
@@ -48,7 +48,9 @@ export const limits = Object.freeze({
48
48
  * Levels of a Policy pattern: an Edge or sameNode is one, and each allOf, anyOf, exists and
49
49
  * composition adds one.
50
50
  */
51
- patternDepth: 4,
51
+ patternDepth: 8,
52
+ /** Nested exists scopes on one path. Boolean operators and named compositions add none. */
53
+ existsDepth: 3,
52
54
  /**
53
55
  * Branches of a Policy's normal form: an anyOf adds those of its operands, an allOf multiplies
54
56
  * them.
@@ -5,7 +5,6 @@ export interface PatternBranch {
5
5
  readonly edges: readonly PatternEdgeUse[];
6
6
  readonly variables: ReadonlyMap<string, PolicyVariableSelector>;
7
7
  readonly requiredVariables: ReadonlySet<string>;
8
- readonly namespace: string;
9
8
  }
10
9
  export interface PatternEdgeUse {
11
10
  readonly pattern: PolicyEdgePattern;
@@ -13,6 +12,11 @@ export interface PatternEdgeUse {
13
12
  }
14
13
  export type PolicyTargetMode = 'object' | 'edge' | 'named';
15
14
  export declare function branchesOf(pattern: PolicyPatternExpression, namespace: string): readonly PatternBranch[];
15
+ /** Give one operand of a named conjunction its own existential variables. A cached expansion
16
+ * uses relative namespaces, so even two paths to the same declaration bind separate witnesses.
17
+ * Terms supplied by the use site (subject, object, inputs and references) remain shared.
18
+ */
19
+ export declare function scopeOperand(branch: PatternBranch, operand: number): PatternBranch;
16
20
  export declare function branchProduct(children: readonly (readonly PatternBranch[])[]): readonly PatternBranch[];
17
21
  export declare function capBranches(values: readonly PatternBranch[]): readonly PatternBranch[];
18
22
  export declare function isConnected(branch: PatternBranch): boolean;
@@ -5,6 +5,26 @@ export function branchesOf(pattern, namespace) {
5
5
  const variables = collectVariableClasses(pattern, namespace);
6
6
  return branchesForNode(pattern, namespace, variables);
7
7
  }
8
+ /** Give one operand of a named conjunction its own existential variables. A cached expansion
9
+ * uses relative namespaces, so even two paths to the same declaration bind separate witnesses.
10
+ * Terms supplied by the use site (subject, object, inputs and references) remain shared.
11
+ */
12
+ export function scopeOperand(branch, operand) {
13
+ if (branch.variables.size === 0)
14
+ return branch;
15
+ const suffix = '/' + operand;
16
+ const key = (term) => (branch.variables.has(term) ? term + suffix : term);
17
+ return {
18
+ terms: new Map([...branch.terms].map(([term, value]) => [key(term), value])),
19
+ equalities: branch.equalities.map(([left, right]) => [key(left), key(right)]),
20
+ edges: branch.edges.map(({ pattern, namespace }) => ({
21
+ pattern,
22
+ namespace: namespace + suffix,
23
+ })),
24
+ variables: new Map([...branch.variables].map(([term, selector]) => [key(term), selector])),
25
+ requiredVariables: new Set([...branch.requiredVariables].map(key)),
26
+ };
27
+ }
8
28
  export function branchProduct(children) {
9
29
  let result = [emptyBranch()];
10
30
  for (const child of children) {
@@ -80,7 +100,6 @@ function branchesForNode(pattern, namespace, variables) {
80
100
  edges: [{ pattern, namespace }],
81
101
  variables,
82
102
  requiredVariables: new Set(),
83
- namespace,
84
103
  },
85
104
  ];
86
105
  }
@@ -98,7 +117,6 @@ function branchesForNode(pattern, namespace, variables) {
98
117
  edges: [],
99
118
  variables,
100
119
  requiredVariables: new Set(),
101
- namespace,
102
120
  },
103
121
  ];
104
122
  }
@@ -120,7 +138,6 @@ function emptyBranch() {
120
138
  edges: [],
121
139
  variables: new Map(),
122
140
  requiredVariables: new Set(),
123
- namespace: '$',
124
141
  };
125
142
  }
126
143
  function mergeBranches(left, right) {
@@ -130,7 +147,6 @@ function mergeBranches(left, right) {
130
147
  edges: [...left.edges, ...right.edges],
131
148
  variables: new Map([...left.variables, ...right.variables]),
132
149
  requiredVariables: new Set([...left.requiredVariables, ...right.requiredVariables]),
133
- namespace: `${left.namespace}&${right.namespace}`,
134
150
  };
135
151
  }
136
152
  function collectVariableClasses(pattern, namespace) {
@@ -149,7 +165,7 @@ function collectVariableClasses(pattern, namespace) {
149
165
  return result;
150
166
  }
151
167
  function variableKey(namespace, id) {
152
- return `variable:${namespace}:${id}`;
168
+ return `variable:${id}@${namespace}`;
153
169
  }
154
170
  /** Disjoint sets of term keys, merged by the equalities of one Policy branch. */
155
171
  export class UnionFind {
@@ -19,6 +19,8 @@ export interface PolicyMeasure {
19
19
  readonly inputs: number;
20
20
  /** Levels of the expanded pattern. */
21
21
  readonly patternDepth: number;
22
+ /** The greatest number of nested exists scopes on one path. */
23
+ readonly existsDepth: number;
22
24
  /** Branches of its normal form, at most `limits.policy.normalizedBranches + 1`. */
23
25
  readonly normalizedBranches: number;
24
26
  /** The most graph predicates, Edges and sameNode equalities, of one branch. */
@@ -75,6 +75,7 @@ export function policyMeasurer(origin, normalized, isLocal, inputOf) {
75
75
  : {
76
76
  inputs: measure.inputs ?? 0,
77
77
  patternDepth: measure.depth,
78
+ existsDepth: measure.existsDepth,
78
79
  normalizedBranches: measure.edgeCounts.length,
79
80
  edgePredicates: Math.max(0, ...measure.edgeCounts),
80
81
  referencedDomains: measure.domains.size,
@@ -85,6 +86,7 @@ function measurePattern(pattern, origin) {
85
86
  if ('sameNode' in pattern)
86
87
  return {
87
88
  depth: 1,
89
+ existsDepth: 0,
88
90
  edgeCounts: [1],
89
91
  domains: new Set([
90
92
  origin,
@@ -94,6 +96,7 @@ function measurePattern(pattern, origin) {
94
96
  if ('source' in pattern)
95
97
  return {
96
98
  depth: 1,
99
+ existsDepth: 0,
97
100
  edgeCounts: [1],
98
101
  domains: new Set([
99
102
  origin,
@@ -105,6 +108,7 @@ function measurePattern(pattern, origin) {
105
108
  const child = measurePattern(pattern.exists.where, origin);
106
109
  return {
107
110
  depth: child.depth + 1,
111
+ existsDepth: child.existsDepth + 1,
108
112
  edgeCounts: child.edgeCounts,
109
113
  domains: new Set([
110
114
  ...child.domains,
@@ -120,10 +124,12 @@ function measurePattern(pattern, origin) {
120
124
  }
121
125
  function combineMeasures(kind, children) {
122
126
  const depth = 1 + Math.max(0, ...children.map((child) => child.depth));
127
+ const existsDepth = Math.max(...children.map((child) => child.existsDepth));
123
128
  const domains = new Set(children.flatMap((child) => [...child.domains]));
124
129
  if (kind === 'anyOf')
125
130
  return {
126
131
  depth,
132
+ existsDepth,
127
133
  edgeCounts: children.flatMap((child) => child.edgeCounts).slice(0, BRANCH_OVERFLOW),
128
134
  domains,
129
135
  };
@@ -141,7 +147,7 @@ function combineMeasures(kind, children) {
141
147
  }
142
148
  edgeCounts = next;
143
149
  }
144
- return { depth, edgeCounts, domains };
150
+ return { depth, existsDepth, edgeCounts, domains };
145
151
  }
146
152
  /** Measure one normalized check tree. */
147
153
  export function measureChecks(expression) {
@@ -45,7 +45,15 @@ export declare class PolicyTyping {
45
45
  readonly scope: PolicyTypingScope;
46
46
  constructor(scope: PolicyTypingScope);
47
47
  /** The normalized branches of a named Policy, `undefined` when it does not expand. */
48
- expandedBranches(name: string, namespace: string): readonly PatternBranch[] | undefined;
48
+ expandedBranches(name: string): readonly PatternBranch[] | undefined;
49
+ /**
50
+ * Type each expanded branch at its own default use, yielding in branch order each branch without
51
+ * a coherent target mode (`target`) or not typed at that use (`typing`); named branches are skipped.
52
+ */
53
+ defaultUseFaults(branches: readonly PatternBranch[]): Generator<{
54
+ readonly index: number;
55
+ readonly kind: 'target' | 'typing';
56
+ }>;
49
57
  /** Compositions inherit the signature of their operands, checked at declaration admission. */
50
58
  signature(name: string): InputSignature | undefined;
51
59
  validDeclaration(name: string): boolean;
@@ -1,29 +1,42 @@
1
1
  import { Key } from '../../../addressing/index.js';
2
2
  import { definitionRefIndex } from '../../../addressing/ordering.js';
3
- import { classSatisfies, isGraphRoot } from '../../class/inheritance.js';
3
+ import { ancestry, classSatisfies, contractEndpoints, isGraphRoot, } from '../../class/inheritance.js';
4
4
  import { limits } from '../../limits.js';
5
5
  import { PolicyComposition } from '../model/policy.js';
6
- import { branchesOf, branchProduct, capBranches, targetMode, termKey, UnionFind, } from './branches.js';
6
+ import { branchesOf, branchProduct, capBranches, scopeOperand, targetMode, termKey, UnionFind, } from './branches.js';
7
7
  import { admittedCheckClasses, checkObjectName } from './checks.js';
8
8
  export class PolicyTyping {
9
9
  scope;
10
- // Expanded branches of each named Policy, cached by node identity. A Policy's expansion is reused
11
- // across every composition path that reaches it (and across every use site and object contract,
12
- // none of which the expansion depends on), so a shared-child composition DAG is expanded in work
13
- // linear in the number of Policies instead of enumerating every path. The expansion result is
14
- // independent of the reaching path up to the opaque term-namespace labels, which only ever
15
- // disambiguate variables within one branch and leave targetMode and branch typing unchanged.
16
- // Two occurrences of one Policy in a branch share labels only when a Policy reaches it by two
17
- // paths; for that to merge distinct variables, the Policy expands deeper than
18
- // `limits.policy.patternDepth`.
10
+ // Cache each declaration once. Its variables are relative to its own expansion. A named
11
+ // conjunction scopes each operand before combining them; disjunctive branches stay separate.
19
12
  #expansions = new Map();
20
13
  #index;
21
14
  constructor(scope) {
22
15
  this.scope = scope;
23
16
  }
24
17
  /** The normalized branches of a named Policy, `undefined` when it does not expand. */
25
- expandedBranches(name, namespace) {
26
- return this.#expandedBranches(name, new Set(), namespace);
18
+ expandedBranches(name) {
19
+ return this.#expandedBranches(name, new Set());
20
+ }
21
+ /**
22
+ * Type each expanded branch at its own default use, yielding in branch order each branch without
23
+ * a coherent target mode (`target`) or not typed at that use (`typing`); named branches are skipped.
24
+ */
25
+ *defaultUseFaults(branches) {
26
+ for (const [index, branch] of branches.entries()) {
27
+ const mode = targetMode(branch);
28
+ if (mode === 'named')
29
+ continue;
30
+ if (mode === undefined) {
31
+ yield { index, kind: 'target' };
32
+ continue;
33
+ }
34
+ const use = mode === 'object'
35
+ ? { kind: 'object', object: { kind: 'default' } }
36
+ : { kind: 'edge', source: { kind: 'default' }, target: { kind: 'default' } };
37
+ if (!this.branchIsTyped(branch, use))
38
+ yield { index, kind: 'typing' };
39
+ }
27
40
  }
28
41
  /** Compositions inherit the signature of their operands, checked at declaration admission. */
29
42
  signature(name) {
@@ -65,7 +78,7 @@ export class PolicyTyping {
65
78
  }
66
79
  namedCheck(name, bindings, actuals) {
67
80
  const signature = this.signature(name);
68
- const branches = this.expandedBranches(name, name);
81
+ const branches = this.expandedBranches(name);
69
82
  if (!signature ||
70
83
  !branches ||
71
84
  Object.keys(bindings).length !== Object.keys(signature).length ||
@@ -93,9 +106,9 @@ export class PolicyTyping {
93
106
  const signature = this.signature(name);
94
107
  if (signature && Object.keys(signature).some((key) => key !== 'source' && key !== 'target'))
95
108
  return false;
96
- const endpoints = endpointPair(declaration);
97
- const sources = this.#concreteEndpointClasses(endpoints[0].accepts);
98
- const targets = this.#concreteEndpointClasses(endpoints[1].accepts);
109
+ const endpoints = contractEndpoints(declaration);
110
+ const sources = this.#concreteEndpointClasses(endpoints[0].endpoint.accepts);
111
+ const targets = this.#concreteEndpointClasses(endpoints[1].endpoint.accepts);
99
112
  return sources.every((source) => targets.every((target) => this.#policyAcceptsEdge(name, { kind: 'exact', ref: source }, { kind: 'exact', ref: target })));
100
113
  }
101
114
  /**
@@ -129,7 +142,7 @@ export class PolicyTyping {
129
142
  }
130
143
  /** Whether each normalized branch of the Policy is typed for an object of this contract. */
131
144
  #policyBranchTyping(name, object) {
132
- const branches = this.#expandedBranches(name, new Set(), `$use:${name}`);
145
+ const branches = this.expandedBranches(name);
133
146
  const signature = this.signature(name);
134
147
  if (signature && (Object.keys(signature).length !== 1 || !Object.hasOwn(signature, 'object')))
135
148
  return undefined;
@@ -139,7 +152,7 @@ export class PolicyTyping {
139
152
  return branches?.map((branch) => this.branchIsTyped(branch, use));
140
153
  }
141
154
  #policyAcceptsEdge(name, source, target) {
142
- const branches = this.#expandedBranches(name, new Set(), `$edge-use:${name}`);
155
+ const branches = this.expandedBranches(name);
143
156
  const signature = this.signature(name);
144
157
  const use = signature
145
158
  ? { kind: 'named', signature, actuals: { source: [source], target: [target] } }
@@ -154,22 +167,22 @@ export class PolicyTyping {
154
167
  this.#index ??= nodeClassIndex(this.scope);
155
168
  return this.#index;
156
169
  }
157
- #expandedBranches(name, visiting, namespace) {
170
+ #expandedBranches(name, visiting) {
158
171
  if (visiting.has(name))
159
172
  return undefined;
160
173
  const cached = this.#expansions.get(name);
161
174
  if (cached !== undefined || this.#expansions.has(name))
162
175
  return cached;
163
- const expanded = this.#expandDeclaration(name, visiting, namespace);
176
+ const expanded = this.#expandDeclaration(name, visiting);
164
177
  this.#expansions.set(name, expanded);
165
178
  return expanded;
166
179
  }
167
- #expandDeclaration(name, visiting, namespace) {
180
+ #expandDeclaration(name, visiting) {
168
181
  const declaration = this.scope.normalized.get(name);
169
182
  if (declaration === undefined)
170
183
  return undefined;
171
184
  if ('match' in declaration)
172
- return branchesOf(declaration.match, namespace);
185
+ return branchesOf(declaration.match, '');
173
186
  const nested = new Set(visiting);
174
187
  nested.add(name);
175
188
  const { operator, operands: refs } = PolicyComposition.of(declaration);
@@ -177,10 +190,12 @@ export class PolicyTyping {
177
190
  for (const [index, ref] of refs.entries()) {
178
191
  if (!this.scope.isLocalPolicy(ref))
179
192
  return undefined;
180
- const expanded = this.#expandedBranches(ref.name, nested, `${namespace}/${index}:${ref.name}`);
193
+ const expanded = this.#expandedBranches(ref.name, nested);
181
194
  if (expanded === undefined)
182
195
  return undefined;
183
- children.push(expanded);
196
+ if (refs.length === 1)
197
+ return expanded;
198
+ children.push(operator === 'allOf' ? expanded.map((branch) => scopeOperand(branch, index)) : expanded);
184
199
  }
185
200
  return operator === 'allOf' ? branchProduct(children) : capBranches(children.flat());
186
201
  }
@@ -434,21 +449,7 @@ function nodeClassIndex(scope) {
434
449
  }
435
450
  /** The keys of the Node Classes a Node Class's ancestry reaches, itself included. */
436
451
  function ancestryKeys(actual, scope) {
437
- const seen = new Set();
438
- const keys = new Set();
439
- const pending = [actual];
440
- for (let value = pending.pop(); value !== undefined; value = pending.pop()) {
441
- if (seen.has(value))
442
- continue;
443
- seen.add(value);
444
- keys.add(definitionRefIndex(value.ref));
445
- for (const parent of value.extends) {
446
- const resolved = scope.resolveClass(parent);
447
- if (resolved?.kind === 'node')
448
- pending.push(resolved);
449
- }
450
- }
451
- return keys;
452
+ return new Set(Array.from(ancestry(actual, (ref) => scope.resolveClass(ref)), ({ ref }) => definitionRefIndex(ref)));
452
453
  }
453
454
  function targetContract(term, use) {
454
455
  if (use.kind === 'named')
@@ -481,7 +482,7 @@ function variantsForEdge(use, typing) {
481
482
  const declaration = typing.scope.edgeDeclaration(edge.class);
482
483
  if (declaration === undefined)
483
484
  return [];
484
- const endpoints = endpointPair(declaration);
485
+ const endpoints = contractEndpoints(declaration);
485
486
  const bounds = edge.repeat ?? { min: 1, max: 1 };
486
487
  if (!Number.isInteger(bounds.min) ||
487
488
  !Number.isInteger(bounds.max) ||
@@ -525,17 +526,11 @@ function variantsForEdge(use, typing) {
525
526
  }
526
527
  return uniqueBy(variants, edgeVariantKey);
527
528
  }
528
- /** The two endpoints of an Edge Class, a directed one's as source then target. */
529
- function endpointPair(declaration) {
530
- return declaration.orientation === 'directed'
531
- ? [declaration.endpoints.source, declaration.endpoints.target]
532
- : declaration.endpoints;
533
- }
534
529
  function startEndpoint(endpoints, reversed) {
535
- return reversed ? endpoints[1] : endpoints[0];
530
+ return (reversed ? endpoints[1] : endpoints[0]).endpoint;
536
531
  }
537
532
  function endEndpoint(endpoints, reversed) {
538
- return reversed ? endpoints[0] : endpoints[1];
533
+ return (reversed ? endpoints[0] : endpoints[1]).endpoint;
539
534
  }
540
535
  /** The values with distinct keys, each at its key's first position and holding its last value. */
541
536
  function uniqueBy(values, key) {
@@ -11,4 +11,28 @@ export interface StateTopology<Transitions extends TransitionRelation = Transiti
11
11
  readonly transitions: Transitions;
12
12
  }
13
13
  export type StateTopologyOf<Value> = Value extends StateTopology<infer Transitions, infer Initial> ? StateTopology<Transitions, Initial> : undefined;
14
+ /** A State topology, or why an input describes none. */
15
+ export type StateTopologyResult = {
16
+ readonly ok: true;
17
+ readonly topology: StateTopology;
18
+ } | {
19
+ readonly ok: false;
20
+ readonly message: string;
21
+ };
22
+ /**
23
+ * The canonical, frozen State topology `input` describes, or why it describes none. It never throws
24
+ * for a portable value, however malformed.
25
+ */
26
+ export declare function validateStateTopology(input: unknown): StateTopologyResult;
27
+ /** The State topology `input` describes; a TypeError says why when it describes none. */
14
28
  export declare function admitStateTopology(input: unknown): StateTopology;
29
+ /**
30
+ * Whether a Property can hold the States of `topology`: it is required and not automatic, and its
31
+ * value schema is a string enumeration of exactly those States, read in `any` order as authored or
32
+ * in the topology's `canonical` order as compiled. The schema is read first: in `any` order its
33
+ * members are sorted as strings, which throws a TypeError for one that cannot become a string.
34
+ */
35
+ export declare function holdsStates(property: {
36
+ readonly required: unknown;
37
+ readonly auto?: unknown;
38
+ }, schema: unknown, topology: StateTopology, order: 'any' | 'canonical'): boolean;
@@ -1,18 +1,23 @@
1
1
  import { compareUnicode } from '../../addressing/ordering.js';
2
- export function admitStateTopology(input) {
2
+ /**
3
+ * The canonical, frozen State topology `input` describes, or why it describes none. It never throws
4
+ * for a portable value, however malformed.
5
+ */
6
+ export function validateStateTopology(input) {
3
7
  if (!isRecord(input) || !exactKeys(input, ['initial', 'transitions']))
4
- invalidInput();
8
+ return refused(SHAPE);
5
9
  const initial = input.initial;
6
10
  const authored = input.transitions;
7
- if (typeof initial !== 'string' || initial.length === 0 || !isRecord(authored))
8
- invalidInput();
11
+ if (typeof initial !== 'string' || initial.length === 0 || !isRecord(authored)) {
12
+ return refused(SHAPE);
13
+ }
9
14
  const states = Object.keys(authored);
10
15
  if (states.length === 0)
11
- throw new TypeError('State topology requires at least one state.');
16
+ return refused('State topology requires at least one state.');
12
17
  if (states.includes(''))
13
- throw new TypeError('State topology has an empty state name.');
18
+ return refused('State topology has an empty state name.');
14
19
  if (!states.includes(initial)) {
15
- throw new TypeError(`State topology initial state "${initial}" is not declared.`);
20
+ return refused(`State topology initial state "${initial}" is not declared.`);
16
21
  }
17
22
  const declared = new Set(states);
18
23
  const transitions = Object.create(null);
@@ -20,17 +25,24 @@ export function admitStateTopology(input) {
20
25
  for (const state of states.sort(compareUnicode)) {
21
26
  const outgoing = authored[state];
22
27
  if (!isRecord(outgoing))
23
- throw new TypeError(`State "${state}" transitions must be an object.`);
28
+ return refused(`State "${state}" transitions must be an object.`);
24
29
  const accepted = Object.create(null);
25
30
  for (const event of Object.keys(outgoing).sort(compareUnicode)) {
26
31
  const target = outgoing[event];
27
32
  if (event.length === 0)
28
- throw new TypeError(`State "${state}" has an empty event name.`);
33
+ return refused(`State "${state}" has an empty event name.`);
29
34
  if (typeof target !== 'string' || !declared.has(target)) {
30
- throw new TypeError(`State "${state}" event "${event}" targets undeclared state "${String(target)}".`);
35
+ // `String` runs a target's own conversion, which can throw: only reading the message runs
36
+ // it, so the refusal is returned whatever the target is.
37
+ return {
38
+ ok: false,
39
+ get message() {
40
+ return `State "${state}" event "${event}" targets undeclared state "${String(target)}".`;
41
+ },
42
+ };
31
43
  }
32
44
  if (target === state) {
33
- throw new TypeError(`State "${state}" event "${event}" is a self-transition.`);
45
+ return refused(`State "${state}" event "${event}" is a self-transition.`);
34
46
  }
35
47
  accepted[event] = target;
36
48
  transitionCount += 1;
@@ -38,7 +50,7 @@ export function admitStateTopology(input) {
38
50
  transitions[state] = Object.freeze(accepted);
39
51
  }
40
52
  if (transitionCount === 0)
41
- throw new TypeError('State topology requires at least one transition.');
53
+ return refused('State topology requires at least one transition.');
42
54
  const reachable = new Set([initial]);
43
55
  const pending = [initial];
44
56
  while (pending.length > 0) {
@@ -50,15 +62,44 @@ export function admitStateTopology(input) {
50
62
  pending.push(target);
51
63
  }
52
64
  }
53
- for (const state of states) {
54
- if (!reachable.has(state)) {
55
- throw new TypeError(`State "${state}" is unreachable from initial "${initial}".`);
56
- }
65
+ const unreachable = states.find((state) => !reachable.has(state));
66
+ if (unreachable !== undefined) {
67
+ return refused(`State "${unreachable}" is unreachable from initial "${initial}".`);
68
+ }
69
+ return { ok: true, topology: Object.freeze({ initial, transitions: Object.freeze(transitions) }) };
70
+ }
71
+ /** The State topology `input` describes; a TypeError says why when it describes none. */
72
+ export function admitStateTopology(input) {
73
+ const result = validateStateTopology(input);
74
+ if (!result.ok)
75
+ throw new TypeError(result.message);
76
+ return result.topology;
77
+ }
78
+ /**
79
+ * Whether a Property can hold the States of `topology`: it is required and not automatic, and its
80
+ * value schema is a string enumeration of exactly those States, read in `any` order as authored or
81
+ * in the topology's `canonical` order as compiled. The schema is read first: in `any` order its
82
+ * members are sorted as strings, which throws a TypeError for one that cannot become a string.
83
+ */
84
+ export function holdsStates(property, schema, topology, order) {
85
+ const enumerates = enumeratesStates(schema, Object.keys(topology.transitions), order);
86
+ return enumerates && Boolean(property.required) && property.auto === undefined;
87
+ }
88
+ function enumeratesStates(schema, states, order) {
89
+ if (!isRecord(schema) || Object.keys(schema).length !== 2 || schema.type !== 'string') {
90
+ return false;
57
91
  }
58
- return Object.freeze({ initial, transitions: Object.freeze(transitions) });
92
+ const members = schema.enum;
93
+ if (!Array.isArray(members) || members.length !== states.length)
94
+ return false;
95
+ if (order === 'canonical')
96
+ return members.every((member, index) => member === states[index]);
97
+ const expected = states.sort();
98
+ return [...members].sort().every((member, index) => member === expected[index]);
59
99
  }
60
- function invalidInput() {
61
- throw new TypeError('State topology must contain exactly initial and transitions.');
100
+ const SHAPE = 'State topology must contain exactly initial and transitions.';
101
+ function refused(message) {
102
+ return { ok: false, message };
62
103
  }
63
104
  function isRecord(input) {
64
105
  return input !== null && typeof input === 'object' && !Array.isArray(input);
@@ -3,3 +3,10 @@ export declare const GRAPH_NODE_PATH_SCHEMA_ID: 'https://schemas.astrale.ai/grap
3
3
  /** Exact locally bundled artifact owned by graph/path/language's governed JSON Schema. */
4
4
  export declare const graphNodePathSchema: JsonSchemaObject;
5
5
  export declare function hasNodePathAnnotation(schema: JsonSchema): boolean;
6
+ /**
7
+ * The `accepts` of `field` where the callable input `input` binds it to one Node: a direct required
8
+ * single-Node Path field of a closed object input, neither of them carrying a combinator, so that
9
+ * the field's own annotation alone states the Classes of its Node. Otherwise the input binds no Node
10
+ * there: `undefined`. Source and compiled admission both read a Policy input binding through it.
11
+ */
12
+ export declare function singleNodePathFieldAccepts(input: unknown, field: string): readonly unknown[] | undefined;
@@ -16,3 +16,35 @@ export function hasNodePathAnnotation(schema) {
16
16
  schema.$ref === GRAPH_NODE_PATH_SCHEMA_ID &&
17
17
  Object.hasOwn(schema, 'x-astrale-path'));
18
18
  }
19
+ /**
20
+ * The `accepts` of `field` where the callable input `input` binds it to one Node: a direct required
21
+ * single-Node Path field of a closed object input, neither of them carrying a combinator, so that
22
+ * the field's own annotation alone states the Classes of its Node. Otherwise the input binds no Node
23
+ * there: `undefined`. Source and compiled admission both read a Policy input binding through it.
24
+ */
25
+ export function singleNodePathFieldAccepts(input, field) {
26
+ if (!isJsonObject(input) || hasCombinator(input))
27
+ return undefined;
28
+ const { properties, required } = input;
29
+ if (input.type !== 'object' ||
30
+ input.additionalProperties !== false ||
31
+ !Array.isArray(required) ||
32
+ !required.includes(field) ||
33
+ !isJsonObject(properties) ||
34
+ !Object.hasOwn(properties, field))
35
+ return undefined;
36
+ const schema = properties[field];
37
+ if (!isJsonObject(schema) || hasCombinator(schema) || schema.$ref !== GRAPH_NODE_PATH_SCHEMA_ID)
38
+ return undefined;
39
+ const annotation = schema['x-astrale-path'];
40
+ return isJsonObject(annotation) &&
41
+ annotation.target === 'node' &&
42
+ annotation.cardinality === 'one' &&
43
+ Array.isArray(annotation.accepts) &&
44
+ annotation.accepts.length > 0
45
+ ? annotation.accepts
46
+ : undefined;
47
+ }
48
+ function hasCombinator(schema) {
49
+ return ['allOf', 'anyOf', 'oneOf', 'not', 'if', 'then', 'else'].some((keyword) => Object.hasOwn(schema, keyword));
50
+ }
@@ -1,4 +1,5 @@
1
1
  import { compareUnicode } from '../../../addressing/ordering.js';
2
+ import { contractEndpoints, walkAncestry, } from '../../../language/class/inheritance.js';
2
3
  import { compareEdgeUniqueTuples, coveringEdgeUniqueTuples, } from '../../../language/class/unique.js';
3
4
  import { deepFreeze } from '../../../language/freeze.js';
4
5
  import { isClassRuleChecks } from '../../../language/policy/model/policy.js';
@@ -62,20 +63,19 @@ export function edgeEndpoints(context, coordinate) {
62
63
  const declaration = context.schemas.get(coordinate.ref.origin)?.classes[coordinate.ref.name];
63
64
  if (declaration?.kind !== 'edge')
64
65
  return undefined;
65
- const accepts = ({ accepts: refs }) => refs.map(keyForDefinitionRef).sort(compareUnicode);
66
+ const accepts = ({ endpoint }) => endpoint.accepts.map(keyForDefinitionRef).sort(compareUnicode);
67
+ const [first, second] = contractEndpoints(declaration);
66
68
  return deepFreeze(declaration.orientation === 'directed'
67
69
  ? {
68
70
  coordinate: 'class',
69
71
  orientation: 'directed',
70
- source: accepts(declaration.endpoints.source),
71
- target: accepts(declaration.endpoints.target),
72
+ source: accepts(first),
73
+ target: accepts(second),
72
74
  }
73
75
  : {
74
76
  coordinate: 'class',
75
77
  orientation: 'undirected',
76
- endpoints: declaration.endpoints
77
- .map(accepts)
78
- .sort((left, right) => compareUnicode(left.join('\n'), right.join('\n'))),
78
+ endpoints: [accepts(first), accepts(second)].sort((left, right) => compareUnicode(left.join('\n'), right.join('\n'))),
79
79
  });
80
80
  }
81
81
  export function propertyMeaning(field) {
@@ -88,21 +88,10 @@ export function propertyMeaning(field) {
88
88
  });
89
89
  }
90
90
  function ancestorKeys(context, ref) {
91
- const seen = new Set();
92
- const visit = (current) => {
93
- const declaration = context.schemas.get(current.origin)?.classes[current.name];
94
- if (declaration === undefined)
95
- return;
96
- for (const parent of declaration.extends) {
97
- const key = keyForDefinitionRef(parent);
98
- if (seen.has(key))
99
- continue;
100
- seen.add(key);
101
- visit(parent);
102
- }
103
- };
104
- visit(ref);
105
- return [...seen].sort(compareUnicode);
91
+ // Each declared parent ref is walked once; one its schema lacks still names an ancestor.
92
+ const parentsOf = (current) => context.schemas.get(current.origin)?.classes[current.name]?.extends ?? [];
93
+ const keys = new Set(Array.from(walkAncestry(parentsOf(ref), parentsOf), keyForDefinitionRef));
94
+ return [...keys].sort(compareUnicode);
106
95
  }
107
96
  /**
108
97
  * The uniqueness tuples covering an Edge Class (`coveringEdgeUniqueTuples`): those it and each of
@@ -172,7 +172,7 @@ const rows = {
172
172
  },
173
173
  DEFINITION_PROJECTION: {
174
174
  subjects: ['fact.projection'],
175
- statement: 'Installing a Domain projects each of its Definitions as one Node at its canonical NodePath with exactly one `of_domain` Edge, its member locator. The Domain Node holds the name and, as `iconSmall`, `iconMedium` or `iconLarge`, the drawing of each size its icon declares, and one `entrypoint` Edge joins it to the View it declares, none without one. A Core Edge endpoint that is no Core Node is a path into the projected declarations.',
175
+ statement: 'Installing a Domain projects each of its Definitions as one Node at its canonical NodePath with exactly one `of_domain` Edge, its member locator. The Domain Node holds the name, as `Named.name` and as the deprecated `Domain.name`, and, as `iconSmall`, `iconMedium` or `iconLarge`, the drawing of each size its icon declares, and one `entrypoint` Edge joins it to the View it declares, none without one. A Core Edge endpoint that is no Core Node is a path into the projected declarations.',
176
176
  laws: [
177
177
  'KS-DECLARATION-LOCATORS',
178
178
  'KS-PROJECTION',