-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcloudflare.worker
More file actions
73 lines (61 loc) · 2.2 KB
/
cloudflare.worker
File metadata and controls
73 lines (61 loc) · 2.2 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
addEventListener('fetch', event => {
event.respondWith(makeWebp(event.request))
})
async function makeWebp(request) {
let extensionRegex = /(\.jpg|\.jpeg|\.png)(\?.*)?$/i
let noExtensionRegex = /\/[^\.]*$/
if(request.headers.get('Accept')
&& request.headers.get('Accept').match(/image\/webp/)
&& (request.url.match(extensionRegex) || request.url.match(noExtensionRegex))
&& !request.url.includes('/original/')) {
const { origin, pathname, search } = new URL(request.url)
/**
* Replace jpg / png with webp
*/
let url = request.url.replace(extensionRegex, '.webp') + search
/**
* Add .webp to extensionless urls
*/
if (!url.includes('.webp')) {
url = origin + pathname + '.webp' + search
}
url = new URL(url)
/**
* Create a new request with the webp url
*/
const modifiedRequest = new Request(url, {
method: request.method,
headers: request.headers
})
/**
* Fetch the webp response
*/
const webpResponse = await fetch(modifiedRequest)
/**
* Add webworker header to the webp response so we can
* check live if the webworking is doing what it should do
*/
const webpHeaders = new Headers(webpResponse.headers)
webpHeaders.set('Content-Type', 'image/webp')
webpHeaders.append('X-WebWorker', 'active')
/**
* Return a new response object
*/
return new Response(webpResponse.body, {
status: webpResponse.status,
statusText: webpResponse.statusText,
headers: webpHeaders
})
} else {
/**
* Set the CORS header so that we can use prod darkroom on staging CMS
*/
const original = await fetch(request)
if (original.headers.get('Access-Control-Allow-Origin') && request.headers.get('Origin')) {
response = new Response(original.body, original)
response.headers.set('Access-Control-Allow-Origin', request.headers.get('Origin') || 'test')
return response
}
return original
}
}