/
gsc.ts
280 lines (251 loc) · 8.75 KB
/
gsc.ts
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
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
import { webmasters_v3 } from "googleapis";
import { Status } from "./types";
import { fetchRetry } from "./utils";
/**
* Converts a given input string to a valid Google Search Console site URL format.
* @param input - The input string to be converted.
* @returns The converted site URL (domain.com or https://domain.com/)
*/
export function convertToSiteUrl(input: string) {
if (input.startsWith("http://") || input.startsWith("https://")) {
return input.endsWith("/") ? input : `${input}/`;
}
return `sc-domain:${input}`;
}
/**
* Converts a given file path to a formatted version suitable for use as a file name.
* @param path - The url to be converted as a file name
* @returns The converted file path
*/
export function convertToFilePath(path: string) {
return path.replace("http://", "http_").replace("https://", "https_").replace("/", "_");
}
/**
* Converts an HTTP URL to a sc-domain URL format.
* @param httpUrl The HTTP URL to be converted.
* @returns The sc-domain formatted URL.
*/
export function convertToSCDomain(httpUrl: string) {
return `sc-domain:${httpUrl.replace("http://", "").replace("https://", "").replace("/", "")}`;
}
/**
* Converts a domain to an HTTP URL.
* @param domain The domain to be converted.
* @returns The HTTP URL.
*/
export function convertToHTTP(domain: string) {
return `http://${domain}/`;
}
/**
* Converts a domain to an HTTPS URL.
* @param domain The domain to be converted.
* @returns The HTTPS URL.
*/
export function convertToHTTPS(domain: string) {
return `https://${domain}/`;
}
/**
* Retrieves a list of sites associated with the specified service account from the Google Webmasters API.
* @param accessToken - The access token for authentication.
* @returns An array containing the site URLs associated with the service account.
*/
export async function getSites(accessToken: string) {
const sitesResponse = await fetchRetry("https://www.googleapis.com/webmasters/v3/sites", {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
});
if (sitesResponse.status === 403) {
console.error("🔐 This service account doesn't have access to any sites.");
return [];
}
const sitesBody: webmasters_v3.Schema$SitesListResponse = await sitesResponse.json();
if (!sitesBody.siteEntry) {
console.error("❌ No sites found, add them to Google Search Console and try again.");
return [];
}
return sitesBody.siteEntry.map((x) => x.siteUrl);
}
/**
* Checks if the site URL is valid and accessible by the service account.
* @param accessToken - The access token for authentication.
* @param siteUrl - The URL of the site to check.
* @returns The corrected URL if found, otherwise the original site URL.
*/
export async function checkSiteUrl(accessToken: string, siteUrl: string) {
const sites = await getSites(accessToken);
let formattedUrls: string[] = [];
// Convert the site URL into all possible formats
if (siteUrl.startsWith("https://")) {
formattedUrls.push(siteUrl);
formattedUrls.push(convertToHTTP(siteUrl));
formattedUrls.push(convertToSCDomain(siteUrl));
} else if (siteUrl.startsWith("http://")) {
formattedUrls.push(siteUrl);
formattedUrls.push(convertToHTTPS(siteUrl));
formattedUrls.push(convertToSCDomain(siteUrl));
} else if (siteUrl.startsWith("sc-domain:")) {
formattedUrls.push(siteUrl);
formattedUrls.push(convertToHTTP(siteUrl.replace("sc-domain:", "")));
formattedUrls.push(convertToHTTPS(siteUrl.replace("sc-domain:", "")));
} else {
console.error("❌ Unknown site URL format.");
console.error("");
process.exit(1);
}
// Check if any of the formatted URLs are accessible
for (const formattedUrl of formattedUrls) {
if (sites.includes(formattedUrl)) {
return formattedUrl;
}
}
// If none of the formatted URLs are accessible
console.error("❌ This service account doesn't have access to this site.");
console.error("");
process.exit(1);
}
/**
* Retrieves the indexing status of a page.
* @param accessToken - The access token for authentication.
* @param siteUrl - The URL of the site.
* @param inspectionUrl - The URL of the page to inspect.
* @returns A promise resolving to the status of indexing.
*/
export async function getPageIndexingStatus(
accessToken: string,
siteUrl: string,
inspectionUrl: string
): Promise<Status> {
try {
const response = await fetchRetry(`https://searchconsole.googleapis.com/v1/urlInspection/index:inspect`, {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
inspectionUrl,
siteUrl,
}),
});
if (response.status === 403) {
console.error(`🔐 This service account doesn't have access to this site.`);
console.error(await response.text());
return Status.Forbidden;
}
if (response.status >= 300) {
if (response.status === 429) {
return Status.RateLimited;
} else {
console.error(`❌ Failed to get indexing status.`);
console.error(`Response was: ${response.status}`);
console.error(await response.text());
return Status.Error;
}
}
const body = await response.json();
return body.inspectionResult.indexStatusResult.coverageState;
} catch (error) {
console.error(`❌ Failed to get indexing status.`);
console.error(`Error was: ${error}`);
throw error;
}
}
/**
* Retrieves an emoji representation corresponding to the given status.
* @param status - The status for which to retrieve the emoji.
* @returns The emoji representing the status.
*/
export function getEmojiForStatus(status: Status) {
switch (status) {
case Status.SubmittedAndIndexed:
return "✅";
case Status.DuplicateWithoutUserSelectedCanonical:
return "😵";
case Status.CrawledCurrentlyNotIndexed:
case Status.DiscoveredCurrentlyNotIndexed:
return "👀";
case Status.PageWithRedirect:
return "🔀";
case Status.URLIsUnknownToGoogle:
return "❓";
case Status.RateLimited:
return "🚦";
default:
return "❌";
}
}
/**
* Retrieves metadata for publishing from the given URL.
* @param accessToken - The access token for authentication.
* @param url - The URL for which to retrieve metadata.
* @returns The status of the request.
*/
export async function getPublishMetadata(accessToken: string, url: string) {
const response = await fetchRetry(
`https://indexing.googleapis.com/v3/urlNotifications/metadata?url=${encodeURIComponent(url)}`,
{
method: "GET",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
}
);
if (response.status === 403) {
console.error(`🔐 This service account doesn't have access to this site.`);
console.error(`Response was: ${response.status}`);
console.error(await response.text());
}
if (response.status === 429) {
console.error("🚦 Rate limit exceeded, try again later.");
console.error("");
console.error(" Quota: https://developers.google.com/search/apis/indexing-api/v3/quota-pricing#quota");
console.error(" Usage: https://console.cloud.google.com/apis/enabled");
console.error("");
process.exit(1);
}
if (response.status >= 500) {
console.error(`❌ Failed to get publish metadata.`);
console.error(`Response was: ${response.status}`);
console.error(await response.text());
}
return response.status;
}
/**
* Requests indexing for the given URL.
* @param accessToken - The access token for authentication.
* @param url - The URL to be indexed.
*/
export async function requestIndexing(accessToken: string, url: string) {
const response = await fetchRetry("https://indexing.googleapis.com/v3/urlNotifications:publish", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${accessToken}`,
},
body: JSON.stringify({
url: url,
type: "URL_UPDATED",
}),
});
if (response.status === 403) {
console.error(`🔐 This service account doesn't have access to this site.`);
console.error(`Response was: ${response.status}`);
}
if (response.status >= 300) {
if (response.status === 429) {
console.error("🚦 Rate limit exceeded, try again later.");
console.error("");
console.error(" Quota: https://developers.google.com/search/apis/indexing-api/v3/quota-pricing#quota");
console.error(" Usage: https://console.cloud.google.com/apis/enabled");
console.error("");
process.exit(1);
} else {
console.error(`❌ Failed to request indexing.`);
console.error(`Response was: ${response.status}`);
console.error(await response.text());
}
}
}