-
Notifications
You must be signed in to change notification settings - Fork 56
/
resolver.js
414 lines (343 loc) · 14.4 KB
/
resolver.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
/* global WeakMap */
const Joi = require('joi');
const Util = require('util');
const Hoek = require('@hapi/hoek');
const Bourne = require('@hapi/bourne');
function randomString(length) {
return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}
class SchemaResolver {
constructor(root, { subSchemas, refineType, refineSchema, strictMode, useDefaults, extensions = [] }) {
this.root = root;
this.subSchemas = subSchemas;
this.refineType = refineType;
this.refineSchema = refineSchema;
this.strictMode = strictMode;
this.walkedSchemas = new WeakMap(); // map of schemas iterated thus far to the generated id they were given
this.useDefaults = useDefaults;
this.joi = Joi.extend(
{
type: 'object',
base: Joi.object(),
coerce: {
from: 'string',
method(value) {
if (typeof value !== 'string' || (value[0] !== '{' && !/^\s*\{/.test(value))) {
return;
}
try {
return { value: Bourne.parse(value) };
} catch (ignoreErr) { } // eslint-disable-line no-empty
}
}
},
{
type: 'array',
base: Joi.array(),
coerce: {
from: 'string',
method(value) {
if (typeof value !== 'string' || (value[0] !== '[' && !/^\s*\[/.test(value))) {
return;
}
try {
return { value: Bourne.parse(value) };
} catch (ignoreErr) { } // eslint-disable-line no-empty
}
}
},
...extensions
);
}
resolve(schema = this.root, ancestors = []) {
let resolvedSchema;
let generatedId = this.walkedSchemas.get(schema);
if (generatedId && ancestors.lastIndexOf(generatedId) > -1) {
// resolve cyclic schema by using joi reference via generated unique ids
return this.resolveLink(schema)
} else if (typeof schema === 'object') {
generatedId = randomString(10)
this.walkedSchemas.set(schema, generatedId)
}
if (typeof schema === 'string') {
// If schema is itself a string, interpret it as a type
resolvedSchema = this.resolveType({ type: schema });
} else if (schema.$ref) {
resolvedSchema = this.resolve(this.resolveReference(schema.$ref), ancestors.concat(generatedId));
} else {
const partialSchemas = [];
if (schema.type) {
partialSchemas.push(this.resolveType(schema, ancestors.concat(generatedId)));
} else if (schema.properties) {
// if no type is specified, just properties
partialSchemas.push(this.object(schema, ancestors.concat(generatedId)))
} else if (schema.format) {
// if no type is specified, just format
partialSchemas.push(this.string(schema))
} else if (schema.enum) {
// If no type is specified, just enum
partialSchemas.push(this.joi.any().valid(...schema.enum));
}
if (schema.anyOf) {
partialSchemas.push(this.resolveAnyOf(schema, ancestors.concat(generatedId)));
}
if (schema.allOf) {
partialSchemas.push(this.resolveAllOf(schema, ancestors.concat(generatedId)));
}
if (schema.oneOf) {
partialSchemas.push(this.resolveOneOf(schema, ancestors.concat(generatedId)));
}
if (schema.not) {
partialSchemas.push(this.resolveNot(schema, ancestors.concat(generatedId)));
}
if (partialSchemas.length === 0) {
//Fall through to whatever.
//eslint-disable-next-line no-console
console.warn('WARNING: schema missing a \'type\' or \'$ref\' or \'enum\': \n%s', JSON.stringify(schema, null, 2));
//TODO: Handle better
partialSchemas.push(this.joi.any());
}
resolvedSchema = partialSchemas.length === 1 ? partialSchemas[0] : this.joi.alternatives(partialSchemas).match('all');
}
if (generatedId) {
// we have finished resolving the schema, now attach the id generated earlier
resolvedSchema = resolvedSchema.id(this.walkedSchemas.get(schema))
}
if (this.refineSchema) {
resolvedSchema = this.refineSchema(resolvedSchema, schema);
}
if (this.useDefaults && schema.default !== undefined) {
resolvedSchema = resolvedSchema.default(schema.default)
}
return resolvedSchema;
}
resolveReference(value) {
let refschema;
const id = value.substr(0, value.indexOf('#') + 1);
const path = value.substr(value.indexOf('#') + 1);
if (id && this.subSchemas) {
refschema = this.subSchemas[id] || this.subSchemas[id.substr(0, id.length - 1)];
}
if (!refschema) {
refschema = this.root;
}
Hoek.assert(refschema, 'Can not find schema reference: ' + value + '.');
let fragment = refschema;
const paths = path.split('/');
for (let i = 1; i < paths.length && fragment; i++) {
fragment = typeof fragment === 'object' && fragment[paths[i]];
}
return fragment;
}
resolveType(schema, ancestors) {
let joischema;
const typeDefinitionMap = {
description: 'description',
title: 'label',
default: 'default'
};
const joitype = (type, format) => {
let joischema;
if (this.refineType) {
type = this.refineType(type, format);
}
switch (type) {
case 'array':
joischema = this.array(schema, ancestors);
break;
case 'boolean':
joischema = this.joi.boolean();
break;
case 'integer':
case 'number':
joischema = this.number(schema);
break;
case 'object':
joischema = this.object(schema, ancestors);
break;
case 'string':
joischema = this.string(schema);
break;
case 'null':
joischema = this.joi.any().valid(null);
break;
default:
joischema = this.joi.types()[type];
}
Hoek.assert(joischema, 'Could not resolve type: ' + schema.type + '.');
return joischema.strict(this.strictMode);
}
if (Util.isArray(schema.type)) {
const schemas = [];
for (let i = 0; i < schema.type.length; i++) {
schemas.push(joitype(schema.type[i], schema.format));
}
joischema = this.joi.alternatives(schemas);
}
else {
joischema = joitype(schema.type, schema.format);
}
Object.keys(typeDefinitionMap).forEach(function (key) {
if (schema[key] !== undefined) {
joischema = joischema[typeDefinitionMap[key]](schema[key]);
}
});
return joischema;
}
resolveOneOf(schema, ancestors) {
Hoek.assert(Util.isArray(schema.oneOf), 'Expected oneOf to be an array.');
return this.joi.alternatives(schema.oneOf.map(schema => this.resolve(schema, ancestors))).match('one');
}
resolveAnyOf(schema, ancestors) {
Hoek.assert(Util.isArray(schema.anyOf), 'Expected anyOf to be an array.');
return this.joi.alternatives(schema.anyOf.map(schema => this.resolve(schema, ancestors))).match('any');
}
resolveAllOf(schema, ancestors) {
Hoek.assert(Util.isArray(schema.allOf), 'Expected allOf to be an array.');
return this.joi.alternatives(schema.allOf.map(schema => this.resolve(schema, ancestors))).match('all');
}
resolveNot(schema, ancestors) {
Hoek.assert(Util.isObject(schema.not), 'Expected Not to be an object.');
return this.joi.alternatives().conditional(
'.',
{
not: this.resolve(schema.not, ancestors),
then: this.joi.any(),
otherwise: this.joi.any().forbidden()
}
);
}
resolveLink(schema) {
return this.joi.link().ref(`#${this.walkedSchemas.get(schema)}`)
}
object(schema, ancestors) {
const resolveproperties = () => {
const schemas = {};
if (!Util.isObject(schema.properties)) {
return;
}
Object.keys(schema.properties).forEach((key) => {
const property = schema.properties[key];
let joischema = this.resolve(property, ancestors);
if (schema.required && !!~schema.required.indexOf(key)) {
joischema = joischema.required();
}
schemas[key] = joischema;
});
return schemas;
}
let joischema = this.joi.object(resolveproperties(schema));
if (Util.isObject(schema.additionalProperties)) {
joischema = joischema.pattern(/^/, this.resolve(schema.additionalProperties, ancestors));
} else {
joischema = joischema.unknown(schema.additionalProperties !== false);
}
Util.isNumber(schema.minProperties) && (joischema = joischema.min(schema.minProperties));
Util.isNumber(schema.maxProperties) && (joischema = joischema.max(schema.maxProperties));
return joischema;
}
array(schema, ancestors) {
let joischema = this.joi.array();
let items;
const resolveAsArray = (value) => {
if (Util.isArray(value)) {
// found an array, thus its _per type_
return value.map((v) => this.resolve(v, ancestors));
}
// it's a single entity, so just resolve it normally
return [this.resolve(value, ancestors)];
}
if (schema.items) {
items = resolveAsArray(schema.items);
joischema = joischema.items(...items);
}
else if (schema.ordered) {
items = resolveAsArray(schema.ordered);
joischema = joischema.ordered(...items);
}
if (items && schema.additionalItems === false) {
joischema = joischema.max(items.length);
}
Util.isNumber(schema.minItems) && (joischema = joischema.min(schema.minItems));
Util.isNumber(schema.maxItems) && (joischema = joischema.max(schema.maxItems));
if (schema.uniqueItems) {
joischema = joischema.unique();
}
return joischema;
}
number(schema) {
let joischema = this.joi.number();
if (schema.type === 'integer') {
joischema = joischema.integer();
}
Util.isNumber(schema.minimum) && (joischema = joischema.min(schema.minimum));
Util.isNumber(schema.maximum) && (joischema = joischema.max(schema.maximum));
Util.isNumber(schema.exclusiveMinimum) && (joischema = joischema.greater(schema.exclusiveMinimum));
Util.isNumber(schema.exclusiveMaximum) && (joischema = joischema.less(schema.exclusiveMaximum));
Util.isNumber(schema.multipleOf) && schema.multipleOf !== 0 && (joischema = joischema.multiple(schema.multipleOf));
return joischema;
}
string(schema) {
let joischema = this.joi.string();
const dateRegex = '(\\d{4})-(0[1-9]|1[0-2])-(0[1-9]|[12][0-9]|3[01])';
const timeRegex = '([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9]|60)(.[0-9]+)?(Z|(\\+|-)([01][0-9]|2[0-3]):([0-5][0-9]))';
const dateTimeRegex = dateRegex + 'T' + timeRegex;
if (schema.enum) {
return this.joi.string().valid(...schema.enum);
}
switch (schema.format) {
case 'date':
return joischema.regex(new RegExp('^' + dateRegex + '$', 'i'), 'JsonSchema date format');
case 'time':
return joischema.regex(new RegExp('^' + timeRegex + '$', 'i'), 'JsonSchema time format');
case 'date-time':
return joischema.regex(new RegExp('^' + dateTimeRegex + '$', 'i'), 'JsonSchema date-time format');
case 'binary':
joischema = this.binary(schema);
break;
case 'email':
return joischema.email();
case 'hostname':
return joischema.hostname();
case 'ipv4':
return joischema.ip({
version: ['ipv4']
});
case 'ipv6':
return joischema.ip({
version: ['ipv6']
});
case 'uri':
return joischema.uri();
case 'byte':
joischema = joischema.base64();
break;
case 'uuid':
return joischema.guid({ version: ['uuidv4'] });
case 'guid':
return joischema.guid();
}
return this.regularString(schema, joischema);
}
regularString(schema, joischema) {
schema.pattern && (joischema = joischema.regex(new RegExp(schema.pattern)));
if (Util.isUndefined(schema.minLength)) {
schema.minLength = 0;
if (!schema.pattern && !schema.format) {
joischema = joischema.allow('');
}
} else if (schema.minLength === 0) {
joischema = joischema.allow('');
}
Util.isNumber(schema.minLength) && (joischema = joischema.min(schema.minLength));
Util.isNumber(schema.maxLength) && (joischema = joischema.max(schema.maxLength));
return joischema;
}
binary(schema) {
let joischema = this.joi.binary();
Util.isNumber(schema.minLength) && (joischema = joischema.min(schema.minLength));
Util.isNumber(schema.maxLength) && (joischema = joischema.max(schema.maxLength));
return joischema;
}
}
module.exports = SchemaResolver;