-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathbackstopjs-generator.js
More file actions
188 lines (169 loc) · 5.14 KB
/
Copy pathbackstopjs-generator.js
File metadata and controls
188 lines (169 loc) · 5.14 KB
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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
const axios = require('axios');
const cheerio = require('cheerio');
const fs = require('fs');
require('dotenv').config();
const cache = new Map();
// Function to fetch data from a URL and cache it
const fetchData = async (url) => {
if (cache.has(url)) {
return cache.get(url);
}
try {
const response = await axios.get(url);
cache.set(url, response.data);
return response.data;
} catch (error) {
console.error(`Error fetching the URL: ${error.message}`);
throw error;
}
};
// Helper function to generate text based on URL
const generateTextFromUrl = (url) => {
return url.replace(/https?:\/\/(www\.)?/, '').replace(/\/$/, '').replace(/[-_]/g, ' ').split('/').pop();
};
// Function to extract links from HTML content based on a selector
const extractLinksFromHtml = (html, selector) => {
const $ = cheerio.load(html);
const links = $(selector);
const urls = [];
links.each((index, element) => {
let href = $(element).attr('href');
if (!href || !href.includes(process.env.WEBSITE_URL)) {
return;
}
let text = $(element).text();
if (!href.startsWith('http')) {
href = `${process.env.WEBSITE_URL}${href}`;
}
if (!text) {
text = generateTextFromUrl(href);
}
urls.push({ href, text });
});
return urls;
};
// Function to extract links from XML content
const extractLinksFromXml = async (xml) => {
const $ = cheerio.load(xml, { xmlMode: true });
const links = $('loc');
const urls = [];
for (const element of links) {
const href = $(element).text();
let text = generateTextFromUrl(href);
if (href.includes('.xml')) {
const nestedUrls = await fetchInternalLinksFromSitemap(href);
urls.push(...nestedUrls);
} else {
urls.push({ href, text });
}
}
return urls;
};
// Function to scrap a website for all the internal links based on a HTML selector
const scrapWebsiteForLinks = async (url, selector) => {
const html = await fetchData(url);
return extractLinksFromHtml(html, selector);
};
// Function to fetch all internal links from sitemap of a website
const fetchInternalLinksFromSitemap = async (url) => {
const xml = await fetchData(url);
return extractLinksFromXml(xml);
};
// Main function to fetch links based on .env settings
const fetchLinks = async () => {
try {
let links;
if (process.env.FETCH_INTERNAL_LINKS_FROM_SITEMAP === 'true') {
links = await fetchInternalLinksFromSitemap(process.env.SITEMAP_URL);
} else {
links = await scrapWebsiteForLinks(process.env.WEBSITE_URL, process.env.LINK_SELECTOR);
}
return links;
} catch (error) {
console.error(`Error fetching links: ${error.message}`);
return [];
}
};
// Function to generate the backstop configuration
const generateBackstopConfig = async () => {
const links = await fetchLinks();
const backstopConfig = {
id: "backstop_playwright",
viewports: [
{
label: "phone",
width: 320,
height: 480
},
{
label: "tablet",
width: 1024,
height: 768
},
{
"label": "desktop",
"width": 1366,
"height": 768
}
],
onBeforeScript: "playwright/onBefore.js",
onReadyScript: "playwright/onReady.js",
scenarioDefaults: {
cookiePath: "backstop_data/engine_scripts/cookies.json",
url: process.env.WEBSITE_BASE_URL,
readySelector: "",
delay: parseInt(process.env.DELAY, 10) || 0,
hideSelectors: process.env.HIDE_SELECTORS ? process.env.HIDE_SELECTORS.split(',') : [],
removeSelectors: process.env.REMOVE_SELECTORS ? process.env.REMOVE_SELECTORS.split(',') : [],
hoverSelector: "",
clickSelector: "",
postInteractionWait: parseInt(process.env.POST_INTERACTION_WAIT, 10) || 1000,
selectors: [],
selectorExpansion: true,
misMatchThreshold: parseFloat(process.env.MISMATCH_THRESHOLD) || 0.1,
requireSameDimensions: true
},
scenarios: links.map(link => {
const path = new URL(link.href).pathname;
const referenceUrl = `${process.env.REFERENCE_URL}${path}`;
return {
label: link.text || link.href,
cookiePath: "backstop_data/engine_scripts/cookies.json",
url: referenceUrl,
referenceUrl: link.href,
readyEvent: "",
};
}),
paths: {
bitmaps_reference: "backstop_data/bitmaps_reference",
bitmaps_test: "backstop_data/bitmaps_test",
engine_scripts: "backstop_data/engine_scripts",
html_report: "backstop_data/html_report",
ci_report: "backstop_data/ci_report"
},
report: ["browser"],
engine: "playwright",
engineOptions: {
args: ["--no-sandbox"]
},
asyncCaptureLimit: 5,
asyncCompareLimit: 50,
debug: false,
debugWindow: false,
archiveReport: true,
scenarioLogsInReports: true
};
fs.writeFileSync('backstop.json', JSON.stringify(backstopConfig, null, 2));
console.log('backstop.json has been generated.');
};
generateBackstopConfig();
module.exports = {
fetchData,
generateTextFromUrl,
extractLinksFromHtml,
extractLinksFromXml,
scrapWebsiteForLinks,
fetchInternalLinksFromSitemap,
fetchLinks,
generateBackstopConfig
};