addEventListener("fetch", event => event.respondWith(handleRequest(event)));
async function handleRequest(event) {
const response = await fetch(event.request, {backend: 'origin_0'});
return acropalypseFilter(response);
}
function acropalypseFilter(response) {
const pngMarker = new Uint8Array([0x89,0x50,0x4e,0x47]);
const pngIEND = new Uint8Array([0x00,0x00,0x00,0x00,0x49,0x45,0x4e,0x44]);
async function processChunks(reader, writer) {
let isPNG = false;
let isIEND = false;
while (true) {
const { done, value: chunk } = await reader.read();
if (done) break;
if (!isPNG && seqFind(chunk, pngMarker) !== -1) {
console.log("It's a PNG");
isPNG = true;
}
if (isIEND) {
writer.write(new Uint8Array(chunk.length));
continue;
} else if (isPNG) {
const idx = seqFind(chunk, pngIEND);
if (idx > 0) {
console.log(`Found IEND at ${idx}`);
isIEND = true;
writer.write(chunk.slice(0, idx));
writer.write(new Uint8Array(chunk.length-idx));
continue;
}
}
writer.write(chunk);
}
writer.close();
reader.releaseLock();
}
if (response.body) {
const {readable, writable} = new TransformStream();
const writer = writable.getWriter();
const reader = response.body.getReader();
processChunks(reader, writer);
return new Response(readable, response);
}
return response;
}
function seqFind(input, target, fromIndex = 0) {
const index = input.indexOf(target[0], fromIndex);
if (target.length === 1 || index === -1) return index;
let i, j;
for (i = index, j = 0; j < target.length && i < input.length; i++, j++) {
if (input[i] !== target[j]) {
return seqFind(input, target, index + 1);
}
}
return (i === index + target.length) ? index : -1;
}