@globaltypesystem/gts-ts 0.1.1 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/store.ts CHANGED
@@ -4,6 +4,13 @@ import { Gts } from './gts';
4
4
  import { GtsExtractor } from './extract';
5
5
  import { XGtsRefValidator } from './x-gts-ref';
6
6
 
7
+ interface ResolvedSchema {
8
+ properties: Record<string, any>;
9
+ required: string[];
10
+ additionalProperties?: boolean;
11
+ type?: string;
12
+ }
13
+
7
14
  export class GtsStore {
8
15
  private byId: Map<string, JsonEntity> = new Map();
9
16
  private config: GtsConfig;
@@ -88,9 +95,13 @@ export class GtsStore {
88
95
 
89
96
  validateInstance(gtsId: string): ValidationResult {
90
97
  try {
91
- const gid = Gts.parseGtsID(gtsId);
98
+ let objId: string = gtsId;
99
+ if (Gts.isValidGtsID(gtsId)) {
100
+ const gid = Gts.parseGtsID(gtsId);
101
+ objId = gid.id;
102
+ }
92
103
 
93
- const obj = this.get(gid.id);
104
+ const obj = this.get(objId);
94
105
  if (!obj) {
95
106
  return {
96
107
  id: gtsId,
@@ -194,6 +205,9 @@ export class GtsStore {
194
205
  const normalized: any = {};
195
206
 
196
207
  for (const [key, value] of Object.entries(obj)) {
208
+ // Strip x-gts-ref so Ajv never sees the unknown keyword
209
+ if (key === 'x-gts-ref') continue;
210
+
197
211
  let newKey = key;
198
212
  let newValue = value;
199
213
 
@@ -221,6 +235,25 @@ export class GtsStore {
221
235
  normalized[newKey] = newValue;
222
236
  }
223
237
 
238
+ // Clean up combinator arrays: remove subschemas that were x-gts-ref-only (now empty after stripping)
239
+ for (const combinator of ['oneOf', 'anyOf', 'allOf']) {
240
+ if (Array.isArray(normalized[combinator])) {
241
+ normalized[combinator] = normalized[combinator].filter((_sub: any, idx: number) => {
242
+ const original = (obj as any)[combinator]?.[idx];
243
+ const isXGtsRefOnly =
244
+ original &&
245
+ typeof original === 'object' &&
246
+ !Array.isArray(original) &&
247
+ Object.keys(original).length === 1 &&
248
+ original['x-gts-ref'] !== undefined;
249
+ return !isXGtsRefOnly;
250
+ });
251
+ if (normalized[combinator].length === 0) {
252
+ delete normalized[combinator];
253
+ }
254
+ }
255
+ }
256
+
224
257
  // Normalize $id values
225
258
  if (normalized['$id'] && typeof normalized['$id'] === 'string') {
226
259
  if (normalized['$id'].startsWith(GTS_URI_PREFIX)) {
@@ -1053,6 +1086,830 @@ export class GtsStore {
1053
1086
  return unique.sort();
1054
1087
  }
1055
1088
 
1089
+ validateSchemaAgainstParent(schemaId: string): ValidationResult {
1090
+ const entity = this.get(schemaId);
1091
+ if (!entity) {
1092
+ return { id: schemaId, ok: false, error: `Entity not found: ${schemaId}` };
1093
+ }
1094
+ if (!entity.isSchema) {
1095
+ return { id: schemaId, ok: false, error: `Entity is not a schema: ${schemaId}` };
1096
+ }
1097
+
1098
+ const content = entity.content;
1099
+
1100
+ // Find parent reference in allOf
1101
+ const parentRef = this.findParentRef(content);
1102
+ if (!parentRef) {
1103
+ // Base schema with no parent → still validate traits
1104
+ return this.validateSchemaTraits(schemaId);
1105
+ }
1106
+
1107
+ // Resolve parent entity
1108
+ const parentId = parentRef.startsWith(GTS_URI_PREFIX) ? parentRef.substring(GTS_URI_PREFIX.length) : parentRef;
1109
+ const parentEntity = this.get(parentId);
1110
+ if (!parentEntity) {
1111
+ return { id: schemaId, ok: false, error: `Parent schema not found: ${parentId}` };
1112
+ }
1113
+ if (!parentEntity.isSchema || !parentEntity.content) {
1114
+ return { id: schemaId, ok: false, error: `Parent entity is not a schema: ${parentId}` };
1115
+ }
1116
+
1117
+ // Detect cyclic $$ref / $ref references in the schema's own content
1118
+ const cycleError = this.detectRefCycle(schemaId, content, new Set([schemaId]));
1119
+ if (cycleError) {
1120
+ return { id: schemaId, ok: false, error: cycleError };
1121
+ }
1122
+
1123
+ // Resolve parent's effective (fully flattened) schema
1124
+ const resolvedParent = this.resolveSchemaFully(parentEntity.content);
1125
+
1126
+ // Extract overlay from derived schema (non-$ref subschemas in allOf + top-level)
1127
+ const overlay = this.extractOverlay(content);
1128
+
1129
+ // Compare overlay against resolved parent
1130
+ const errors = this.compareOverlayToBase(overlay, resolvedParent, '');
1131
+ if (errors.length > 0) {
1132
+ return { id: schemaId, ok: false, error: errors.join('; ') };
1133
+ }
1134
+
1135
+ // OP#13: Validate schema traits across the inheritance chain
1136
+ const traitsResult = this.validateSchemaTraits(schemaId);
1137
+ if (!traitsResult.ok) {
1138
+ return traitsResult;
1139
+ }
1140
+
1141
+ return { id: schemaId, ok: true, error: '' };
1142
+ }
1143
+
1144
+ // OP#13: Validate schema traits across the inheritance chain
1145
+ private validateSchemaTraits(schemaId: string): ValidationResult {
1146
+ // Build the chain of schema IDs from base to leaf
1147
+ const chain = this.buildSchemaChain(schemaId);
1148
+
1149
+ // Collect trait schemas and trait values from each level, tracking immutability
1150
+ const traitSchemas: any[] = [];
1151
+ const mergedTraits: Record<string, any> = {};
1152
+ const lockedTraits = new Set<string>();
1153
+ const knownDefaults = new Map<string, any>();
1154
+
1155
+ for (const chainSchemaId of chain) {
1156
+ const entity = this.get(chainSchemaId);
1157
+ if (!entity || !entity.content) continue;
1158
+
1159
+ // Collect trait schemas from this level and track which properties this level introduces
1160
+ const prevSchemaCount = traitSchemas.length;
1161
+ this.collectTraitSchemas(entity.content, traitSchemas);
1162
+ const levelSchemaProps = new Set<string>();
1163
+ for (const ts of traitSchemas.slice(prevSchemaCount)) {
1164
+ if (typeof ts === 'object' && ts !== null && typeof ts.properties === 'object' && ts.properties !== null) {
1165
+ for (const [propName, propSchema] of Object.entries(ts.properties)) {
1166
+ levelSchemaProps.add(propName);
1167
+ // Detect default override: ancestor default cannot be changed by descendant
1168
+ if (
1169
+ typeof propSchema === 'object' &&
1170
+ propSchema !== null &&
1171
+ 'default' in (propSchema as Record<string, any>)
1172
+ ) {
1173
+ const newDefault = (propSchema as Record<string, any>).default;
1174
+ if (knownDefaults.has(propName)) {
1175
+ const oldDefault = knownDefaults.get(propName);
1176
+ if (JSON.stringify(oldDefault) !== JSON.stringify(newDefault)) {
1177
+ return {
1178
+ id: schemaId,
1179
+ ok: false,
1180
+ error: `trait schema default for '${propName}' in '${chainSchemaId}' overrides default set by ancestor`,
1181
+ };
1182
+ }
1183
+ } else {
1184
+ knownDefaults.set(propName, newDefault);
1185
+ }
1186
+ }
1187
+ }
1188
+ }
1189
+ }
1190
+
1191
+ // Collect trait values from this level
1192
+ const levelTraits: Record<string, any> = {};
1193
+ this.collectTraitValues(entity.content, levelTraits);
1194
+
1195
+ // Check immutability: trait values set by ancestor are locked unless
1196
+ // this level also introduces a trait schema covering that property
1197
+ for (const [k, v] of Object.entries(levelTraits)) {
1198
+ if (k in mergedTraits && JSON.stringify(mergedTraits[k]) !== JSON.stringify(v) && lockedTraits.has(k)) {
1199
+ return {
1200
+ id: schemaId,
1201
+ ok: false,
1202
+ error: `trait '${k}' in '${chainSchemaId}' overrides value set by ancestor`,
1203
+ };
1204
+ }
1205
+ }
1206
+
1207
+ // Mark trait values as locked or unlocked based on whether this level
1208
+ // also introduced a trait schema covering the property
1209
+ for (const k of Object.keys(levelTraits)) {
1210
+ if (levelSchemaProps.has(k)) {
1211
+ lockedTraits.delete(k);
1212
+ } else {
1213
+ lockedTraits.add(k);
1214
+ }
1215
+ }
1216
+
1217
+ Object.assign(mergedTraits, levelTraits);
1218
+ }
1219
+
1220
+ // If no trait schemas in the chain, nothing to validate
1221
+ if (traitSchemas.length === 0) {
1222
+ if (Object.keys(mergedTraits).length > 0) {
1223
+ return {
1224
+ id: schemaId,
1225
+ ok: false,
1226
+ error: 'x-gts-traits values provided but no x-gts-traits-schema is defined in the inheritance chain',
1227
+ };
1228
+ }
1229
+ return { id: schemaId, ok: true, error: '' };
1230
+ }
1231
+
1232
+ // Validate each trait schema
1233
+ for (let i = 0; i < traitSchemas.length; i++) {
1234
+ const ts = traitSchemas[i];
1235
+
1236
+ // Check: trait schema must have type "object" (or no type, which defaults to object)
1237
+ if (typeof ts === 'object' && ts !== null && ts.type && ts.type !== 'object') {
1238
+ return {
1239
+ id: schemaId,
1240
+ ok: false,
1241
+ error: `x-gts-traits-schema must have type "object", got "${ts.type}"`,
1242
+ };
1243
+ }
1244
+
1245
+ // Check: trait schema must not contain x-gts-traits
1246
+ if (typeof ts === 'object' && ts !== null && ts['x-gts-traits']) {
1247
+ return {
1248
+ id: schemaId,
1249
+ ok: false,
1250
+ error: 'x-gts-traits-schema must not contain x-gts-traits',
1251
+ };
1252
+ }
1253
+ }
1254
+
1255
+ // Resolve $ref inside trait schemas and check for cycles
1256
+ const resolvedTraitSchemas: any[] = [];
1257
+ for (const ts of traitSchemas) {
1258
+ try {
1259
+ const resolved = this.resolveTraitSchemaRefs(ts, new Set());
1260
+ resolvedTraitSchemas.push(resolved);
1261
+ } catch (e) {
1262
+ return {
1263
+ id: schemaId,
1264
+ ok: false,
1265
+ error: e instanceof Error ? e.message : String(e),
1266
+ };
1267
+ }
1268
+ }
1269
+
1270
+ // Build effective trait schema (allOf composition)
1271
+ let effectiveSchema: any;
1272
+ if (resolvedTraitSchemas.length === 1) {
1273
+ effectiveSchema = resolvedTraitSchemas[0];
1274
+ } else {
1275
+ effectiveSchema = {
1276
+ type: 'object',
1277
+ allOf: resolvedTraitSchemas,
1278
+ };
1279
+ }
1280
+
1281
+ // Apply defaults from trait schema to merged traits
1282
+ const effectiveTraits = this.applyTraitDefaults(effectiveSchema, mergedTraits);
1283
+
1284
+ // Validate effective traits against effective schema using AJV
1285
+ try {
1286
+ const normalizedSchema = this.normalizeSchema(effectiveSchema);
1287
+ const validate = this.ajv.compile(normalizedSchema);
1288
+ const isValid = validate(effectiveTraits);
1289
+ if (!isValid) {
1290
+ const errors =
1291
+ validate.errors?.map((e) => `${e.instancePath} ${e.message}`).join('; ') || 'Trait validation failed';
1292
+ return { id: schemaId, ok: false, error: `trait validation: ${errors}` };
1293
+ }
1294
+ } catch (e) {
1295
+ return {
1296
+ id: schemaId,
1297
+ ok: false,
1298
+ error: `failed to compile trait schema: ${e instanceof Error ? e.message : String(e)}`,
1299
+ };
1300
+ }
1301
+
1302
+ // Check for unresolved trait properties (no value and no default)
1303
+ const allProps = this.collectAllTraitProperties(effectiveSchema);
1304
+ for (const [propName, propSchema] of Object.entries(allProps)) {
1305
+ const hasValue = propName in effectiveTraits;
1306
+ const hasDefault = typeof propSchema === 'object' && propSchema !== null && 'default' in propSchema;
1307
+ if (!hasValue && !hasDefault) {
1308
+ return {
1309
+ id: schemaId,
1310
+ ok: false,
1311
+ error: `trait property '${propName}' is not resolved: no value provided and no default defined`,
1312
+ };
1313
+ }
1314
+ }
1315
+
1316
+ return { id: schemaId, ok: true, error: '' };
1317
+ }
1318
+
1319
+ // OP#13: Entity-level traits validation
1320
+ validateEntityTraits(entityId: string): ValidationResult {
1321
+ const entity = this.get(entityId);
1322
+ if (!entity) {
1323
+ return { id: entityId, ok: false, error: `Entity not found: ${entityId}` };
1324
+ }
1325
+
1326
+ if (!entity.isSchema) {
1327
+ return { id: entityId, ok: true, error: '' };
1328
+ }
1329
+
1330
+ // Build the chain for this schema
1331
+ const chain = this.buildSchemaChain(entityId);
1332
+
1333
+ const traitSchemas: any[] = [];
1334
+ let hasTraitValues = false;
1335
+
1336
+ for (const chainSchemaId of chain) {
1337
+ const chainEntity = this.get(chainSchemaId);
1338
+ if (!chainEntity || !chainEntity.content) continue;
1339
+
1340
+ this.collectTraitSchemas(chainEntity.content, traitSchemas);
1341
+
1342
+ const levelTraits: Record<string, any> = {};
1343
+ this.collectTraitValues(chainEntity.content, levelTraits);
1344
+ if (Object.keys(levelTraits).length > 0) {
1345
+ hasTraitValues = true;
1346
+ }
1347
+ }
1348
+
1349
+ if (traitSchemas.length === 0) {
1350
+ return { id: entityId, ok: true, error: '' };
1351
+ }
1352
+
1353
+ // If trait schemas exist but no trait values, entity is incomplete
1354
+ if (!hasTraitValues) {
1355
+ return {
1356
+ id: entityId,
1357
+ ok: false,
1358
+ error: 'Entity defines x-gts-traits-schema but no x-gts-traits values are provided',
1359
+ };
1360
+ }
1361
+
1362
+ // Each trait schema must have additionalProperties: false (closed)
1363
+ for (const ts of traitSchemas) {
1364
+ if (typeof ts === 'object' && ts !== null) {
1365
+ if (ts.additionalProperties !== false) {
1366
+ return {
1367
+ id: entityId,
1368
+ ok: false,
1369
+ error: 'Trait schema must set additionalProperties: false for entity validation',
1370
+ };
1371
+ }
1372
+ }
1373
+ }
1374
+
1375
+ return { id: entityId, ok: true, error: '' };
1376
+ }
1377
+
1378
+ // Build the schema chain from base to leaf for a given schema ID
1379
+ private buildSchemaChain(schemaId: string): string[] {
1380
+ // Parse the schema ID to get segments
1381
+ try {
1382
+ const gtsId = Gts.parseGtsID(schemaId);
1383
+ const segments = gtsId.segments;
1384
+ const chain: string[] = [];
1385
+
1386
+ for (let i = 0; i < segments.length; i++) {
1387
+ const id =
1388
+ 'gts.' +
1389
+ segments
1390
+ .slice(0, i + 1)
1391
+ .map((s) => s.segment)
1392
+ .join('');
1393
+ chain.push(id);
1394
+ }
1395
+
1396
+ return chain;
1397
+ } catch {
1398
+ return [schemaId];
1399
+ }
1400
+ }
1401
+
1402
+ // Collect x-gts-traits-schema from a schema content (recursing into allOf)
1403
+ private collectTraitSchemas(content: any, out: any[], depth: number = 0): void {
1404
+ if (depth > 64 || typeof content !== 'object' || content === null) return;
1405
+
1406
+ if (content['x-gts-traits-schema'] !== undefined) {
1407
+ out.push(content['x-gts-traits-schema']);
1408
+ }
1409
+
1410
+ if (Array.isArray(content.allOf)) {
1411
+ for (const item of content.allOf) {
1412
+ this.collectTraitSchemas(item, out, depth + 1);
1413
+ }
1414
+ }
1415
+ }
1416
+
1417
+ // Collect x-gts-traits from a schema content (recursing into allOf)
1418
+ private collectTraitValues(content: any, merged: Record<string, any>, depth: number = 0): void {
1419
+ if (depth > 64 || typeof content !== 'object' || content === null) return;
1420
+
1421
+ if (typeof content['x-gts-traits'] === 'object' && content['x-gts-traits'] !== null) {
1422
+ Object.assign(merged, content['x-gts-traits']);
1423
+ }
1424
+
1425
+ if (Array.isArray(content.allOf)) {
1426
+ for (const item of content.allOf) {
1427
+ this.collectTraitValues(item, merged, depth + 1);
1428
+ }
1429
+ }
1430
+ }
1431
+
1432
+ // Resolve $ref inside a trait schema, detecting cycles
1433
+ private resolveTraitSchemaRefs(schema: any, visited: Set<string>, depth: number = 0): any {
1434
+ if (depth > 64) return schema;
1435
+ if (typeof schema !== 'object' || schema === null) return schema;
1436
+
1437
+ const result: any = {};
1438
+
1439
+ for (const [key, value] of Object.entries(schema)) {
1440
+ if (key === '$$ref' || key === '$ref') {
1441
+ const refUri = value as string;
1442
+ const refId = refUri.startsWith(GTS_URI_PREFIX) ? refUri.substring(GTS_URI_PREFIX.length) : refUri;
1443
+
1444
+ if (visited.has(refId)) {
1445
+ throw new Error(`Cyclic reference detected in trait schema: ${refId}`);
1446
+ }
1447
+ visited.add(refId);
1448
+
1449
+ const refEntity = this.get(refId);
1450
+ if (!refEntity || !refEntity.content) {
1451
+ throw new Error(`Unresolvable trait schema reference: ${refUri}`);
1452
+ }
1453
+ const resolved = this.resolveTraitSchemaRefs(refEntity.content, visited, depth + 1);
1454
+ // Merge resolved content into result
1455
+ for (const [rk, rv] of Object.entries(resolved)) {
1456
+ if (rk !== '$id' && rk !== '$$id' && rk !== '$schema' && rk !== '$$schema') {
1457
+ result[rk] = rv;
1458
+ }
1459
+ }
1460
+ continue;
1461
+ }
1462
+
1463
+ if (key === 'allOf' && Array.isArray(value)) {
1464
+ result.allOf = (value as any[]).map((item) => this.resolveTraitSchemaRefs(item, visited, depth + 1));
1465
+ } else if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
1466
+ result[key] = this.resolveTraitSchemaRefs(value, new Set(visited), depth + 1);
1467
+ } else {
1468
+ result[key] = value;
1469
+ }
1470
+ }
1471
+
1472
+ return result;
1473
+ }
1474
+
1475
+ // Apply defaults from trait schema to trait values
1476
+ private applyTraitDefaults(schema: any, traits: Record<string, any>): Record<string, any> {
1477
+ const result = { ...traits };
1478
+ const props = this.collectAllTraitProperties(schema);
1479
+
1480
+ for (const [propName, propSchema] of Object.entries(props)) {
1481
+ if (!(propName in result) && typeof propSchema === 'object' && propSchema !== null && 'default' in propSchema) {
1482
+ result[propName] = propSchema.default;
1483
+ }
1484
+ }
1485
+
1486
+ return result;
1487
+ }
1488
+
1489
+ // Collect all properties from a trait schema (handling allOf composition)
1490
+ private collectAllTraitProperties(schema: any, depth: number = 0): Record<string, any> {
1491
+ const props: Record<string, any> = {};
1492
+ if (depth > 64 || typeof schema !== 'object' || schema === null) return props;
1493
+
1494
+ if (typeof schema.properties === 'object' && schema.properties !== null) {
1495
+ Object.assign(props, schema.properties);
1496
+ }
1497
+
1498
+ if (Array.isArray(schema.allOf)) {
1499
+ for (const item of schema.allOf) {
1500
+ Object.assign(props, this.collectAllTraitProperties(item, depth + 1));
1501
+ }
1502
+ }
1503
+
1504
+ return props;
1505
+ }
1506
+
1507
+ // Detect cyclic $$ref/$ref references reachable from a schema's content
1508
+ private detectRefCycle(originId: string, content: any, visited: Set<string>, depth: number = 0): string | null {
1509
+ if (depth > 64 || !content || typeof content !== 'object') return null;
1510
+
1511
+ // Check direct ref on this object
1512
+ const ref = content['$$ref'] || content['$ref'];
1513
+ if (typeof ref === 'string') {
1514
+ const refId = ref.startsWith(GTS_URI_PREFIX) ? ref.substring(GTS_URI_PREFIX.length) : ref;
1515
+ if (visited.has(refId)) {
1516
+ return `Cyclic reference detected: ${refId}`;
1517
+ }
1518
+ const refEntity = this.get(refId);
1519
+ if (refEntity && refEntity.content) {
1520
+ visited.add(refId);
1521
+ const inner = this.detectRefCycle(originId, refEntity.content, visited, depth + 1);
1522
+ if (inner) return inner;
1523
+ }
1524
+ }
1525
+
1526
+ // Recurse into allOf
1527
+ if (Array.isArray(content.allOf)) {
1528
+ for (const sub of content.allOf) {
1529
+ const inner = this.detectRefCycle(originId, sub, visited, depth + 1);
1530
+ if (inner) return inner;
1531
+ }
1532
+ }
1533
+
1534
+ return null;
1535
+ }
1536
+
1537
+ private findParentRef(schema: any): string | null {
1538
+ if (!schema || !schema.allOf || !Array.isArray(schema.allOf)) {
1539
+ return null;
1540
+ }
1541
+ for (const sub of schema.allOf) {
1542
+ if (sub && typeof sub === 'object') {
1543
+ const ref = sub['$$ref'] || sub['$ref'];
1544
+ if (typeof ref === 'string') {
1545
+ return ref;
1546
+ }
1547
+ }
1548
+ }
1549
+ return null;
1550
+ }
1551
+
1552
+ private resolveSchemaFully(schema: any, visited: Set<string> = new Set()): ResolvedSchema {
1553
+ const result: ResolvedSchema = {
1554
+ properties: {},
1555
+ required: [],
1556
+ additionalProperties: undefined,
1557
+ type: schema.type,
1558
+ };
1559
+
1560
+ // If this schema has allOf, resolve each part
1561
+ if (schema.allOf && Array.isArray(schema.allOf)) {
1562
+ for (const sub of schema.allOf) {
1563
+ const ref = sub['$$ref'] || sub['$ref'];
1564
+ if (typeof ref === 'string') {
1565
+ // Resolve referenced schema
1566
+ const refId = ref.startsWith(GTS_URI_PREFIX) ? ref.substring(GTS_URI_PREFIX.length) : ref;
1567
+ if (visited.has(refId)) {
1568
+ continue;
1569
+ }
1570
+ visited.add(refId);
1571
+ const refEntity = this.get(refId);
1572
+ if (refEntity && refEntity.content) {
1573
+ const resolved = this.resolveSchemaFully(refEntity.content, visited);
1574
+ Object.assign(result.properties, resolved.properties);
1575
+ if (resolved.required) {
1576
+ result.required.push(...resolved.required);
1577
+ }
1578
+ if (resolved.additionalProperties !== undefined) {
1579
+ result.additionalProperties = resolved.additionalProperties;
1580
+ }
1581
+ if (resolved.type && !result.type) {
1582
+ result.type = resolved.type;
1583
+ }
1584
+ }
1585
+ } else {
1586
+ // Non-ref subschema - merge it
1587
+ const resolved = this.resolveSchemaFully(sub, visited);
1588
+ // For overlay properties, merge them (they override)
1589
+ for (const [propName, propSchema] of Object.entries(resolved.properties || {})) {
1590
+ if (result.properties[propName]) {
1591
+ // Merge property constraints - overlay tightens base
1592
+ result.properties[propName] = this.mergePropertySchemas(result.properties[propName], propSchema);
1593
+ } else {
1594
+ result.properties[propName] = propSchema;
1595
+ }
1596
+ }
1597
+ if (resolved.required) {
1598
+ result.required.push(...resolved.required);
1599
+ }
1600
+ if (resolved.additionalProperties !== undefined) {
1601
+ result.additionalProperties = resolved.additionalProperties;
1602
+ }
1603
+ }
1604
+ }
1605
+ }
1606
+
1607
+ // Add direct properties
1608
+ if (schema.properties) {
1609
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
1610
+ if (result.properties[propName]) {
1611
+ result.properties[propName] = this.mergePropertySchemas(result.properties[propName], propSchema);
1612
+ } else {
1613
+ result.properties[propName] = propSchema;
1614
+ }
1615
+ }
1616
+ }
1617
+
1618
+ // Add direct required
1619
+ if (schema.required && Array.isArray(schema.required)) {
1620
+ result.required.push(...schema.required);
1621
+ }
1622
+
1623
+ // Direct additionalProperties
1624
+ if (schema.additionalProperties !== undefined) {
1625
+ result.additionalProperties = schema.additionalProperties;
1626
+ }
1627
+
1628
+ // Deduplicate required
1629
+ result.required = Array.from(new Set(result.required));
1630
+
1631
+ return result;
1632
+ }
1633
+
1634
+ private mergePropertySchemas(base: any, overlay: any): any {
1635
+ if (base === false || overlay === false) {
1636
+ return false;
1637
+ }
1638
+ if (typeof base !== 'object' || typeof overlay !== 'object') {
1639
+ return overlay;
1640
+ }
1641
+ const merged: any = { ...base };
1642
+ for (const [key, val] of Object.entries(overlay)) {
1643
+ if (key === 'properties' && merged.properties) {
1644
+ merged.properties = { ...merged.properties, ...(val as any) };
1645
+ } else if (key === 'required' && merged.required) {
1646
+ const mergedReq = new Set([...(merged.required as string[]), ...(val as string[])]);
1647
+ merged.required = Array.from(mergedReq);
1648
+ } else {
1649
+ merged[key] = val;
1650
+ }
1651
+ }
1652
+ return merged;
1653
+ }
1654
+
1655
+ private extractOverlay(schema: any): ResolvedSchema {
1656
+ const overlay: ResolvedSchema = {
1657
+ properties: {},
1658
+ required: [],
1659
+ additionalProperties: undefined,
1660
+ };
1661
+
1662
+ if (schema.allOf && Array.isArray(schema.allOf)) {
1663
+ for (const sub of schema.allOf) {
1664
+ const ref = sub['$$ref'] || sub['$ref'];
1665
+ if (typeof ref === 'string') {
1666
+ continue; // Skip ref subschemas
1667
+ }
1668
+ // This is a non-ref overlay subschema
1669
+ if (sub.properties) {
1670
+ for (const [propName, propSchema] of Object.entries(sub.properties)) {
1671
+ overlay.properties[propName] = overlay.properties[propName]
1672
+ ? this.mergePropertySchemas(overlay.properties[propName], propSchema)
1673
+ : propSchema;
1674
+ }
1675
+ }
1676
+ if (sub.required && Array.isArray(sub.required)) {
1677
+ overlay.required.push(...sub.required);
1678
+ }
1679
+ if (sub.additionalProperties !== undefined) {
1680
+ overlay.additionalProperties = sub.additionalProperties;
1681
+ }
1682
+ }
1683
+ }
1684
+
1685
+ // Add top-level properties (outside allOf)
1686
+ if (schema.properties) {
1687
+ for (const [propName, propSchema] of Object.entries(schema.properties)) {
1688
+ overlay.properties[propName] = overlay.properties[propName]
1689
+ ? this.mergePropertySchemas(overlay.properties[propName], propSchema)
1690
+ : propSchema;
1691
+ }
1692
+ }
1693
+ if (schema.required && Array.isArray(schema.required)) {
1694
+ overlay.required.push(...schema.required);
1695
+ }
1696
+ if (schema.additionalProperties !== undefined && overlay.additionalProperties === undefined) {
1697
+ overlay.additionalProperties = schema.additionalProperties;
1698
+ }
1699
+
1700
+ return overlay;
1701
+ }
1702
+
1703
+ private compareOverlayToBase(overlay: ResolvedSchema, baseResolved: ResolvedSchema, path: string): string[] {
1704
+ const errors: string[] = [];
1705
+ const overlayProps = overlay.properties || {};
1706
+ const baseProps = baseResolved.properties || {};
1707
+
1708
+ for (const [propName, propSchema] of Object.entries(overlayProps)) {
1709
+ const propPath = path ? `${path}.${propName}` : propName;
1710
+
1711
+ // Property schema set to false
1712
+ if (propSchema === false) {
1713
+ if (baseProps[propName] !== undefined) {
1714
+ errors.push(`Property '${propPath}' is set to false but exists in base`);
1715
+ }
1716
+ continue;
1717
+ }
1718
+
1719
+ const baseProp = baseProps[propName];
1720
+
1721
+ if (baseProp === undefined || baseProp === null) {
1722
+ // New property not in base
1723
+ if (baseResolved.additionalProperties === false) {
1724
+ errors.push(`Property '${propPath}' not in base and base has additionalProperties: false`);
1725
+ }
1726
+ continue;
1727
+ }
1728
+
1729
+ if (baseProp === false) {
1730
+ // Base already set property to false, overlay can't use it
1731
+ errors.push(`Property '${propPath}' is forbidden in base`);
1732
+ continue;
1733
+ }
1734
+
1735
+ // Both base and overlay have this property — compare constraints
1736
+ if (typeof propSchema === 'object' && propSchema !== null) {
1737
+ errors.push(...this.comparePropertyConstraints(propSchema, baseProp, propPath));
1738
+ }
1739
+ }
1740
+
1741
+ // Check additionalProperties
1742
+ if (baseResolved.additionalProperties === false) {
1743
+ if (overlay.additionalProperties === true) {
1744
+ errors.push('Cannot loosen additionalProperties from false to true');
1745
+ } else if (overlay.additionalProperties === undefined) {
1746
+ errors.push('Base has additionalProperties: false but derived does not restate it');
1747
+ }
1748
+ }
1749
+
1750
+ return errors;
1751
+ }
1752
+
1753
+ private comparePropertyConstraints(derived: any, base: any, propPath: string): string[] {
1754
+ const errors: string[] = [];
1755
+
1756
+ if (typeof base !== 'object' || base === null) {
1757
+ return errors;
1758
+ }
1759
+
1760
+ // Type check
1761
+ const baseType = base.type;
1762
+ const derivedType = derived.type;
1763
+ if (baseType !== undefined && derivedType !== undefined) {
1764
+ if (Array.isArray(derivedType)) {
1765
+ // Derived has array type — widening (fail)
1766
+ if (!Array.isArray(baseType)) {
1767
+ errors.push(`Property '${propPath}' widens type from '${baseType}' to array`);
1768
+ return errors;
1769
+ }
1770
+ }
1771
+ if (Array.isArray(baseType)) {
1772
+ if (!Array.isArray(derivedType)) {
1773
+ // Could be narrowing from array type
1774
+ if (!baseType.includes(derivedType)) {
1775
+ errors.push(`Property '${propPath}' type '${derivedType}' not in base types [${baseType}]`);
1776
+ return errors;
1777
+ }
1778
+ }
1779
+ } else if (!Array.isArray(derivedType)) {
1780
+ // Both scalar types
1781
+ if (baseType !== derivedType) {
1782
+ errors.push(`Property '${propPath}' type changed from '${baseType}' to '${derivedType}'`);
1783
+ return errors;
1784
+ }
1785
+ }
1786
+ }
1787
+
1788
+ // Determine if the overlay adds any NEW constraint keywords not in the base.
1789
+ // Under allOf semantics, base constraints are preserved. Drops are only flagged
1790
+ // when the overlay doesn't introduce any new tightening constraints.
1791
+ const CONSTRAINT_KEYWORDS = [
1792
+ 'maxLength',
1793
+ 'minLength',
1794
+ 'maximum',
1795
+ 'minimum',
1796
+ 'maxItems',
1797
+ 'minItems',
1798
+ 'enum',
1799
+ 'const',
1800
+ 'pattern',
1801
+ 'items',
1802
+ ];
1803
+ const baseConstraintKeys = new Set(CONSTRAINT_KEYWORDS.filter((kw) => base[kw] !== undefined));
1804
+ const derivedConstraintKeys = new Set(CONSTRAINT_KEYWORDS.filter((kw) => derived[kw] !== undefined));
1805
+ const hasNewConstraints = [...derivedConstraintKeys].some((kw) => !baseConstraintKeys.has(kw));
1806
+
1807
+ // Max constraints (tightening = lower value OK; loosening = higher value FAIL)
1808
+ for (const kw of ['maxLength', 'maximum', 'maxItems']) {
1809
+ if (base[kw] !== undefined) {
1810
+ if (derived[kw] === undefined) {
1811
+ if (!hasNewConstraints) {
1812
+ errors.push(`Property '${propPath}' drops constraint '${kw}'`);
1813
+ }
1814
+ } else if (derived[kw] > base[kw]) {
1815
+ errors.push(`Property '${propPath}' loosens '${kw}' from ${base[kw]} to ${derived[kw]}`);
1816
+ }
1817
+ }
1818
+ }
1819
+
1820
+ // Min constraints (tightening = higher value OK; loosening = lower value FAIL)
1821
+ for (const kw of ['minLength', 'minimum', 'minItems']) {
1822
+ if (base[kw] !== undefined) {
1823
+ if (derived[kw] === undefined) {
1824
+ if (!hasNewConstraints) {
1825
+ errors.push(`Property '${propPath}' drops constraint '${kw}'`);
1826
+ }
1827
+ } else if (derived[kw] < base[kw]) {
1828
+ errors.push(`Property '${propPath}' loosens '${kw}' from ${base[kw]} to ${derived[kw]}`);
1829
+ }
1830
+ }
1831
+ }
1832
+
1833
+ // Enum check
1834
+ if (base.enum !== undefined) {
1835
+ if (derived.enum === undefined) {
1836
+ if (!hasNewConstraints) {
1837
+ errors.push(`Property '${propPath}' drops constraint 'enum'`);
1838
+ }
1839
+ } else {
1840
+ const baseSet = new Set(base.enum.map((v: any) => JSON.stringify(v)));
1841
+ for (const val of derived.enum) {
1842
+ if (!baseSet.has(JSON.stringify(val))) {
1843
+ errors.push(`Property '${propPath}' enum value '${val}' not in base enum`);
1844
+ }
1845
+ }
1846
+ }
1847
+ }
1848
+
1849
+ // Const check
1850
+ if (base.const !== undefined) {
1851
+ if (derived.const === undefined) {
1852
+ if (!hasNewConstraints) {
1853
+ errors.push(`Property '${propPath}' drops constraint 'const'`);
1854
+ }
1855
+ } else if (JSON.stringify(base.const) !== JSON.stringify(derived.const)) {
1856
+ errors.push(
1857
+ `Property '${propPath}' const conflict: ${JSON.stringify(derived.const)} vs base ${JSON.stringify(base.const)}`
1858
+ );
1859
+ }
1860
+ }
1861
+ // Check const in derived against base numeric constraints
1862
+ if (derived.const !== undefined && typeof derived.const === 'number') {
1863
+ if (base.minimum !== undefined && derived.const < base.minimum) {
1864
+ errors.push(`Property '${propPath}' const ${derived.const} violates base minimum ${base.minimum}`);
1865
+ }
1866
+ if (base.maximum !== undefined && derived.const > base.maximum) {
1867
+ errors.push(`Property '${propPath}' const ${derived.const} violates base maximum ${base.maximum}`);
1868
+ }
1869
+ }
1870
+
1871
+ // Pattern check
1872
+ if (base.pattern !== undefined) {
1873
+ if (derived.pattern === undefined) {
1874
+ if (!hasNewConstraints) {
1875
+ errors.push(`Property '${propPath}' drops constraint 'pattern'`);
1876
+ }
1877
+ } else if (base.pattern !== derived.pattern) {
1878
+ errors.push(`Property '${propPath}' pattern changed from '${base.pattern}' to '${derived.pattern}'`);
1879
+ }
1880
+ }
1881
+
1882
+ // Items check (array items)
1883
+ if (base.items !== undefined) {
1884
+ if (derived.items === undefined) {
1885
+ if (!hasNewConstraints) {
1886
+ errors.push(`Property '${propPath}' drops constraint 'items'`);
1887
+ }
1888
+ } else if (typeof base.items === 'object' && typeof derived.items === 'object') {
1889
+ errors.push(...this.comparePropertyConstraints(derived.items, base.items, `${propPath}.items`));
1890
+ }
1891
+ }
1892
+
1893
+ // Nested object: recursively compare
1894
+ if (base.type === 'object' && derived.type === 'object') {
1895
+ if (base.properties || derived.properties) {
1896
+ const nestedOverlay = {
1897
+ properties: derived.properties || {},
1898
+ required: derived.required || [],
1899
+ additionalProperties: derived.additionalProperties,
1900
+ };
1901
+ const nestedBase = {
1902
+ properties: base.properties || {},
1903
+ required: base.required || [],
1904
+ additionalProperties: base.additionalProperties,
1905
+ };
1906
+ errors.push(...this.compareOverlayToBase(nestedOverlay, nestedBase, propPath));
1907
+ }
1908
+ }
1909
+
1910
+ return errors;
1911
+ }
1912
+
1056
1913
  getAttribute(gtsId: string, path: string): any {
1057
1914
  const entity = this.get(gtsId);
1058
1915
  if (!entity) {