Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 52 additions & 0 deletions src/open-api/utils/dereference.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,57 @@
import { dereference } from './dereference.js'

it('follows chained $ref pointers to a leaf value', async () => {
await expect(
dereference({
foo: {
$ref: '#/components/schemas/A',
},
components: {
schemas: {
A: { $ref: '#/components/schemas/B' },
B: { $ref: '#/components/schemas/C' },
C: { type: 'string' },
},
},
}),
).resolves.toMatchInlineSnapshot(`
{
"components": {
"schemas": {
"A": {
"type": "string",
},
"B": {
"type": "string",
},
"C": {
"type": "string",
},
},
},
"foo": {
"type": "string",
},
}
`)
})

it('throws when a $ref chain is circular', async () => {
await expect(
dereference({
foo: {
$ref: '#/components/schemas/A',
},
components: {
schemas: {
A: { $ref: '#/components/schemas/B' },
B: { $ref: '#/components/schemas/A' },
},
},
}),
).rejects.toThrow(/circular \$ref chain/i)
})

it('dereferences', async () => {
await expect(
dereference({
Expand Down
24 changes: 22 additions & 2 deletions src/open-api/utils/dereference.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,28 @@ export async function dereference(document: unknown, root?: any): Promise<any> {

if (typeof document === 'object' && document !== null) {
if ('$ref' in document && typeof document['$ref'] === 'string') {
const path = pointerToPath(document['$ref'])
return path.reduce((item, key) => item[key], root)
const visited = new Set<string>()
let resolved: any = document
while (
resolved !== null &&
typeof resolved === 'object' &&
'$ref' in resolved &&
typeof resolved['$ref'] === 'string'
) {
const ref = resolved['$ref']
if (visited.has(ref)) {
throw new Error(
`Failed to dereference document: circular $ref chain detected (${[
...visited,
ref,
].join(' -> ')})`,
)
}
visited.add(ref)
const path = pointerToPath(ref)
resolved = path.reduce((item, key) => item[key], root)
}
return dereference(resolved, root)
}

await Promise.all(
Expand Down