1
1
const debug = require ( 'debug' ) ( 'loki:chrome:app' ) ;
2
2
const chromeLauncher = require ( 'chrome-launcher' ) ;
3
3
const CDP = require ( 'chrome-remote-interface' ) ;
4
+ const getRandomPort = require ( 'find-free-port-sync' ) ;
5
+ const {
6
+ getAbsoluteURL,
7
+ getLocalIPAddress,
8
+ createStaticServer,
9
+ } = require ( '@loki/core' ) ;
4
10
const { createChromeTarget } = require ( '@loki/target-chrome-core' ) ;
5
11
12
+ function getStaticServerConfig ( baseUrl ) {
13
+ let staticServerPath ;
14
+ let staticServerPort ;
15
+
16
+ let chromeUrl = getAbsoluteURL ( baseUrl ) ;
17
+ const isLocalFile = chromeUrl . indexOf ( 'file:' ) === 0 ;
18
+
19
+ if ( chromeUrl . indexOf ( 'http://localhost' ) === 0 || isLocalFile ) {
20
+ const ip = getLocalIPAddress ( ) ;
21
+
22
+ if ( ! ip ) {
23
+ throw new Error (
24
+ 'Unable to detect local IP address, try passing --host argument'
25
+ ) ;
26
+ }
27
+
28
+ if ( isLocalFile ) {
29
+ staticServerPort = getRandomPort ( ) ;
30
+ staticServerPath = chromeUrl . substr ( 'file:' . length ) ;
31
+ chromeUrl = `http://${ ip } :${ staticServerPort } ` ;
32
+ } else {
33
+ chromeUrl = chromeUrl . replace ( 'localhost' , ip ) ;
34
+ }
35
+ }
36
+
37
+ return {
38
+ chromeUrl,
39
+ isLocalFile,
40
+ staticServerPath,
41
+ staticServerPort,
42
+ } ;
43
+ }
44
+
6
45
function createChromeAppTarget ( {
7
46
baseUrl = 'http://localhost:6006' ,
47
+ useStaticServer = true ,
8
48
chromeFlags = [ '--headless' , '--disable-gpu' , '--hide-scrollbars' ] ,
9
49
} ) {
10
50
let instance ;
51
+ let staticServer ;
52
+
53
+ const { chromeUrl, isLocalFile, staticServerPath, staticServerPort } =
54
+ getStaticServerConfig ( baseUrl ) ;
11
55
12
56
async function start ( options = { } ) {
57
+ if ( useStaticServer && isLocalFile ) {
58
+ staticServer = createStaticServer ( staticServerPath ) ;
59
+ staticServer . listen ( staticServerPort ) ;
60
+ debug ( `Starting static file server at ${ chromeUrl } ` ) ;
61
+ }
13
62
const launchOptions = Object . assign (
14
63
{
15
64
chromeFlags,
@@ -30,6 +79,10 @@ function createChromeAppTarget({
30
79
} else {
31
80
debug ( 'No chrome instance to kill' ) ;
32
81
}
82
+
83
+ if ( useStaticServer && staticServer ) {
84
+ staticServer . close ( ) ;
85
+ }
33
86
}
34
87
35
88
async function createNewDebuggerInstance ( ) {
@@ -47,7 +100,12 @@ function createChromeAppTarget({
47
100
return client ;
48
101
}
49
102
50
- return createChromeTarget ( start , stop , createNewDebuggerInstance , baseUrl ) ;
103
+ return createChromeTarget (
104
+ start ,
105
+ stop ,
106
+ createNewDebuggerInstance ,
107
+ useStaticServer ? chromeUrl : baseUrl
108
+ ) ;
51
109
}
52
110
53
111
module . exports = createChromeAppTarget ;
0 commit comments