Skip to content

Commit b925c6d

Browse files
committed
Fix regex require finder
1 parent f1bc097 commit b925c6d

File tree

2 files changed

+60
-2
lines changed

2 files changed

+60
-2
lines changed

packages/app/src/sandbox/eval/transpilers/babel/worker/simple-get-require-statements.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
const lineRegex = /require\s*\(['|"|`]([^"|'|`]*)['|"|`]\)|require\s*\((.*)\)/g;
22
const partRegex = /require\s*\(['|"|`]([^"|'|`]*)['|"|`]\)|require\s*\((.*)\)/;
3-
const commentRegex = /(\s*\*)|(\/\/)/;
3+
const commentRegex = /^(\s*\/?\*)|(\/\/)/;
44

55
/**
66
* This is the regex version of getting all require statements, it makes the assumption
@@ -21,7 +21,7 @@ export default function getRequireStatements(code: string) {
2121
const match = codePart.match(partRegex);
2222

2323
if (match) {
24-
if (commentMatch && line.indexOf('require') > commentMatch.index) {
24+
if (commentMatch && line.indexOf(codePart) > commentMatch.index) {
2525
// It's in a comment
2626
return;
2727
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
import getRequireStatements from './simple-get-require-statements';
2+
3+
describe('simple-get-require-statements', () => {
4+
it('finds a simple require statement', () => {
5+
const code = `require('test')`;
6+
7+
expect(getRequireStatements(code)).toStrictEqual([
8+
{ type: 'direct', path: 'test' },
9+
]);
10+
});
11+
12+
it('finds multiple require statement', () => {
13+
const code = `require('test');
14+
require('test2')`;
15+
16+
expect(getRequireStatements(code)).toStrictEqual([
17+
{ type: 'direct', path: 'test' },
18+
{ type: 'direct', path: 'test2' },
19+
]);
20+
});
21+
22+
it('ignores commented require statement', () => {
23+
const code = `require('test');
24+
// require('test2')`;
25+
26+
expect(getRequireStatements(code)).toStrictEqual([
27+
{ type: 'direct', path: 'test' },
28+
]);
29+
});
30+
31+
it('allows comment after require statement', () => {
32+
const code = `require('test');
33+
require('test2') // yes very nice`;
34+
35+
expect(getRequireStatements(code)).toStrictEqual([
36+
{ type: 'direct', path: 'test' },
37+
{ type: 'direct', path: 'test2' },
38+
]);
39+
});
40+
41+
it('ignores second comment after require statement', () => {
42+
const code = `require('test');
43+
require('test2') // yes very nice require('nice')`;
44+
45+
expect(getRequireStatements(code)).toStrictEqual([
46+
{ type: 'direct', path: 'test' },
47+
{ type: 'direct', path: 'test2' },
48+
]);
49+
});
50+
51+
it('handles a * that looks like a comment', () => {
52+
const code = `$export($export.S + $export.F * !require('./_iter-detect')(function (iter) { Array.from(iter); }), 'Array', {`;
53+
54+
expect(getRequireStatements(code)).toStrictEqual([
55+
{ type: 'direct', path: './_iter-detect' },
56+
]);
57+
});
58+
});

0 commit comments

Comments
 (0)