1
+ module . exports = ScriptInjectorStream ;
2
+
3
+ var fs = require ( 'fs' )
4
+ , Transform = require ( 'stream' ) . Transform ;
5
+
6
+ if ( ! Transform ) { // shim for node 0.8
7
+ Transform = require ( 'readable-stream/transform' ) ;
8
+ }
9
+
10
+ var hp = require ( 'htmlparser2' ) ;
11
+
12
+ function ScriptInjectorStream ( script , options ) {
13
+ var self = this ;
14
+ if ( ! ( self instanceof ScriptInjectorStream ) ) {
15
+ return new ScriptInjectorStream ( script , options ) ;
16
+ }
17
+
18
+ Transform . call ( self , options ) ;
19
+
20
+ self . _script = script ? script . toString ( )
21
+ : ';(' + function ( ) { console . log ( "You didn't provide a script to inject" ) } + ')()' ;
22
+ self . needToAddScript = true ;
23
+ self . htmlParser = new hp . Parser ( {
24
+ onprocessinginstruction : function ( name , data ) {
25
+ self . push ( '<' + data + '>' ) ;
26
+ } ,
27
+ onopentag : function ( name , attribs ) {
28
+ var output = '' ;
29
+ if ( name === 'script' && self . needToAddScript ) {
30
+ self . needToAddScript = false ;
31
+ output += '<script type=\"text/javascript\">\n;(' + self . _script + ')()\n<\/script>\n' ;
32
+ }
33
+ output += '<' + name ;
34
+ for ( var key in attribs ) {
35
+ output += ' ' + key + '=\"' + attribs [ key ] + '\"' ;
36
+ }
37
+ output += '>' ;
38
+ self . push ( output ) ;
39
+ } ,
40
+ ontext : function ( text ) {
41
+ self . push ( text ) ;
42
+ } ,
43
+ onclosetag : function ( name ) {
44
+ if ( name === 'body' && self . needToAddScript ) {
45
+ self . needToAddScript = false ;
46
+ self . push ( '<script type=\"text/javascript\">\n;(' + self . _script + ')()\n<\/script>\n' )
47
+ }
48
+ self . push ( '<\/' + name + '>' ) ;
49
+ }
50
+ } ) ;
51
+
52
+ self . on ( 'end' , function ( ) { self . htmlParser . parseComplete ( ) } ) ;
53
+
54
+ }
55
+
56
+ ScriptInjectorStream . prototype = Object . create (
57
+ Transform . prototype , { constructor : { value : ScriptInjectorStream } } ) ;
58
+
59
+ ScriptInjectorStream . prototype . _transform = function ( chunk , encoding , done ) {
60
+ this . htmlParser . write ( chunk ) ;
61
+ done ( ) ;
62
+ }
0 commit comments