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
18 changes: 17 additions & 1 deletion lib/types/keys.js
Original file line number Diff line number Diff line change
Expand Up @@ -602,7 +602,23 @@ module.exports = Any.extend({
if (schema.$_terms.keys) {
const topo = new Topo.Sorter();
for (const child of schema.$_terms.keys) {
Common.tryWithPath(() => topo.add(child, { after: child.schema.$_rootReferences(), group: child.key }), child.key);
Common.tryWithPath(() => topo.add(child, { after: child.schema.$_rootReferences(), group: child.key, manual: true }), child.key);

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Very nice find! Though I'd go for a less repetitive version like calling an external function:

schema.$_terms.keys = new internals.Keys(...internals.sortKeys(schema.$_terms.keys));

.....

internals.sortKeys = function (keys, manual = true) {

    const topo = new Topo.Sorter();
    for (const child of keys) {
        Common.tryWithPath(() => topo.add(child, { after: child.schema.$_rootReferences(), group: child.key, manual }), child.key);
    }

    try {
        return topo.sort();
    }
    catch {
        return internals.sortKeys(keys, false);
    }
};

}

try {
topo.sort();
}
catch (err) {
// Sorting failed (e.g. circular references). Replay the adds one at a
// time, sorting after each, to identify the offending key in the error.
const detailed = new Topo.Sorter();
for (const child of schema.$_terms.keys) {
Common.tryWithPath(() => detailed.add(child, { after: child.schema.$_rootReferences(), group: child.key }), child.key);
}

// The replay above always throws first - this is an unreachable safety net

throw err; // $lab:coverage:ignore$
}

schema.$_terms.keys = new internals.Keys(...topo.nodes);
Expand Down
25 changes: 25 additions & 0 deletions test/types/object.js
Original file line number Diff line number Diff line change
Expand Up @@ -1638,6 +1638,31 @@ describe('object', () => {
[{ type: 'a', set: true, flag: true }, false, '"flag" must be [false]']
]);
});

it('errors on circular references between sibling keys', () => {

const err = expect(() => {

Joi.object({
a: Joi.ref('b'),
b: Joi.ref('a')
});
}).to.throw('item added into group b created a dependencies error');

expect(err.path).to.equal('b');
});

it('errors on circular references introduced by rebuild', () => {

const schema = Joi.object({
a: Joi.any(),
b: Joi.any()
})
.fork('a', (s) => s.default(Joi.ref('b')));

const err = expect(() => schema.fork('b', (s) => s.default(Joi.ref('a')))).to.throw('item added into group a created a dependencies error');
expect(err.path).to.equal('a');
});
});

describe('length()', () => {
Expand Down