forked from codesandbox/codesandbox-client
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsimple-get-require-statements.ts
More file actions
56 lines (49 loc) · 1.56 KB
/
simple-get-require-statements.ts
File metadata and controls
56 lines (49 loc) · 1.56 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
const lineRegex = /require\s*\(['|"|`]([^"|'|`]*)['|"|`]\)|require\s*\((.*)\)/g;
const partRegex = /require\s*\(['|"|`]([^"|'|`]*)['|"|`]\)|require\s*\((.*)\)/;
const commentRegex = /^(\s*\/?\*)|(\/\/)/;
/**
* This is the regex version of getting all require statements, it makes the assumption
* that the file is commonjs and only has `require()` statements.
*/
export default function getRequireStatements(code: string) {
const results = [];
code.split('\n').forEach(line => {
const commentMatch = commentRegex.exec(line);
if (commentMatch && commentMatch.index === 0) {
return;
}
if (line.includes('require("".concat')) {
throw new Error('Glob require is part of statement');
}
const matches = line.match(lineRegex);
if (matches) {
matches.forEach(codePart => {
const match = codePart.match(partRegex);
if (match) {
if (commentMatch && line.indexOf(codePart) > commentMatch.index) {
// It's in a comment
return;
}
if (match[1]) {
if (
!results.find(r => r.type === 'direct' && r.path === match[1])
) {
results.push({
type: 'direct',
path: match[1],
});
}
} else if (match[2]) {
if (!results.find(r => r.type === 'glob' && r.path === match[2])) {
results.push({
type: 'glob',
path: match[2],
});
}
}
}
});
}
});
return results;
}