@atolis-hq/corum 0.1.40 → 0.1.41

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.
@@ -6,7 +6,7 @@ export class AsyncAPIAdapter {
6
6
  const { document, diagnostics } = await parseSpec(entry.spec);
7
7
  if (!document)
8
8
  return { nodes: [], edges: [], diagnostics };
9
- const { nodes, edges, diagnostics: mapDiagnostics } = mapDocument(document, entry, context.packConfig, context.componentNameReplacements);
9
+ const { nodes, edges, diagnostics: mapDiagnostics } = mapDocument(document, entry, context.packConfig, context.componentNameReplacements, context.existingSchemas);
10
10
  return { nodes, edges, diagnostics: [...diagnostics, ...mapDiagnostics] };
11
11
  }
12
12
  }
@@ -1,5 +1,6 @@
1
1
  import { applyComponentNameReplacements } from '../../import/config.js';
2
2
  import { sanitizeIdSegment } from '../../loader/id-grammar.js';
3
+ import { shapeDriftDiagnostic } from '../shared/schema-reuse.js';
3
4
  export function extractValue(strategy, operation, message) {
4
5
  switch (strategy.strategy) {
5
6
  case 'channel-segment': {
@@ -208,12 +209,13 @@ export function extractHeaders(rawHeaders, scalarTypes, specPath) {
208
209
  }
209
210
  return { headers, diagnostics };
210
211
  }
211
- export function mapDocument(document, entry, packConfig, componentNameReplacements = []) {
212
+ export function mapDocument(document, entry, packConfig, componentNameReplacements = [], existingSchemas = new Map()) {
212
213
  const nodes = [];
213
214
  const edges = [];
214
215
  const diagnostics = [];
215
216
  const sharedSchemas = new Map();
216
217
  const sourceSchemas = new Map();
218
+ const reusedSchemaNames = new Set();
217
219
  const rawDoc = document.json();
218
220
  for (const [name, schema] of Object.entries(rawDoc.components?.schemas ?? {})) {
219
221
  sourceSchemas.set(name, schema);
@@ -260,8 +262,18 @@ export function mapDocument(document, entry, packConfig, componentNameReplacemen
260
262
  if (s.enum) {
261
263
  sharedSchemas.set(name, `${component}.EnumDefinition.${name}`);
262
264
  }
263
- else if (sharedSchemaNames.has(name)) {
264
- sharedSchemas.set(name, `${component}.Schema.${name}`);
265
+ else {
266
+ const candidateId = `${component}.Schema.${name}`;
267
+ // ADR-009b rule 1: reuse an existing standalone schema before inlining —
268
+ // never demote it, and never duplicate it, even if this document would
269
+ // otherwise treat it as single-use.
270
+ if (existingSchemas.has(candidateId)) {
271
+ sharedSchemas.set(name, candidateId);
272
+ reusedSchemaNames.add(name);
273
+ }
274
+ else if (sharedSchemaNames.has(name)) {
275
+ sharedSchemas.set(name, candidateId);
276
+ }
265
277
  }
266
278
  }
267
279
  for (const [name, schema] of Object.entries(rawDoc.components?.schemas ?? {})) {
@@ -281,11 +293,24 @@ export function mapDocument(document, entry, packConfig, componentNameReplacemen
281
293
  }
282
294
  continue;
283
295
  }
284
- if (!sharedSchemaNames.has(name))
296
+ if (!sharedSchemaNames.has(name) && !reusedSchemaNames.has(name))
285
297
  continue;
286
298
  const [component] = registeredId.split('.');
299
+ if (reusedSchemaNames.has(name)) {
300
+ // ADR-009b rule 2: shape-drift warning — surface contract drift instead of
301
+ // silently merging it. Never create a duplicate/inline node for a reused schema.
302
+ const incomingFields = new Set(Object.keys(s.properties ?? {}));
303
+ const existingFields = existingSchemas.get(registeredId);
304
+ if (existingFields) {
305
+ const drift = shapeDriftDiagnostic(name, registeredId, incomingFields, existingFields, entry.spec);
306
+ if (drift)
307
+ diagnostics.push(drift);
308
+ }
309
+ continue;
310
+ }
287
311
  nodes.push(makeNode(packConfig.constructs['payloadSchema']?.template ?? 'Schema', component, entry.spec, registeredId));
288
312
  emitFields(s, registeredId, 'fields', undefined, packConfig, entry.spec, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, new Map(), new Map());
313
+ existingSchemas.set(registeredId, new Set(Object.keys(s.properties ?? {})));
289
314
  }
290
315
  const seenMessages = new Map();
291
316
  const allOperations = document.allOperations().all();
@@ -2,11 +2,11 @@ import { parseSpec } from './parser.js';
2
2
  import { mapDocument } from './mapper.js';
3
3
  export class CorumAdapter {
4
4
  adapterId = 'corum';
5
- async import(entry, _context) {
5
+ async import(entry, context) {
6
6
  const { document, diagnostics } = parseSpec(entry.spec);
7
7
  if (!document)
8
8
  return { nodes: [], edges: [], diagnostics };
9
- const { nodes, edges, diagnostics: mapDiagnostics } = mapDocument(document, entry.spec);
9
+ const { nodes, edges, diagnostics: mapDiagnostics } = mapDocument(document, entry.spec, context.existingSchemas);
10
10
  return { nodes, edges, diagnostics: [...diagnostics, ...mapDiagnostics] };
11
11
  }
12
12
  }
@@ -1,9 +1,10 @@
1
+ import { shapeDriftDiagnostic } from '../shared/schema-reuse.js';
1
2
  const VALID_EDGE_TYPES = new Set([
2
3
  'triggers', 'produces', 'reads', 'uses-type', 'calls', 'implements',
3
4
  'maps-to', 'derived-from', 'renamed-from', 'has-field', 'has-value',
4
5
  ]);
5
6
  const UNRESOLVED_COMPONENT = '_unresolved';
6
- export function mapDocument(document, specPath) {
7
+ export function mapDocument(document, specPath, existingSchemas = new Map()) {
7
8
  const nodes = [];
8
9
  const edges = [];
9
10
  const diagnostics = [];
@@ -44,7 +45,7 @@ export function mapDocument(document, specPath) {
44
45
  nodes.push(node);
45
46
  if (schemaName) {
46
47
  const expanded = new Map();
47
- expandSchema(schemaName, normalizedNodeId, allSchemas, nodes, edges, specPath, component, expanded, refToNodeId, schemaComponents);
48
+ expandSchema(schemaName, normalizedNodeId, allSchemas, nodes, edges, specPath, component, expanded, refToNodeId, schemaComponents, existingSchemas, diagnostics);
48
49
  }
49
50
  }
50
51
  for (const schemaName of Object.keys(allSchemas)) {
@@ -66,14 +67,14 @@ export function mapDocument(document, specPath) {
66
67
  file: specPath,
67
68
  message: `Schema '${schemaName}' is only referenced by unresolved schema edges; keeping it under ${UNRESOLVED_COMPONENT}`,
68
69
  });
69
- materializeStandaloneSchema(schemaName, UNRESOLVED_COMPONENT, allSchemas, nodes, edges, specPath, refToNodeId, schemaComponents);
70
+ materializeStandaloneSchema(schemaName, UNRESOLVED_COMPONENT, allSchemas, nodes, edges, specPath, refToNodeId, schemaComponents, existingSchemas, diagnostics);
70
71
  continue;
71
72
  }
72
73
  if (ownership.kind === 'inline') {
73
- expandSchema(schemaName, ownership.rootNodeId, allSchemas, nodes, edges, specPath, ownership.component, new Map(), refToNodeId, schemaComponents);
74
+ expandSchema(schemaName, ownership.rootNodeId, allSchemas, nodes, edges, specPath, ownership.component, new Map(), refToNodeId, schemaComponents, existingSchemas, diagnostics);
74
75
  continue;
75
76
  }
76
- materializeStandaloneSchema(schemaName, ownership.component, allSchemas, nodes, edges, specPath, refToNodeId, schemaComponents);
77
+ materializeStandaloneSchema(schemaName, ownership.component, allSchemas, nodes, edges, specPath, refToNodeId, schemaComponents, existingSchemas, diagnostics);
77
78
  }
78
79
  // Build case-insensitive fallback index to handle PascalCase/camelCase mismatches
79
80
  // between edge field refs and actual schema property names
@@ -298,7 +299,7 @@ function localSchemaName(schemaName) {
298
299
  ? schemaName.slice(schemaName.lastIndexOf('.') + 1)
299
300
  : schemaName;
300
301
  }
301
- function materializeStandaloneSchema(schemaName, component, allSchemas, nodes, edges, specPath, refToNodeId, schemaComponents) {
302
+ function materializeStandaloneSchema(schemaName, component, allSchemas, nodes, edges, specPath, refToNodeId, schemaComponents, existingSchemas, diagnostics) {
302
303
  const schemaLocalName = localSchemaName(schemaName);
303
304
  const schemaDef = allSchemas[schemaName];
304
305
  const isEnumSchema = Array.isArray(schemaDef?.enum) && !schemaDef?.properties;
@@ -329,13 +330,16 @@ function materializeStandaloneSchema(schemaName, component, allSchemas, nodes, e
329
330
  refToNodeId.set(fieldRef, fieldId);
330
331
  const fieldNode = makeNode('Field', component, specPath, fieldId, undefined, {});
331
332
  const required = Array.isArray(schemaDef?.required) && schemaDef.required.includes(fieldName);
332
- fieldNode.properties = resolveFieldProperties(fieldName, rawProp, required, schemaId, schemaId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents);
333
+ fieldNode.properties = resolveFieldProperties(fieldName, rawProp, required, schemaId, schemaId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents, existingSchemas, diagnostics);
333
334
  nodes.push(fieldNode);
334
335
  edges.push(makeHasFieldEdge(schemaId, fieldId));
335
336
  }
337
+ // ADR-009b rule 1 support: register this newly-materialized standalone schema
338
+ // so later same-run entries (and expandSchema's reuse-before-inline check) see it.
339
+ existingSchemas.set(schemaId, new Set(Object.keys(schemaDef?.properties ?? {})));
336
340
  return schemaId;
337
341
  }
338
- function expandSchema(schemaName, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, refToNodeId, schemaComponents = new Map()) {
342
+ function expandSchema(schemaName, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, refToNodeId, schemaComponents = new Map(), existingSchemas = new Map(), diagnostics = []) {
339
343
  const existing = expanded.get(schemaName);
340
344
  if (existing)
341
345
  return existing;
@@ -368,6 +372,22 @@ function expandSchema(schemaName, rootNodeId, allSchemas, nodes, edges, specPath
368
372
  }
369
373
  return refToNodeId.get(schemaRef);
370
374
  }
375
+ // ADR-009b rule 1: reuse an existing standalone schema before inlining it under
376
+ // this root — never create a duplicate copy of a schema that already stands
377
+ // alone (whether in the target graph or materialized earlier in this same run).
378
+ const reuseComponent = schemaComponents.get(schemaName) ?? component;
379
+ const reuseCandidateId = `${reuseComponent}.Schema.${schemaLocalName}`;
380
+ const existingFields = existingSchemas.get(reuseCandidateId);
381
+ if (existingFields) {
382
+ expanded.set(schemaName, reuseCandidateId);
383
+ if (!refToNodeId.has(schemaRef))
384
+ refToNodeId.set(schemaRef, reuseCandidateId);
385
+ const incomingFields = new Set(Object.keys(schemaDef?.properties ?? {}));
386
+ const drift = shapeDriftDiagnostic(schemaName, reuseCandidateId, incomingFields, existingFields, specPath);
387
+ if (drift)
388
+ diagnostics.push(drift);
389
+ return reuseCandidateId;
390
+ }
371
391
  const schemaId = `${rootNodeId}.schemas.${schemaLocalName}`;
372
392
  expanded.set(schemaName, schemaId);
373
393
  if (!refToNodeId.has(schemaRef))
@@ -382,18 +402,18 @@ function expandSchema(schemaName, rootNodeId, allSchemas, nodes, edges, specPath
382
402
  refToNodeId.set(fieldRef, fieldId);
383
403
  const fieldNode = makeNode('Field', component, specPath, fieldId, undefined, {});
384
404
  const required = Array.isArray(schemaDef?.required) && schemaDef.required.includes(fieldName);
385
- fieldNode.properties = resolveFieldProperties(fieldName, rawProp, required, schemaId, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents);
405
+ fieldNode.properties = resolveFieldProperties(fieldName, rawProp, required, schemaId, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents, existingSchemas, diagnostics);
386
406
  nodes.push(fieldNode);
387
407
  edges.push(makeHasFieldEdge(schemaId, fieldId));
388
408
  }
389
409
  return schemaId;
390
410
  }
391
- function resolveFieldProperties(fieldName, prop, required, schemaId, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents) {
411
+ function resolveFieldProperties(fieldName, prop, required, schemaId, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents, existingSchemas, diagnostics) {
392
412
  const nullable = !required;
393
413
  if (typeof prop.$ref === 'string') {
394
414
  const refName = schemaRefName(prop.$ref);
395
415
  if (refName) {
396
- const refId = expandSchema(refName, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, refToNodeId, schemaComponents);
416
+ const refId = expandSchema(refName, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, refToNodeId, schemaComponents, existingSchemas, diagnostics);
397
417
  return { $ref: refId, nullable, collection: 'one' };
398
418
  }
399
419
  return { type: 'string', nullable, collection: 'one' };
@@ -404,7 +424,7 @@ function resolveFieldProperties(fieldName, prop, required, schemaId, rootNodeId,
404
424
  if (items && typeof items.$ref === 'string') {
405
425
  const refName = schemaRefName(items.$ref);
406
426
  if (refName) {
407
- const refId = expandSchema(refName, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, refToNodeId, schemaComponents);
427
+ const refId = expandSchema(refName, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, refToNodeId, schemaComponents, existingSchemas, diagnostics);
408
428
  return { $ref: refId, nullable, collection: 'array' };
409
429
  }
410
430
  }
@@ -412,13 +432,13 @@ function resolveFieldProperties(fieldName, prop, required, schemaId, rootNodeId,
412
432
  return { type: itemType, nullable, collection: 'array' };
413
433
  }
414
434
  if (type === 'object' && prop.additionalProperties !== undefined) {
415
- createMapping(fieldName, prop.additionalProperties, schemaId, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents);
435
+ createMapping(fieldName, prop.additionalProperties, schemaId, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents, existingSchemas, diagnostics);
416
436
  return { $ref: `#/mappings/${fieldName}`, nullable, collection: 'one' };
417
437
  }
418
438
  const scalarType = mapScalar(type ?? 'string', prop.format);
419
439
  return { type: scalarType, nullable, collection: 'one' };
420
440
  }
421
- function createMapping(mappingName, addlDef, schemaId, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents) {
441
+ function createMapping(mappingName, addlDef, schemaId, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents, existingSchemas, diagnostics) {
422
442
  const existing = localMappings.get(mappingName);
423
443
  if (existing)
424
444
  return existing;
@@ -434,7 +454,7 @@ function createMapping(mappingName, addlDef, schemaId, rootNodeId, allSchemas, n
434
454
  if (typeof addl.$ref === 'string') {
435
455
  const refName = schemaRefName(addl.$ref);
436
456
  if (refName) {
437
- props.$ref = expandSchema(refName, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, refToNodeId, schemaComponents);
457
+ props.$ref = expandSchema(refName, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, refToNodeId, schemaComponents, existingSchemas, diagnostics);
438
458
  }
439
459
  else {
440
460
  props.type = 'string';
@@ -446,7 +466,7 @@ function createMapping(mappingName, addlDef, schemaId, rootNodeId, allSchemas, n
446
466
  if (items && typeof items.$ref === 'string') {
447
467
  const refName = schemaRefName(items.$ref);
448
468
  if (refName) {
449
- props.$ref = expandSchema(refName, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, refToNodeId, schemaComponents);
469
+ props.$ref = expandSchema(refName, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, refToNodeId, schemaComponents, existingSchemas, diagnostics);
450
470
  }
451
471
  else {
452
472
  props.type = 'string';
@@ -458,7 +478,7 @@ function createMapping(mappingName, addlDef, schemaId, rootNodeId, allSchemas, n
458
478
  }
459
479
  else if (addl.type === 'object' && addl.additionalProperties !== undefined) {
460
480
  const innerName = `${mappingName}-values`;
461
- props.$ref = createMapping(innerName, addl.additionalProperties, schemaId, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents);
481
+ props.$ref = createMapping(innerName, addl.additionalProperties, schemaId, rootNodeId, allSchemas, nodes, edges, specPath, component, expanded, localMappings, refToNodeId, schemaComponents, existingSchemas, diagnostics);
462
482
  }
463
483
  else {
464
484
  props.type = mapScalar(addl.type ?? 'string', addl.format);
@@ -6,7 +6,7 @@ export class OpenAPIAdapter {
6
6
  const { document, diagnostics } = await parseSpec(entry.spec);
7
7
  if (!document)
8
8
  return { nodes: [], edges: [], diagnostics };
9
- const { nodes, edges, diagnostics: mapDiagnostics } = mapDocument(document, entry, context.packConfig, context.componentNameReplacements);
9
+ const { nodes, edges, diagnostics: mapDiagnostics } = mapDocument(document, entry, context.packConfig, context.componentNameReplacements, context.existingSchemas);
10
10
  return { nodes, edges, diagnostics: [...diagnostics, ...mapDiagnostics] };
11
11
  }
12
12
  }
@@ -1,5 +1,6 @@
1
1
  import { applyComponentNameReplacements } from '../../import/config.js';
2
2
  import { sanitizeIdSegment } from '../../loader/id-grammar.js';
3
+ import { shapeDriftDiagnostic } from '../shared/schema-reuse.js';
3
4
  export function deriveComponent(path, mapping) {
4
5
  if (mapping.strategy === 'hardcoded')
5
6
  return mapping.component;
@@ -40,12 +41,13 @@ export function deriveNodeId(kind, component, name, parentId, section) {
40
41
  export function refName(ref) {
41
42
  return ref.split('/').pop() ?? ref;
42
43
  }
43
- export function mapDocument(document, entry, packConfig, componentNameReplacements = []) {
44
+ export function mapDocument(document, entry, packConfig, componentNameReplacements = [], existingSchemas = new Map()) {
44
45
  const nodes = [];
45
46
  const edges = [];
46
47
  const diagnostics = [];
47
48
  const sharedSchemas = new Map();
48
49
  const sourceSchemas = new Map();
50
+ const reusedSchemaNames = new Set();
49
51
  for (const [name, schema] of Object.entries(document.components?.schemas ?? {})) {
50
52
  if (!isRefSchema(schema))
51
53
  sourceSchemas.set(name, schema);
@@ -66,8 +68,18 @@ export function mapDocument(document, entry, packConfig, componentNameReplacemen
66
68
  if (s.type !== 'object' && s.enum) {
67
69
  sharedSchemas.set(name, `${component}.EnumDefinition.${name}`);
68
70
  }
69
- else if (sharedSchemaNames.has(name)) {
70
- sharedSchemas.set(name, `${component}.Schema.${name}`);
71
+ else {
72
+ const candidateId = `${component}.Schema.${name}`;
73
+ // ADR-009b rule 1: reuse an existing standalone schema before inlining —
74
+ // never demote it, and never duplicate it, even if this document would
75
+ // otherwise treat it as single-use.
76
+ if (existingSchemas.has(candidateId)) {
77
+ sharedSchemas.set(name, candidateId);
78
+ reusedSchemaNames.add(name);
79
+ }
80
+ else if (sharedSchemaNames.has(name)) {
81
+ sharedSchemas.set(name, candidateId);
82
+ }
71
83
  }
72
84
  }
73
85
  }
@@ -93,17 +105,30 @@ export function mapDocument(document, entry, packConfig, componentNameReplacemen
93
105
  });
94
106
  continue;
95
107
  }
96
- if (!sharedSchemaNames.has(name))
108
+ if (!sharedSchemaNames.has(name) && !reusedSchemaNames.has(name))
97
109
  continue;
98
110
  const schemaId = sharedSchemas.get(name);
99
111
  if (!schemaId) {
100
112
  diagnostics.push({ severity: 'warning', file: entry.spec, message: `Cannot derive component for schema ${name}, skipping` });
101
113
  continue;
102
114
  }
115
+ if (reusedSchemaNames.has(name)) {
116
+ // ADR-009b rule 2: shape-drift warning — surface contract drift instead of
117
+ // silently merging it. Never create a duplicate/inline node for a reused schema.
118
+ const incomingFields = new Set(Object.keys(s.properties ?? {}));
119
+ const existingFields = existingSchemas.get(schemaId);
120
+ if (existingFields) {
121
+ const drift = shapeDriftDiagnostic(name, schemaId, incomingFields, existingFields, entry.spec);
122
+ if (drift)
123
+ diagnostics.push(drift);
124
+ }
125
+ continue;
126
+ }
103
127
  const [component] = schemaId.split('.');
104
128
  const node = makeNode(packConfig.constructs.requestSchema?.template ?? 'Schema', component, entry.spec, schemaId);
105
129
  nodes.push(node);
106
130
  emitFields(s, schemaId, 'fields', undefined, packConfig, entry.spec, nodes, edges, diagnostics, sharedSchemas, sourceSchemas, new Map(), new Map());
131
+ existingSchemas.set(schemaId, new Set(Object.keys(s.properties ?? {})));
107
132
  }
108
133
  }
109
134
  for (const [urlPath, pathItem] of Object.entries(document.paths ?? {})) {
@@ -163,9 +188,29 @@ export function mapDocument(document, entry, packConfig, componentNameReplacemen
163
188
  }
164
189
  return { nodes, edges, diagnostics };
165
190
  }
191
+ // Structural walk of $ref values — visits every object/array reachable from the
192
+ // root and calls `visit` on any literal `#/components/schemas/{name}` ref found.
193
+ // Never treats plain strings (descriptions, examples, defaults) as refs.
194
+ function walkRefs(node, visit) {
195
+ if (Array.isArray(node)) {
196
+ for (const item of node)
197
+ walkRefs(item, visit);
198
+ return;
199
+ }
200
+ if (typeof node !== 'object' || node === null)
201
+ return;
202
+ const obj = node;
203
+ const ref = obj['$ref'];
204
+ if (typeof ref === 'string' && ref.startsWith('#/components/schemas/')) {
205
+ visit(ref.slice('#/components/schemas/'.length));
206
+ }
207
+ for (const value of Object.values(obj)) {
208
+ walkRefs(value, visit);
209
+ }
210
+ }
166
211
  function countSchemaOperationUsage(document) {
167
212
  const counts = new Map();
168
- const schemaNames = Object.keys(document.components?.schemas ?? {});
213
+ const schemaNames = new Set(Object.keys(document.components?.schemas ?? {}));
169
214
  for (const [, pathItem] of Object.entries(document.paths ?? {})) {
170
215
  if (!pathItem)
171
216
  continue;
@@ -174,11 +219,13 @@ function countSchemaOperationUsage(document) {
174
219
  const operation = pathItem[method];
175
220
  if (!operation)
176
221
  continue;
177
- const opJson = JSON.stringify(operation);
178
- for (const name of schemaNames) {
179
- if (opJson.includes(`"#/components/schemas/${name}"`)) {
180
- counts.set(name, (counts.get(name) ?? 0) + 1);
181
- }
222
+ const referenced = new Set();
223
+ walkRefs(operation, (name) => {
224
+ if (schemaNames.has(name))
225
+ referenced.add(name);
226
+ });
227
+ for (const name of referenced) {
228
+ counts.set(name, (counts.get(name) ?? 0) + 1);
182
229
  }
183
230
  }
184
231
  }
@@ -201,7 +248,10 @@ function collectAllSharedSchemaNames(document, opCounts) {
201
248
  const sharedSchema = document.components?.schemas?.[sharedName];
202
249
  if (isRefSchema(sharedSchema))
203
250
  continue;
204
- if (JSON.stringify(sharedSchema).includes(`"#/components/schemas/${candidateName}"`)) {
251
+ let references = false;
252
+ walkRefs(sharedSchema, (name) => { if (name === candidateName)
253
+ references = true; });
254
+ if (references) {
205
255
  shared.add(candidateName);
206
256
  changed = true;
207
257
  break;
@@ -491,7 +541,7 @@ function deriveComponentForSchema(name, document, entry, componentNameReplacemen
491
541
  for (const [schemaName, schema] of Object.entries(document.components?.schemas ?? {})) {
492
542
  if (schemaName === name || isRefSchema(schema))
493
543
  continue;
494
- if (JSON.stringify(schema).includes(`"#/components/schemas/${name}"`)) {
544
+ if (referencesSchema(schema, name)) {
495
545
  const comp = deriveComponentForSchema(schemaName, document, entry, componentNameReplacements, visited);
496
546
  if (comp)
497
547
  return comp;
@@ -499,6 +549,9 @@ function deriveComponentForSchema(name, document, entry, componentNameReplacemen
499
549
  }
500
550
  return undefined;
501
551
  }
502
- function referencesSchema(operation, schemaName) {
503
- return JSON.stringify(operation).includes(`"#/components/schemas/${schemaName}"`);
552
+ function referencesSchema(container, schemaName) {
553
+ let found = false;
554
+ walkRefs(container, (name) => { if (name === schemaName)
555
+ found = true; });
556
+ return found;
504
557
  }
@@ -0,0 +1,23 @@
1
+ export function setsEqual(a, b) {
2
+ if (a.size !== b.size)
3
+ return false;
4
+ for (const value of a)
5
+ if (!b.has(value))
6
+ return false;
7
+ return true;
8
+ }
9
+ /**
10
+ * ADR-009b rule 2: when an adapter reuses an existing standalone schema
11
+ * instead of inlining a duplicate, warn if the incoming field set differs
12
+ * from the existing node's — this is the signal for cross-source contract
13
+ * drift that reuse-before-inline would otherwise merge silently.
14
+ */
15
+ export function shapeDriftDiagnostic(schemaName, standaloneId, incomingFields, existingFields, specPath) {
16
+ if (setsEqual(incomingFields, existingFields))
17
+ return undefined;
18
+ return {
19
+ severity: 'warning',
20
+ file: specPath,
21
+ message: `Schema "${schemaName}" reused from existing standalone schema ${standaloneId}, but its field set differs (shape drift): incoming [${[...incomingFields].sort().join(', ')}] vs existing [${[...existingFields].sort().join(', ')}]`,
22
+ };
23
+ }
@@ -22,6 +22,9 @@ export function loadImportConfig(filePath) {
22
22
  throw new Error(`Invalid import config: deduplication entries must have non-empty "primary" and "secondary"`);
23
23
  }
24
24
  }
25
+ if (cfg.edgeCasing !== undefined && cfg.edgeCasing !== 'preserve' && cfg.edgeCasing !== 'match') {
26
+ throw new Error(`Invalid import config: edgeCasing must be "preserve" or "match"`);
27
+ }
25
28
  return cfg;
26
29
  }
27
30
  export function applyComponentNameReplacements(name, replacements) {
@@ -0,0 +1,47 @@
1
+ /**
2
+ * Import-time fix for cross-source field-casing drift: when dedup drops a
3
+ * secondary adapter's node in favour of an exact-ID match from the primary
4
+ * adapter (e.g. both define `orders.Schema.Money`), any nested children that
5
+ * differ only in casing between the two sources (`fields.Amount` vs
6
+ * `fields.amount`) are *not* considered a collision by dedup — the secondary's
7
+ * child nodes are simply dropped, leaving the secondary's own edges pointing
8
+ * at a field id that no longer exists.
9
+ *
10
+ * This resolves those edges against the final merged node set: an endpoint
11
+ * that fails an exact match is retried case-insensitively, and rewritten to
12
+ * the exact surviving casing when the match is unambiguous. Ambiguous or
13
+ * still-unresolved endpoints are left untouched — they fall through to the
14
+ * existing "edge to/from unresolved node" diagnostic at load time, unchanged
15
+ * from today's behaviour.
16
+ */
17
+ export function resolveEdgeCasing(graph, edges, diagnostics) {
18
+ const lowerIndex = new Map();
19
+ for (const id of graph.nodesById.keys()) {
20
+ const lower = id.toLowerCase();
21
+ const list = lowerIndex.get(lower);
22
+ if (list)
23
+ list.push(id);
24
+ else
25
+ lowerIndex.set(lower, [id]);
26
+ }
27
+ function resolve(endpoint) {
28
+ if (graph.nodesById.has(endpoint))
29
+ return { id: endpoint, changed: false };
30
+ const candidates = lowerIndex.get(endpoint.toLowerCase());
31
+ if (candidates && candidates.length === 1)
32
+ return { id: candidates[0], changed: true };
33
+ return { id: endpoint, changed: false };
34
+ }
35
+ return edges.map((edge) => {
36
+ const from = resolve(edge.from);
37
+ const to = resolve(edge.to);
38
+ if (!from.changed && !to.changed)
39
+ return edge;
40
+ diagnostics.push({
41
+ severity: 'warning',
42
+ file: '',
43
+ message: `[INFO] Resolved edge casing mismatch: ${edge.from} -> ${from.id}, ${edge.to} -> ${to.id}`,
44
+ });
45
+ return { ...edge, from: from.id, to: to.id, id: `${from.id}__${edge.type}__${to.id}` };
46
+ });
47
+ }
@@ -6,6 +6,8 @@ import { serializeGraph } from '../writer/graph-writer.js';
6
6
  import { getAdapter } from '../adapters/index.js';
7
7
  import { diffNodes } from '../reconcile/index.js';
8
8
  import { deduplicateResults } from './dedup.js';
9
+ import { buildExistingSchemaIndex, detectSchemaPromotions, rewritePromotedSchemaEdges } from './schema-promotion.js';
10
+ import { resolveEdgeCasing } from './edge-casing.js';
9
11
  export async function runImport(config, runtimeConfig, options = {}) {
10
12
  const allDiagnostics = [];
11
13
  const source = runtimeConfig.source;
@@ -32,6 +34,10 @@ export async function runImport(config, runtimeConfig, options = {}) {
32
34
  // Diff against the branch we are importing into, so repeated imports to the
33
35
  // same design branch stay idempotent; a new branch starts from the default.
34
36
  const graph = await loadGraph({ source, ref: targetBranchExists ? targetBranch : defaultBranch });
37
+ // ADR-009b: snapshot of node identities before this run, and the shared
38
+ // reuse-before-inline index (target graph + same-run entries as they land).
39
+ const priorNodeIds = new Set(graph.nodesById.keys());
40
+ const existingSchemas = buildExistingSchemaIndex(graph);
35
41
  const entryResults = [];
36
42
  for (const entry of config.imports) {
37
43
  const packConfig = await loadPackAdapterConfig(runtimeConfig, entry.adapter);
@@ -50,6 +56,7 @@ export async function runImport(config, runtimeConfig, options = {}) {
50
56
  packConfig,
51
57
  templates: graph.templates,
52
58
  componentNameReplacements: config.componentNameReplacements ?? [],
59
+ existingSchemas,
53
60
  });
54
61
  allDiagnostics.push(...result.diagnostics);
55
62
  if (result.diagnostics.some(d => d.severity === 'error'))
@@ -61,14 +68,28 @@ export async function runImport(config, runtimeConfig, options = {}) {
61
68
  allDiagnostics.push(...diagnostics);
62
69
  entryResults.splice(0, entryResults.length, ...deduped);
63
70
  }
71
+ const newlyCreatedSchemaIds = new Set();
72
+ for (const er of entryResults) {
73
+ for (const node of er.nodes) {
74
+ const parts = node.id.split('.');
75
+ if (parts.length === 3 && parts[1] === 'Schema')
76
+ newlyCreatedSchemaIds.add(node.id);
77
+ }
78
+ }
79
+ // Merge every entry's nodes first, so casing resolution below sees the
80
+ // fully-merged node set regardless of import order among entries.
64
81
  for (const er of entryResults) {
65
82
  const { toAdd, toUpdate, toRemove } = diffNodes(er.nodes, graph.nodesById, er.specPath);
66
83
  for (const node of [...toAdd, ...toUpdate, ...toRemove]) {
67
84
  graph.nodesById.set(node.id, node);
68
85
  }
69
- for (const edge of er.edges) {
70
- if (isStructuralEdgeType(graph, edge.type))
71
- continue;
86
+ }
87
+ for (const er of entryResults) {
88
+ let edgesToAppend = er.edges.filter(edge => !isStructuralEdgeType(graph, edge.type));
89
+ if (config.edgeCasing === 'match') {
90
+ edgesToAppend = resolveEdgeCasing(graph, edgesToAppend, allDiagnostics);
91
+ }
92
+ for (const edge of edgesToAppend) {
72
93
  const existing = graph.edgesByFrom.get(edge.from) ?? [];
73
94
  if (!existing.some(e => e.id === edge.id)) {
74
95
  graph.edgesByFrom.set(edge.from, [...existing, edge]);
@@ -77,6 +98,10 @@ export async function runImport(config, runtimeConfig, options = {}) {
77
98
  }
78
99
  }
79
100
  }
101
+ // ADR-009b rule 4: mechanically rewrite edges when a schema was promoted
102
+ // inline → standalone by this run.
103
+ const promotions = detectSchemaPromotions(priorNodeIds, newlyCreatedSchemaIds);
104
+ rewritePromotedSchemaEdges(graph, promotions, allDiagnostics);
80
105
  const graphPath = runtimeConfig.kind === 'filesystem' ? runtimeConfig.graphPath : undefined;
81
106
  const contentMap = serializeGraph(graph, { sourceGraphPath: graphPath, outputGraphPath: graphPath });
82
107
  await source.commit(targetBranch, contentMap, 'corum import', { replaceGraphContent: true, ...(targetBranchExists ? {} : { createBranchIfMissing: true }) });
@@ -0,0 +1,103 @@
1
+ /**
2
+ * ADR-009b rule 1 support: index of existing standalone schemas (`{component}.Schema.{name}`)
3
+ * and their field names, used by adapters to reuse-before-inline and to detect shape drift.
4
+ * Schemas marked `removed` are excluded — they are no longer available for reuse.
5
+ */
6
+ export function buildExistingSchemaIndex(graph) {
7
+ const index = new Map();
8
+ for (const node of graph.nodesById.values()) {
9
+ const parts = node.id.split('.');
10
+ if (parts.length !== 3 || parts[1] !== 'Schema')
11
+ continue;
12
+ if (node.state === 'removed')
13
+ continue;
14
+ const fields = new Set();
15
+ const prefix = `${node.id}.fields.`;
16
+ for (const other of graph.nodesById.values()) {
17
+ if (!other.id.startsWith(prefix))
18
+ continue;
19
+ if (other.id.slice(prefix.length).includes('.'))
20
+ continue;
21
+ fields.add(other.id.slice(prefix.length));
22
+ }
23
+ index.set(node.id, fields);
24
+ }
25
+ return index;
26
+ }
27
+ /**
28
+ * ADR-009b rule 4: detect inline→standalone promotions produced by this run —
29
+ * a newly created standalone schema (`{C}.Schema.{N}`) that did not exist before
30
+ * this run, matched against any prior inline copy (`{rootId}.schemas.{N}`) under
31
+ * the same component.
32
+ */
33
+ export function detectSchemaPromotions(priorNodeIds, newlyCreatedSchemaIds) {
34
+ const promotions = [];
35
+ for (const newId of newlyCreatedSchemaIds) {
36
+ if (priorNodeIds.has(newId))
37
+ continue;
38
+ const [component, , name] = newId.split('.');
39
+ for (const oldId of priorNodeIds) {
40
+ if (oldId.split('.')[0] !== component)
41
+ continue;
42
+ if (oldId.endsWith(`.schemas.${name}`)) {
43
+ promotions.push({ oldPrefix: oldId, newPrefix: newId });
44
+ }
45
+ }
46
+ }
47
+ return promotions;
48
+ }
49
+ /**
50
+ * ADR-009b rule 4: mechanically rewrite every edge endpoint that falls under a
51
+ * promoted schema's old subtree to the new subtree — import-derived and
52
+ * design-derived edges alike. Warns (and leaves the edge untouched) when the
53
+ * rewritten target does not exist in the new subtree.
54
+ */
55
+ export function rewritePromotedSchemaEdges(graph, promotions, diagnostics) {
56
+ if (promotions.length === 0)
57
+ return;
58
+ const allEdges = new Map();
59
+ for (const edges of graph.edgesByFrom.values()) {
60
+ for (const edge of edges)
61
+ allEdges.set(edge.id, edge);
62
+ }
63
+ function rewriteEndpoint(id) {
64
+ for (const { oldPrefix, newPrefix } of promotions) {
65
+ if (id !== oldPrefix && !id.startsWith(`${oldPrefix}.`))
66
+ continue;
67
+ const rewritten = newPrefix + id.slice(oldPrefix.length);
68
+ if (!graph.nodesById.has(rewritten))
69
+ return { id, changed: false, unresolved: true };
70
+ return { id: rewritten, changed: true, unresolved: false };
71
+ }
72
+ return { id, changed: false, unresolved: false };
73
+ }
74
+ for (const edge of allEdges.values()) {
75
+ const from = rewriteEndpoint(edge.from);
76
+ const to = rewriteEndpoint(edge.to);
77
+ if (from.unresolved || to.unresolved) {
78
+ diagnostics.push({
79
+ severity: 'warning',
80
+ file: '',
81
+ message: `Cannot rewrite edge ${edge.id} for schema promotion — rewritten target does not exist (unresolvable)`,
82
+ });
83
+ continue;
84
+ }
85
+ if (!from.changed && !to.changed)
86
+ continue;
87
+ removeEdge(graph, edge);
88
+ const rewritten = { ...edge, from: from.id, to: to.id, id: `${from.id}__${edge.type}__${to.id}` };
89
+ addEdge(graph, rewritten);
90
+ }
91
+ }
92
+ function removeEdge(graph, edge) {
93
+ const fromList = graph.edgesByFrom.get(edge.from);
94
+ if (fromList)
95
+ graph.edgesByFrom.set(edge.from, fromList.filter(e => e.id !== edge.id));
96
+ const toList = graph.edgesByTo.get(edge.to);
97
+ if (toList)
98
+ graph.edgesByTo.set(edge.to, toList.filter(e => e.id !== edge.id));
99
+ }
100
+ function addEdge(graph, edge) {
101
+ graph.edgesByFrom.set(edge.from, [...(graph.edgesByFrom.get(edge.from) ?? []), edge]);
102
+ graph.edgesByTo.set(edge.to, [...(graph.edgesByTo.get(edge.to) ?? []), edge]);
103
+ }
@@ -18,14 +18,40 @@ import { getTemplateSchema } from '../loader/template-props.js';
18
18
  * - Edge property validation: edge.properties validated against the
19
19
  * matching EdgeTypeDef's `properties` schema, using the same shallow
20
20
  * validator as node properties.
21
+ * - ADR-009b rule 5: flags an inline schema (`{rootId}.schemas.{name}`)
22
+ * whose (component, name) matches an existing standalone schema
23
+ * (`{component}.Schema.{name}`) — the order-dependent interim state
24
+ * between an importer creating the inline copy and a later re-import
25
+ * converging it via reuse-before-inline.
21
26
  */
22
27
  export function lintGraph(graph) {
23
28
  const diagnostics = [];
24
29
  lintNodeProperties(graph, diagnostics);
25
30
  lintEdgeTypeConstraints(graph, diagnostics);
26
31
  lintEdgeProperties(graph, diagnostics);
32
+ lintInlineStandaloneSchemaCollisions(graph, diagnostics);
27
33
  return diagnostics;
28
34
  }
35
+ function lintInlineStandaloneSchemaCollisions(graph, diagnostics) {
36
+ for (const node of graph.nodesById.values()) {
37
+ const parts = node.id.split('.');
38
+ // Only inline schema nodes themselves (`{rootId}.schemas.{name}`) — not their
39
+ // fields/descendants, and not standalone schemas (`{component}.Schema.{name}`).
40
+ if (parts.length < 3 || parts[parts.length - 2] !== 'schemas')
41
+ continue;
42
+ const name = parts[parts.length - 1];
43
+ const standaloneId = `${node.component}.Schema.${name}`;
44
+ const standalone = graph.nodesById.get(standaloneId);
45
+ if (!standalone || standalone.state === 'removed')
46
+ continue;
47
+ diagnostics.push({
48
+ severity: 'warning',
49
+ file: approxFilePath(graph, node),
50
+ nodeId: node.id,
51
+ message: `inline schema '${node.id}' collides with existing standalone schema '${standaloneId}' — re-import to converge via reuse-before-inline`,
52
+ });
53
+ }
54
+ }
29
55
  function lintNodeProperties(graph, diagnostics) {
30
56
  for (const node of graph.nodesById.values()) {
31
57
  const template = graph.templates.get(node.template);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atolis-hq/corum",
3
- "version": "0.1.40",
3
+ "version": "0.1.41",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",