Improve this whole script, ensure it can work perfectly in cloudflare worker environment and constraints. Improve its performance, speed, initialisation time, reduce cold start, ensure it can work perfectly in any condition. adress all of the edge cases. Show the full potential and send the full improved code without breaking anything. -- addEventListener('fetch', event => {
  event.respondWith(handleRequest(event.request));
});

const config = {
  allowedDomains: ['https://api.abhibhai.com', 'http://localhost:8080'],
  headers: { 'Content-Type': 'application/json' },
  timeout: 10000,
  allowedMethods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS', 'PATCH', 'HEAD'],
  forwardHeaders: [
    'Authorization',
    'Content-Type',
    'User-Agent',
    'Accept-Language',
    'X-Requested-With',
    'If-Modified-Since',
    'Cache-Control',
  ],
  cacheControl: {
    enabled: true,
    maxAge: 3600,
    staleWhileRevalidate: 86400,
  },
  transformResponse: false,
  logging: {
    level: 'info',
  },
  allowedTargetHosts: [],
};

const AUTHORIZATION_KEY = 'yuichi1234k';

class ProxyError extends Error {
  constructor(message, status) {
    super(message);
    this.name = 'ProxyError';
    this.status = status;
  }
}

async function handleRequest(request) {
  const url = new URL(request.url);
  const origin = request.headers.get('Origin') || '';

  try {
    if (request.method === 'OPTIONS') {
      return handlePreflightRequest(request, origin);
    }

    if (request.method === 'POST' && url.pathname === '/modify-config') {
      return handleModifyConfig(request);
    }

    if (request.method === 'GET' && url.pathname === '/config-status') {
      return getConfigStatus(request);
    }

    await validateRequest(request, origin);

    const response = await forwardRequest(request, url);
    return createCorsResponse(response, origin);
  } catch (error) {
    return handleError(error, origin);
  }
}

async function validateRequest(request, origin) {
  if (!isAllowedOrigin(origin)) {
    throw new ProxyError('Unauthorized: Invalid Origin', 403);
  }

  if (!config.allowedMethods.includes(request.method)) {
    throw new ProxyError(`Method Not Allowed: ${request.method}`, 405);
  }
}

function isAllowedOrigin(origin) {
  if (!origin) {
    return true;
  }
  return config.allowedDomains.some(domain => {
    if (domain.endsWith('')) {
      return origin.startsWith(domain.slice(0, -1));
    }
    return origin === domain;
  });
}

async function forwardRequest(request, url) {
  const targetUrl = url.pathname.slice(1);

  if (!targetUrl) {
    throw new ProxyError('Bad Request: Missing target URL', 400);
  }

  let parsedTargetUrl;
  try {
    parsedTargetUrl = new URL(targetUrl);
  } catch (e) {
    throw new ProxyError('Bad Request: Invalid target URL', 400);
  }

  if (
    config.allowedTargetHosts.length > 0 &&
    !config.allowedTargetHosts.includes(parsedTargetUrl.host)
  ) {
    throw new ProxyError('Forbidden: Target host is not allowed', 403);
  }

  const init = {
    method: request.method,
    headers: new Headers(),
    redirect: 'follow',
  };

  for (const header of config.forwardHeaders) {
    const value = request.headers.get(header);
    if (value) {
      init.headers.set(header, value);
    }
  }

  Object.entries(config.headers).forEach(([key, value]) => {
    init.headers.set(key, value);
  });

  if (!['GET', 'HEAD'].includes(request.method)) {
    const contentType = request.headers.get('Content-Type') || '';
    if (contentType.includes('application/json')) {
      const body = await request.text();
      init.body = body;
    } else {
      init.body = await request.arrayBuffer();
    }
  }

  const controller = new AbortController();
  const timeoutId = setTimeout(() => controller.abort(), config.timeout);
  init.signal = controller.signal;

  try {
    const response = await fetch(parsedTargetUrl.toString(), init);
    clearTimeout(timeoutId);

    if (!response.ok) {
      throw new ProxyError(`Target server responded with status ${response.status}`, response.status);
    }

    return config.transformResponse ? transformResponse(response) : response;
  } catch (error) {
    if (error.name === 'AbortError') {
      throw new ProxyError('Request timed out', 504);
    }
    throw error;
  }
}

async function transformResponse(response) {
  return response;
}

function createCorsResponse(response, origin) {
  const corsHeaders = new Headers(response.headers);

  if (isAllowedOrigin(origin)) {
    corsHeaders.set('Access-Control-Allow-Origin', origin);
    corsHeaders.set('Access-Control-Allow-Credentials', 'true');
  } else {
    corsHeaders.set('Access-Control-Allow-Origin', '');
  }

  corsHeaders.set('Access-Control-Allow-Methods', config.allowedMethods.join(', '));
  corsHeaders.set('Access-Control-Allow-Headers', config.forwardHeaders.join(', '));
  corsHeaders.set('Access-Control-Expose-Headers', '');

  if (config.cacheControl.enabled) {
    corsHeaders.set(
      'Cache-Control',
      `max-age=${config.cacheControl.maxAge}, stale-while-revalidate=${config.cacheControl.staleWhileRevalidate}`
    );
  }

  return new Response(response.body, {
    status: response.status,
    statusText: response.statusText,
    headers: corsHeaders,
  });
}

function handlePreflightRequest(request, origin) {
  if (!isAllowedOrigin(origin)) {
    throw new ProxyError('Unauthorized: Invalid Origin', 403);
  }

  const requestHeaders = request.headers.get('Access-Control-Request-Headers') || '';
  const requestMethod = request.headers.get('Access-Control-Request-Method') || '';

  if (!config.allowedMethods.includes(requestMethod.toUpperCase())) {
    throw new ProxyError(`Method Not Allowed: ${requestMethod}`, 405);
  }

  const headers = {
    'Access-Control-Allow-Origin': origin,
    'Access-Control-Allow-Methods': config.allowedMethods.join(', '),
    'Access-Control-Allow-Headers': requestHeaders || config.forwardHeaders.join(', '),
    'Access-Control-Allow-Credentials': 'true',
    'Access-Control-Max-Age': '86400',
  };

  return new Response(null, {
    status: 204,
    headers: headers,
  });
}

async function handleModifyConfig(request) {
  const authKey = request.headers.get('Authorization');
  if (authKey !== AUTHORIZATION_KEY) {
    throw new ProxyError('Unauthorized: Invalid Authorization Key', 403);
  }

  let body;
  try {
    body = await request.json();
  } catch (error) {
    throw new ProxyError('Bad Request: Invalid JSON body', 400);
  }

  updateConfig(body);

  return new Response(
    JSON.stringify({ success: true, fullConfig: getPublicConfig() }),
    {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    }
  );
}

function updateConfig(body) {
  const immutableKeys = ['logging', 'transformResponse'];

  for (const key in body) {
    if (config.hasOwnProperty(key) && !immutableKeys.includes(key)) {
      if (typeof config[key] === 'object' && !Array.isArray(config[key])) {
        config[key] = { ...config[key], ...body[key] };
      } else {
        config[key] = body[key];
      }
    }
  }
}

function getConfigStatus(request) {
  const authKey = request.headers.get('Authorization');
  if (authKey !== AUTHORIZATION_KEY) {
    throw new ProxyError('Unauthorized: Invalid Authorization Key', 403);
  }

  return new Response(JSON.stringify(getPublicConfig()), {
    status: 200,
    headers: { 'Content-Type': 'application/json' },
  });
}

function getPublicConfig() {
  const { headers, ...publicConfig } = config;
  return publicConfig;
}

function handleError(error, origin) {
  const status = error instanceof ProxyError ? error.status : 500;
  const message =
    config.logging.level === 'debug' && error.stack ? error.stack : error.message;

  logError(error);

  const headers = {
    'Content-Type': 'application/json',
  };

  if (isAllowedOrigin(origin)) {
    headers['Access-Control-Allow-Origin'] = origin;
    headers['Access-Control-Allow-Credentials'] = 'true';
  } else {
    headers['Access-Control-Allow-Origin'] = '';
  }

  return new Response(JSON.stringify({ error: message }), {
    status: status,
    headers: headers,
  });
}

function logError(error) {
  const logLevel = config.logging.level;
  const logLevels = ['debug', 'info', 'warn', 'error'];

  if (logLevels.indexOf(logLevel) <= logLevels.indexOf('error')) {
    console.error('Proxy Error:', error.message);
    if (logLevel === 'debug' && error.stack) {
      console.error(error.stack);
    }
  }
}