-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheleventy-google-fonts.js
48 lines (41 loc) · 1.02 KB
/
eleventy-google-fonts.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
const https = require('https')
const UA = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.61 Safari/537.36'
const isValidURL = url => {
return /fonts.googleapis.com/.test(url)
}
const downloadFont = url => {
return new Promise((resolve) => {
let rawData = ''
https.get(
url,
{
headers: {
'user-agent': UA,
},
},
res => {
res.on('data', chunk => {
rawData += chunk
})
res.on('end', () => {
resolve(rawData.toString('utf8'))
})
}
)
})
}
const createInlineCss = async url => {
if (!isValidURL(url)) {
throw new Error('Invalid Google Fonts URL')
}
const content = await downloadFont(url)
return (
`<link rel="preconnect" href="https://fonts.gstatic.com">`+
`<link data-href="${url}" rel="stylesheet">`+
`<style data-href='${url}'>${content}</style>`
)
}
module.exports = {
isValidURL: isValidURL,
createInlineCss: createInlineCss
}