forked from jestjs/jest
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathwatch_plugin_registry.js
More file actions
80 lines (68 loc) · 2.28 KB
/
watch_plugin_registry.js
File metadata and controls
80 lines (68 loc) · 2.28 KB
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
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {WatchPlugin} from '../types';
import getType from 'jest-get-type';
const RESERVED_KEYS = [
0x03, // Jest should handle ctrl-c interrupt
];
export default class WatchPluginRegistry {
_rootDir: string;
_watchPluginsByKey: Map<number, WatchPlugin>;
constructor(rootDir: string) {
this._rootDir = rootDir;
this._watchPluginsByKey = new Map();
}
loadPluginPath(pluginModulePath: string) {
// $FlowFixMe dynamic require
let maybePlugin = require(pluginModulePath);
// Since we're loading the module from a dynamic path, assert its shape
// before assuming it's a valid watch plugin.
if (getType(maybePlugin) !== 'object') {
throw new Error(
`Jest watch plugin ${pluginModulePath} must be an ES Module or export an object`,
);
}
if (getType(maybePlugin.default) === 'object') {
maybePlugin = maybePlugin.default;
}
if (getType(maybePlugin.key) !== 'number') {
throw new Error(
`Jest watch plugin ${pluginModulePath} must export 'key' as a number`,
);
}
if (getType(maybePlugin.prompt) !== 'string') {
throw new Error(
`Jest watch plugin ${pluginModulePath} must export 'prompt' as a string`,
);
}
if (getType(maybePlugin.apply) !== 'function') {
throw new Error(
`Jest watch plugin ${pluginModulePath} must export 'apply' as a function`,
);
}
const plugin: WatchPlugin = ((maybePlugin: any): WatchPlugin);
if (RESERVED_KEYS.includes(maybePlugin.key)) {
throw new Error(
`Jest watch plugin ${pluginModulePath} tried to register reserved key ${String.fromCodePoint(
maybePlugin.key,
)}`,
);
}
// TODO: Reject registering when another plugin has claimed the key?
this._watchPluginsByKey.set(plugin.key, plugin);
}
getPluginByPressedKey(pressedKey: number): ?WatchPlugin {
return this._watchPluginsByKey.get(pressedKey);
}
getPluginsOrderedByKey(): Array<WatchPlugin> {
return Array.from(this._watchPluginsByKey.values()).sort(
(a, b) => a.key - b.key,
);
}
}