@atolis-hq/corum 0.1.38 → 0.1.40

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.
@@ -0,0 +1,195 @@
1
+ import { getEdgeTypeConstraints } from '../graph/roles.js';
2
+ import { getTemplateSchema } from '../loader/template-props.js';
3
+ /**
4
+ * Full linter rule set (ADR-006 / ADR-006b, review finding S6).
5
+ *
6
+ * Runs against an already-loaded Graph and returns warning-severity
7
+ * diagnostics only — the linter never raises errors, since the underlying
8
+ * structural invariants it depends on (node/edge existence, template
9
+ * resolution) are already enforced by the loader itself. Callers append the
10
+ * result to the loader's diagnostics array; `strict` loads are unaffected
11
+ * because they only throw on `error` severity.
12
+ *
13
+ * Rules implemented (see docs/adr/REF-006-rules.md for the full catalogue):
14
+ * - T-003/T-004/T-005: node properties validated (shallow) against the
15
+ * owning template's JSON-schema-like `properties` block.
16
+ * - E-005/E-006: explicit (non-generated) edges validated against the
17
+ * endpoint templates' declared `edge-types` outgoing/incoming/supports.
18
+ * - Edge property validation: edge.properties validated against the
19
+ * matching EdgeTypeDef's `properties` schema, using the same shallow
20
+ * validator as node properties.
21
+ */
22
+ export function lintGraph(graph) {
23
+ const diagnostics = [];
24
+ lintNodeProperties(graph, diagnostics);
25
+ lintEdgeTypeConstraints(graph, diagnostics);
26
+ lintEdgeProperties(graph, diagnostics);
27
+ return diagnostics;
28
+ }
29
+ function lintNodeProperties(graph, diagnostics) {
30
+ for (const node of graph.nodesById.values()) {
31
+ const template = graph.templates.get(node.template);
32
+ if (!template?.properties)
33
+ continue;
34
+ const schema = getTemplateSchema(template.properties);
35
+ const file = approxFilePath(graph, node);
36
+ if (!schema.additionalProperties) {
37
+ for (const key of Object.keys(node.properties)) {
38
+ if (!(key in schema.properties)) {
39
+ diagnostics.push({
40
+ severity: 'warning',
41
+ file,
42
+ nodeId: node.id,
43
+ message: `unknown property '${key}' is not declared in template '${node.template}'`,
44
+ });
45
+ }
46
+ }
47
+ }
48
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
49
+ const value = node.properties[key];
50
+ if (value === undefined)
51
+ continue;
52
+ const type = propSchema.type;
53
+ if (typeof type === 'string' && !valueMatchesType(value, type)) {
54
+ diagnostics.push({
55
+ severity: 'warning',
56
+ file,
57
+ nodeId: node.id,
58
+ message: `property '${key}' expected type '${type}' but got '${describeType(value)}'`,
59
+ });
60
+ }
61
+ }
62
+ for (const key of schema.required) {
63
+ if (node.properties[key] === undefined) {
64
+ diagnostics.push({
65
+ severity: 'warning',
66
+ file,
67
+ nodeId: node.id,
68
+ message: `missing required property '${key}' declared by template '${node.template}'`,
69
+ });
70
+ }
71
+ }
72
+ }
73
+ }
74
+ function lintEdgeTypeConstraints(graph, diagnostics) {
75
+ for (const edges of graph.edgesByFrom.values()) {
76
+ for (const edge of edges) {
77
+ if (edge.generated)
78
+ continue;
79
+ const fromNode = graph.nodesById.get(edge.from);
80
+ if (fromNode) {
81
+ const constraints = getEdgeTypeConstraints(graph.templates, fromNode.template);
82
+ if (constraints) {
83
+ const allowed = new Set([...(constraints.outgoing ?? []), ...(constraints.supports ?? [])]);
84
+ if (!allowed.has(edge.type)) {
85
+ diagnostics.push({
86
+ severity: 'warning',
87
+ file: approxFilePath(graph, fromNode),
88
+ nodeId: fromNode.id,
89
+ message: `edge type '${edge.type}' is not declared as outgoing or supported by template '${fromNode.template}' (edge ${edge.id})`,
90
+ });
91
+ }
92
+ }
93
+ }
94
+ const toNode = graph.nodesById.get(edge.to);
95
+ if (toNode) {
96
+ const constraints = getEdgeTypeConstraints(graph.templates, toNode.template);
97
+ if (constraints) {
98
+ const allowed = new Set([...(constraints.incoming ?? []), ...(constraints.supports ?? [])]);
99
+ if (!allowed.has(edge.type)) {
100
+ diagnostics.push({
101
+ severity: 'warning',
102
+ file: approxFilePath(graph, toNode),
103
+ nodeId: toNode.id,
104
+ message: `edge type '${edge.type}' is not declared as incoming or supported by template '${toNode.template}' (edge ${edge.id})`,
105
+ });
106
+ }
107
+ }
108
+ }
109
+ }
110
+ }
111
+ }
112
+ function lintEdgeProperties(graph, diagnostics) {
113
+ if (!graph.edgeTypes)
114
+ return;
115
+ for (const edges of graph.edgesByFrom.values()) {
116
+ for (const edge of edges) {
117
+ const def = graph.edgeTypes.get(edge.type);
118
+ if (!def?.properties)
119
+ continue;
120
+ const schema = getTemplateSchema(def.properties);
121
+ const props = edge.properties ?? {};
122
+ const file = edgePropertyFile(graph, edge);
123
+ if (!schema.additionalProperties) {
124
+ for (const key of Object.keys(props)) {
125
+ if (!(key in schema.properties)) {
126
+ diagnostics.push({
127
+ severity: 'warning',
128
+ file,
129
+ message: `edge '${edge.id}' has unknown property '${key}' not declared by edge type '${edge.type}'`,
130
+ });
131
+ }
132
+ }
133
+ }
134
+ for (const [key, propSchema] of Object.entries(schema.properties)) {
135
+ const value = props[key];
136
+ if (value === undefined)
137
+ continue;
138
+ const type = propSchema.type;
139
+ if (typeof type === 'string' && !valueMatchesType(value, type)) {
140
+ diagnostics.push({
141
+ severity: 'warning',
142
+ file,
143
+ message: `edge '${edge.id}' property '${key}' expected type '${type}' but got '${describeType(value)}'`,
144
+ });
145
+ }
146
+ }
147
+ for (const key of schema.required) {
148
+ if (props[key] === undefined) {
149
+ diagnostics.push({
150
+ severity: 'warning',
151
+ file,
152
+ message: `edge '${edge.id}' missing required property '${key}' declared by edge type '${edge.type}'`,
153
+ });
154
+ }
155
+ }
156
+ }
157
+ }
158
+ }
159
+ function edgePropertyFile(graph, edge) {
160
+ const fromNode = graph.nodesById.get(edge.from);
161
+ return fromNode ? approxFilePath(graph, fromNode) : edge.id;
162
+ }
163
+ /** Best-effort node-id-to-cluster-file mapping (mirrors writer/graph-writer.ts clusterPath), for diagnostic messages only. */
164
+ function approxFilePath(graph, node) {
165
+ let current = node;
166
+ while (current.parentId) {
167
+ const parent = graph.nodesById.get(current.parentId);
168
+ if (!parent)
169
+ break;
170
+ current = parent;
171
+ }
172
+ const parts = current.id.split('.');
173
+ if (parts.length < 2)
174
+ return current.id;
175
+ const [component, template, ...rest] = parts;
176
+ return `components/${component}/${template}s/${rest.join('/') || template}.yaml`;
177
+ }
178
+ function valueMatchesType(value, type) {
179
+ switch (type) {
180
+ case 'string': return typeof value === 'string';
181
+ case 'boolean': return typeof value === 'boolean';
182
+ case 'number': return typeof value === 'number';
183
+ case 'integer': return typeof value === 'number' && Number.isInteger(value);
184
+ case 'array': return Array.isArray(value);
185
+ case 'object': return typeof value === 'object' && value !== null && !Array.isArray(value);
186
+ default: return true;
187
+ }
188
+ }
189
+ function describeType(value) {
190
+ if (Array.isArray(value))
191
+ return 'array';
192
+ if (value === null)
193
+ return 'null';
194
+ return typeof value;
195
+ }
@@ -1,7 +1,15 @@
1
1
  import { parse as parseYaml } from 'yaml';
2
2
  import { getOwnedSections } from './pack-loader.js';
3
3
  import { listYamlKeys, readYaml } from '../source/content-utils.js';
4
- import { STRUCTURAL_EDGE_BY_ITEM_TEMPLATE, VALID_STABILITY_SET, VALID_STATE_SET } from './constants.js';
4
+ import { VALID_STABILITY_SET, VALID_STATE_SET } from './constants.js';
5
+ import { validateRootId, validateSegment } from './id-grammar.js';
6
+ import { getTemplateRole } from '../graph/roles.js';
7
+ import { getPropertySchemasFromTemplate } from './template-props.js';
8
+ /** Containment edge generated for owned children, keyed by the child template's declared role. */
9
+ const STRUCTURAL_EDGE_BY_ROLE = {
10
+ field: 'has-field',
11
+ value: 'has-value',
12
+ };
5
13
  export function loadClusters(content, templates, diagnostics) {
6
14
  const result = { nodes: new Map(), edgesByFrom: new Map(), edgesByTo: new Map() };
7
15
  for (const key of listYamlKeys(content, 'components')) {
@@ -24,12 +32,17 @@ export function loadClusters(content, templates, diagnostics) {
24
32
  diagnostics.push({ severity: 'error', file: key, message: 'cluster missing required root fields' });
25
33
  continue;
26
34
  }
35
+ const idError = validateRootId(record.id);
36
+ if (idError) {
37
+ diagnostics.push({ severity: 'error', file: key, message: idError });
38
+ continue;
39
+ }
27
40
  const root = {
28
41
  id: record.id,
29
42
  template: record.template,
30
43
  component: meta.component,
31
- state: asState(meta.state, 'proposed'),
32
- stability: asStability(meta.stability, 'unstable'),
44
+ state: asState(meta.state, 'proposed', diagnostics, key, record.id),
45
+ stability: asStability(meta.stability, 'unstable', diagnostics, key, record.id),
33
46
  schemaVersion: record.schemaVersion,
34
47
  lastModifiedAt: meta.lastModifiedAt,
35
48
  ...(typeof meta.extractedFrom === 'string' && { extractedFrom: meta.extractedFrom }),
@@ -41,11 +54,11 @@ export function loadClusters(content, templates, diagnostics) {
41
54
  const rootTemplate = templates.get(root.template);
42
55
  if (rootTemplate) {
43
56
  for (const target of getNodeRefTargets(root, rootTemplate)) {
44
- const readsId = `${root.id}__reads__${target}`;
57
+ const usesTypeId = `${root.id}__uses-type__${target}`;
45
58
  const existingFrom = result.edgesByFrom.get(root.id) ?? [];
46
- if (!existingFrom.some(e => e.id === readsId)) {
59
+ if (!existingFrom.some(e => e.id === usesTypeId)) {
47
60
  addEdge(result, {
48
- id: readsId, from: root.id, to: target, type: 'reads',
61
+ id: usesTypeId, from: root.id, to: target, type: 'uses-type',
49
62
  state: root.state, stability: root.stability, generated: true,
50
63
  });
51
64
  }
@@ -55,19 +68,6 @@ export function loadClusters(content, templates, diagnostics) {
55
68
  }
56
69
  return result;
57
70
  }
58
- function getPropertySchemasFromTemplate(props) {
59
- if (Array.isArray(props.allOf)) {
60
- const merged = {};
61
- for (const schema of props.allOf) {
62
- Object.assign(merged, getPropertySchemasFromTemplate(schema));
63
- }
64
- return merged;
65
- }
66
- if (typeof props.properties === 'object' && props.properties !== null) {
67
- return props.properties;
68
- }
69
- return {};
70
- }
71
71
  function getNodeRefTargets(node, template) {
72
72
  if (!template.properties)
73
73
  return [];
@@ -106,6 +106,16 @@ function materialiseChildren(result, parent, clusterRoot, source, templates, fil
106
106
  if (!isRecord(section))
107
107
  continue;
108
108
  for (const [localName, value] of Object.entries(section)) {
109
+ const segmentError = validateSegment(localName);
110
+ if (segmentError) {
111
+ diagnostics.push({
112
+ severity: 'error',
113
+ file: filePath,
114
+ nodeId: parent.id,
115
+ message: `owned item name '${localName}' in ${sectionName}: ${segmentError}`,
116
+ });
117
+ continue;
118
+ }
109
119
  if (!isRecord(value)) {
110
120
  diagnostics.push({
111
121
  severity: 'error',
@@ -118,16 +128,18 @@ function materialiseChildren(result, parent, clusterRoot, source, templates, fil
118
128
  const childId = `${parent.id}.${sectionName}.${localName}`;
119
129
  const child = {
120
130
  id: childId,
131
+ parentId: parent.id,
121
132
  template: childTemplateName,
122
133
  component: parent.component,
123
- state: asState(value.state, parent.state),
124
- stability: asStability(value.stability, parent.stability),
134
+ state: asState(value.state, parent.state, diagnostics, filePath, childId),
135
+ stability: asStability(value.stability, parent.stability, diagnostics, filePath, childId),
125
136
  schemaVersion: parent.schemaVersion,
126
137
  lastModifiedAt: parent.lastModifiedAt,
127
138
  properties: stripOwnedSections(value, childTemplateName, templates),
128
139
  };
129
140
  addNode(result, child, filePath, diagnostics);
130
- const edgeType = STRUCTURAL_EDGE_BY_ITEM_TEMPLATE[childTemplateName];
141
+ const childRole = getTemplateRole(templates, childTemplateName);
142
+ const edgeType = childRole !== undefined ? STRUCTURAL_EDGE_BY_ROLE[childRole] : undefined;
131
143
  if (edgeType) {
132
144
  addEdge(result, {
133
145
  id: `${parent.id}__${edgeType}__${child.id}`,
@@ -141,14 +153,14 @@ function materialiseChildren(result, parent, clusterRoot, source, templates, fil
141
153
  const childTemplate = templates.get(child.template);
142
154
  if (childTemplate) {
143
155
  for (const target of getNodeRefTargets(child, childTemplate)) {
144
- const readsId = `${clusterRoot.id}__reads__${target}`;
156
+ const usesTypeId = `${clusterRoot.id}__uses-type__${target}`;
145
157
  const existingFrom = result.edgesByFrom.get(clusterRoot.id) ?? [];
146
- if (!existingFrom.some(e => e.id === readsId)) {
158
+ if (!existingFrom.some(e => e.id === usesTypeId)) {
147
159
  addEdge(result, {
148
- id: readsId,
160
+ id: usesTypeId,
149
161
  from: clusterRoot.id,
150
162
  to: target,
151
- type: 'reads',
163
+ type: 'uses-type',
152
164
  state: clusterRoot.state,
153
165
  stability: clusterRoot.stability,
154
166
  generated: true,
@@ -183,9 +195,19 @@ function addEdge(result, edge) {
183
195
  function isRecord(value) {
184
196
  return typeof value === 'object' && value !== null && !Array.isArray(value);
185
197
  }
186
- function asState(value, fallback) {
187
- return typeof value === 'string' && VALID_STATE_SET.has(value) ? value : fallback;
198
+ function asState(value, fallback, diagnostics, file, nodeId) {
199
+ if (value === undefined)
200
+ return fallback;
201
+ if (typeof value === 'string' && VALID_STATE_SET.has(value))
202
+ return value;
203
+ diagnostics.push({ severity: 'warning', file, nodeId, message: `invalid state '${String(value)}', defaulting to '${fallback}'` });
204
+ return fallback;
188
205
  }
189
- function asStability(value, fallback) {
190
- return typeof value === 'string' && VALID_STABILITY_SET.has(value) ? value : fallback;
206
+ function asStability(value, fallback, diagnostics, file, nodeId) {
207
+ if (value === undefined)
208
+ return fallback;
209
+ if (typeof value === 'string' && VALID_STABILITY_SET.has(value))
210
+ return value;
211
+ diagnostics.push({ severity: 'warning', file, nodeId, message: `invalid stability '${String(value)}', defaulting to '${fallback}'` });
212
+ return fallback;
191
213
  }
@@ -11,22 +11,26 @@ export const VALID_STABILITIES = [
11
11
  'stable',
12
12
  'deprecated',
13
13
  ];
14
- export const VALID_EDGE_TYPES = [
15
- 'triggers',
16
- 'produces',
17
- 'reads',
18
- 'calls',
19
- 'implements',
20
- 'maps-to',
21
- 'derived-from',
22
- 'renamed-from',
23
- 'has-field',
24
- 'has-value',
25
- ];
14
+ /**
15
+ * Core edge type definitions — the single declaration of the built-in
16
+ * vocabulary and its semantic categories. Packs extend this set via
17
+ * `edge-types.yaml` (see loader/edge-type-loader.ts).
18
+ */
19
+ export const CORE_EDGE_TYPES = {
20
+ 'triggers': { name: 'triggers', category: 'semantic' },
21
+ 'produces': { name: 'produces', category: 'semantic' },
22
+ 'reads': { name: 'reads', category: 'semantic' },
23
+ 'uses-type': { name: 'uses-type', category: 'semantic' },
24
+ 'calls': { name: 'calls', category: 'semantic' },
25
+ 'implements': { name: 'implements', category: 'semantic' },
26
+ 'maps-to': { name: 'maps-to', category: 'lineage' },
27
+ 'derived-from': { name: 'derived-from', category: 'lineage' },
28
+ 'renamed-from': { name: 'renamed-from', category: 'lineage', hidden: true },
29
+ 'has-field': { name: 'has-field', category: 'structural' },
30
+ 'has-value': { name: 'has-value', category: 'structural' },
31
+ };
32
+ export const CORE_EDGE_TYPE_MAP = new Map(Object.entries(CORE_EDGE_TYPES));
33
+ export const VALID_EDGE_TYPES = Object.keys(CORE_EDGE_TYPES);
26
34
  export const VALID_STATE_SET = new Set(VALID_STATES);
27
35
  export const VALID_STABILITY_SET = new Set(VALID_STABILITIES);
28
36
  export const VALID_EDGE_TYPE_SET = new Set(VALID_EDGE_TYPES);
29
- export const STRUCTURAL_EDGE_BY_ITEM_TEMPLATE = {
30
- Field: 'has-field',
31
- EnumValue: 'has-value',
32
- };
@@ -1,7 +1,7 @@
1
1
  import { parse as parseYaml } from 'yaml';
2
- import { VALID_EDGE_TYPE_SET } from './constants.js';
2
+ import { CORE_EDGE_TYPE_MAP, VALID_STABILITY_SET, VALID_STATE_SET } from './constants.js';
3
3
  import { listYamlKeys, readYaml } from '../source/content-utils.js';
4
- export function loadEdges(content, nodes, diagnostics) {
4
+ export function loadEdges(content, nodes, diagnostics, edgeTypes = CORE_EDGE_TYPE_MAP) {
5
5
  const result = { edgesByFrom: new Map(), edgesByTo: new Map() };
6
6
  for (const key of listYamlKeys(content, 'edges')) {
7
7
  let raw;
@@ -21,7 +21,7 @@ export function loadEdges(content, nodes, diagnostics) {
21
21
  diagnostics.push({ severity: 'error', file: key, message: 'edge missing required from, to, or type' });
22
22
  continue;
23
23
  }
24
- if (!VALID_EDGE_TYPE_SET.has(edgeRecord.type)) {
24
+ if (!edgeTypes.has(edgeRecord.type)) {
25
25
  diagnostics.push({ severity: 'error', file: key, message: `invalid edge type: ${edgeRecord.type}` });
26
26
  continue;
27
27
  }
@@ -36,19 +36,39 @@ export function loadEdges(content, nodes, diagnostics) {
36
36
  }
37
37
  if (unresolvedEndpoint)
38
38
  continue;
39
+ const properties = edgeRecord.properties;
39
40
  addEdge(result, {
40
41
  id: `${edgeRecord.from}__${edgeRecord.type}__${edgeRecord.to}`,
41
42
  from: edgeRecord.from,
42
43
  to: edgeRecord.to,
43
44
  type: edgeRecord.type,
44
- state: typeof edgeRecord.state === 'string' ? edgeRecord.state : 'proposed',
45
- stability: typeof edgeRecord.stability === 'string' ? edgeRecord.stability : 'unstable',
45
+ state: resolveState(edgeRecord.state, diagnostics, key),
46
+ stability: resolveStability(edgeRecord.stability, diagnostics, key),
46
47
  notes: typeof edgeRecord.notes === 'string' ? edgeRecord.notes : undefined,
48
+ ...(typeof properties === 'object' && properties !== null && !Array.isArray(properties) && {
49
+ properties: properties,
50
+ }),
47
51
  });
48
52
  }
49
53
  }
50
54
  return result;
51
55
  }
56
+ function resolveState(value, diagnostics, file) {
57
+ if (value === undefined)
58
+ return 'proposed';
59
+ if (typeof value === 'string' && VALID_STATE_SET.has(value))
60
+ return value;
61
+ diagnostics.push({ severity: 'warning', file, message: `invalid edge state '${String(value)}', defaulting to 'proposed'` });
62
+ return 'proposed';
63
+ }
64
+ function resolveStability(value, diagnostics, file) {
65
+ if (value === undefined)
66
+ return 'unstable';
67
+ if (typeof value === 'string' && VALID_STABILITY_SET.has(value))
68
+ return value;
69
+ diagnostics.push({ severity: 'warning', file, message: `invalid edge stability '${String(value)}', defaulting to 'unstable'` });
70
+ return 'unstable';
71
+ }
52
72
  function addEdge(result, edge) {
53
73
  const from = result.edgesByFrom.get(edge.from) ?? [];
54
74
  from.push(edge);
@@ -0,0 +1,72 @@
1
+ import { parse as parseYaml } from 'yaml';
2
+ import { listYamlKeys, readYaml } from '../source/content-utils.js';
3
+ import { CORE_EDGE_TYPES } from './constants.js';
4
+ const VALID_CATEGORIES = new Set(['structural', 'semantic', 'lineage']);
5
+ /** Edge type names appear inside edge ids ({from}__{type}__{to}). */
6
+ const EDGE_TYPE_NAME_RE = /^[a-z][a-z0-9-]*$/;
7
+ /**
8
+ * Build the edge type vocabulary: core definitions plus any `edge-types.yaml`
9
+ * declared by loaded packs. Core definitions cannot be overridden; collisions
10
+ * between packs keep the first definition with a warning.
11
+ */
12
+ export function loadEdgeTypes(packContent, diagnostics) {
13
+ const edgeTypes = new Map(Object.entries(CORE_EDGE_TYPES));
14
+ const keys = listYamlKeys(packContent, '').filter(key => key.endsWith('/edge-types.yaml'));
15
+ for (const key of keys) {
16
+ let raw;
17
+ try {
18
+ raw = parseYaml(readYaml(packContent, key));
19
+ }
20
+ catch (err) {
21
+ diagnostics.push({ severity: 'error', file: key, message: `failed to parse YAML: ${err}` });
22
+ continue;
23
+ }
24
+ const declared = raw?.['edge-types'];
25
+ if (typeof declared !== 'object' || declared === null || Array.isArray(declared)) {
26
+ diagnostics.push({ severity: 'error', file: key, message: `edge-types.yaml must declare an 'edge-types' map` });
27
+ continue;
28
+ }
29
+ for (const [name, defRaw] of Object.entries(declared)) {
30
+ if (!EDGE_TYPE_NAME_RE.test(name)) {
31
+ diagnostics.push({
32
+ severity: 'error',
33
+ file: key,
34
+ message: `invalid edge type name '${name}': must match ${EDGE_TYPE_NAME_RE}`,
35
+ });
36
+ continue;
37
+ }
38
+ if (typeof defRaw !== 'object' || defRaw === null) {
39
+ diagnostics.push({ severity: 'error', file: key, message: `edge type '${name}' must be an object` });
40
+ continue;
41
+ }
42
+ const def = defRaw;
43
+ if (typeof def.category !== 'string' || !VALID_CATEGORIES.has(def.category)) {
44
+ diagnostics.push({
45
+ severity: 'error',
46
+ file: key,
47
+ message: `edge type '${name}' has invalid category '${String(def.category)}': expected structural, semantic, or lineage`,
48
+ });
49
+ continue;
50
+ }
51
+ const existing = edgeTypes.get(name);
52
+ if (existing) {
53
+ diagnostics.push({
54
+ severity: 'warning',
55
+ file: key,
56
+ message: `edge type '${name}' is already declared${name in CORE_EDGE_TYPES ? ' by core' : ''} — keeping the existing definition`,
57
+ });
58
+ continue;
59
+ }
60
+ edgeTypes.set(name, {
61
+ name,
62
+ category: def.category,
63
+ ...(typeof def.description === 'string' && { description: def.description }),
64
+ ...(typeof def.properties === 'object' && def.properties !== null && {
65
+ properties: def.properties,
66
+ }),
67
+ ...(def.hidden === true && { hidden: true }),
68
+ });
69
+ }
70
+ }
71
+ return edgeTypes;
72
+ }
@@ -0,0 +1,68 @@
1
+ /**
2
+ * Node ID grammar — defined once, enforced in the loader and adapters.
3
+ *
4
+ * IDs are dot-separated segments encoding the ownership hierarchy:
5
+ * {component}.{Template}.{name}(.{section}.{localName})*
6
+ *
7
+ * Reserved:
8
+ * - `.` separates segments (never appears inside one).
9
+ * - `__` separates edge ID parts ({from}__{type}__{to}), so it must never
10
+ * appear inside a node ID segment.
11
+ *
12
+ * Segments are non-empty runs of ASCII letters, digits, `_`, and `-`
13
+ * (`__` remains reserved — see the explicit check). Leading `_` marks
14
+ * generated quarantine components such as `_unresolved`.
15
+ */
16
+ export const ID_SEGMENT_RE = /^[A-Za-z0-9_-]+$/;
17
+ /** Minimum segments for a cluster root: component.Template.name */
18
+ export const MIN_ROOT_SEGMENTS = 3;
19
+ /** Returns an error message, or null when the id is well-formed. */
20
+ export function validateNodeId(id) {
21
+ const segments = id.split('.');
22
+ for (const segment of segments) {
23
+ if (segment === '') {
24
+ return `invalid node id '${id}': empty segment ('.' is the hierarchy separator)`;
25
+ }
26
+ if (segment.includes('__')) {
27
+ return `invalid node id '${id}': '__' is reserved for edge ids`;
28
+ }
29
+ if (!ID_SEGMENT_RE.test(segment)) {
30
+ return `invalid node id '${id}': segment '${segment}' must match ${ID_SEGMENT_RE}`;
31
+ }
32
+ }
33
+ return null;
34
+ }
35
+ /** Returns an error message, or null when the id is a well-formed cluster root id. */
36
+ export function validateRootId(id) {
37
+ const base = validateNodeId(id);
38
+ if (base)
39
+ return base;
40
+ if (id.split('.').length < MIN_ROOT_SEGMENTS) {
41
+ return `invalid cluster root id '${id}': expected at least ${MIN_ROOT_SEGMENTS} segments (component.Template.name)`;
42
+ }
43
+ return null;
44
+ }
45
+ /** Returns an error message, or null when the value is a valid single segment. */
46
+ export function validateSegment(segment) {
47
+ if (segment === '')
48
+ return `invalid id segment: empty`;
49
+ if (segment.includes('__'))
50
+ return `invalid id segment '${segment}': '__' is reserved for edge ids`;
51
+ if (!ID_SEGMENT_RE.test(segment)) {
52
+ return `invalid id segment '${segment}': must match ${ID_SEGMENT_RE}`;
53
+ }
54
+ return null;
55
+ }
56
+ /**
57
+ * Make an externally-sourced name (operationId, message name, schema name…)
58
+ * safe to use as a single ID segment. Deterministic: reserved characters
59
+ * become `-`, runs are collapsed, and leading/trailing `-` are trimmed.
60
+ */
61
+ export function sanitizeIdSegment(name) {
62
+ const cleaned = name
63
+ .replace(/[^A-Za-z0-9_-]+/g, '-')
64
+ .replace(/_{2,}/g, '_')
65
+ .replace(/-{2,}/g, '-')
66
+ .replace(/^[-_]+|[-_]+$/g, '');
67
+ return cleaned === '' ? 'unnamed' : cleaned;
68
+ }
@@ -4,7 +4,9 @@ import { LoadError, QueryError } from '../schema/index.js';
4
4
  import { computeDiff, computeOverlay } from '../graph/overlay.js';
5
5
  import { loadClusters } from './cluster-loader.js';
6
6
  import { loadEdges } from './edge-loader.js';
7
+ import { loadEdgeTypes } from './edge-type-loader.js';
7
8
  import { loadPacks } from './pack-loader.js';
9
+ import { lintGraph } from '../linter/index.js';
8
10
  export async function loadGraph(options) {
9
11
  const { strict = true } = options;
10
12
  const diagnostics = [];
@@ -16,9 +18,10 @@ export async function loadGraph(options) {
16
18
  const ref = options.ref ?? defaultRef;
17
19
  const packContent = await source.loadPackContent(defaultRef);
18
20
  const templates = loadPacks(packContent, diagnostics);
21
+ const edgeTypes = loadEdgeTypes(packContent, diagnostics);
19
22
  const graphContent = await source.loadGraphContent(ref);
20
23
  const clusterResult = loadClusters(graphContent, templates, diagnostics);
21
- const edgeResult = loadEdges(graphContent, clusterResult.nodes, diagnostics);
24
+ const edgeResult = loadEdges(graphContent, clusterResult.nodes, diagnostics, edgeTypes);
22
25
  const edgesByFrom = cloneEdgeMap(clusterResult.edgesByFrom);
23
26
  const edgesByTo = cloneEdgeMap(clusterResult.edgesByTo);
24
27
  mergeEdgeMaps(edgesByFrom, edgeResult.edgesByFrom);
@@ -28,9 +31,11 @@ export async function loadGraph(options) {
28
31
  edgesByFrom,
29
32
  edgesByTo,
30
33
  templates,
34
+ edgeTypes,
31
35
  diagnostics,
32
36
  sourceContent: graphContent,
33
37
  };
38
+ diagnostics.push(...lintGraph(graph));
34
39
  if (strict && diagnostics.some(d => d.severity === 'error')) {
35
40
  throw new LoadError(diagnostics);
36
41
  }