/
importer.ts
194 lines (170 loc) · 6.18 KB
/
importer.ts
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
import { ModulePatcher, TBabelCore, TBabelJest, TTypeScript } from '../types'
import { rootLogger } from './logger'
import { Memoize } from './memoize'
import { Errors, Helps, ImportReasons, interpolate } from './messages'
import { VersionCheckers } from './version-checkers'
const logger = rootLogger.child({ namespace: 'Importer' })
// When adding an optional dependency which has another reason, add the reason in ImportReasons, and
// create a new method in Importer. Thus uses the importer.yourMethod(ImportReasons.TheReason)
// in the relevant code, so that the user knows why it needs it and how to install it in the
// case it can't import.
interface ImportOptions {
alternatives?: string[]
installTip?: string | Array<{ module: string; label: string }>
}
const passThru = (action: () => void) => (input: any) => {
action()
return input
}
/**
* @internal
*/
export class Importer {
@Memoize()
static get instance() {
logger.debug('creating Importer singleton')
// here we can define patches to apply to modules.
// it could be fixes that are not deployed, or
// abstractions so that multiple versions work the same
return new Importer({
'@babel/core': [passThru(VersionCheckers.babelCore.warn)],
'babel-jest': [passThru(VersionCheckers.babelJest.warn)],
typescript: [passThru(VersionCheckers.typescript.warn)],
jest: [passThru(VersionCheckers.jest.warn)],
})
}
constructor(protected _patches: { [moduleName: string]: ModulePatcher[] } = {}) {}
babelJest(why: ImportReasons): TBabelJest {
return this._import(why, 'babel-jest')
}
babelCore(why: ImportReasons): TBabelCore {
return this._import(why, '@babel/core')
}
typescript(why: ImportReasons, which: string): TTypeScript {
return this._import(why, which)
}
@Memoize((...args: string[]) => args.join(':'))
tryThese(moduleName: string, ...fallbacks: string[]) {
let name: string
let loaded: RequireResult<true> | undefined
const tries = [moduleName, ...fallbacks]
// tslint:disable-next-line:no-conditional-assignment
while ((name = tries.shift() as string) !== undefined) {
const req = requireWrapper(name)
// remove exports from what we're going to log
const contextReq: any = { ...req }
delete contextReq.exports
if (req.exists) {
// module exists
loaded = req as RequireResult<true>
if (loaded.error) {
// require-ing it failed
logger.error({ requireResult: contextReq }, `failed loading module '${name}'`, loaded.error.message)
} else {
// it has been loaded, let's patch it
logger.debug({ requireResult: contextReq }, 'loaded module', name)
loaded.exports = this._patch(name, loaded.exports)
}
break
} else {
// module does not exists in the path
logger.debug({ requireResult: contextReq }, `module '${name}' not found`)
continue
}
}
// return the loaded one, could be one that has been loaded, or one which has failed during load
// but not one which does not exists
return loaded
}
tryTheseOr<T>(moduleNames: [string, ...string[]] | string, missingResult: T, allowLoadError?: boolean): T
tryTheseOr<T>(moduleNames: [string, ...string[]] | string, missingResult?: T, allowLoadError?: boolean): T | undefined
tryTheseOr<T>(moduleNames: [string, ...string[]] | string, missingResult?: T, allowLoadError = false): T | undefined {
const args: [string, ...string[]] = Array.isArray(moduleNames) ? moduleNames : [moduleNames]
const result = this.tryThese(...args)
if (!result) return missingResult
if (!result.error) return result.exports as T
if (allowLoadError) return missingResult
throw result.error
}
@Memoize(name => name)
protected _patch<T>(name: string, unpatched: T): T {
if (name in this._patches) {
logger.debug('patching', name)
return this._patches[name].reduce((mod, patcher) => patcher(mod), unpatched)
}
return unpatched
}
protected _import(
why: string,
moduleName: string,
{ alternatives = [], installTip = moduleName }: ImportOptions = {},
): any {
// try to load any of the alternative after trying main one
const res = this.tryThese(moduleName, ...alternatives)
// if we could load one, return it
if (res && res.exists) {
if (!res.error) return res.exports
// it could not load because of a failure while importing, but it exists
throw new Error(interpolate(Errors.LoadingModuleFailed, { module: res.given, error: res.error.message }))
}
// if it couldn't load, build a nice error message so the user can fix it by himself
const msg = alternatives.length ? Errors.UnableToLoadAnyModule : Errors.UnableToLoadOneModule
const loadModule = [moduleName, ...alternatives].map(m => `"${m}"`).join(', ')
if (typeof installTip === 'string') {
installTip = [{ module: installTip, label: `install "${installTip}"` }]
}
const fix = installTip
.map(tip => {
return ` ${installTip.length === 1 ? '↳' : '•'} ${interpolate(Helps.FixMissingModule, tip)}`
})
.join('\n')
throw new Error(
interpolate(msg, {
module: loadModule,
reason: why,
fix,
}),
)
}
}
/**
* @internal
*/
export const importer = Importer.instance
/**
* @internal
*/
export interface RequireResult<E = boolean> {
exists: E
given: string
path?: string
exports?: any
error?: Error
}
function requireWrapper(moduleName: string): RequireResult {
let path: string
let exists = false
try {
path = resolveModule(moduleName)
exists = true
} catch (error) {
return { error, exists, given: moduleName }
}
const result: RequireResult = { exists, path, given: moduleName }
try {
result.exports = requireModule(moduleName)
} catch (error) {
result.error = error
}
return result
}
let requireModule = (mod: string) => require(mod)
let resolveModule = (mod: string) => require.resolve(mod)
/**
* @internal
*/
// so that we can test easier
export function __requireModule(localRequire: typeof requireModule, localResolve: typeof resolveModule) {
requireModule = localRequire
resolveModule = localResolve
}