/
sitemap.js
166 lines (150 loc) · 5.58 KB
/
sitemap.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
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
/*
* Copyright 2024 Adobe. All rights reserved.
* This file is licensed to you under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. You may obtain a copy
* of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under
* the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS
* OF ANY KIND, either express or implied. See the License for the specific language
* governing permissions and limitations under the License.
*/
import zlib from 'zlib';
import fetch from 'node-fetch';
import dotenv from 'dotenv';
import { parseStringPromise } from 'xml2js';
import { createAssessment, getRobotsTxt, USER_AGENT } from './assessment-lib.js';
dotenv.config();
const userAgentHeader = { headers: { 'User-Agent': USER_AGENT } };
const userSiteUrl = process.argv[2];
async function checkPage(url) {
const warnings = [];
const errors = [];
// drafts files in sitemap
if (url.includes('draft')) {
warnings.push(`Detected draft file: ${url}`);
}
// file returns 2xx.
try {
const response = await fetch(url, { method: 'HEAD', 'User-Agent': USER_AGENT });
if (!response.ok) errors.push(`must return 2xx but returns ${response.status}`);
} catch (error) {
errors.push(`${url} returns error ${error.message}`);
}
return { errors, warnings };
}
async function fetchSitemapXml(url) {
const response = await fetch(url, userAgentHeader);
if (!response.ok || response.status === '404' || response.headers.get('content-type').includes('text/html')) {
throw new Error(`HTTP Response Code: ${response.status}, Content-Type: ${response.headers.get('content-type')}`);
}
const contentType = response.headers.get('content-type');
const xml = contentType.includes('application/x-gzip')
? zlib.gunzipSync(Buffer.from(await response.arrayBuffer())).toString()
: await response.text();
return xml;
}
async function fetchSitemapsFromSource(sources) {
async function parseSitemap(xml, sitemapObject) {
try {
const result = await parseStringPromise(xml);
if (result.urlset && result.urlset.url) {
return [{
url: sitemapObject.url,
source: sitemapObject.source,
locs: result.urlset.url.length,
}, ...result.urlset.url.map((urlEntry) => ({
page: urlEntry.loc[0],
source: sitemapObject.url,
}))];
} else if (result.sitemapindex && result.sitemapindex.sitemap) {
const sitemaps = await fetchSitemapsFromSource(result.sitemapindex.sitemap.map((entry) => ({
url: entry.loc[0],
source: sitemapObject.url,
})));
return [{
url: sitemapObject.url,
source: sitemapObject.source,
locs: result.sitemapindex.sitemap.length,
}, ...sitemaps];
}
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
}
return [];
}
const sitemapFetchPromises = sources.map(async (sitemapObject) => {
try {
try {
const fetchedXml = await fetchSitemapXml(sitemapObject.url);
return await parseSitemap(fetchedXml, sitemapObject);
} catch (fetchError) {
return { url: sitemapObject.url, source: sitemapObject.source, error: fetchError.message };
}
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
return [];
}
});
const urls = await Promise.all(sitemapFetchPromises);
return urls.flat();
}
// Handle Sitemap in robots.txt
async function fetchSitemapsFromRobots(siteUrl) {
const robots = await getRobotsTxt(siteUrl);
const sitemapSources = [];
if (robots.exists && robots.sitemaps) {
sitemapSources.push(...robots.sitemaps.map((url) => ({ url, source: '/robots.txt' })));
}
return fetchSitemapsFromSource(sitemapSources);
}
export async function fetchSitemapsFromBaseUrl(url) {
let sitemaps = await fetchSitemapsFromRobots(userSiteUrl);
if (!sitemaps.length) {
sitemaps = await fetchSitemapsFromSource([
{ url: new URL('sitemap.xml', url).toString(), source: 'Default path /sitemap.xml' },
]);
if (!sitemaps.length) {
sitemaps = await fetchSitemapsFromSource([
{ url: new URL('sitemap_index.xml', url).toString(), source: 'Default path /sitemap_index.xml' },
]);
}
}
return sitemaps;
};
(async () => {
const assessment = await createAssessment(userSiteUrl, 'Sitemap');
assessment.setRowHeadersAndDefaults({
sitemapOrPage: '',
source: '',
locs: 0,
error: '',
warning: '',
});
const sitemaps = await fetchSitemapsFromBaseUrl(userSiteUrl);
// Assessment for sitemaps
sitemaps.forEach(async (sitemap) => {
if (sitemap.url) {
assessment.addColumn({
sitemapOrPage: sitemap.url, source: sitemap.source, locs: sitemap.locs, error: sitemap.error || '', warning: sitemap.warning || '',
});
}
});
// Assessments for pages. We filer by unique pages, because they can appear in multiple sitemaps.
const seenPages = new Set();
const promises = sitemaps
.filter((item) => !!item.page)
.filter((item) => (seenPages.has(item.page) ? false : seenPages.add(item.page)))
.map(async (item) => {
const { errors, warnings } = await checkPage(item.page);
if (errors.length > 0 || warnings.length > 0) {
assessment.addColumn({
sitemapOrPage: item.page, source: item.source, error: errors.join(', '), warning: warnings.join(', '),
});
}
});
await Promise.all(promises);
assessment.end();
})();