@sentropic/diagram-core 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -78,6 +78,64 @@ optional grid. It is stored here, and deliberately not imported from a renderer
78
78
  package: a migration-versioned persisted schema must not be hostage to another
79
79
  package's type evolution.
80
80
 
81
+ ### Endpoint provenance: fold and chain
82
+
83
+ Endpoints attach a relation role to a drawn occurrence. When the drawing differs
84
+ from its semantic target, exactly one provenance arm supplies the witness:
85
+
86
+ | Form | Fields beyond `role`, `occurrence` |
87
+ | --- | --- |
88
+ | Plain | None; the occurrence draws the role target directly. |
89
+ | Fold | `semanticTarget` and `sourceOccurrence`; the current fold proves the representative. |
90
+ | Chain | `semanticTarget` and `chainProvenance`; `sourceOccurrence` is absent. |
91
+
92
+ `chainProvenance` contains a profile-declared `predicateId`, ordered relation
93
+ `hops` from the semantic target to the drawn entity, and aggregate-only `members`.
94
+ Profiles declare `chainPredicates` as serialisable DATA: typed directed steps,
95
+ repeat modes, strict string/boolean attribute constraints, alternatives and
96
+ `unique`, `ordered`, `first-drawn` or `aggregate` selection. Types include resolved
97
+ ancestry in their own profile. Walks see only that profile's semantic entities,
98
+ relations and attributes; the sole view input is whether an occurrence exists
99
+ for an entity. Geometry, groups, collapsed state and filters cannot prove a chain.
100
+ A drawn port is tested through its owner entity.
101
+
102
+ Walks stop at the first admitted end and close cycles with an iterative branch
103
+ stack. Completed suffixes are reused while their cycle-pruning ancestors remain
104
+ on the branch, preserving the first witness in candidate order. `first-drawn`
105
+ accepts a drawn completed single-step prefix (the exposer in an external-API
106
+ chain) without requiring the remaining suffix. A drawn non-admitted intermediate
107
+ blocks further lifting.
108
+ Aggregates recompute the complete member set, test each member's target and source
109
+ chains, sort by UTF-16 `(sourceId, targetId, relationId)`, and require the smallest
110
+ member as carrier. Any occurrence of the same repo entity is an equivalent end.
111
+
112
+ `validateView` reports `occurrence-endpoint-mismatch` with one of
113
+ `chain-not-declared`, `chain-hop-mismatch`, `chain-not-proven`, `chain-ambiguous`
114
+ or `chain-aggregation-mismatch` in `details.check`. Candidate lists are in `refs`;
115
+ details remain scalar. Pairing failures retain the fold `provenance-missing`
116
+ template, and dangling witness refs precede chain checks. `validateProfile` uses
117
+ `type-definition-conflict` with `chain-duplicate-id`, `chain-unknown-type`,
118
+ `chain-invalid-direction`, `chain-invalid-repeat` or `chain-members-not-aggregate`;
119
+ functions fail serialisation with `value-not-serialisable`.
120
+
121
+ Selection owns its cardinality outcome: several distinct ends under `unique`
122
+ give `chain-not-proven` with `cause: "cardinality"`; several drawn ends in the
123
+ chosen `ordered` alternative give `chain-ambiguous`. Semantic cardinality remains
124
+ profile-side; `validateView` never calls `validateDocument`.
125
+
126
+ Projection, removal repair and replacement inverses carry chain endpoints
127
+ verbatim, including hop/member order, and leave validation to `validateView`.
128
+ Old views keep their canonical bytes. Frozen schemas `@1/@2` refuse chain fields;
129
+ `@3` adds the exclusive pairing forms and resolves by exact pin only, without
130
+ changing the presentation pin. The package includes
131
+ [`schemas/diagram-view-schema-3.json`](schemas/diagram-view-schema-3.json) and its
132
+ [canonical SHA-256](schemas/diagram-view-schema-3.sha256):
133
+ `b415c05197692baa5f74ab35e3150ce58079cf9f06201df5e581d222a8d2c0df`.
134
+ This branch includes the successor `@3` schema lot but defers the specification's
135
+ `0.2.0` release lot: the current package version and downstream dependency pins
136
+ remain `0.1.0`. The release conductor owns that version/pin/lockfile update and
137
+ the owner-confirmed tag; schema inclusion does not certify downstream adoption.
138
+
81
139
  ### Commands are transactions
82
140
 
83
141
  `applyTransaction(state, transaction, { registry })` returns either
@@ -184,6 +242,8 @@ src/refs.ts the seven nominal reference types, their guards and diagnos
184
242
  src/diagnostics.ts one code per refusal; nothing returns a boolean validity
185
243
  src/attributes.ts typed attribute values and their schemas
186
244
  src/profile.ts profile declarations, registry, and profile self-validation
245
+ src/chain-profile.ts chain predicate DATA declaration checks
246
+ src/chain.ts indexed document-only chain walks, selection and aggregate witnesses
187
247
  src/profiles/ generic@1 (complete), bpmn@1 / archimate@1 / uml@1 (skeletons)
188
248
  src/document.ts SemanticDocument, entities, relations, ports, resources, extensions
189
249
  src/view.ts ViewDocument, the three occurrence kinds, groups, filters, presentation
@@ -211,3 +271,10 @@ reference types are not interchangeable with one `@ts-expect-error` per
211
271
  illegitimate assignment (42 ordered pairs). Those assertions only mean something
212
272
  if a compiler reads them. Remove the brand from `Ref<K>` and `check` reports 42
213
273
  × TS2578 ("Unused '@ts-expect-error' directive") — measured, not assumed.
274
+
275
+ ## Numbered flows (DC-2c.1)
276
+
277
+ `withFlowTypes`, `validateFlows` and `flowIndex` provide authored flow relations
278
+ and scenarios. Relation refinements resolve through `relationBaseType` and
279
+ `relationSchema`, preserving inherited roles and constraints. See
280
+ [the authoring contract and mapping examples](../../docs/DC2C_NUMBERED_FLOWS.md).
package/dist/bindings.js CHANGED
@@ -28,6 +28,7 @@ const IMPOSED_ADAPTERS = {
28
28
  "archimate@1": LEGACY_CONSTRAINTS_ADAPTER,
29
29
  "bpmn@1": LEGACY_CONSTRAINTS_ADAPTER,
30
30
  "uml@1": LEGACY_CONSTRAINTS_ADAPTER,
31
+ "erd@1": SCOPED_CONSTRAINTS_ADAPTER,
31
32
  "generic@2": SCOPED_CONSTRAINTS_ADAPTER,
32
33
  "archimate@2": SCOPED_CONSTRAINTS_ADAPTER,
33
34
  "uml@2": SCOPED_CONSTRAINTS_ADAPTER,
@@ -0,0 +1,4 @@
1
+ import { type Diagnostic } from "./diagnostics.js";
2
+ import type { Profile } from "./profile.js";
3
+ export declare function validateChainPredicates(profile: Profile): readonly Diagnostic[];
4
+ //# sourceMappingURL=chain-profile.d.ts.map
@@ -0,0 +1,85 @@
1
+ /** Declaration checks for the optional, serialisable chain DATA vocabulary. */
2
+ import { tryCanonicalise } from "./canonical.js";
3
+ import { diagnostic } from "./diagnostics.js";
4
+ export function validateChainPredicates(profile) {
5
+ if (profile.chainPredicates === undefined)
6
+ return [];
7
+ const root = `profiles.${profile.id}.chainPredicates`;
8
+ const serialised = tryCanonicalise(profile.chainPredicates, root);
9
+ if (!serialised.ok)
10
+ return serialised.diagnostics;
11
+ const diagnostics = [];
12
+ const entities = new Set(profile.entityTypes.map((type) => type.id));
13
+ const relations = new Set(profile.relationTypes.map((type) => type.id));
14
+ const attributes = new Set(profile.entityTypes.flatMap((type) => type.attributes.map((field) => field.name)));
15
+ const seen = new Set();
16
+ for (const [index, predicate] of profile.chainPredicates.entries()) {
17
+ const path = `${root}[${index}]`;
18
+ const fail = (check, field) => {
19
+ diagnostics.push(diagnostic({
20
+ code: "type-definition-conflict", path: `${path}${field}`,
21
+ message: `chain predicate ${predicate.id} fails check ${check}`,
22
+ details: { check },
23
+ }));
24
+ };
25
+ const types = (values, known, field) => {
26
+ if (values.length === 0 || values.some((value) => !known.has(value)))
27
+ fail("chain-unknown-type", field);
28
+ };
29
+ const constraints = (values, field) => {
30
+ for (const [i, constraint] of (values ?? []).entries()) {
31
+ if (!attributes.has(constraint.attribute))
32
+ fail("chain-unknown-type", `${field}[${i}].attribute`);
33
+ }
34
+ };
35
+ const walk = (value, field) => {
36
+ types(value.endTypes, entities, `${field}.endTypes`);
37
+ constraints(value.endConstraints, `${field}.endConstraints`);
38
+ if (value.steps.length === 0)
39
+ fail("chain-unknown-type", `${field}.steps`);
40
+ for (const [i, step] of value.steps.entries()) {
41
+ types(step.relationTypes, relations, `${field}.steps[${i}].relationTypes`);
42
+ if (step.direction !== "forward" && step.direction !== "inverse") {
43
+ fail("chain-invalid-direction", `${field}.steps[${i}].direction`);
44
+ }
45
+ if (!["one", "zeroOrMore", "oneOrMore"].includes(step.repeat)) {
46
+ fail("chain-invalid-repeat", `${field}.steps[${i}].repeat`);
47
+ }
48
+ }
49
+ };
50
+ if (predicate.id.length === 0 || seen.has(predicate.id))
51
+ fail("chain-duplicate-id", ".id");
52
+ seen.add(predicate.id);
53
+ types(predicate.appliesTo.relationTypes, relations, ".appliesTo.relationTypes");
54
+ types(predicate.appliesTo.startTypes, entities, ".appliesTo.startTypes");
55
+ const roles = new Set(profile.relationTypes
56
+ .filter((type) => predicate.appliesTo.relationTypes.includes(type.id))
57
+ .flatMap((type) => type.roles.map((role) => role.role)));
58
+ types(predicate.appliesTo.roles, roles, ".appliesTo.roles");
59
+ constraints(predicate.startConstraints, ".startConstraints");
60
+ if (predicate.alternatives.length === 0)
61
+ fail("chain-unknown-type", ".alternatives");
62
+ predicate.alternatives.forEach((alternative, i) => walk(alternative, `.alternatives[${i}]`));
63
+ const aggregation = predicate.aggregation;
64
+ const raw = predicate;
65
+ if (predicate.selection !== "aggregate") {
66
+ if (aggregation !== undefined || raw["sort"] !== undefined || raw["members"] !== undefined) {
67
+ fail("chain-members-not-aggregate", ".aggregation");
68
+ }
69
+ }
70
+ else if (aggregation?.memberRelationTypes === undefined || aggregation.memberTargetChain === undefined ||
71
+ aggregation.memberSourceChain === undefined) {
72
+ fail("chain-members-not-aggregate", ".aggregation");
73
+ }
74
+ else {
75
+ types(aggregation.memberRelationTypes, relations, ".aggregation.memberRelationTypes");
76
+ walk(aggregation.memberTargetChain, ".aggregation.memberTargetChain");
77
+ walk(aggregation.memberSourceChain, ".aggregation.memberSourceChain");
78
+ if (aggregation.sort !== undefined && aggregation.sort !== "sourceId,targetId,relationId") {
79
+ fail("chain-members-not-aggregate", ".aggregation.sort");
80
+ }
81
+ }
82
+ }
83
+ return diagnostics;
84
+ }
85
+ //# sourceMappingURL=chain-profile.js.map
@@ -0,0 +1,11 @@
1
+ /** Document-only chain evaluation. The sole view input is the drawn-target index. */
2
+ import { type Diagnostic } from "./diagnostics.js";
3
+ import type { Relation, SemanticDocument } from "./document.js";
4
+ import type { ProfileRegistry } from "./profile.js";
5
+ import type { EntityRef, OccurrenceRef, PortRef, RelationRef } from "./refs.js";
6
+ import type { TypeResolver } from "./resolver.js";
7
+ import type { RelationOccurrenceEndpoint } from "./view.js";
8
+ type Target = EntityRef | PortRef | RelationRef;
9
+ export declare function createChainValidator(document: SemanticDocument, registry: ProfileRegistry, resolver: TypeResolver, drawnTargets: ReadonlyMap<OccurrenceRef, Target>): (relation: Relation, occurrence: OccurrenceRef, endpoint: RelationOccurrenceEndpoint, path: string, scoped: boolean) => Diagnostic | undefined;
10
+ export {};
11
+ //# sourceMappingURL=chain.d.ts.map
package/dist/chain.js ADDED
@@ -0,0 +1,284 @@
1
+ /** Document-only chain evaluation. The sole view input is the drawn-target index. */
2
+ import { diagnostic } from "./diagnostics.js";
3
+ const compare = (a, b) => a < b ? -1 : a > b ? 1 : 0;
4
+ export function createChainValidator(document, registry, resolver, drawnTargets) {
5
+ const indexes = new Map();
6
+ const entityOf = (target) => {
7
+ if (document.entities[target] !== undefined)
8
+ return target;
9
+ return document.ports[target]?.owner;
10
+ };
11
+ const drawnEntities = new Set([...drawnTargets.values()].map(entityOf).filter((id) => id !== undefined));
12
+ const ancestries = new Map();
13
+ // Once per validateView: type -> source/target adjacency, sorted by relation id.
14
+ for (const relation of Object.values(document.relations).sort((a, b) => compare(a.id, b.id))) {
15
+ let index = indexes.get(relation.profile);
16
+ if (index === undefined) {
17
+ index = { types: new Map(), relations: [] };
18
+ indexes.set(relation.profile, index);
19
+ }
20
+ index.relations.push(relation);
21
+ let adjacency = index.types.get(relation.type);
22
+ if (adjacency === undefined) {
23
+ adjacency = { forward: new Map(), inverse: new Map() };
24
+ index.types.set(relation.type, adjacency);
25
+ }
26
+ const sources = relation.endpoints.filter((e) => e.role === "source").map((e) => entityOf(e.target));
27
+ const targets = relation.endpoints.filter((e) => e.role === "target").map((e) => entityOf(e.target));
28
+ for (const source of sources)
29
+ for (const target of targets) {
30
+ if (source === undefined || target === undefined || document.entities[source]?.profile !== relation.profile ||
31
+ document.entities[target]?.profile !== relation.profile)
32
+ continue;
33
+ const append = (map, from, end) => {
34
+ const edges = map.get(from) ?? [];
35
+ edges.push({ relation: relation.id, end });
36
+ map.set(from, edges);
37
+ };
38
+ append(adjacency.forward, source, target);
39
+ append(adjacency.inverse, target, source);
40
+ }
41
+ }
42
+ const matches = (profile, id, types, constraints = []) => {
43
+ const entity = document.entities[id];
44
+ if (entity?.profile !== profile.id)
45
+ return false;
46
+ let byType = ancestries.get(profile);
47
+ if (byType === undefined) {
48
+ byType = new Map();
49
+ ancestries.set(profile, byType);
50
+ }
51
+ if (!byType.has(entity.type)) {
52
+ const resolution = resolver.resolve(profile, entity.type);
53
+ byType.set(entity.type, resolution.ok ? resolution.resolved.ancestry : undefined);
54
+ }
55
+ const ancestry = byType.get(entity.type);
56
+ if (ancestry === undefined || !types.some((type) => ancestry.includes(type)))
57
+ return false;
58
+ return constraints.every(({ attribute, equals }) => {
59
+ const value = entity.attributes[attribute];
60
+ return typeof equals === "boolean"
61
+ ? value?.kind === "boolean" && value.value === equals
62
+ : (value?.kind === "text" || value?.kind === "enum") && value.value === equals;
63
+ });
64
+ };
65
+ function* candidates(profile, node, step, excluded) {
66
+ for (const type of step.relationTypes) {
67
+ for (const edge of indexes.get(profile.id)?.types.get(type)?.[step.direction].get(node) ?? []) {
68
+ if (edge.relation !== excluded)
69
+ yield edge;
70
+ }
71
+ }
72
+ }
73
+ /** Iterative DFS with branch-local (entity, step) visits and shared path trails. */
74
+ function* walk(profile, start, path, excluded, drawnPrefix = false) {
75
+ if (document.entities[start]?.profile !== profile.id || path.steps.length === 0)
76
+ return;
77
+ const frames = [{ node: start, step: 0, used: false, prefixEnd: false, entered: false }];
78
+ const visiting = new Set();
79
+ const completed = new Map();
80
+ const hops = [];
81
+ const nodes = [{ entity: start, prefixEnd: false }];
82
+ const pop = () => {
83
+ const frame = frames.pop();
84
+ if (frame.key !== undefined) {
85
+ visiting.delete(frame.key);
86
+ // A cycle back into this suffix is internal, not an external
87
+ // ancestor dependency of the completed suffix.
88
+ frame.blockers?.delete(frame.key);
89
+ completed.set(frame.memoKey, frame.blockers ?? new Set());
90
+ }
91
+ const parent = frames[frames.length - 1];
92
+ if (parent !== undefined && frame.blockers !== undefined) {
93
+ parent.blockers ??= new Set();
94
+ for (const key of frame.blockers)
95
+ if (key !== parent.key)
96
+ parent.blockers.add(key);
97
+ }
98
+ if (frame.edge !== undefined) {
99
+ hops.pop();
100
+ nodes.pop();
101
+ }
102
+ };
103
+ function* moves(frame, step) {
104
+ const mayStop = frame.used || step.repeat === "zeroOrMore";
105
+ if (mayStop && frame.step + 1 < path.steps.length) {
106
+ yield { node: frame.node, step: frame.step + 1, used: false, prefixEnd: false };
107
+ }
108
+ if (step.repeat === "one" && frame.used)
109
+ return;
110
+ for (const edge of candidates(profile, frame.node, step, excluded)) {
111
+ yield { node: edge.end, step: frame.step, used: true, edge,
112
+ prefixEnd: step.repeat === "one" && frame.step + 1 < path.steps.length };
113
+ }
114
+ }
115
+ while (frames.length > 0) {
116
+ const frame = frames[frames.length - 1];
117
+ const step = path.steps[frame.step];
118
+ if (!frame.entered) {
119
+ frame.entered = true;
120
+ const key = `${frame.step}:${frame.node}`;
121
+ if (visiting.has(key)) {
122
+ frame.blockers = new Set([key]);
123
+ pop();
124
+ continue;
125
+ }
126
+ const memoKey = `${frame.used}:${key}`;
127
+ const blockers = completed.get(memoKey);
128
+ // All ends of this suffix were already emitted in canonical order.
129
+ // Reuse only if the ancestors that pruned it are still on this branch;
130
+ // otherwise another context may permit a previously blocked route.
131
+ if (blockers !== undefined && [...blockers].every((blocked) => visiting.has(blocked))) {
132
+ frame.blockers = new Set(blockers);
133
+ pop();
134
+ continue;
135
+ }
136
+ frame.memoKey = memoKey;
137
+ visiting.add(key);
138
+ frame.key = key;
139
+ const mayStop = frame.used || step.repeat === "zeroOrMore";
140
+ if ((drawnPrefix && frame.prefixEnd && drawnEntities.has(frame.node)) ||
141
+ (mayStop && frame.step === path.steps.length - 1 && matches(profile, frame.node, path.endTypes, path.endConstraints))) {
142
+ yield { end: frame.node, hops: [...hops], nodes: [...nodes] };
143
+ pop();
144
+ continue;
145
+ }
146
+ frame.moves = moves(frame, step);
147
+ }
148
+ const next = frame.moves.next();
149
+ if (next.done) {
150
+ pop();
151
+ continue;
152
+ }
153
+ if (next.value.edge !== undefined) {
154
+ hops.push(next.value.edge.relation);
155
+ nodes.push({ entity: next.value.node, prefixEnd: next.value.prefixEnd });
156
+ }
157
+ frames.push({ ...next.value, entered: false });
158
+ }
159
+ }
160
+ return (relation, occurrence, endpoint, path, scoped) => {
161
+ const provenance = endpoint.chainProvenance;
162
+ const semantic = endpoint.semanticTarget;
163
+ const foldFailure = (check) => diagnostic({
164
+ code: "occurrence-endpoint-mismatch", path: `${path}.occurrence`,
165
+ message: `projected endpoint for role ${endpoint.role} fails check ${check}`,
166
+ refs: [occurrence, endpoint.occurrence], details: { role: endpoint.role, check },
167
+ });
168
+ const refs = [occurrence, endpoint.occurrence, semantic];
169
+ const fail = (check, details = {}, extra = []) => diagnostic({
170
+ code: "occurrence-endpoint-mismatch", path: `${path}.occurrence`,
171
+ message: `chain endpoint for role ${endpoint.role} fails check ${check} (predicate ${provenance.predicateId})`,
172
+ refs: [...refs, ...extra], details: { role: endpoint.role, check, predicateId: provenance.predicateId, ...details },
173
+ });
174
+ for (const ref of [...provenance.hops, ...(provenance.members ?? [])]) {
175
+ if (document.relations[ref] === undefined)
176
+ return diagnostic({
177
+ code: "dangling-reference", path: `${path}.occurrence`, message: `${ref} is no relation of this document`, refs: [ref],
178
+ });
179
+ }
180
+ if (!relation.endpoints.some((e) => e.role === endpoint.role && e.target === semantic))
181
+ return foldFailure("provenance-mismatch");
182
+ const drawn = drawnTargets.get(endpoint.occurrence);
183
+ if (drawn === undefined)
184
+ return diagnostic({
185
+ code: "dangling-reference", path: `${path}.occurrence`,
186
+ message: scoped ? `${endpoint.occurrence} is no entity, port or relation occurrence of this view`
187
+ : `${endpoint.occurrence} is no entity or port occurrence of this view`, refs: [endpoint.occurrence],
188
+ });
189
+ const profile = registry.get(relation.profile);
190
+ const predicate = profile?.chainPredicates?.find((p) => p.id === provenance.predicateId);
191
+ if (profile === undefined || predicate === undefined)
192
+ return fail("chain-not-declared");
193
+ const start = entityOf(semantic);
194
+ const end = entityOf(drawn);
195
+ if (!predicate.appliesTo.relationTypes.includes(relation.type) || !predicate.appliesTo.roles.includes(endpoint.role) ||
196
+ start === undefined || !matches(profile, start, predicate.appliesTo.startTypes, predicate.startConstraints))
197
+ return fail("chain-hop-mismatch");
198
+ if ((predicate.selection === "aggregate") !== (provenance.members !== undefined))
199
+ return fail("chain-hop-mismatch");
200
+ let expected;
201
+ if (predicate.selection === "aggregate") {
202
+ const aggregation = predicate.aggregation;
203
+ if (aggregation === undefined)
204
+ return fail("chain-hop-mismatch");
205
+ const members = [];
206
+ for (const member of indexes.get(profile.id)?.relations ?? []) {
207
+ if (!aggregation.memberRelationTypes.includes(member.type))
208
+ continue;
209
+ const source = member.endpoints.find((e) => e.role === "source")?.target;
210
+ const target = member.endpoints.find((e) => e.role === "target")?.target;
211
+ const s = source === undefined ? undefined : entityOf(source);
212
+ const t = target === undefined ? undefined : entityOf(target);
213
+ if (s === undefined || t === undefined || walk(profile, t, aggregation.memberTargetChain, relation.id).next().done)
214
+ continue;
215
+ for (const route of walk(profile, s, aggregation.memberSourceChain, relation.id)) {
216
+ if (route.end === end) {
217
+ members.push({ relation: member, source: s, target: t, route });
218
+ break;
219
+ }
220
+ }
221
+ }
222
+ members.sort((a, b) => compare(a.source, b.source) || compare(a.target, b.target) || compare(a.relation.id, b.relation.id));
223
+ const declared = provenance.members;
224
+ const firstDifference = members.findIndex((m, i) => m.relation.id !== declared[i]);
225
+ if (members.length === 0 || members.length !== declared.length || firstDifference !== -1 || members[0].relation.id !== relation.id) {
226
+ const differing = firstDifference === -1 ? declared[members.length] : declared[firstDifference] ?? members[firstDifference]?.relation.id;
227
+ const carrier = members[0]?.relation.id;
228
+ return fail("chain-aggregation-mismatch", { expectedCount: members.length, declaredCount: declared.length }, carrier !== relation.id && carrier !== undefined ? [carrier] : differing === undefined ? [] : [differing]);
229
+ }
230
+ expected = members[0].route;
231
+ }
232
+ else if (predicate.selection === "first-drawn") {
233
+ search: for (const alternative of predicate.alternatives) {
234
+ for (const route of walk(profile, start, alternative, relation.id, true)) {
235
+ const index = route.nodes.findIndex((node) => drawnEntities.has(node.entity));
236
+ if (index === -1)
237
+ return fail("chain-not-proven");
238
+ const node = route.nodes[index];
239
+ // A completed one-step prefix is an admitted lift (e.g. the exposer).
240
+ // Nodes inside a repeating step must satisfy that path's end test.
241
+ if (!node.prefixEnd && index !== route.nodes.length - 1)
242
+ return fail("chain-not-proven", { blockingDrawn: node.entity });
243
+ if (node.entity !== end)
244
+ return fail("chain-not-proven", { earlierDrawn: node.entity });
245
+ expected = { ...route, end: node.entity, hops: route.hops.slice(0, index) };
246
+ break search;
247
+ }
248
+ }
249
+ }
250
+ else {
251
+ const ends = new Map();
252
+ for (const alternative of predicate.alternatives) {
253
+ for (const route of walk(profile, start, alternative, relation.id)) {
254
+ if (predicate.selection === "ordered" && !drawnEntities.has(route.end))
255
+ continue;
256
+ if (!ends.has(route.end))
257
+ ends.set(route.end, route);
258
+ }
259
+ if (predicate.selection === "ordered" && ends.size > 0)
260
+ break;
261
+ }
262
+ if (ends.size > 1) {
263
+ return predicate.selection === "unique" ? fail("chain-not-proven", { cause: "cardinality" })
264
+ : fail("chain-ambiguous", { candidateCount: ends.size }, [...ends.keys()].sort(compare));
265
+ }
266
+ expected = ends.values().next().value;
267
+ }
268
+ if (expected === undefined)
269
+ return fail("chain-not-proven");
270
+ if (expected.end !== end)
271
+ return fail("chain-not-proven", { expectedEnd: expected.end });
272
+ if (provenance.hops.length === 0)
273
+ return fail("chain-not-proven");
274
+ const length = Math.max(provenance.hops.length, expected.hops.length);
275
+ for (let i = 0; i < length; i++) {
276
+ if (provenance.hops[i] !== expected.hops[i]) {
277
+ const hop = provenance.hops[i] ?? expected.hops[i];
278
+ return fail("chain-hop-mismatch", { hopIndex: i, hop }, [hop]);
279
+ }
280
+ }
281
+ return undefined;
282
+ };
283
+ }
284
+ //# sourceMappingURL=chain.js.map
package/dist/commands.js CHANGED
@@ -181,9 +181,11 @@ function stripProvenance(view) {
181
181
  continue;
182
182
  const stripped = {
183
183
  ...occurrence,
184
- endpoints: occurrence.endpoints.map((endpoint) => endpoint.sourceOccurrence === undefined
185
- ? { role: endpoint.role, occurrence: endpoint.occurrence }
186
- : { role: endpoint.role, occurrence: endpoint.sourceOccurrence }),
184
+ endpoints: occurrence.endpoints.map((endpoint) => endpoint.chainProvenance !== undefined
185
+ ? endpoint
186
+ : endpoint.sourceOccurrence === undefined
187
+ ? { role: endpoint.role, occurrence: endpoint.occurrence }
188
+ : { role: endpoint.role, occurrence: endpoint.sourceOccurrence }),
187
189
  };
188
190
  relationOccurrences = withKey(relationOccurrences, key, stripped);
189
191
  changed = true;
@@ -9,9 +9,9 @@
9
9
  * fixture - the test asserts the CODE, not merely the failure.
10
10
  */
11
11
  /** Stable, machine-readable refusal codes. Additive; never renamed in place. */
12
- export type DiagnosticCode =
12
+ export type DiagnosticCode = "erd-missing-pk" | "erd-multiple-pk" | "erd-dangling-fk" | "erd-missing-end" | "erd-duplicate-field" | "erd-invalid-fk-target"
13
13
  /** A reference resolves to nothing in its namespace. */
14
- "dangling-reference"
14
+ | "dangling-reference"
15
15
  /** A well-formed reference of the wrong namespace (occurrence where entity was required, …). */
16
16
  | "reference-type-mismatch"
17
17
  /** A relation type declared `shape: "tree"` closes a cycle. */
@@ -27,7 +27,7 @@ export type DiagnosticCode =
27
27
  /** A command's `baseRevision` is not the state's revision. Carries expected and seen. */
28
28
  | "revision-conflict"
29
29
  /** An extension at validation level `unsupported`: preserved on import, never promoted. */
30
- | "extension-unsupported" | "malformed-ref" | "duplicate-id" | "record-key-mismatch" | "schema-version-malformed" | "schema-migration-required" | "document-not-an-object" | "unknown-profile" | "profile-not-declared" | "unknown-entity-type" | "unknown-relation-type" | "unknown-port-type" | "type-definition-conflict" | "attribute-type-mismatch" | "attribute-required-missing" | "enum-value-not-allowed" | "quantity-unit-not-allowed" | "text-too-long" | "date-not-iso8601" | "unique-attribute-violation" | "endpoint-role-unknown" | "endpoint-cardinality-violation" | "endpoint-target-not-allowed" | "hierarchy-multiple-parents" | "port-direction-not-allowed" | "port-owner-mismatch" | "view-document-mismatch" | "revision-divergence" | "occurrence-endpoint-mismatch" | "value-not-finite" | "value-not-serialisable" | "limit-exceeded"
30
+ | "extension-unsupported" | "malformed-ref" | "duplicate-id" | "record-key-mismatch" | "schema-version-malformed" | "schema-migration-required" | "document-not-an-object" | "unknown-profile" | "profile-not-declared" | "unknown-entity-type" | "unknown-relation-type" | "unknown-port-type" | "flow-types-conflict" | "flow-step-missing" | "flow-step-duplicate" | "flow-branch-overflow" | "flow-scenario-unknown" | "flow-scenario-misused" | "flow-step-end-invalid" | "flow-branch-without-sibling" | "flow-step-gap" | "type-definition-conflict" | "type-definition-reserved" | "type-definition-ambiguous" | "attribute-type-mismatch" | "attribute-required-missing" | "enum-value-not-allowed" | "quantity-unit-not-allowed" | "text-too-long" | "date-not-iso8601" | "unique-attribute-violation" | "endpoint-role-unknown" | "endpoint-cardinality-violation" | "endpoint-target-not-allowed" | "hierarchy-multiple-parents" | "port-direction-not-allowed" | "port-owner-mismatch" | "view-document-mismatch" | "revision-divergence" | "occurrence-endpoint-mismatch" | "value-not-finite" | "value-not-serialisable" | "limit-exceeded"
31
31
  /** A hierarchy endpoint targets a foreign-profile entity with no admitted semantic join (M3 §3.2.3). */
32
32
  | "endpoint-without-join" | "legend-key-parent-invalid" | "tone-category-unknown" | "text-pattern-mismatch" | "quantity-not-integer" | "quantity-below-min" | "quantity-above-max" | "relationship-matrix-violation" | "multiplicity-invalid" | "stereotype-application-invalid" | "reference-target-type" | "struct-type-unknown" | "struct-field-not-in-schema" | "struct-type-not-allowed" | "supertype-unknown" | "supertype-cycle" | "attribute-conflict" | "abstract-instantiated" | "unknown-command" | "target-already-exists" | "target-missing" | "delete-policy-required" | "delete-policy-refused" | "placement-kind-mismatch" | "inverse-budget-exceeded" | "extension-hash-mismatch" | "extension-source-not-retained" | "view-already-exists";
33
33
  export type DiagnosticSeverity = "error" | "warning";
@@ -0,0 +1,5 @@
1
+ import { type Diagnostic } from './diagnostics.js';
2
+ import type { SemanticDocument } from './document.js';
3
+ import type { Profile } from './profile.js';
4
+ export declare function validateErdKeys(document: SemanticDocument, profile: Profile, maxFields: number): Diagnostic[];
5
+ //# sourceMappingURL=erd-validate.d.ts.map
@@ -0,0 +1,33 @@
1
+ import { diagnostic } from './diagnostics.js';
2
+ export function validateErdKeys(document, profile, maxFields) {
3
+ const out = [];
4
+ const report = (code, path, message) => out.push(diagnostic({ code, path, message }));
5
+ for (const entity of Object.values(document.entities).filter(e => e.profile === profile.id)) {
6
+ const fields = Object.values(document.ports).filter(p => p.owner === entity.id);
7
+ const path = 'entities.' + entity.id;
8
+ const keys = fields.filter(p => p.attributes.pk?.kind === 'boolean' && p.attributes.pk.value);
9
+ if (keys.length !== 1)
10
+ report(keys.length ? 'erd-multiple-pk' : 'erd-missing-pk', path, 'An entity requires exactly one primary key');
11
+ if (fields.length > maxFields)
12
+ report('limit-exceeded', path, 'Too many attribute rows: ' + fields.length);
13
+ if (new Set(fields.map(p => p.name)).size !== fields.length || new Set(fields.map(p => p.attributes.ordinal?.kind === 'quantity' ? p.attributes.ordinal.value : -1)).size !== fields.length)
14
+ report('erd-duplicate-field', path, 'Field names and ordinals must be distinct');
15
+ for (const field of fields) {
16
+ const fk = field.attributes.fk;
17
+ if (fk?.kind !== 'reference')
18
+ continue;
19
+ const target = document.ports[fk.value];
20
+ if (!target)
21
+ report('erd-dangling-fk', 'ports.' + field.id, 'Foreign key target is missing: ' + fk.value);
22
+ else if (target.profile !== profile.id || target.attributes.pk?.kind !== 'boolean' || !target.attributes.pk.value)
23
+ report('erd-invalid-fk-target', 'ports.' + field.id, 'Foreign key must target a primary key');
24
+ }
25
+ }
26
+ for (const relation of Object.values(document.relations).filter(r => r.profile === profile.id)) {
27
+ for (const role of ['from', 'to'])
28
+ if (!relation.endpoints.some(e => e.role === role))
29
+ report('erd-missing-end', 'relations.' + relation.id, 'Missing relationship end: ' + role);
30
+ }
31
+ return out;
32
+ }
33
+ //# sourceMappingURL=erd-validate.js.map
package/dist/erd.d.ts ADDED
@@ -0,0 +1,69 @@
1
+ import { type Entity, type SemanticPort, type Relation } from './document.js';
2
+ import { type EntityOccurrence, type PortOccurrence, type RelationOccurrence } from './view.js';
3
+ import { type DiagramPresentation } from './presentation.js';
4
+ import type { ErdCardinality } from './profiles/erd.js';
5
+ export interface EngramErdField {
6
+ readonly name: string;
7
+ readonly type: string;
8
+ readonly pk: boolean;
9
+ readonly fk: {
10
+ readonly class: string;
11
+ readonly field: string;
12
+ } | null;
13
+ readonly nullable: boolean;
14
+ }
15
+ export interface EngramErdScene {
16
+ readonly id: string;
17
+ readonly container: string;
18
+ readonly classes: readonly {
19
+ readonly name: string;
20
+ readonly fields: readonly EngramErdField[];
21
+ }[];
22
+ readonly relations: readonly {
23
+ readonly name: string;
24
+ readonly roleLabel: string;
25
+ readonly from: {
26
+ readonly class: string;
27
+ readonly cardinality: ErdCardinality;
28
+ readonly role?: string;
29
+ };
30
+ readonly to: {
31
+ readonly class: string;
32
+ readonly cardinality: ErdCardinality;
33
+ readonly role?: string;
34
+ };
35
+ }[];
36
+ }
37
+ /** Injective encoding into the narrow local-reference grammar, including punctuation and Unicode. */
38
+ export declare const erdLocalId: (name: string) => string;
39
+ export declare const erdEntityOccurrence: (entity: string) => import("./refs.js").OccurrenceRef;
40
+ export declare const erdPortOccurrence: (port: string, side?: "east" | "west") => import("./refs.js").OccurrenceRef;
41
+ /** One scene relation stays one semantic relation, including many-to-many and self references. */
42
+ export declare function convertEngramErdScene(scene: EngramErdScene): {
43
+ document: {
44
+ entities: Record<string, Entity>;
45
+ ports: Record<string, SemanticPort>;
46
+ relations: Record<string, Relation>;
47
+ documentId: import("./refs.js").DocumentRef;
48
+ schemaVersion: import("./document.js").SchemaVersion;
49
+ revision: number;
50
+ profileRefs: readonly import("./profile.js").ProfileId[];
51
+ typeDefinitions: Readonly<Record<string, import("./document.js").TypeDefinition>>;
52
+ resources: Readonly<Record<string, import("./document.js").ResourceDescriptor>>;
53
+ extensions: readonly import("./document.js").PreservedExtension[];
54
+ };
55
+ view: {
56
+ entityOccurrences: Record<string, EntityOccurrence>;
57
+ portOccurrences: Record<string, PortOccurrence>;
58
+ relationOccurrences: Record<string, RelationOccurrence>;
59
+ viewId: import("./refs.js").ViewRef;
60
+ semanticDocumentId: import("./refs.js").DocumentRef;
61
+ revision: number;
62
+ groups: Readonly<Record<string, import("./view.js").VisualGroup>>;
63
+ filters: readonly import("./view.js").ViewFilter[];
64
+ presentation: import("./view.js").PresentationState;
65
+ summaryLabels?: Readonly<Record<string, import("./view.js").SummaryDefinition>>;
66
+ };
67
+ presentation: DiagramPresentation;
68
+ };
69
+ //# sourceMappingURL=erd.d.ts.map