UNPKG

1.56 kBJavaScriptView Raw
1'use strict';
2
3var $ = require('./util/helpers');
4
5$.findByRef = require('./util/find-reference');
6$.resolveSchema = require('./util/resolve-schema');
7$.normalizeSchema = require('./util/normalize-schema');
8
9var instance = module.exports = function() {
10 function $ref(fakeroot, schema, refs, ex) {
11 if (typeof fakeroot === 'object') {
12 ex = refs;
13 refs = schema;
14 schema = fakeroot;
15 fakeroot = undefined;
16 }
17
18 if (typeof schema !== 'object') {
19 throw new Error('schema must be an object');
20 }
21
22 if (typeof refs === 'object' && refs !== null) {
23 var aux = refs;
24
25 refs = [];
26
27 for (var k in aux) {
28 aux[k].id = aux[k].id || k;
29 refs.push(aux[k]);
30 }
31 }
32
33 if (typeof refs !== 'undefined' && !Array.isArray(refs)) {
34 ex = !!refs;
35 refs = [];
36 }
37
38 function push(ref) {
39 if (typeof ref.id === 'string') {
40 var id = $.resolveURL(fakeroot, ref.id).replace(/\/#?$/, '');
41
42 if (id.indexOf('#') > -1) {
43 var parts = id.split('#');
44
45 if (parts[1].charAt() === '/') {
46 id = parts[0];
47 } else {
48 id = parts[1] || parts[0];
49 }
50 }
51
52 if (!$ref.refs[id]) {
53 $ref.refs[id] = ref;
54 }
55 }
56 }
57
58 (refs || []).concat([schema]).forEach(function(ref) {
59 schema = $.normalizeSchema(fakeroot, ref, push);
60 push(schema);
61 });
62
63 return $.resolveSchema(schema, $ref.refs, ex);
64 }
65
66 $ref.refs = {};
67 $ref.util = $;
68
69 return $ref;
70};
71
72instance.util = $;