import * as ipaddr from 'ipaddr.js';

const KEEP_IPV4_BYTES = 3;
const KEEP_IPV6_BYTES = 6;

async function handleRequest(event) {
  let ip = event.client.address;
  
  try {
    let anon = anonymize(ip);
    console.log(`IP ${ip} anonymized to ${anon}`);
  } catch (e) {
    console.log(e.message);
  }

  return new Response('', { status: 200 });
};

function anonymize(ip) {
  const parsedIp = ipaddr.parse(ip);
  const KEEP_BYTES = parsedIp.kind() == 'ipv4' ? KEEP_IPV4_BYTES : KEEP_IPV6_BYTES;
  let b = parsedIp.toByteArray().map((part, i) => i < KEEP_BYTES ? part : 0);
  return ipaddr.fromByteArray(b).toString();
}

addEventListener('fetch', event => event.respondWith(handleRequest(event)));