Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
80698 views
1
'use strict';
2
3
/*eslint-disable max-len*/
4
5
var common = require('./common');
6
var YAMLException = require('./exception');
7
var Type = require('./type');
8
9
10
function compileList(schema, name, result) {
11
var exclude = [];
12
13
schema.include.forEach(function (includedSchema) {
14
result = compileList(includedSchema, name, result);
15
});
16
17
schema[name].forEach(function (currentType) {
18
result.forEach(function (previousType, previousIndex) {
19
if (previousType.tag === currentType.tag) {
20
exclude.push(previousIndex);
21
}
22
});
23
24
result.push(currentType);
25
});
26
27
return result.filter(function (type, index) {
28
return -1 === exclude.indexOf(index);
29
});
30
}
31
32
33
function compileMap(/* lists... */) {
34
var result = {}, index, length;
35
36
function collectType(type) {
37
result[type.tag] = type;
38
}
39
40
for (index = 0, length = arguments.length; index < length; index += 1) {
41
arguments[index].forEach(collectType);
42
}
43
44
return result;
45
}
46
47
48
function Schema(definition) {
49
this.include = definition.include || [];
50
this.implicit = definition.implicit || [];
51
this.explicit = definition.explicit || [];
52
53
this.implicit.forEach(function (type) {
54
if (type.loadKind && 'scalar' !== type.loadKind) {
55
throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.');
56
}
57
});
58
59
this.compiledImplicit = compileList(this, 'implicit', []);
60
this.compiledExplicit = compileList(this, 'explicit', []);
61
this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit);
62
}
63
64
65
Schema.DEFAULT = null;
66
67
68
Schema.create = function createSchema() {
69
var schemas, types;
70
71
switch (arguments.length) {
72
case 1:
73
schemas = Schema.DEFAULT;
74
types = arguments[0];
75
break;
76
77
case 2:
78
schemas = arguments[0];
79
types = arguments[1];
80
break;
81
82
default:
83
throw new YAMLException('Wrong number of arguments for Schema.create function');
84
}
85
86
schemas = common.toArray(schemas);
87
types = common.toArray(types);
88
89
if (!schemas.every(function (schema) { return schema instanceof Schema; })) {
90
throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.');
91
}
92
93
if (!types.every(function (type) { return type instanceof Type; })) {
94
throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.');
95
}
96
97
return new Schema({
98
include: schemas,
99
explicit: types
100
});
101
};
102
103
104
module.exports = Schema;
105
106