This repository was archived by the owner on Sep 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
137 lines (129 loc) · 4.44 KB
/
index.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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
const nodePath = require('path');
const url = require('url');
const matchAll = require('string.prototype.matchall');
const puppeteer = require('puppeteer');
const request = require('request-promise-native');
const webpack = require('webpack');
function makeUrlsAbsolute(css, hrefOfCssFile) {
const matches = Array.from(matchAll(css, /url\(['"]?([^)'"]+)['"]?\)/g));
let modified = css;
const { protocol, hostname, path } = url.parse(hrefOfCssFile);
const baseUrl = [protocol, '//', hostname].join('');
const relativeBase = [baseUrl, path.replace(/\/[^/]+$/, '/')].join('');
matches.forEach(([matched, potentialUrl]) => {
if (potentialUrl.startsWith('data:')) {
// data uri
return;
}
if (/^https?:/.test(potentialUrl)) {
// absolute url
return;
}
if (potentialUrl.startsWith('%23')) {
// potential `url()` inside an inlined svg
return;
}
if (/^\//.test(potentialUrl)) {
modified = modified.split(matched).join(`url(${baseUrl}${potentialUrl})`);
} else {
// path.normalize will transform things like '/a/b/c/../d.js' to '/a/b/d.js'
const fullUrl = nodePath.normalize(`${relativeBase}${potentialUrl}`);
modified = modified.split(matched).join(`url(${fullUrl})`);
}
});
return modified;
}
async function extractCSSChunks(page) {
const baseUrl = await page.evaluate(() => window.location.origin);
const protocol = await page.evaluate(() => window.location.protocol);
const inline = await page.evaluate(() =>
Array.from(document.querySelectorAll('style')).map(el => {
return el.innerHTML || Array.from(el.sheet.cssRules).map((r) => r.cssText).join('\n')
;
}),
);
const hrefs = (await page.evaluate(() =>
Array.from(document.querySelectorAll('link[rel="stylesheet"][href]')).map(el =>
el.getAttribute('href'),
),
)).map(href => {
if (href.startsWith('http')) {
return href;
}
if (href.startsWith('//')) {
return protocol + href;
}
return baseUrl + href;
});
const external = await Promise.all(hrefs.map(async href => {
const content = await request({ method: 'GET', url: href, gzip: true });
return makeUrlsAbsolute(content, href);
}));
return external.concat(inline);
}
async function waitFor(page, selector, attempt = 0) {
const ready = await page.evaluate(
sel => {
const el = document.body.querySelector(sel);
if (!el) {
return false;
}
return true;
},
selector,
);
if (ready) return true;
if (attempt > 50) {
throw new Error(`Timeout while waiting for selector "${selector}"`);
}
await new Promise((resolve) => setTimeout(resolve, 50));
return waitFor(page, selector, attempt + 1);
}
async function logIn(page, { url, username, password }) {
await page.goto(url);
const usernameInputSelector = 'input[name=email],input[type=email]';
const passwordInputSelector = 'input[type=password]';
await waitFor(page, usernameInputSelector);
await page.type(usernameInputSelector, username);
await page.type(passwordInputSelector, password);
await page.keyboard.press('Enter');
await page.waitForNavigation({ waitUntil: 'load' });
}
module.exports = function happoScrapePlugin({ pages }) {
const plugin = {};
plugin.customizeWebpackConfig = async config => {
const browser = await puppeteer.launch();
const page = await browser.newPage();
const cssChunks = new Set();
const result = [];
for (const { url, auth, examples, wrapper = (html) => html } of pages) {
console.log(`\nLoading ${url}...`);
if (auth) {
await logIn(page, auth);
}
await page.goto(url);
for (const { name, selector, waitForSelector } of examples) {
console.log(`Preparing selector ${selector}...`);
await waitFor(page, selector);
if (waitForSelector) {
await waitFor(page, waitForSelector);
}
const html = await page.evaluate(sel => document.body.querySelector(sel).outerHTML, selector);
result.push({ html: wrapper(html), component: name });
}
(await extractCSSChunks(page)).forEach(chunk => cssChunks.add(chunk));
}
config.plugins.push(
new webpack.DefinePlugin({
HAPPO_DATA: JSON.stringify({
examples: result,
}),
}),
);
plugin.css = Array.from(cssChunks).join('\n');
await browser.close();
return config;
};
plugin.pathToExamplesFile = nodePath.resolve(__dirname, 'happoExamples.js');
return plugin;
};