diff --git a/src/generateDiff.ts b/src/generateDiff.ts index 87ccc7e..5244329 100644 --- a/src/generateDiff.ts +++ b/src/generateDiff.ts @@ -1,6 +1,9 @@ import { compare } from 'fast-json-patch'; -import { formatDiffOutput } from './helpers/DiffHelpers'; +import { + formatDiffOutput, + removeCircularReferences, +} from './helpers/DiffHelpers'; import { DiffOutput } from './types'; /** @@ -15,6 +18,9 @@ export default function generateDiff( firstDocument: any, secondDocument: any ): DiffOutput[] { - const diffOutput = compare(firstDocument, secondDocument); - return formatDiffOutput(diffOutput, firstDocument); + // resolved `$ref`s make recursive schemas circular, which `compare` can't clone + const first = removeCircularReferences(firstDocument); + const second = removeCircularReferences(secondDocument); + const diffOutput = compare(first, second); + return formatDiffOutput(diffOutput, first); } diff --git a/src/helpers/DiffHelpers.ts b/src/helpers/DiffHelpers.ts index d30108c..83bca77 100644 --- a/src/helpers/DiffHelpers.ts +++ b/src/helpers/DiffHelpers.ts @@ -116,3 +116,47 @@ export function incompatibleDocuments( } return false; } + +/** + * Copies a document, replacing each reference back to an ancestor (as in a + * recursive schema once `$ref`s are resolved) with a marker naming that + * ancestor's JSON pointer. Shared, non-recursive references are copied as is. + * Naming the ancestor keeps a recursive reference that is redirected elsewhere + * visible in the diff. + * @param value The document, or a part of it + * @param {String} path The JSON pointer of `value` + * @param ancestors The objects being copied above `value`, with their pointers + * @returns A copy of `value` without circular references + * + * @private + */ +export function removeCircularReferences( + value: any, + path = '', + ancestors = new Map() +): any { + if (typeof value !== 'object' || value === null) { + return value; + } + const ancestorPath = ancestors.get(value); + if (ancestorPath !== undefined) { + return `[Circular ${ancestorPath || '/'}]`; + } + ancestors.set(value, path); + const copy = Array.isArray(value) + ? value.map((item, index) => + removeCircularReferences(item, `${path}/${index}`, ancestors) + ) + : Object.fromEntries( + Object.entries(value).map(([key, item]) => [ + key, + removeCircularReferences( + item, + `${path}/${key.replace(/~/g, '~0').replace(/\//g, '~1')}`, + ancestors + ), + ]) + ); + ancestors.delete(value); + return copy; +} diff --git a/test/generateDiff.spec.ts b/test/generateDiff.spec.ts index e53d2da..823d53b 100644 --- a/test/generateDiff.spec.ts +++ b/test/generateDiff.spec.ts @@ -56,4 +56,30 @@ describe('Diff', () => { ) ).toStrictEqual(diffOutput); }); + + test('Check diff output with circular references through parser', async () => { + const specDocument = readFileSync( + resolve('./test/spec/asyncapi-v3-circular.yml'), + 'utf-8' + ); + const first = await parser.parse(specDocument); + const second = await parser.parse( + specDocument.replace('type: string', 'type: number') + ); + expect( + generateDiff(first.document?.json(), first.document?.json()) + ).toStrictEqual([]); + expect( + generateDiff(first.document?.json(), second.document?.json()) + ).toEqual( + expect.arrayContaining([ + { + action: 'edit', + path: '/channels/entities/messages/entityCreated/payload/properties/filters/items/anyOf/1/type', + before: 'string', + after: 'number', + }, + ]) + ); + }); }); diff --git a/test/helpers/DiffHelpers.spec.ts b/test/helpers/DiffHelpers.spec.ts index ca2e220..87e2f05 100644 --- a/test/helpers/DiffHelpers.spec.ts +++ b/test/helpers/DiffHelpers.spec.ts @@ -3,6 +3,7 @@ import { Operation } from 'fast-json-patch'; import { formatAction, getBeforeValue, + removeCircularReferences, setIndex, formatDiffOutput, getDocumentMajorVersion, @@ -92,3 +93,38 @@ describe('between different asyncapi version', () => { expect(incompatibleDocuments({asyncapi: '3.0.0'}, {asyncapi: '3.0.0'})).toBeFalsy(); }); }); + +describe('removeCircularReferences', () => { + test('replaces references back to an ancestor and keeps shared ones', () => { + const shared = { type: 'string' }; + const node: any = { a: shared, b: shared }; + node.items = [node]; + expect(removeCircularReferences(node)).toStrictEqual({ + a: { type: 'string' }, + b: { type: 'string' }, + items: ['[Circular /]'], + }); + }); + + test('names the ancestor, so redirecting a recursive reference is a change', () => { + const a: any = {}; + const b: any = {}; + a.child = b; + b.child = a; + const toA = removeCircularReferences(a); + b.child = b; + expect(toA).toStrictEqual({ child: { child: '[Circular /]' } }); + expect(removeCircularReferences(a)).toStrictEqual({ + child: { child: '[Circular /child]' }, + }); + }); + + test('escapes keys in the JSON pointer', () => { + const node: any = {}; + node['a/b~c'] = { back: node, self: null }; + node['a/b~c'].self = node['a/b~c']; + expect(removeCircularReferences(node)).toStrictEqual({ + 'a/b~c': { back: '[Circular /]', self: '[Circular /a~1b~0c]' }, + }); + }); +}); diff --git a/test/spec/asyncapi-v3-circular.yml b/test/spec/asyncapi-v3-circular.yml new file mode 100644 index 0000000..8b3b483 --- /dev/null +++ b/test/spec/asyncapi-v3-circular.yml @@ -0,0 +1,24 @@ +asyncapi: 3.0.0 +info: + title: Circular + version: 1.0.0 +channels: + entities: + address: entities + messages: + entityCreated: + payload: + $ref: '#/components/schemas/entity' +components: + schemas: + filters: + type: array + items: + anyOf: + - $ref: '#/components/schemas/filters' + - type: string + entity: + type: object + properties: + filters: + $ref: '#/components/schemas/filters'