1
1
const got = require ( 'got' )
2
2
const chromium = require ( 'chrome-aws-lambda' )
3
3
const normalizeUrl = require ( 'normalize-url' )
4
+ const isUrl = require ( 'is-url' )
4
5
5
6
const extractCss = async url => {
6
7
const browser = await chromium . puppeteer . launch ( {
7
8
executablePath : await chromium . executablePath ,
8
9
args : chromium . args ,
9
- headless : chromium . headless
10
+ headless : true
10
11
} )
11
12
12
13
const page = await browser . newPage ( )
13
14
14
- // // Start CSS coverage. This is the meat and bones of this module
15
+ // Start CSS coverage. This is the meat and bones of this module
15
16
await page . coverage . startCSSCoverage ( )
16
17
17
18
const response = await page . goto ( url , { waitUntil : 'networkidle2' } )
@@ -23,15 +24,13 @@ const extractCss = async url => {
23
24
24
25
return Promise . reject (
25
26
new Error (
26
- `There was an error retrieving CSS from ${ url } .\n\tHTTP status code: ${
27
- response . statusCode
28
- } (${ response . statusText } )`
27
+ `There was an error retrieving CSS from ${ url } .\n\tHTTP status code: ${ response . statusCode } (${ response . statusText } )`
29
28
)
30
29
)
31
30
}
32
31
33
- // // Coverage contains a lot of <style> and <link> CSS,
34
- // // but not all...
32
+ // Coverage contains a lot of <style> and <link> CSS,
33
+ // but not all...
35
34
const coverage = await page . coverage . stopCSSCoverage ( )
36
35
37
36
// Get all CSS generated with the CSSStyleSheet API
@@ -67,15 +66,27 @@ const extractCss = async url => {
67
66
module . exports = async ( req , res ) => {
68
67
const url = normalizeUrl ( req . url . slice ( 1 ) , { stripWWW : false } )
69
68
69
+ if ( ! isUrl ( url ) ) {
70
+ res . statusCode = 406
71
+ res . setHeader ( 'Content-Type' , 'application/json' )
72
+ return res . end (
73
+ JSON . stringify ( {
74
+ message : 'The provided URL is not valid'
75
+ } )
76
+ )
77
+ }
78
+
70
79
try {
71
80
const css = url . endsWith ( '.css' )
72
81
? ( await got ( url ) ) . body
73
82
: await extractCss ( url )
74
83
75
84
res . setHeader ( 'Content-Type' , 'text/css' )
76
-
77
- return res . status ( 200 ) . send ( css )
85
+ res . statusCode = 200
86
+ return res . end ( css )
78
87
} catch ( error ) {
79
- return res . status ( 400 ) . json ( error )
88
+ res . statusCode = 500
89
+ res . setHeader ( 'Content-Type' , 'application/json' )
90
+ return res . end ( JSON . stringify ( error ) )
80
91
}
81
92
}
0 commit comments