Skip to content

Commit

Permalink
fix(regex): [dynamic] ignore matches in string literals
Browse files Browse the repository at this point in the history
- https://regex101.com/r/PTPAvU/27

Signed-off-by: Lexus Drumgold <unicornware@flexdevelopment.llc>
  • Loading branch information
unicornware committed Mar 1, 2023
1 parent b0d854b commit 1851baf
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 16 deletions.
39 changes: 24 additions & 15 deletions src/__tests__/import-dynamic.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,23 +12,32 @@ describe('unit:DYNAMIC_IMPORT_REGEX', () => {
TEST_SUBJECT.lastIndex = 0
})

describe('comments', () => {
it('should ignore import in multi-line comment', () => {
// Arrange
const code = dedent`
/**
* @example
* const { readPackage } = await import('read-pkg')
*/
`
it('should ignore match in multi-line comment', () => {
// Arrange
const code = dedent`
/**
* @example
* const { readPackage } = await import('read-pkg')
*/
`

// Act + Expect
expect(TEST_SUBJECT.test(code)).to.be.false
})

// Act + Expect
expect(TEST_SUBJECT.test(code)).to.be.false
})
it('should ignore match in single-line comment', () => {
expect(TEST_SUBJECT.test('// await import("./init.mjs")')).to.be.false
})

it('should ignore import in single-line comment', () => {
expect(TEST_SUBJECT.test('// await import("./init.mjs")')).to.be.false
})
it('should ignore match in string literal', () => {
// Arrange
const code = dedent`
const str1 = 'await import("foo")'
const str2 = "await import('foo')"
`

// Act + Expect
expect(TEST_SUBJECT.test(code)).to.be.false
})

describe('conditional imports', () => {
Expand Down
2 changes: 1 addition & 1 deletion src/import-dynamic.ts
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,6 @@
* @const {RegExp} DYNAMIC_IMPORT_REGEX
*/
const DYNAMIC_IMPORT_REGEX: RegExp =
/(?<=^|[\s;])(?:(?:const\s*|let\s*|var\s*)?(?<imports>(?:[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*)|(?<=const\s*|let\s*|var\s*)(?:[\w\t\n\r "$'*,./:{}-]+?))\s*=\s*)?(?:await\s+)?(?<expression>import\((?<specifier>[\S\t\n\r]+?)(?:,\s*(?<options>\{\s*assert:.+[\w\t\n\r "':]+\}\s*\}))?\))(?<!(?:\/\/|\*).*)/gu
/(?<=^|[\n;](?:[\t ]*(?:\w+ )?)?)(?:(?:const\s*|let\s*|var\s*)?(?<imports>(?:[$_\p{ID_Start}][$\u200C\u200D\p{ID_Continue}]*)|(?<=const\s*|let\s*|var\s*)(?:[\w\t\n\r "$'*,./:{}-]+?))\s*=\s*)?(?:await\s+)?(?<expression>import\((?<specifier>[\S\t\n\r]+?)(?:,\s*(?<options>\{\s*assert:.+[\w\t\n\r "':]+\}\s*\}))?\))/gu

export default DYNAMIC_IMPORT_REGEX

0 comments on commit 1851baf

Please sign in to comment.