-
-
Notifications
You must be signed in to change notification settings - Fork 6.5k
/
worker.js
88 lines (78 loc) · 2.36 KB
/
worker.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
/**
* Copyright (c) 2014-present, Facebook, Inc. All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
import type {SerializableError} from 'types/TestResult';
import type {HasteImpl, WorkerMessage, WorkerCallback} from './types';
import path from 'path';
import docblock from 'jest-docblock';
import fs from 'graceful-fs';
import H from './constants';
import extractRequires from './lib/extract_requires';
const JSON_EXTENSION = '.json';
const PACKAGE_JSON = path.sep + 'package' + JSON_EXTENSION;
let hasteImpl: ?HasteImpl = null;
let hasteImplModulePath: ?string = null;
const formatError = (error: string | Error): SerializableError => {
if (typeof error === 'string') {
return {
message: error,
stack: null,
type: 'Error',
};
}
return {
code: error.code || undefined,
message: error.message,
stack: error.stack,
type: 'Error',
};
};
// Cannot be ESM export or worker-farm is confused
module.exports = (data: WorkerMessage, callback: WorkerCallback): void => {
if (
data.hasteImplModulePath &&
data.hasteImplModulePath !== hasteImplModulePath
) {
if (hasteImpl) {
throw new Error('jest-haste-map: hasteImplModulePath changed');
}
hasteImplModulePath = data.hasteImplModulePath;
hasteImpl =
// $FlowFixMe: dynamic require
(require(hasteImplModulePath): HasteImpl);
}
try {
const filePath = data.filePath;
const content = fs.readFileSync(filePath, 'utf8');
let module;
let id;
let dependencies;
if (filePath.endsWith(PACKAGE_JSON)) {
const fileData = JSON.parse(content);
if (fileData.name) {
id = fileData.name;
module = [filePath, H.PACKAGE];
}
} else if (!filePath.endsWith(JSON_EXTENSION)) {
if (hasteImpl) {
id = hasteImpl.getHasteName(filePath);
} else {
const doc = docblock.parse(docblock.extract(content));
id = doc.providesModule || doc.provides;
}
dependencies = extractRequires(content);
if (id) {
module = [filePath, H.MODULE];
}
}
callback(null, {dependencies, id, module});
} catch (error) {
callback(formatError(error));
}
};