1
+ const { parse } = require ( '@test/test-target' ) ;
2
+
3
+ describe ( 'issue 226' , function ( ) {
4
+ it ( 'get node line' , function ( ) {
5
+ const html = `<div>
6
+ <img src="http://localhost/foo.png" />
7
+ <img src="http://localhost/bar.png" />
8
+ <img src="http://localhost/foo.png" />
9
+ <img src="./foo.png" ></img>
10
+
11
+ <img src="./bar.png" ></img>
12
+ <img src="./foo.png" ></img>
13
+ </div>` ;
14
+ lintHtml ( html ) . should . deepEqual ( [ {
15
+ line : 2 ,
16
+ message : 'image src "http://localhost/foo.png" uses localhost'
17
+ } , {
18
+ line : 3 ,
19
+ message : 'image src "http://localhost/bar.png" uses localhost'
20
+ } , {
21
+ line : 4 ,
22
+ message : 'image src "http://localhost/foo.png" uses localhost'
23
+ } , {
24
+ line : 5 ,
25
+ message : 'image src "./foo.png" is relative and must be absolute'
26
+ } , {
27
+ line : 7 ,
28
+ message : 'image src "./bar.png" is relative and must be absolute'
29
+ } , {
30
+ line : 8 ,
31
+ message : 'image src "./foo.png" is relative and must be absolute'
32
+ } ] ) ;
33
+ } ) ;
34
+ } ) ;
35
+
36
+ /**
37
+ * Get line no of Image elements
38
+ * @param {String } html
39
+ */
40
+ function lintHtml ( html ) {
41
+ const lint = [ ] ;
42
+ // check html for images with relative paths or localhost
43
+ const root = parse ( html ) ;
44
+ const images = root . querySelectorAll ( "img" ) ;
45
+ function getLine ( node ) {
46
+ const r = html . substring ( 0 , node . range [ 0 ] ) . match ( / \n / g) ;
47
+ if ( r ) {
48
+ return r . length + 1 ;
49
+ }
50
+ return 1 ;
51
+ }
52
+ for ( const image of images ) {
53
+ const src = image . getAttribute ( "src" ) ;
54
+ if ( ! src ) continue ;
55
+ if ( src . startsWith ( "http://localhost" ) ) {
56
+ lint . push ( {
57
+ line : getLine ( image ) ,
58
+ message : `image src "${ src } " uses localhost` ,
59
+ } ) ;
60
+ } else if ( ! src . startsWith ( "http" ) ) {
61
+ lint . push ( {
62
+ line : getLine ( image ) ,
63
+ message : `image src "${ src } " is relative and must be absolute` ,
64
+ } ) ;
65
+ }
66
+ }
67
+ return lint ;
68
+ }
0 commit comments