-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
48 lines (41 loc) · 1.14 KB
/
index.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
/**
* Copyright 2020 - Frederik Ring <frederik.ring@gmail.com>
* SPDX-License-Identifier: MIT
*/
var through = require('through2')
var Ajv = require('ajv')
var pack = require('ajv-pack')
var ajv = new Ajv({ sourceCode: true })
module.exports = transform
var isSchemaRe = /\.schema$/
var isSchemaSecure = ajv.compile(require('ajv/lib/refs/json-schema-secure.json'))
function transform (file, options) {
options = Object.assign({ secure: true }, options)
var matcher = options.matcher
? new RegExp(options.matcher)
: isSchemaRe
if (!matcher.test(file)) {
return through()
}
var buf = ''
return through(function (chunk, enc, next) {
buf += chunk
next()
}, function (done) {
var moduleCode
try {
var schema = JSON.parse(buf)
if (options.secure && !isSchemaSecure(schema)) {
throw new Error(
'Schema "' + file + '" is not secure, will not compile: ' + JSON.stringify(isSchemaSecure.errors)
)
}
var validate = ajv.compile(schema)
moduleCode = pack(ajv, validate)
} catch (err) {
return done(err)
}
this.push(moduleCode)
this.push(null)
})
}