diff --git a/packages/differs.core/src/classifiers.ts b/packages/differs.core/src/classifiers.ts index 59b3930..f5f5241 100644 --- a/packages/differs.core/src/classifiers.ts +++ b/packages/differs.core/src/classifiers.ts @@ -184,6 +184,8 @@ export const CLASSIFICATION_SETS = { * ``` */ export function classify(change: RawChange): ChangeSeverity { + if (change.enumConstraintEquivalent) return 'non-breaking'; + const { type } = change; // Check each category in order of specificity diff --git a/packages/differs.core/src/types.ts b/packages/differs.core/src/types.ts index c907e57..7cf7eb4 100644 --- a/packages/differs.core/src/types.ts +++ b/packages/differs.core/src/types.ts @@ -23,13 +23,7 @@ export { CHANGE_TYPE_SEVERITY } from '@contractual/types'; * JSON Schema type values */ export type JSONSchemaType = - | 'string' - | 'number' - | 'integer' - | 'boolean' - | 'object' - | 'array' - | 'null'; + 'string' | 'number' | 'integer' | 'boolean' | 'object' | 'array' | 'null'; /** * Normalized type representation (always an array for comparison) @@ -311,6 +305,8 @@ export function deepEqual(a: unknown, b: unknown): boolean { if (a === null || b === null) return a === b; + if (Array.isArray(a) !== Array.isArray(b)) return false; + if (Array.isArray(a) && Array.isArray(b)) { if (a.length !== b.length) return false; return a.every((val, idx) => deepEqual(val, b[idx])); @@ -322,7 +318,7 @@ export function deepEqual(a: unknown, b: unknown): boolean { const aKeys = Object.keys(aObj); const bKeys = Object.keys(bObj); if (aKeys.length !== bKeys.length) return false; - return aKeys.every((key) => deepEqual(aObj[key], bObj[key])); + return aKeys.every((key) => Object.hasOwn(bObj, key) && deepEqual(aObj[key], bObj[key])); } return false; diff --git a/packages/differs.core/src/walker.ts b/packages/differs.core/src/walker.ts index e1d47db..bf2d1ac 100644 --- a/packages/differs.core/src/walker.ts +++ b/packages/differs.core/src/walker.ts @@ -390,7 +390,6 @@ function compareEnum( oldValue: undefined, newValue: newEnum, }); - return changes; } // Enum removed @@ -401,7 +400,6 @@ function compareEnum( oldValue: oldEnum, newValue: undefined, }); - return changes; } // Both have enums - compare values @@ -459,7 +457,24 @@ function compareEnum( } } - return changes; + // Prove equivalence where both schemas are available, rather than pairing + // unrelated raw changes later by their potentially shared display paths. + const constToEnum = + oldEnum === undefined && + oldSchema.const !== undefined && + newSchema.const === undefined && + newEnum?.length === 1 && + deepEqual(oldSchema.const, newEnum[0]); + const enumToConst = + newEnum === undefined && + newSchema.const !== undefined && + oldSchema.const === undefined && + oldEnum?.length === 1 && + deepEqual(oldEnum[0], newSchema.const); + + return constToEnum || enumToConst + ? changes.map((change) => ({ ...change, enumConstraintEquivalent: true })) + : changes; } /** diff --git a/packages/differs.openapi/src/differ.test.ts b/packages/differs.openapi/src/differ.test.ts index a882430..97fb9f2 100644 --- a/packages/differs.openapi/src/differ.test.ts +++ b/packages/differs.openapi/src/differ.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from 'vitest'; +import { assembleResult, deepEqual, walk } from '@contractual/differs.core'; import { diffOpenApiObjects } from './differ.js'; import { diffStructural } from './structural.js'; @@ -183,3 +184,258 @@ describe('OpenAPI enum compatibility direction', () => { }); }); }); + +describe('OpenAPI enum constraint interactions', () => { + test.each(['request', 'response'] as const)( + '%s const removal is retained when an enum is added', + (direction) => { + const oldSpec = openApiSpec(direction, false, { const: 'a' }); + const newSpec = openApiSpec(direction, false, { enum: ['a', 'b'] }); + const rawChanges = diffStructural(oldSpec, newSpec); + expect(rawChanges).toEqual([ + expect.objectContaining({ type: 'enum-added', newValue: ['a', 'b'] }), + expect.objectContaining({ + type: 'enum-removed', + oldValue: 'a', + path: expect.stringMatching(/\/const$/), + }), + ]); + const result = diffOpenApiObjects(oldSpec, newSpec); + expect(result.changes).toContainEqual( + expect.objectContaining({ + category: direction === 'response' ? 'enum-removed' : 'enum-added', + severity: 'breaking', + }) + ); + expect(result.suggestedBump).toBe('major'); + } + ); + + test('enum removal does not hide a simultaneous const replacement', () => { + const result = diffOpenApiObjects( + openApiSpec('response', false, { enum: ['a', 'b'], const: 'a' }), + openApiSpec('response', false, { const: 'c' }) + ); + expect(result.changes).toEqual([ + expect.objectContaining({ category: 'enum-removed', severity: 'breaking' }), + expect.objectContaining({ + category: 'enum-value-removed', + oldValue: 'a', + newValue: 'c', + severity: 'breaking', + }), + ]); + expect(result.suggestedBump).toBe('major'); + }); + + test.each(['request', 'response'] as const)( + '%s enum changes inside overlapping oneOf branches require a major bump', + (direction) => { + const before = { + oneOf: [ + { type: 'string', enum: ['a', 'b'] }, + { type: 'string', enum: ['b'] }, + ], + }; + const after = { + oneOf: [ + { type: 'string', enum: ['a'] }, + { type: 'string', enum: ['b'] }, + ], + }; + for (const [oldSchema, newSchema] of [ + [before, after], + [after, before], + ]) { + const result = diffOpenApiObjects( + openApiSpec(direction, false, oldSchema), + openApiSpec(direction, false, newSchema) + ); + expect(result.changes).toEqual([ + expect.objectContaining({ + severity: 'breaking', + path: expect.stringContaining('/oneOf/0/enum'), + }), + ]); + expect(result.suggestedBump).toBe('major'); + } + } + ); +}); + +test('enum removal retains a simultaneous const addition for input compatibility', () => { + const changes = walk({ type: 'string', enum: ['a', 'b'] }, { type: 'string', const: 'a' }); + + expect(changes).toEqual([ + { path: '/enum', type: 'enum-removed', oldValue: ['a', 'b'], newValue: undefined }, + { path: '/const', type: 'enum-added', oldValue: undefined, newValue: 'a' }, + ]); + expect(assembleResult(changes, { type: 'string', const: 'a' }).suggestedBump).toBe('major'); +}); + +describe('equivalent singleton enum and const substitutions', () => { + test.each(['request', 'response'] as const)( + '%s substitutions preserve the value set', + (direction) => { + for (const value of ['a', null, { nested: ['a'] }]) { + const schemaType = + value === null ? 'null' : typeof value === 'object' ? 'object' : 'string'; + const schemas = [ + { type: schemaType, enum: [value] }, + { type: schemaType, const: value }, + ]; + for (const [oldSchema, newSchema] of [schemas, [...schemas].reverse()]) { + const oldSpec = openApiSpec(direction, false, oldSchema); + const newSpec = openApiSpec(direction, false, newSchema); + expect(diffStructural(oldSpec, newSpec)).toHaveLength(2); + const result = diffOpenApiObjects(oldSpec, newSpec); + expect(result.changes).toHaveLength(2); + expect(result.changes.every((change) => change.severity === 'non-breaking')).toBe(true); + expect(result.suggestedBump).toBe('minor'); + expect(assembleResult(walk(oldSchema, newSchema), newSchema).suggestedBump).toBe('minor'); + } + } + } + ); + + test('equivalent substitutions remain compatible inside oneOf', () => { + const before = { oneOf: [{ const: 'a' }, { const: 'b' }] }; + const after = { oneOf: [{ enum: ['a'] }, { const: 'b' }] }; + for (const direction of ['request', 'response'] as const) { + const result = diffOpenApiObjects( + openApiSpec(direction, false, before), + openApiSpec(direction, false, after) + ); + expect(result.changes).toHaveLength(2); + expect(result.changes.every((change) => change.severity === 'non-breaking')).toBe(true); + expect(result.suggestedBump).toBe('minor'); + } + }); + + test('different singleton values still require a major bump', () => { + for (const [oldSchema, newSchema] of [ + [{ const: 'a' }, { enum: ['b'] }], + [{ enum: ['a'] }, { const: 'b' }], + ]) { + for (const direction of ['request', 'response'] as const) { + expect( + diffOpenApiObjects( + openApiSpec(direction, false, oldSchema), + openApiSpec(direction, false, newSchema) + ).suggestedBump + ).toBe('major'); + } + expect(assembleResult(walk(oldSchema, newSchema), newSchema).suggestedBump).toBe('major'); + } + }); +}); + +test('parameter names cannot imitate oneOf schema paths', () => { + function spec(values: string[]) { + return { + openapi: '3.1.0', + info: { title: 'Parameters', version: '1.0.0' }, + paths: { + '/example': { + get: { + parameters: [ + { in: 'query', name: 'x/oneOf/0/x~y', schema: { type: 'string', enum: values } }, + ], + responses: { 200: { description: 'OK' } }, + }, + }, + }, + }; + } + const result = diffOpenApiObjects(spec(['a']), spec(['a', 'b'])); + expect(result.changes).toEqual([ + expect.objectContaining({ + category: 'enum-value-added', + severity: 'non-breaking', + path: '/paths/~1example/get/parameters/x~1oneOf~10~1x~0y/schema/enum', + }), + ]); + expect(result.suggestedBump).toBe('minor'); +}); + +test('same-name parameters do not share equivalence evidence', () => { + function spec(querySchema: Record, headerSchema: Record) { + return { + openapi: '3.1.0', + info: { title: 'Parameters', version: '1.0.0' }, + paths: { + '/example': { + get: { + parameters: [ + { in: 'query', name: 'x', schema: querySchema }, + { in: 'header', name: 'x', schema: headerSchema }, + ], + responses: { 200: { description: 'OK' } }, + }, + }, + }, + }; + } + const result = diffOpenApiObjects(spec({ enum: ['a'] }, {}), spec({}, { const: 'a' })); + expect(result.changes).toContainEqual( + expect.objectContaining({ category: 'enum-added', severity: 'breaking' }) + ); + expect(result.suggestedBump).toBe('major'); +}); + +test('object const equivalence ignores key order', () => { + const before = { const: { a: 1, b: 2 } }; + const after = { enum: [{ b: 2, a: 1 }] }; + expect(assembleResult(walk(before, after), after).suggestedBump).toBe('minor'); +}); + +test('coexisting enum and const constraints are not treated as substitutions', () => { + const before = { enum: ['a'], const: 'b' }; + const after = { enum: ['a'] }; + for (const change of walk(before, after)) expect(change.enumConstraintEquivalent).toBeUndefined(); + expect( + diffOpenApiObjects( + openApiSpec('response', false, before), + openApiSpec('response', false, after) + ).suggestedBump + ).toBe('major'); +}); + +test('arrays and objects with numeric keys are different enum values', () => { + const before = { const: ['a'] }; + const after = { enum: [{ 0: 'a' }] }; + const changes = walk(before, after); + expect(changes.every((change) => change.enumConstraintEquivalent === undefined)).toBe(true); + expect(assembleResult(changes, after).suggestedBump).toBe('major'); +}); + +test('JSON object equality requires matching own keys, including __proto__', () => { + const ownPrototypeKey = JSON.parse('{"__proto__":{}}'); + const differentKey = JSON.parse('{"different":"value"}'); + for (const [left, right] of [ + [ownPrototypeKey, differentKey], + [differentKey, ownPrototypeKey], + ]) { + expect(deepEqual(left, right)).toBe(false); + for (const [before, after] of [ + [{ const: left }, { enum: [right] }], + [{ enum: [left] }, { const: right }], + ]) { + const changes = walk(before, after); + expect(changes.every((change) => change.enumConstraintEquivalent === undefined)).toBe(true); + expect(assembleResult(changes, after).suggestedBump).toBe('major'); + } + } + + const sameLeft = JSON.parse('{"__proto__":{},"nested":{"a":1,"b":[2]}}'); + const sameRight = JSON.parse('{"nested":{"b":[2],"a":1},"__proto__":{}}'); + for (const [left, right] of [ + [sameLeft, sameRight], + [sameRight, sameLeft], + ]) { + expect(deepEqual(left, right)).toBe(true); + expect( + assembleResult(walk({ const: left }, { enum: [right] }), { enum: [right] }).suggestedBump + ).toBe('minor'); + } +}); diff --git a/packages/differs.openapi/src/differ.ts b/packages/differs.openapi/src/differ.ts index 328bde3..9f4f2e6 100644 --- a/packages/differs.openapi/src/differ.ts +++ b/packages/differs.openapi/src/differ.ts @@ -40,6 +40,15 @@ export function diffOpenApiObjects( } function classifyOpenApiChange(change: RawChange, newSpec: unknown): ChangeSeverity { + if (change.enumConstraintEquivalent) return 'non-breaking'; + + // oneOf accepts exactly one matching branch. Either narrowing or widening + // a branch can invalidate old inputs or introduce outputs old clients reject. + // Without proving branch disjointness, treat enum changes conservatively. + if (change.type.startsWith('enum-') && /\/oneOf\/\d+\//.test(change.path)) { + return 'breaking'; + } + if (change.schemaDirection === 'output') { // Responses must remain valid against the schema known to existing clients. // A const replacement is disjoint, rather than a narrowing: the walker diff --git a/packages/differs.openapi/src/structural.ts b/packages/differs.openapi/src/structural.ts index 78bfeb2..eabbb64 100644 --- a/packages/differs.openapi/src/structural.ts +++ b/packages/differs.openapi/src/structural.ts @@ -181,7 +181,7 @@ function diffParameters(oldOp: OperationMap, newOp: OperationMap, basePath: stri for (const [key, oldParam] of oldByKey) { if (!newByKey.has(key)) { changes.push({ - path: `${basePath}/parameters/${oldParam.name}`, + path: `${basePath}/parameters/${escapeJsonPointer(String(oldParam.name))}`, type: 'parameter-removed' as ChangeType, oldValue: key, }); @@ -191,7 +191,7 @@ function diffParameters(oldOp: OperationMap, newOp: OperationMap, basePath: stri // Check required change if (oldParam.required !== newParam.required) { changes.push({ - path: `${basePath}/parameters/${oldParam.name}/required`, + path: `${basePath}/parameters/${escapeJsonPointer(String(oldParam.name))}/required`, type: 'parameter-required-changed' as ChangeType, oldValue: oldParam.required, newValue: newParam.required, @@ -203,7 +203,7 @@ function diffParameters(oldOp: OperationMap, newOp: OperationMap, basePath: stri const schemaChanges = walk( oldParam.schema, newParam.schema, - `${basePath}/parameters/${oldParam.name}/schema` + `${basePath}/parameters/${escapeJsonPointer(String(oldParam.name))}/schema` ); changes.push(...withSchemaDirection(schemaChanges, 'input')); } @@ -215,7 +215,7 @@ function diffParameters(oldOp: OperationMap, newOp: OperationMap, basePath: stri // Required parameter added = breaking, optional = non-breaking // Store required flag in newValue so classifiers can check changes.push({ - path: `${basePath}/parameters/${newParam.name}`, + path: `${basePath}/parameters/${escapeJsonPointer(String(newParam.name))}`, type: newParam.required ? ('parameter-required-added' as ChangeType) : ('parameter-added' as ChangeType), diff --git a/packages/types/governance.ts b/packages/types/governance.ts index 2900707..76f2cd6 100644 --- a/packages/types/governance.ts +++ b/packages/types/governance.ts @@ -272,6 +272,8 @@ export interface RawChange { newValue?: unknown; /** Consumer-relative direction of the surrounding schema, when known */ schemaDirection?: SchemaDirection; + /** Walker proved an exclusive const/singleton-enum substitution preserves accepted values. */ + enumConstraintEquivalent?: boolean; } /**