@atolis-hq/corum 0.1.39 → 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.
@@ -1,4 +1,5 @@
1
1
  import { applyComponentNameReplacements } from '../../import/config.js';
2
+ import { sanitizeIdSegment } from '../../loader/id-grammar.js';
2
3
  export function extractValue(strategy, operation, message) {
3
4
  switch (strategy.strategy) {
4
5
  case 'channel-segment': {
@@ -76,9 +77,11 @@ export function classifyEvent(classification, operation, message) {
76
77
  return value === classification.domainValue ? 'DomainEvent' : 'IntegrationEvent';
77
78
  }
78
79
  export function deriveNodeId(kind, component, name, opts) {
80
+ // Spec-supplied names (message names, schema names) may contain dots or other
81
+ // characters reserved by the node ID grammar — sanitise them to one segment.
79
82
  if (kind === 'event')
80
- return `${component}.${opts?.template ?? 'IntegrationEvent'}.${name}`;
81
- return `${opts.parentId}.${opts.section}.${name}`;
83
+ return `${sanitizeIdSegment(component)}.${opts?.template ?? 'IntegrationEvent'}.${sanitizeIdSegment(name)}`;
84
+ return `${opts.parentId}.${opts.section}.${sanitizeIdSegment(name)}`;
82
85
  }
83
86
  // Extract the original component schema name from a resolved schema object.
84
87
  // @asyncapi/parser resolves $refs inline but tags each resolved object with
@@ -1,5 +1,5 @@
1
1
  const VALID_EDGE_TYPES = new Set([
2
- 'triggers', 'produces', 'reads', 'calls', 'implements',
2
+ 'triggers', 'produces', 'reads', 'uses-type', 'calls', 'implements',
3
3
  'maps-to', 'derived-from', 'renamed-from', 'has-field', 'has-value',
4
4
  ]);
5
5
  const UNRESOLVED_COMPONENT = '_unresolved';
@@ -315,7 +315,7 @@ function materializeStandaloneSchema(schemaName, component, allSchemas, nodes, e
315
315
  continue;
316
316
  const valueId = `${schemaId}.values.${value}`;
317
317
  refToNodeId.set(`${schemaRef}/properties/${value}`, valueId);
318
- nodes.push(makeNode('EnumValue', component, specPath, valueId, undefined, { value }));
318
+ nodes.push(makeNode('EnumValue', component, specPath, valueId, undefined, { name: value }));
319
319
  edges.push(makeHasValueEdge(schemaId, valueId));
320
320
  }
321
321
  return schemaId;
@@ -362,7 +362,7 @@ function expandSchema(schemaName, rootNodeId, allSchemas, nodes, edges, specPath
362
362
  continue;
363
363
  const valueId = `${enumId}.values.${value}`;
364
364
  refToNodeId.set(`${schemaRef}/properties/${value}`, valueId);
365
- nodes.push(makeNode('EnumValue', enumComponent, specPath, valueId, undefined, { value }));
365
+ nodes.push(makeNode('EnumValue', enumComponent, specPath, valueId, undefined, { name: value }));
366
366
  edges.push(makeHasValueEdge(enumId, valueId));
367
367
  }
368
368
  }
@@ -1,4 +1,5 @@
1
1
  import { applyComponentNameReplacements } from '../../import/config.js';
2
+ import { sanitizeIdSegment } from '../../loader/id-grammar.js';
2
3
  export function deriveComponent(path, mapping) {
3
4
  if (mapping.strategy === 'hardcoded')
4
5
  return mapping.component;
@@ -30,9 +31,11 @@ function resolveAllOfRef(schema) {
30
31
  return schema;
31
32
  }
32
33
  export function deriveNodeId(kind, component, name, parentId, section) {
34
+ // Spec-supplied names (operationIds, schema names) may contain dots or other
35
+ // characters reserved by the node ID grammar — sanitise them to one segment.
33
36
  if (kind === 'operation')
34
- return `${component}.APIEndpoint.${name}`;
35
- return `${parentId}.${section}.${name}`;
37
+ return `${sanitizeIdSegment(component ?? '')}.APIEndpoint.${sanitizeIdSegment(name)}`;
38
+ return `${parentId}.${section}.${sanitizeIdSegment(name)}`;
36
39
  }
37
40
  export function refName(ref) {
38
41
  return ref.split('/').pop() ?? ref;
@@ -59,6 +59,23 @@ program
59
59
  port: opts.port,
60
60
  });
61
61
  });
62
+ program
63
+ .command('lint')
64
+ .description('Lint the graph and report diagnostics')
65
+ .option('--graph <path>', 'Override graph path')
66
+ .action(async (opts) => {
67
+ const config = buildRuntimeConfig(opts.graph);
68
+ try {
69
+ const graph = await loadGraph({ source: config.source, strict: false });
70
+ reportDiagnostics(graph.diagnostics, 'Lint complete');
71
+ if (graph.diagnostics.some(d => d.severity === 'error'))
72
+ process.exit(1);
73
+ }
74
+ catch (err) {
75
+ process.stderr.write(`[ERROR] ${err instanceof Error ? err.message : String(err)}\n`);
76
+ process.exit(2);
77
+ }
78
+ });
62
79
  const CONFIG_TEMPLATE = `# Corum project configuration
63
80
  # Uncomment and set the options relevant to your setup.
64
81
  # All values can be overridden by environment variables (CORUM_*) or CLI flags.
@@ -147,6 +164,7 @@ const importCmd = program.command('import')
147
164
  .description('Import specifications into the graph')
148
165
  .option('--config <path>', 'Path to import config YAML')
149
166
  .option('--graph <path>', 'Override CORUM_GRAPH_PATH')
167
+ .option('-b, --branch <name>', 'Target branch to commit the import to (required for git sources)')
150
168
  .addHelpText('after', '\nFor import config file format and options, see: https://github.com/atolis-hq/corum#readme')
151
169
  .action(async (opts) => {
152
170
  if (!opts.config) {
@@ -156,7 +174,7 @@ const importCmd = program.command('import')
156
174
  try {
157
175
  const runtimeConfig = buildRuntimeConfig(opts.graph);
158
176
  const config = loadImportConfig(path.resolve(opts.config));
159
- const result = await runImport(config, runtimeConfig);
177
+ const result = await runImport(config, runtimeConfig, { branch: opts.branch });
160
178
  reportDiagnostics(result.diagnostics);
161
179
  if (result.diagnostics.some(d => d.severity === 'error'))
162
180
  process.exit(1);
@@ -174,11 +192,12 @@ importCmd
174
192
  .option('--pattern <regex>', 'Regex pattern (uri-segment strategy)')
175
193
  .option('--component <name>', 'Component name (hardcoded strategy)')
176
194
  .option('--graph <path>', 'Override CORUM_GRAPH_PATH')
195
+ .option('-b, --branch <name>', 'Target branch to commit the import to (required for git sources)')
177
196
  .action(async (spec, opts) => {
178
197
  try {
179
198
  const runtimeConfig = buildRuntimeConfig(opts.graph);
180
199
  const entry = buildOpenAPIConfig(spec, opts.componentStrategy, opts.segment, opts.pattern, opts.component);
181
- const result = await runImport({ imports: [entry] }, runtimeConfig);
200
+ const result = await runImport({ imports: [entry] }, runtimeConfig, { branch: opts.branch });
182
201
  reportDiagnostics(result.diagnostics);
183
202
  if (result.diagnostics.some(d => d.severity === 'error'))
184
203
  process.exit(1);
@@ -199,6 +218,7 @@ importCmd
199
218
  .option('--event-classification <mode>', 'Event classification: always-integration, always-domain', 'always-integration')
200
219
  .option('--include-consumed', 'Also import receive (consumed) operations', false)
201
220
  .option('--graph <path>', 'Override CORUM_GRAPH_PATH')
221
+ .option('-b, --branch <name>', 'Target branch to commit the import to (required for git sources)')
202
222
  .action(async (spec, opts) => {
203
223
  try {
204
224
  const runtimeConfig = buildRuntimeConfig(opts.graph);
@@ -214,7 +234,7 @@ importCmd
214
234
  if (opts.includeConsumed) {
215
235
  entry.includeConsumed = true;
216
236
  }
217
- const result = await runImport({ imports: [entry] }, runtimeConfig);
237
+ const result = await runImport({ imports: [entry] }, runtimeConfig, { branch: opts.branch });
218
238
  reportDiagnostics(result.diagnostics);
219
239
  if (result.diagnostics.some(d => d.severity === 'error'))
220
240
  process.exit(1);
@@ -228,11 +248,12 @@ importCmd
228
248
  .command('corum <spec>')
229
249
  .description('Import a corum interchange file into the graph')
230
250
  .option('--graph <path>', 'Override CORUM_GRAPH_PATH')
251
+ .option('-b, --branch <name>', 'Target branch to commit the import to (required for git sources)')
231
252
  .action(async (spec, opts) => {
232
253
  try {
233
254
  const runtimeConfig = buildRuntimeConfig(opts.graph);
234
255
  const entry = { adapter: 'corum', spec: path.resolve(spec) };
235
- const result = await runImport({ imports: [entry] }, runtimeConfig);
256
+ const result = await runImport({ imports: [entry] }, runtimeConfig, { branch: opts.branch });
236
257
  reportDiagnostics(result.diagnostics);
237
258
  if (result.diagnostics.some(d => d.severity === 'error'))
238
259
  process.exit(1);
@@ -279,14 +300,14 @@ function buildRuntimeConfig(graphOverride) {
279
300
  process.env.CORUM_GRAPH_PATH = path.resolve(graphOverride);
280
301
  return createGraphRuntimeConfig();
281
302
  }
282
- function reportDiagnostics(diagnostics) {
303
+ function reportDiagnostics(diagnostics, label = 'Import complete') {
283
304
  for (const d of diagnostics) {
284
305
  const prefix = d.severity === 'error' ? 'ERROR' : 'WARN';
285
306
  process.stderr.write(`[${prefix}] ${d.file}: ${d.message}\n`);
286
307
  }
287
308
  const errors = diagnostics.filter(d => d.severity === 'error').length;
288
309
  const warnings = diagnostics.filter(d => d.severity === 'warning').length;
289
- process.stdout.write(`Import complete. ${errors} error(s), ${warnings} warning(s).\n`);
310
+ process.stdout.write(`${label}. ${errors} error(s), ${warnings} warning(s).\n`);
290
311
  }
291
312
  function reportGraphDiagnostics(diagnostics) {
292
313
  const warnings = diagnostics.filter(d => d.severity === 'warning');
@@ -1,15 +1,33 @@
1
1
  import { QueryError } from '../schema/index.js';
2
- export const STRUCTURAL_EDGE_TYPES = new Set(['has-field', 'has-value', 'renamed-from']);
3
- export const STRUCTURAL_NODE_TEMPLATES = new Set(['Field', 'Schema', 'EnumDefinition', 'EnumValue', 'Mapping']);
4
- export const SEMANTIC_EDGE_TYPES = new Set([
5
- 'triggers',
6
- 'produces',
7
- 'reads',
8
- 'calls',
9
- 'implements',
10
- 'maps-to',
11
- 'derived-from',
12
- ]);
2
+ import { CORE_EDGE_TYPE_MAP } from '../loader/constants.js';
3
+ import { getDataTemplates, getStructuralTemplates, templateHasRole } from './roles.js';
4
+ /** Templates whose nodes are structural children, derived from declared template roles. */
5
+ export function getStructuralNodeTemplates(graph) {
6
+ return getStructuralTemplates(graph.templates);
7
+ }
8
+ export function getEdgeTypeDef(graph, type) {
9
+ return (graph.edgeTypes ?? CORE_EDGE_TYPE_MAP).get(type);
10
+ }
11
+ /** Structural edges encode containment (has-field, has-value, pack-declared structural types). */
12
+ export function isStructuralEdgeType(graph, type) {
13
+ return getEdgeTypeDef(graph, type)?.category === 'structural';
14
+ }
15
+ /**
16
+ * Visible edges appear in summaries, lineage defaults, and collapsed cluster
17
+ * views: everything that is neither structural containment nor hidden
18
+ * bookkeeping (e.g. renamed-from).
19
+ */
20
+ export function isVisibleEdgeType(graph, type) {
21
+ const def = getEdgeTypeDef(graph, type);
22
+ if (!def)
23
+ return true;
24
+ return def.category !== 'structural' && def.hidden !== true;
25
+ }
26
+ export function getVisibleEdgeTypes(graph) {
27
+ return [...(graph.edgeTypes ?? CORE_EDGE_TYPE_MAP).values()]
28
+ .filter(def => def.category !== 'structural' && def.hidden !== true)
29
+ .map(def => def.name);
30
+ }
13
31
  export function listNodes(graph, filter = {}) {
14
32
  return [...graph.nodesById.values()].filter(node => {
15
33
  if (filter.templates?.length && !filter.templates.includes(node.template))
@@ -50,11 +68,13 @@ export function getCluster(graph, nodeId) {
50
68
  }
51
69
  return { root, children, edges };
52
70
  }
53
- // Shared data-type templates whose structural children (fields, values) and referenced types
54
- // are included when expanding external node references into a cluster view.
55
- // Operational templates (DomainEvent, Command, APIEndpoint, etc.) are excluded — callers get
56
- // only their root metadata, not their internal schema trees.
57
- const DATA_NODE_TEMPLATES = new Set(['Schema', 'EnumDefinition']);
71
+ // Shared data-type templates (role type-container/enum-container) whose structural children
72
+ // (fields, values) and referenced types are included when expanding external node references
73
+ // into a cluster view. Operational templates (DomainEvent, Command, APIEndpoint, etc.) are
74
+ // excluded — callers get only their root metadata, not their internal schema trees.
75
+ function isDataNodeTemplate(graph, templateName) {
76
+ return getDataTemplates(graph.templates).has(templateName);
77
+ }
58
78
  export function getClusterView(graph, nodeId, includeEdgeTypes = []) {
59
79
  const cluster = getCluster(graph, nodeId);
60
80
  if (includeEdgeTypes.length === 0) {
@@ -67,9 +87,9 @@ export function getClusterView(graph, nodeId, includeEdgeTypes = []) {
67
87
  }
68
88
  const clusterIds = new Set([cluster.root.id, ...cluster.children.map(node => node.id)]);
69
89
  const requestedTypes = new Set(includeEdgeTypes);
70
- // reads edges are directional (consumer → type); only follow outbound so viewing a shared
71
- // Schema doesn't pull in every endpoint that references it
72
- const inboundTypes = new Set([...requestedTypes].filter(t => t !== 'reads'));
90
+ // reads and uses-type edges are directional (consumer → type); only follow outbound so
91
+ // viewing a shared Schema doesn't pull in every endpoint that references it
92
+ const inboundTypes = new Set([...requestedTypes].filter(t => t !== 'reads' && t !== 'uses-type'));
73
93
  const edges = [...cluster.edges];
74
94
  const seen = new Set(cluster.edges.map(edge => edge.id));
75
95
  for (const id of clusterIds) {
@@ -105,7 +125,7 @@ export function getClusterView(graph, nodeId, includeEdgeTypes = []) {
105
125
  *
106
126
  * Policy:
107
127
  * - Schema and EnumDefinition nodes: include structural children (fields/values) and
108
- * follow their outbound `reads` edges one hop to collect referenced data types.
128
+ * follow their outbound `uses-type` edges one hop to collect referenced data types.
109
129
  * - All other templates: include only the root node (metadata for connectivity panels).
110
130
  */
111
131
  export function expandExternalNodes(graph, externalIds) {
@@ -126,7 +146,7 @@ export function expandExternalNodes(graph, externalIds) {
126
146
  continue;
127
147
  result.add(rawId);
128
148
  const node = graph.nodesById.get(rawId);
129
- if (DATA_NODE_TEMPLATES.has(node.template))
149
+ if (isDataNodeTemplate(graph, node.template))
130
150
  dataQueue.push(rawId);
131
151
  }
132
152
  for (const id of dataQueue) {
@@ -136,15 +156,15 @@ export function expandExternalNodes(graph, externalIds) {
136
156
  if (childId.startsWith(prefix))
137
157
  result.add(childId);
138
158
  }
139
- // Follow outbound reads one hop to collect referenced enum/schema types
159
+ // Follow outbound uses-type one hop to collect referenced enum/schema types
140
160
  for (const edge of graph.edgesByFrom.get(id) ?? []) {
141
- if (edge.type !== 'reads' || result.has(edge.to))
161
+ if (edge.type !== 'uses-type' || result.has(edge.to))
142
162
  continue;
143
163
  const target = graph.nodesById.get(edge.to);
144
164
  if (!target)
145
165
  continue;
146
166
  result.add(edge.to);
147
- if (DATA_NODE_TEMPLATES.has(target.template)) {
167
+ if (isDataNodeTemplate(graph, target.template)) {
148
168
  const targetPrefix = `${edge.to}.`;
149
169
  for (const childId of graph.nodesById.keys()) {
150
170
  if (childId.startsWith(targetPrefix))
@@ -163,7 +183,7 @@ export function getLinkedFields(graph, nodeId) {
163
183
  throw new QueryError(`Node not found: ${nodeId}`);
164
184
  const prefix = `${nodeId}.`;
165
185
  const ownedFieldIds = new Set([...graph.nodesById.entries()]
166
- .filter(([id, node]) => id.startsWith(prefix) && node.template === 'Field')
186
+ .filter(([id, node]) => id.startsWith(prefix) && templateHasRole(graph.templates, node.template, 'field'))
167
187
  .map(([id]) => id));
168
188
  const edges = [];
169
189
  const nodeIds = new Set();
@@ -184,6 +204,12 @@ export function getLinkedFields(graph, nodeId) {
184
204
  };
185
205
  }
186
206
  function findParent(graph, nodeId) {
207
+ const node = graph.nodesById.get(nodeId);
208
+ if (node?.parentId !== undefined && graph.nodesById.has(node.parentId)) {
209
+ return node.parentId;
210
+ }
211
+ // Fallback for nodes without a materialised parentId (e.g. adapter output
212
+ // before a load round-trip): walk the ID hierarchy in 2-segment strides.
187
213
  const parts = nodeId.split('.');
188
214
  let endIdx = parts.length - 2;
189
215
  while (endIdx >= 1) {
@@ -240,7 +266,7 @@ export function getGraphSummary(graph) {
240
266
  const edgesByType = {};
241
267
  for (const edgeList of graph.edgesByFrom.values()) {
242
268
  for (const edge of edgeList) {
243
- if (!SEMANTIC_EDGE_TYPES.has(edge.type))
269
+ if (!isVisibleEdgeType(graph, edge.type))
244
270
  continue;
245
271
  edgesByType[edge.type] = (edgesByType[edge.type] ?? 0) + 1;
246
272
  nodesWithEdges.add(edge.from);
@@ -329,19 +355,21 @@ export function getLineage(graph, startNodeIds, options = {}) {
329
355
  const defaultEdgeTypes = new Set();
330
356
  for (const edgeList of graph.edgesByFrom.values()) {
331
357
  for (const edge of edgeList) {
332
- if (!STRUCTURAL_EDGE_TYPES.has(edge.type))
358
+ if (isVisibleEdgeType(graph, edge.type))
333
359
  defaultEdgeTypes.add(edge.type);
334
360
  }
335
361
  }
336
362
  const edgeTypeSet = options.edgeTypes ? new Set(options.edgeTypes) : defaultEdgeTypes;
337
- const inboundTypeSet = new Set([...edgeTypeSet].filter(type => !(readsOutboundOnly && type === 'reads')));
363
+ // reads and uses-type are directional (consumer → type); readsOutboundOnly (default true)
364
+ // excludes both from inbound traversal so a shared type doesn't pull in every consumer
365
+ const inboundTypeSet = new Set([...edgeTypeSet].filter(type => !(readsOutboundOnly && (type === 'reads' || type === 'uses-type'))));
338
366
  const useAllowlist = (options.nodeTypes?.length ?? 0) > 0;
339
367
  const allowedTemplates = useAllowlist ? new Set(options.nodeTypes) : null;
340
368
  const excludedTemplates = useAllowlist
341
369
  ? null
342
370
  : options.excludeNodeTypes?.length
343
371
  ? new Set(options.excludeNodeTypes)
344
- : STRUCTURAL_NODE_TEMPLATES;
372
+ : getStructuralNodeTemplates(graph);
345
373
  function isIncluded(node) {
346
374
  if (allowedTemplates)
347
375
  return allowedTemplates.has(node.template);
@@ -0,0 +1,66 @@
1
+ const STRUCTURAL_ROLES = new Set(['field', 'value', 'type-container', 'enum-container', 'mapping']);
2
+ const DATA_ROLES = new Set(['type-container', 'enum-container']);
3
+ /** Resolve a template's role, walking the extends chain (nearest declaration wins). */
4
+ export function getTemplateRole(templates, templateName) {
5
+ const seen = new Set();
6
+ let current = templates.get(templateName);
7
+ while (current && !seen.has(current.name)) {
8
+ seen.add(current.name);
9
+ const role = current.info?.role;
10
+ if (typeof role === 'string')
11
+ return role;
12
+ current = current.extends ? templates.get(current.extends) : undefined;
13
+ }
14
+ return undefined;
15
+ }
16
+ export function templateHasRole(templates, templateName, role) {
17
+ return getTemplateRole(templates, templateName) === role;
18
+ }
19
+ /**
20
+ * Resolve a template's declared `edge-types` constraints, walking the
21
+ * `extends` chain (nearest declaration wins, matching getTemplateRole).
22
+ * Returns undefined when neither the template nor any ancestor declares an
23
+ * `edge-types` block — such templates are unconstrained for edge endpoint
24
+ * linting purposes.
25
+ */
26
+ export function getEdgeTypeConstraints(templates, templateName) {
27
+ const seen = new Set();
28
+ let current = templates.get(templateName);
29
+ while (current && !seen.has(current.name)) {
30
+ seen.add(current.name);
31
+ const declared = current['edge-types'];
32
+ if (declared)
33
+ return declared;
34
+ current = current.extends ? templates.get(current.extends) : undefined;
35
+ }
36
+ return undefined;
37
+ }
38
+ const structuralCache = new WeakMap();
39
+ const dataCache = new WeakMap();
40
+ /** Templates whose nodes are materialised structural children (hidden from top-level listings). */
41
+ export function getStructuralTemplates(templates) {
42
+ let cached = structuralCache.get(templates);
43
+ if (!cached) {
44
+ cached = collectByRoles(templates, STRUCTURAL_ROLES);
45
+ structuralCache.set(templates, cached);
46
+ }
47
+ return cached;
48
+ }
49
+ /** Templates representing shared data types whose children are expanded in cluster views. */
50
+ export function getDataTemplates(templates) {
51
+ let cached = dataCache.get(templates);
52
+ if (!cached) {
53
+ cached = collectByRoles(templates, DATA_ROLES);
54
+ dataCache.set(templates, cached);
55
+ }
56
+ return cached;
57
+ }
58
+ function collectByRoles(templates, roles) {
59
+ const result = new Set();
60
+ for (const name of templates.keys()) {
61
+ const role = getTemplateRole(templates, name);
62
+ if (role !== undefined && roles.has(role))
63
+ result.add(name);
64
+ }
65
+ return result;
66
+ }
@@ -1,89 +1,81 @@
1
- import { STRUCTURAL_EDGE_TYPES, STRUCTURAL_NODE_TEMPLATES } from './index.js';
1
+ import { getStructuralNodeTemplates, isVisibleEdgeType } from './index.js';
2
+ import { getTemplateRole } from './roles.js';
2
3
  const FIELD_EDGE_TYPES = new Set(['maps-to', 'derived-from']);
3
4
  export function collapseClusterSchemas(graph, cluster) {
4
5
  const rootId = cluster.root.id;
5
6
  const rootPrefix = `${rootId}.`;
6
7
  // Indexes keyed by local name or parent ID
7
8
  const schemaChildIds = new Set();
8
- const schemaNames = new Map(); // localName → exists
9
- const enumNames = new Map(); // localName → exists
9
+ const schemaNames = new Map(); // localName → nodeId
10
+ const enumNames = new Map(); // localName → nodeId
10
11
  const fieldsByParentId = new Map(); // parentId → fieldName → Node
11
12
  const valuesByEnumId = new Map(); // enumId → value names
12
13
  const valuesBySchemaId = new Map(); // schemaId → value names (enum-like schemas)
13
14
  const mappingsByParentId = new Map(); // parentSchemaId → mapName → Node
14
15
  const semanticDescendants = [];
16
+ // Classification is role- and ownership-driven: a node's template role
17
+ // (resolved through the extends chain) decides how it collapses, and its
18
+ // materialised parentId decides where. Section names never matter here, so
19
+ // packs may own schemas/fields under any section name.
20
+ const localName = (n) => n.id.slice(n.id.lastIndexOf('.') + 1);
21
+ const parentRole = (n) => {
22
+ const parent = n.parentId !== undefined ? graph.nodesById.get(n.parentId) : undefined;
23
+ return parent ? getTemplateRole(graph.templates, parent.template) : undefined;
24
+ };
15
25
  for (const n of cluster.descendants) {
16
26
  if (!n.id.startsWith(rootPrefix)) {
17
27
  semanticDescendants.push(n);
18
28
  continue;
19
29
  }
20
- const suffix = n.id.slice(rootPrefix.length);
21
- if (n.template === 'Schema') {
22
- const m = /^schemas\.([^.]+)$/.exec(suffix);
23
- if (m) {
24
- schemaNames.set(m[1], true);
25
- schemaChildIds.add(n.id);
26
- continue;
27
- }
30
+ const role = getTemplateRole(graph.templates, n.template);
31
+ if (role === 'type-container' && n.parentId === rootId) {
32
+ schemaNames.set(localName(n), n.id);
33
+ schemaChildIds.add(n.id);
34
+ continue;
28
35
  }
29
- if (n.template === 'EnumDefinition') {
30
- const m = /^enums\.([^.]+)$/.exec(suffix);
31
- if (m) {
32
- enumNames.set(m[1], true);
33
- schemaChildIds.add(n.id);
34
- continue;
35
- }
36
+ if (role === 'enum-container' && n.parentId === rootId) {
37
+ enumNames.set(localName(n), n.id);
38
+ schemaChildIds.add(n.id);
39
+ continue;
36
40
  }
37
- if (n.template === 'Field') {
38
- const m = /^(.+)\.fields\.([^.]+)$/.exec(suffix);
39
- if (m) {
40
- const parentId = `${rootId}.${m[1]}`;
41
- const existing = fieldsByParentId.get(parentId) ?? new Map();
42
- existing.set(m[2], n);
43
- fieldsByParentId.set(parentId, existing);
44
- schemaChildIds.add(n.id);
45
- continue;
46
- }
41
+ if (role === 'field' && n.parentId !== undefined) {
42
+ const existing = fieldsByParentId.get(n.parentId) ?? new Map();
43
+ existing.set(localName(n), n);
44
+ fieldsByParentId.set(n.parentId, existing);
45
+ schemaChildIds.add(n.id);
46
+ continue;
47
47
  }
48
- if (n.template === 'EnumValue') {
49
- const enumM = /^enums\.([^.]+)\.values\.([^.]+)$/.exec(suffix);
50
- if (enumM) {
51
- const enumId = `${rootId}.enums.${enumM[1]}`;
52
- const values = valuesByEnumId.get(enumId) ?? [];
53
- values.push(typeof n.properties.name === 'string' ? n.properties.name : enumM[2]);
54
- valuesByEnumId.set(enumId, values);
48
+ if (role === 'value' && n.parentId !== undefined) {
49
+ const owner = parentRole(n);
50
+ if (owner === 'enum-container') {
51
+ const values = valuesByEnumId.get(n.parentId) ?? [];
52
+ values.push(typeof n.properties.name === 'string' ? n.properties.name : localName(n));
53
+ valuesByEnumId.set(n.parentId, values);
55
54
  schemaChildIds.add(n.id);
56
55
  continue;
57
56
  }
58
- // Also handle EnumValue nodes under schemas section (enum-like schemas)
59
- const schemaM = /^schemas\.([^.]+)\.values\.([^.]+)$/.exec(suffix);
60
- if (schemaM) {
61
- const schemaId = `${rootId}.schemas.${schemaM[1]}`;
62
- const values = valuesBySchemaId.get(schemaId) ?? [];
63
- values.push(typeof n.properties.name === 'string' ? n.properties.name : schemaM[2]);
64
- valuesBySchemaId.set(schemaId, values);
57
+ // Enum-like schemas: value nodes owned directly by a type-container
58
+ if (owner === 'type-container') {
59
+ const values = valuesBySchemaId.get(n.parentId) ?? [];
60
+ values.push(typeof n.properties.name === 'string' ? n.properties.name : localName(n));
61
+ valuesBySchemaId.set(n.parentId, values);
65
62
  schemaChildIds.add(n.id);
66
63
  continue;
67
64
  }
68
65
  }
69
- if (n.template === 'Mapping') {
70
- const m = /^schemas\.([^.]+)\.mappings\.([^.]+)$/.exec(suffix);
71
- if (m) {
72
- const parentId = `${rootId}.schemas.${m[1]}`;
73
- const existing = mappingsByParentId.get(parentId) ?? new Map();
74
- existing.set(m[2], n);
75
- mappingsByParentId.set(parentId, existing);
76
- schemaChildIds.add(n.id);
77
- continue;
78
- }
66
+ if (role === 'mapping' && n.parentId !== undefined && parentRole(n) === 'type-container') {
67
+ const existing = mappingsByParentId.get(n.parentId) ?? new Map();
68
+ existing.set(localName(n), n);
69
+ mappingsByParentId.set(n.parentId, existing);
70
+ schemaChildIds.add(n.id);
71
+ continue;
79
72
  }
80
73
  semanticDescendants.push(n);
81
74
  }
82
75
  // Build schemas output
83
76
  const schemas = {};
84
77
  const schemaEnums = {};
85
- for (const localName of schemaNames.keys()) {
86
- const schemaId = `${rootId}.schemas.${localName}`;
78
+ for (const [localName, schemaId] of schemaNames) {
87
79
  const fields = fieldsByParentId.get(schemaId) ?? new Map();
88
80
  // Enum-like schema: has EnumValue children but no Field children
89
81
  const schemaValues = valuesBySchemaId.get(schemaId);
@@ -100,14 +92,14 @@ export function collapseClusterSchemas(graph, cluster) {
100
92
  }
101
93
  // Build enums output
102
94
  const enums = {};
103
- for (const localName of enumNames.keys()) {
104
- const enumId = `${rootId}.enums.${localName}`;
95
+ for (const [localName, enumId] of enumNames) {
105
96
  enums[localName] = { values: valuesByEnumId.get(enumId) ?? [] };
106
97
  }
107
- // Filter edges: drop structural edge types and any edge originating from a schema child
108
- const filteredEdges = cluster.edges.filter(e => !STRUCTURAL_EDGE_TYPES.has(e.type) && !schemaChildIds.has(e.from));
98
+ // Filter edges: drop structural/hidden edge types and any edge originating from a schema child
99
+ const filteredEdges = cluster.edges.filter(e => isVisibleEdgeType(graph, e.type) && !schemaChildIds.has(e.from));
109
100
  // Filter includedNodes: drop structural template nodes
110
- const filteredIncludedNodes = cluster.includedNodes.filter(n => !STRUCTURAL_NODE_TEMPLATES.has(n.template));
101
+ const structuralTemplates = getStructuralNodeTemplates(graph);
102
+ const filteredIncludedNodes = cluster.includedNodes.filter(n => !structuralTemplates.has(n.template));
111
103
  return {
112
104
  root: cluster.root,
113
105
  schemas,
@@ -124,15 +116,13 @@ function buildField(fieldNode, graph, rootId, parentMappings) {
124
116
  const isNullable = props.nullable === true;
125
117
  let field = {};
126
118
  const ref = typeof props.$ref === 'string' ? props.$ref : undefined;
127
- if (ref?.startsWith('#/mappings/')) {
128
- const mapName = ref.slice('#/mappings/'.length);
129
- const mapNode = parentMappings.get(mapName);
130
- if (mapNode) {
131
- field = buildMappingField(mapNode, graph);
132
- }
133
- else {
134
- field = { $ref: ref };
135
- }
119
+ // Local refs (#/{section}/{name}) to a sibling mapping node collapse inline.
120
+ // Mapping-ness comes from the collected role-mapping siblings, not from the
121
+ // section name in the ref.
122
+ const localRefMatch = ref !== undefined ? /^#\/[^/]+\/(.+)$/.exec(ref) : null;
123
+ const mapNode = localRefMatch ? parentMappings.get(localRefMatch[1]) : undefined;
124
+ if (ref !== undefined && mapNode) {
125
+ field = buildMappingField(mapNode, graph, new Set([mapNode.id]));
136
126
  }
137
127
  else if (ref) {
138
128
  field = { $ref: ref };
@@ -162,7 +152,7 @@ function buildField(fieldNode, graph, rootId, parentMappings) {
162
152
  field.edges = fieldEdges;
163
153
  return field;
164
154
  }
165
- function buildMappingField(mapNode, graph) {
155
+ function buildMappingField(mapNode, graph, seen) {
166
156
  const props = mapNode.properties;
167
157
  const key = typeof props['key-type'] === 'string' ? props['key-type'] : 'string';
168
158
  const isArrayValue = props['value-collection'] === 'array';
@@ -173,9 +163,9 @@ function buildMappingField(mapNode, graph) {
173
163
  else if (typeof props.$ref === 'string') {
174
164
  const ref = props.$ref;
175
165
  const refNode = graph.nodesById.get(ref);
176
- if (refNode?.template === 'Mapping') {
177
- // Nested mapping — recurse once (no further recursion guard needed for realistic depths)
178
- valueField = buildMappingField(refNode, graph);
166
+ if (refNode && getTemplateRole(graph.templates, refNode.template) === 'mapping' && !seen.has(refNode.id)) {
167
+ seen.add(refNode.id);
168
+ valueField = buildMappingField(refNode, graph, seen);
179
169
  }
180
170
  else {
181
171
  valueField = { $ref: ref };