forked from cloudflare/worker-emscripten-template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
65 lines (51 loc) · 1.88 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
// import the emscripten glue code
import emscripten from './build/module.js'
addEventListener('fetch', event => {
event.respondWith(handleRequest(event))
})
// this is where the magic happens
// we send our own instantiateWasm function
// to the emscripten module
// so we can initialize the WASM instance ourselves
// since Workers puts your wasm file in global scope
// as a binding. In this case, this binding is called
// `wasm` as that is the name Wrangler uses
// for any uploaded wasm module
let emscripten_module = new Promise((resolve, reject) => {
emscripten({
instantiateWasm(info, receive) {
let instance = new WebAssembly.Instance(wasm, info)
receive(instance)
return instance.exports
},
}).then(module => {
resolve({
init: module.cwrap('init', 'number', ['number']),
resize: module.cwrap('resize', 'number', ['number', 'number']),
module: module,
})
})
})
async function handleRequest(event) {
let request = event.request
let response = await fetch(request)
let type = response.headers.get('Content-Type') || ''
if (!type.startsWith('image/')) return response
let width = new URL(request.url).searchParams.get('width')
if (!width) return response
let resizer = await emscripten_module
let bytes = new Uint8Array(await response.arrayBuffer())
let ptr = resizer.init(bytes.length)
resizer.module.HEAPU8.set(bytes, ptr)
let newSize = resizer.resize(bytes.length, parseInt(width))
if (newSize == 0) {
return new Response(bytes, response)
}
let resultBytes = resizer.module.HEAPU8.slice(ptr, ptr + newSize)
// Create a new response with the image bytes. Our resizer module always
// outputs JPEG regardless of input type, so change the header.
let newResponse = new Response(resultBytes, response)
newResponse.headers.set('Content-Type', 'image/jpeg')
// Return the response.
return newResponse
}