-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathworker.js
35 lines (30 loc) · 1.21 KB
/
worker.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
addEventListener('fetch', event => {
event.respondWith(handleRequest(event.request))
})
async function handleRequest(request) {
const url = new URL(request.url);
const workerURL = `${url.origin}/pypi/simple`;
// Handle requests to the PyPI simple index
if (url.pathname.startsWith('/pypi/')) {
const pypiPath = url.pathname.replace('/pypi', '');
const pypiUrl = `https://pypi.org${pypiPath}`;
const response = await fetch(pypiUrl);
let body = await response.text();
// Rewrite URLs in the response body to go through the Cloudflare Worker
body = body.replace(/https:\/\/files.pythonhosted.org/g, `${url.origin}/files`);
return new Response(body, {
headers: { 'Content-Type': 'text/html' }
});
}
// Handle requests to files.pythonhosted.org
if (url.pathname.startsWith('/files/')) {
const filePath = url.pathname.replace('/files', '');
const fileUrl = `https://files.pythonhosted.org${filePath}`;
const response = await fetch(fileUrl);
// Ensure the response is forwarded as a binary stream
return new Response(response.body, {
headers: response.headers
});
}
return new Response('This worker serves PyPI packages and their files', { status: 200 });
}