summaryrefslogtreecommitdiff
path: root/ext/bg/js/json-schema.js
blob: 7a7f2489479734ebc71bfb9fed4b2c31d4ac79e7 (plain)
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
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
/*
 * Copyright (C) 2019-2020  Alex Yatskov <alex@foosoft.net>
 * Author: Alex Yatskov <alex@foosoft.net>
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */


class JsonSchemaProxyHandler {
    constructor(schema) {
        this._schema = schema;
    }

    getPrototypeOf(target) {
        return Object.getPrototypeOf(target);
    }

    setPrototypeOf() {
        throw new Error('setPrototypeOf not supported');
    }

    isExtensible(target) {
        return Object.isExtensible(target);
    }

    preventExtensions(target) {
        Object.preventExtensions(target);
        return true;
    }

    getOwnPropertyDescriptor(target, property) {
        return Object.getOwnPropertyDescriptor(target, property);
    }

    defineProperty() {
        throw new Error('defineProperty not supported');
    }

    has(target, property) {
        return property in target;
    }

    get(target, property) {
        if (typeof property === 'symbol') {
            return target[property];
        }

        if (Array.isArray(target)) {
            if (typeof property === 'string' && /^\d+$/.test(property)) {
                property = parseInt(property, 10);
            } else if (typeof property === 'string') {
                return target[property];
            }
        }

        const propertySchema = JsonSchemaProxyHandler.getPropertySchema(this._schema, property);
        if (propertySchema === null) {
            return;
        }

        const value = target[property];
        return value !== null && typeof value === 'object' ? JsonSchema.createProxy(value, propertySchema) : value;
    }

    set(target, property, value) {
        if (Array.isArray(target)) {
            if (typeof property === 'string' && /^\d+$/.test(property)) {
                property = parseInt(property, 10);
                if (property > target.length) {
                    throw new Error('Array index out of range');
                }
            } else if (typeof property === 'string') {
                target[property] = value;
                return true;
            }
        }

        const propertySchema = JsonSchemaProxyHandler.getPropertySchema(this._schema, property);
        if (propertySchema === null) {
            throw new Error(`Property ${property} not supported`);
        }

        value = JsonSchema.isolate(value);

        const error = JsonSchemaProxyHandler.validate(value, propertySchema);
        if (error !== null) {
            throw new Error(`Invalid value: ${error}`);
        }

        target[property] = value;
        return true;
    }

    deleteProperty(target, property) {
        const required = this._schema.required;
        if (Array.isArray(required) && required.includes(property)) {
            throw new Error(`${property} cannot be deleted`);
        }
        return Reflect.deleteProperty(target, property);
    }

    ownKeys(target) {
        return Reflect.ownKeys(target);
    }

    apply() {
        throw new Error('apply not supported');
    }

    construct() {
        throw new Error('construct not supported');
    }

    static getPropertySchema(schema, property) {
        const type = schema.type;
        if (Array.isArray(type)) {
            throw new Error(`Ambiguous property type for ${property}`);
        }
        switch (type) {
            case 'object':
            {
                const properties = schema.properties;
                if (JsonSchemaProxyHandler.isObject(properties)) {
                    if (Object.prototype.hasOwnProperty.call(properties, property)) {
                        return properties[property];
                    }
                }

                const additionalProperties = schema.additionalProperties;
                if (additionalProperties === false) {
                    return null;
                } if (JsonSchemaProxyHandler.isObject(additionalProperties)) {
                    return additionalProperties;
                } else {
                    return JsonSchemaProxyHandler._unconstrainedSchema;
                }
            }
            case 'array':
            {
                const items = schema.items;
                return JsonSchemaProxyHandler.isObject(items) ? items : null;
            }
            default:
                return null;
        }
    }

    static validate(value, schema) {
        let result = JsonSchemaProxyHandler.validateSingleSchema(value, schema);
        if (result !== null) { return result; }

        result = JsonSchemaProxyHandler.validateConditional(value, schema);
        if (result !== null) { return result; }

        result = JsonSchemaProxyHandler.validateAllOf(value, schema);
        if (result !== null) { return result; }

        result = JsonSchemaProxyHandler.validateAnyOf(value, schema);
        if (result !== null) { return result; }

        result = JsonSchemaProxyHandler.validateOneOf(value, schema);
        if (result !== null) { return result; }

        result = JsonSchemaProxyHandler.validateNoneOf(value, schema);
        if (result !== null) { return result; }

        return null;
    }

    static validateConditional(value, schema) {
        const ifCondition = schema.if;
        if (!JsonSchemaProxyHandler.isObject(ifCondition)) { return null; }

        const thenSchema = schema.then;
        if (JsonSchemaProxyHandler.isObject(thenSchema)) {
            const result = JsonSchemaProxyHandler.validate(value, thenSchema);
            if (result !== null) { return `then conditional didn't match: ${result}`; }
        }

        const elseSchema = schema.else;
        if (JsonSchemaProxyHandler.isObject(elseSchema)) {
            const result = JsonSchemaProxyHandler.validate(value, thenSchema);
            if (result !== null) { return `else conditional didn't match: ${result}`; }
        }

        return null;
    }

    static validateAllOf(value, schema) {
        const subSchemas = schema.allOf;
        if (!Array.isArray(subSchemas)) { return null; }

        for (let i = 0; i < subSchemas.length; ++i) {
            const result = JsonSchemaProxyHandler.validate(value, subSchemas[i]);
            if (result !== null) { return `allOf[${i}] schema didn't match: ${result}`; }
        }
        return null;
    }

    static validateAnyOf(value, schema) {
        const subSchemas = schema.anyOf;
        if (!Array.isArray(subSchemas)) { return null; }

        for (let i = 0; i < subSchemas.length; ++i) {
            const result = JsonSchemaProxyHandler.validate(value, subSchemas[i]);
            if (result === null) { return null; }
        }
        return '0 anyOf schemas matched';
    }

    static validateOneOf(value, schema) {
        const subSchemas = schema.oneOf;
        if (!Array.isArray(subSchemas)) { return null; }

        let count = 0;
        for (let i = 0; i < subSchemas.length; ++i) {
            const result = JsonSchemaProxyHandler.validate(value, subSchemas[i]);
            if (result === null) { ++count; }
        }
        return count === 1 ? null : `${count} oneOf schemas matched`;
    }

    static validateNoneOf(value, schema) {
        const subSchemas = schema.not;
        if (!Array.isArray(subSchemas)) { return null; }

        for (let i = 0; i < subSchemas.length; ++i) {
            const result = JsonSchemaProxyHandler.validate(value, subSchemas[i]);
            if (result === null) { return `not[${i}] schema matched`; }
        }
        return null;
    }

    static validateSingleSchema(value, schema) {
        const type = JsonSchemaProxyHandler.getValueType(value);
        const schemaType = schema.type;
        if (!JsonSchemaProxyHandler.isValueTypeAny(value, type, schemaType)) {
            return `Value type ${type} does not match schema type ${schemaType}`;
        }

        const schemaEnum = schema.enum;
        if (Array.isArray(schemaEnum) && !JsonSchemaProxyHandler.valuesAreEqualAny(value, schemaEnum)) {
            return 'Invalid enum value';
        }

        switch (type) {
            case 'number':
                return JsonSchemaProxyHandler.validateNumber(value, schema);
            case 'string':
                return JsonSchemaProxyHandler.validateString(value, schema);
            case 'array':
                return JsonSchemaProxyHandler.validateArray(value, schema);
            case 'object':
                return JsonSchemaProxyHandler.validateObject(value, schema);
            default:
                return null;
        }
    }

    static validateNumber(value, schema) {
        const multipleOf = schema.multipleOf;
        if (typeof multipleOf === 'number' && Math.floor(value / multipleOf) * multipleOf !== value) {
            return `Number is not a multiple of ${multipleOf}`;
        }

        const minimum = schema.minimum;
        if (typeof minimum === 'number' && value < minimum) {
            return `Number is less than ${minimum}`;
        }

        const exclusiveMinimum = schema.exclusiveMinimum;
        if (typeof exclusiveMinimum === 'number' && value <= exclusiveMinimum) {
            return `Number is less than or equal to ${exclusiveMinimum}`;
        }

        const maximum = schema.maximum;
        if (typeof maximum === 'number' && value > maximum) {
            return `Number is greater than ${maximum}`;
        }

        const exclusiveMaximum = schema.exclusiveMaximum;
        if (typeof exclusiveMaximum === 'number' && value >= exclusiveMaximum) {
            return `Number is greater than or equal to ${exclusiveMaximum}`;
        }

        return null;
    }

    static validateString(value, schema) {
        const minLength = schema.minLength;
        if (typeof minLength === 'number' && value.length < minLength) {
            return 'String length too short';
        }

        const maxLength = schema.minLength;
        if (typeof maxLength === 'number' && value.length > maxLength) {
            return 'String length too long';
        }

        return null;
    }

    static validateArray(value, schema) {
        const minItems = schema.minItems;
        if (typeof minItems === 'number' && value.length < minItems) {
            return 'Array length too short';
        }

        const maxItems = schema.maxItems;
        if (typeof maxItems === 'number' && value.length > maxItems) {
            return 'Array length too long';
        }

        return null;
    }

    static validateObject(value, schema) {
        const properties = new Set(Object.getOwnPropertyNames(value));

        const required = schema.required;
        if (Array.isArray(required)) {
            for (const property of required) {
                if (!properties.has(property)) {
                    return `Missing property ${property}`;
                }
            }
        }

        const minProperties = schema.minProperties;
        if (typeof minProperties === 'number' && properties.length < minProperties) {
            return 'Not enough object properties';
        }

        const maxProperties = schema.maxProperties;
        if (typeof maxProperties === 'number' && properties.length > maxProperties) {
            return 'Too many object properties';
        }

        for (const property of properties) {
            const propertySchema = JsonSchemaProxyHandler.getPropertySchema(schema, property);
            if (propertySchema === null) {
                return `No schema found for ${property}`;
            }
            const error = JsonSchemaProxyHandler.validate(value[property], propertySchema);
            if (error !== null) {
                return error;
            }
        }

        return null;
    }

    static isValueTypeAny(value, type, schemaTypes) {
        if (typeof schemaTypes === 'string') {
            return JsonSchemaProxyHandler.isValueType(value, type, schemaTypes);
        } else if (Array.isArray(schemaTypes)) {
            for (const schemaType of schemaTypes) {
                if (JsonSchemaProxyHandler.isValueType(value, type, schemaType)) {
                    return true;
                }
            }
            return false;
        }
        return true;
    }

    static isValueType(value, type, schemaType) {
        return (
            type === schemaType ||
            (schemaType === 'integer' && Math.floor(value) === value)
        );
    }

    static getValueType(value) {
        const type = typeof value;
        if (type === 'object') {
            if (value === null) { return 'null'; }
            if (Array.isArray(value)) { return 'array'; }
        }
        return type;
    }

    static valuesAreEqualAny(value1, valueList) {
        for (const value2 of valueList) {
            if (JsonSchemaProxyHandler.valuesAreEqual(value1, value2)) {
                return true;
            }
        }
        return false;
    }

    static valuesAreEqual(value1, value2) {
        return value1 === value2;
    }

    static getDefaultTypeValue(type) {
        if (typeof type === 'string') {
            switch (type) {
                case 'null':
                    return null;
                case 'boolean':
                    return false;
                case 'number':
                case 'integer':
                    return 0;
                case 'string':
                    return '';
                case 'array':
                    return [];
                case 'object':
                    return {};
            }
        }
        return null;
    }

    static getValidValueOrDefault(schema, value) {
        let type = JsonSchemaProxyHandler.getValueType(value);
        const schemaType = schema.type;
        if (!JsonSchemaProxyHandler.isValueTypeAny(value, type, schemaType)) {
            let assignDefault = true;

            const schemaDefault = schema.default;
            if (typeof schemaDefault !== 'undefined') {
                value = JsonSchema.isolate(schemaDefault);
                type = JsonSchemaProxyHandler.getValueType(value);
                assignDefault = !JsonSchemaProxyHandler.isValueTypeAny(value, type, schemaType);
            }

            if (assignDefault) {
                value = JsonSchemaProxyHandler.getDefaultTypeValue(schemaType);
                type = JsonSchemaProxyHandler.getValueType(value);
            }
        }

        switch (type) {
            case 'object':
                value = JsonSchemaProxyHandler.populateObjectDefaults(value, schema);
                break;
            case 'array':
                value = JsonSchemaProxyHandler.populateArrayDefaults(value, schema);
                break;
        }

        return value;
    }

    static populateObjectDefaults(value, schema) {
        const properties = new Set(Object.getOwnPropertyNames(value));

        const required = schema.required;
        if (Array.isArray(required)) {
            for (const property of required) {
                properties.delete(property);

                const propertySchema = JsonSchemaProxyHandler.getPropertySchema(schema, property);
                if (propertySchema === null) { continue; }
                value[property] = JsonSchemaProxyHandler.getValidValueOrDefault(propertySchema, value[property]);
            }
        }

        for (const property of properties) {
            const propertySchema = JsonSchemaProxyHandler.getPropertySchema(schema, property);
            if (propertySchema === null) {
                Reflect.deleteProperty(value, property);
            } else {
                value[property] = JsonSchemaProxyHandler.getValidValueOrDefault(propertySchema, value[property]);
            }
        }

        return value;
    }

    static populateArrayDefaults(value, schema) {
        for (let i = 0, ii = value.length; i < ii; ++i) {
            const propertySchema = JsonSchemaProxyHandler.getPropertySchema(schema, i);
            if (propertySchema === null) { continue; }
            value[i] = JsonSchemaProxyHandler.getValidValueOrDefault(propertySchema, value[i]);
        }

        return value;
    }

    static isObject(value) {
        return typeof value === 'object' && value !== null && !Array.isArray(value);
    }
}

JsonSchemaProxyHandler._unconstrainedSchema = {};

class JsonSchema {
    static createProxy(target, schema) {
        return new Proxy(target, new JsonSchemaProxyHandler(schema));
    }

    static getValidValueOrDefault(schema, value) {
        return JsonSchemaProxyHandler.getValidValueOrDefault(schema, value);
    }

    static isolate(value) {
        if (value === null) { return null; }

        switch (typeof value) {
            case 'boolean':
            case 'number':
            case 'string':
            case 'bigint':
            case 'symbol':
                return value;
        }

        const stringValue = JSON.stringify(value);
        return typeof stringValue === 'string' ? JSON.parse(stringValue) : null;
    }
}