-
Notifications
You must be signed in to change notification settings - Fork 17
/
register-handler.js
93 lines (73 loc) · 2.36 KB
/
register-handler.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
/**
* Copyright 2015 Urban Airship Inc. and Contributors. Subject to the LICENSE
* file at the top-level directory of this distribution and at
* https://github.com/urbanairship/frock/blob/master/LICENSE
*/
const bole = require('bole')
const {sync: resolve} = require('resolve')
const semver = require('semver')
const {extensions} = require('interpret')
const rechoir = require('rechoir')
const pkg = require('../package.json')
const log = bole('frock/register-handler')
module.exports = createHandlerRegister
function createHandlerRegister (pwd, _require = require) {
const handlers = new Map()
const paths = new Map()
handlers.register = register
handlers.destroy = destroy
return handlers
function register (name) {
if (handlers.has(name)) {
return handlers.get(name)
}
const handlerPath = resolve(name, {basedir: pwd, extensions: ['.js', '.ts']})
try {
rechoir.prepare(extensions, handlerPath)
} catch (e) {
// pass, but log the error
log.error(`Error preparing transform for ${name}\n ${e.message}`)
}
const handler = _require(handlerPath)
handlers.set(name, handler.default || handler)
paths.set(name, handlerPath)
// only perform package version checks for installable mocks
if (handlerPath.includes('node_modules')) {
let pkgPath
let lpkg
try {
pkgPath = resolve(
name.replace(/\/$/, '') + '/package.json',
{basedir: pwd}
)
lpkg = _require(pkgPath)
} catch (e) {
log.debug(`unable to require path ${e.message}`)
}
if (lpkg && lpkg.frock && lpkg.frock['compatible-versions']) {
const compat = lpkg.frock['compatible-versions']
if (!semver.satisfies(pkg.version, compat)) {
log.warn(
`handler ${name} claims compatibility with ${compat}, but you ` +
`are using frock version ${pkg.version}. You may experience ` +
`unexpected behavior.`
)
}
} else {
log.warn(
`handler ${name} did not specify its compatible frock versions!`
)
}
}
log.debug(`registered handler ${name}`)
return handler
}
function destroy () {
log.debug(`unloading all required handlers`)
for (let val of paths.values()) {
delete _require.cache[val]
}
handlers.clear()
paths.clear()
}
}