@@ -5,32 +5,60 @@ import { MagicRegExpTransformPlugin } from '../src/transform'
5
5
6
6
describe ( 'transformer' , ( ) => {
7
7
it ( 'preserves context for dynamic regexps' , ( ) => {
8
- expect ( transform ( `console.log(createRegExp(anyOf(keys)))` ) ) . not . toBeDefined ( )
8
+ expect (
9
+ transform ( [
10
+ "import { createRegExp } from 'magic-regexp'" ,
11
+ `console.log(createRegExp(anyOf(keys)))` ,
12
+ ] )
13
+ ) . not . toBeDefined ( )
9
14
} )
10
15
11
16
it ( 'statically replaces regexps where possible' , ( ) => {
12
17
const code = transform ( [
18
+ "import { createRegExp, exactly, anyOf } from 'magic-regexp'" ,
19
+ '//' , // this lets us tree-shake the import for use in our test-suite
13
20
"const re1 = createRegExp(exactly('bar').notBefore('foo'))" ,
14
21
"const re2 = createRegExp(anyOf(exactly('bar'), 'foo'))" ,
15
22
"const re3 = createRegExp('/foo/bar')" ,
16
23
// This line will be double-escaped in the snapshot
17
24
"re3.test('/foo/bar')" ,
18
25
] )
19
26
expect ( code ) . toMatchInlineSnapshot ( `
20
- "const re1 = /bar(?!foo)/
27
+ "import { createRegExp, exactly, anyOf } from 'magic-regexp'
28
+ //
29
+ const re1 = /bar(?!foo)/
21
30
const re2 = /(bar|foo)/
22
31
const re3 = /\\\\/foo\\\\/bar/
23
32
re3.test('/foo/bar')"
24
33
` )
25
34
// ... but we test it here.
26
- expect ( eval ( code ) ) . toMatchInlineSnapshot ( 'true' )
35
+ expect ( eval ( code . split ( '//' ) . pop ( ) ) ) . toMatchInlineSnapshot ( 'true' )
36
+ } )
37
+
38
+ it ( 'respects how users import library' , ( ) => {
39
+ const code = transform ( [
40
+ "import { createRegExp as cRE } from 'magic-regexp'" ,
41
+ 'import { exactly as ext, createRegExp } from "magic-regexp"' ,
42
+ 'import * as magicRE from "magic-regexp"' ,
43
+ "const re1 = cRE(ext('bar').notBefore('foo'))" ,
44
+ "const re2 = magicRE.createRegExp(magicRE.anyOf('bar', 'foo'))" ,
45
+ "const re3 = createRegExp('test/value')" ,
46
+ ] )
47
+ expect ( code ) . toMatchInlineSnapshot ( `
48
+ "import { createRegExp as cRE } from 'magic-regexp'
49
+ import { exactly as ext, createRegExp } from \\"magic-regexp\\"
50
+ import * as magicRE from \\"magic-regexp\\"
51
+ const re1 = /bar(?!foo)/
52
+ const re2 = /(bar|foo)/
53
+ const re3 = /test\\\\/value/"
54
+ ` )
27
55
} )
28
56
} )
29
57
30
58
const transform = ( code : string | string [ ] ) => {
31
59
const plugin = MagicRegExpTransformPlugin . vite ( )
32
60
return plugin . transform . call (
33
- { parse : ( code : string ) => parse ( code , { ecmaVersion : 2022 } ) } ,
61
+ { parse : ( code : string ) => parse ( code , { ecmaVersion : 2022 , sourceType : 'module' } ) } ,
34
62
Array . isArray ( code ) ? code . join ( '\n' ) : code ,
35
63
'some-id.js'
36
64
) ?. code
0 commit comments