forked from newfold-labs/cf-worker-wp-github-release-api
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
385 lines (323 loc) · 8.08 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
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
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
/**
* Handle the incoming request.
*
* @param event {Event}
*
* @returns {Promise<Response>}
*/
async function handleRequest(event) {
const request = event.request;
const url = new URL(request.url);
// Construct the cache key from the cache URL
const cacheKey = new Request(url.toString(), request);
const cache = caches.default;
// Check if response is in cache
let response = await cache.match(cacheKey);
// If cached, return stored result
if (response) {
return response;
}
// Get the data from the request
const data = getDataFromRequest(request);
// Run some error checks
if (data.type !== 'theme' && data.type !== 'plugin') {
return getErrorResponse("The first URL path segment is missing a valid entity type. Must be either 'plugins' or 'themes'.");
}
if (!data.vendor) {
return getErrorResponse('The second URL path segment is missing. It should contain the vendor name.');
}
if (!data.package) {
return getErrorResponse('The third URL path segment is missing. It should contain the package name.');
}
// Get the release
try {
data.latestRelease = await getLatestRelease(data);
data.release = data.version ? await getRelease(data) : data.latestRelease;
} catch (e) {
return getErrorResponse(e.message, 404);
}
const filePath = `https://raw.githubusercontent.com/${ data.vendor }/${ data.package }/${ data.release.tag_name }/${ data.file }`;
response = await gitHubRequest(filePath);
// Unable to read base file
if (response.status !== 200) {
return getResponse(`Unable to fetch ${ data.type } file: ${ filePath }`, 404);
}
// Get file headers
data.fileHeaders = getFileHeaders(await response.text());
// Get payload
const payload = getPayload(data);
// Force a download
if (data.isDownload) {
return Response.redirect(payload.download, 301);
}
// Prepare response
response = getResponse(payload);
// Set cache header
response.headers.append('Cache-Control', 's-maxage=180');
// Cache response
event.waitUntil(cache.put(cacheKey, response.clone()));
// Return response to the user
return response;
}
/**
* Get data from the request.
*
* @param request
* @returns {{}}
*/
function getDataFromRequest(request) {
const url = new URL(request.url);
const segments = url.pathname.split('/').filter((value) => !!value);
if (url.hostname === 'hiive.cloud') {
segments.shift(); // Remove /workers
segments.shift(); // Remove /release-api
}
// Set entity type
let type = segments.shift();
if (type && (type === 'plugin' || type === 'plugins')) {
type = 'plugin';
}
if (type && (type === 'theme' || type === 'themes')) {
type = 'theme';
}
// Set vendor name
const vendor = segments.shift();
// Set package name
const _package = segments.shift();
// Check if we should download
let isDownload = segments.includes('download');
if (isDownload) {
segments.pop(); // Remove segment so we don't accidentally grab it in the next step
}
// Set version, if provided
let version = segments.shift();
// Set slug
const slug = url.searchParams.get('slug') || _package;
// Set file
const file = url.searchParams.get('file') || (type === 'theme' ? 'style.css' : `${ _package }.php`);
// Set basename
const basename = `${ slug }/${ file }`;
return {
basename,
file,
isDownload,
package: _package, // Package is a reserved keyword in JavaScript
slug,
type,
vendor,
version
};
}
/**
* Get response payload.
*
* @param data {{}}
* @returns {{}}
*/
function getPayload(data) {
const payload = {
slug: data.slug,
name: data.type === 'theme' ? data.fileHeaders['Theme Name'] : data.fileHeaders['Plugin Name'],
homepage: (data.type === 'theme' ? data.fileHeaders['Theme URI'] : data.fileHeaders['Plugin URI']) || '',
type: data.type,
version: data.latestRelease.tag_name,
sections: {
description: data.fileHeaders['Description'] || '',
changelog: data.release.body || '',
},
author: data.fileHeaders['Author'] || '',
author_homepage: data.fileHeaders['Author URI'] || '',
last_update: data.release.published_at || '',
requires: data.fileHeaders['Requires at least'] || '',
requires_php: data.fileHeaders['Requires PHP'] || '',
tested: data.fileHeaders['Tested up to'] || '',
download_url: data.release.assets[0].browser_download_url,
};
if (data.type === 'plugin') {
payload.basename = data.basename;
}
return payload;
}
/**
* Get the latest viable release.
*
* @param data {{}}
*
* @returns {Promise<*>}
*/
async function getLatestRelease(data) {
let release, releases, response;
// Fetch the most recent releases from GitHub
response = await gitHubRequest(
`https://api.github.com/repos/${ data.vendor }/${ data.package }/releases`
);
releases = await response.json();
// Proxy error response
if (response.status !== 200) {
throw releases;
}
if (!releases || !Array.isArray(releases) || !releases.length) {
throw 'No releases available!';
}
// Sort by date published
releases.sort(
function(a,b) {
return (a.published_at > b.published_at) ? -1 : ((a.published_at < b.published_at) ? 1 : 0);
}
);
const validReleases = [];
for (release of releases) {
// Skip over draft releases
if(release.draft) {
continue;
}
// Skip over pre-releases
if(release.prerelease) {
continue;
}
// Skip over releases without release assets.
if (!release.assets.length) {
continue;
}
validReleases.push(release);
}
if(validReleases.length <= 0) {
throw 'No valid releases available!';
}
return validReleases[0];
}
/**
* Get a specific plugin or theme release.
*
* @param data {{}}
*
* @returns {Promise<*>}
*/
async function getRelease(data) {
let release, releases, response;
// Fetch a specific release from GitHub
response = await gitHubRequest(
`https://api.github.com/repos/${ data.vendor }/${ data.package }/releases/tags/${ data.version }`
);
release = await response.json();
// Proxy error response
if (response.status !== 200) {
throw release;
}
// Release doesn't have a downloadable
if (!release.assets.length) {
throw `Release ${ data.version } doesn't have a release asset!`
}
return release;
}
/**
* Get status text code given an HTTP status code.
*
* @param code {integer}
* @returns {string}
*/
function getStatusText(code) {
switch (code) {
case 400:
return 'Bad Request';
case 404:
return 'Not Found';
default:
return 'OK';
}
}
/**
* Get a new Response object.
*
* @param payload {{}}
* @param status {integer}
*
* @returns {Response}
*/
function getResponse(payload, status = 200) {
return new Response(
JSON.stringify(payload, null, 2),
{
status,
statusText: getStatusText(status),
headers: {
"Content-Type": "application/json"
}
}
);
}
/**
* Get a new Response object and set up error payload.
*
* @param message {string}
* @param statusCode {integer}
*
* @returns {Response}
*/
function getErrorResponse(message, statusCode = 400) {
return getResponse({status: 'error', message}, statusCode);
}
/**
* Make a request to GitHub.
*
* @param url {string}
*
* @returns {Promise<Response>}
*/
async function gitHubRequest(url) {
return await fetch(
url,
{
method: 'GET',
headers: {
'Accept': 'application/vnd.github.v3+json',
'Authorization': 'Basic ' + btoa(`${ GITHUB_USER }:${ GITHUB_TOKEN }`),
'User-Agent': 'Cloudflare Workers'
}
}
);
}
/**
* Get plugin or theme file headers.
*
* @param fileContents {string}
* @returns {{}}
*/
function getFileHeaders(fileContents) {
const headers = [
'Author',
'Author URI',
'Description',
'Domain Path',
'License',
'License URI',
'Plugin Name',
'Plugin URI',
'Requires at least',
'Requires PHP',
'Tested up to',
'Text Domain',
'Theme Name',
'Theme URI',
'Version'
];
const fileHeaders = {};
headers.forEach((header) => {
let regex = new RegExp(header + ':(.*)', 'gm');
let matches = regex.exec(fileContents);
if (matches && matches.hasOwnProperty(1)) {
fileHeaders[header] = matches[1].trim();
}
});
return fileHeaders;
}
addEventListener(
'fetch',
(event) => {
event.respondWith(
handleRequest(event).catch(
(err) => new Response(err.stack, {status: 500})
)
);
}
);