1. Content Type Support: 
   - Ensure the script always supports and uses only the content type provided with the request.
   - Expand support to include all content types.

2. Header Management:
   - Do not send any IP-related headers.
   - Prevent the destination URL from detecting the use of a proxy.

3. URL Management:
   - Simplify the process of changing which URLs are allowed or disallowed from being forwarded to the destination.

4. Script Improvement:
   - Continuously improve the script further.

5. Cloudflare Workers Compatibility:
   - Maintain compatibility with Cloudflare Workers' environment and constraints, considering memory, execution timeout, and request limits.

6. Customization and Flexibility:
   - Make the script highly customizable and flexible.

7. Edge Case Handling:
   - Address and handle all potential edge cases that have not been addressed yet.

8. Performance Optimization:
   - Optimize the script to be as fast as possible.
   - Reduce cold start time as much as possible.

9. Code and Technique Quality:
   - Enhance the quality of the code and the techniques used.
   - Advance the script further to improve its overall quality.

10. CORS Management:
    - Always prevent CORS errors for allowed domain users, regardless of the method or situation.
    - Bypass CORS restrictions on all requests/responses related to allowed domains.
    - Ensure the 'Access-Control-Allow-Origin' header is always present on requested resources before sending to users.
    - Ensure it prevents CORS policy errors for all users from allowed domains.

11. Request and Response Handling:
    - Add support for more content types.
    - Ensure all methods work perfectly with the script proxy service without any issues.
    - Do not wait for the full requested resources to load.
    - Ensure it can handle all types of requests and responses with all types of methods perfectly.

12. Integration:
    - Integrate changes without breaking or conflicting with existing functionalities or duplicating anything.

13. Comprehensive Improvement:
    - Continuously improve the provided Cloudflare Worker script further.
    - Ensure any user from allowed domains won't encounter any CORS policy errors, regardless of the method they use.
    - Make it impossible for allowed domain users to face any type of CORS error in any method or situation.

14. Up-to-date Compatibility:
    - Ensure the compatibility of the whole script with the latest Cloudflare Workers' environment and constraints.

15. Adherence to Constraints:
    - Adhere to all up-to-date constraints, including memory, execution timeout, and request limits.

16. Functional Integration:
    - Correctly integrate the script into existing functionalities without breaking or conflicting with anything.
    - Always consider the consequences and reactions of your changes or actions.

Make it impossible for all of the users from allowed domain to encounter any type of CORS policy error no matter the method, situation, request and response. Now, ensure to always add all of the necessary CORS headers on the REQUESTED RESOURCES correctly BEFORE sending it to the user. don't damage the request and response payloads. If a content type is mentioned on the request then only use that content type mentioned in the request for that particular request/response cycle. don't clone or damage the requests and responses just do only the necessary things. don't let the destination url know about the proxy use. don't forward any ip and proxy related identify headers to the destination url. handle all methods requests and responses correctly and effectively with efficiency as they should be handled. when making any changes or modifications, allways consider all of the consequences and reaction and handl them correctly. Always Give only the robust codes. Intregate all of these new changes correctly, effectively and then send the fully working full improved code without breaking and duplicating anything.
----
// Default Configuration
const DEFAULT_CONFIG = {
  ALLOWED_DOMAINS: new Set([
    'https://api.abhibhai.com',
    'https://lnee.netlify.app',
    'https://proxe.netlify.app',
    'http://localhost:8080',
  ]),
  BLOCKED_TARGET_HOSTS: new Set(['blocked.example.com']),
  FORWARD_HEADERS: new Set([
    'Accept',
    'Accept-Language',
    'User-Agent',
    'Content-Type',
    'Authorization',
    'Cache-Control',
    'Pragma',
    'Expires',
    'Last-Modified',
    'If-Modified-Since',
    'If-None-Match',
  ]),
  REMOVE_HEADERS: new Set([
    'cf-connecting-ip',
    'x-forwarded-for',
    'x-real-ip',
    'cookie',
    'proxy-authorization',
    'from',
    'via',
    'referer',
    'x-request-id',
    'x-csrf-token',
    'x-xsrf-token',
    'x-forwarded-proto',
    'x-forwarded-protocol',
    'x-forwarded-ssl',
    'x-url-scheme',
  ]),
  TIMEOUT: 29000,
  LOGGING_LEVEL: 'warn',
  AUTH_KEY: 'yuichi1234k', // Replace with a secure key
  SECURITY_HEADERS: {
    'X-Content-Type-Options': 'nosniff',
    'Referrer-Policy': 'strict-origin-when-cross-origin',
    'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload',
  },
  CUSTOM_ERROR_RESPONSES: {},
  RATE_LIMIT: {
    REQUESTS_PER_MINUTE: 60,
    BURST: 10,
  },
  CACHE_CONTROL: {
    DEFAULT_MAX_AGE: 300, // 5 minutes
    CUSTOM_RULES: {},
  },
  STREAM_THRESHOLD: 1024 * 1024, // 1MB
};

let CONFIG = { ...DEFAULT_CONFIG };

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

addEventListener('fetch', (event) => {
  event.passThroughOnException();
  event.respondWith(
    handleRequest(event).catch((error) =>
      handleError(error, event.request.headers.get('Origin'))
    )
  );
});

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

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

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

  if (!isAllowedOrigin(origin)) {
    throw new ProxyError('Forbidden', 403);
  }

  if (!(await checkRateLimit(request))) {
    throw new ProxyError('Rate limit exceeded', 429);
  }

  return forwardRequest(request, url, origin);
}

function isAllowedOrigin(origin) {
  return CONFIG.ALLOWED_DOMAINS.has(origin) || CONFIG.ALLOWED_DOMAINS.has('*');
}

async function forwardRequest(request, url, origin) {
  const targetUrl = request.headers.get('x-target-url') || url.searchParams.get('target');

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

  let parsedTargetUrl;
  try {
    parsedTargetUrl = new URL(targetUrl);
  } catch (err) {
    throw new ProxyError('Invalid URL format', 400);
  }

  if (CONFIG.BLOCKED_TARGET_HOSTS.has(parsedTargetUrl.host)) {
    throw new ProxyError('Forbidden: Target host is not allowed', 403);
  }

  const init = {
    method: request.method,
    headers: new Headers(),
    redirect: 'follow',
    cf: { timeout: CONFIG.TIMEOUT / 1000 }, // Convert ms to seconds
  };

  // Forward headers, excluding the ones to be removed
  for (const [key, value] of request.headers.entries()) {
    const lowerKey = key.toLowerCase();
    if (!CONFIG.REMOVE_HEADERS.has(lowerKey) && lowerKey !== 'origin') {
      init.headers.set(key, value);
    }
  }

  // Set Content-Type for non-GET requests if not specified
  if (!request.headers.has('Content-Type') && request.method !== 'GET' && request.method !== 'HEAD') {
    init.headers.set('Content-Type', 'application/octet-stream');
  }

  // Handle request body
  if (['POST', 'PUT', 'PATCH'].includes(request.method)) {
    init.body = request.body;
  }

  const response = await fetch(parsedTargetUrl.toString(), init);
  return createCorsResponse(response, origin, request.headers.get('Content-Type'));
}

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

  // Remove disallowed headers from the response
  for (const header of CONFIG.REMOVE_HEADERS) {
    responseHeaders.delete(header);
  }

  // Apply CORS headers
  for (const [key, value] of corsHeaders.entries()) {
    responseHeaders.set(key, value);
  }

  // Apply security headers
  for (const [key, value] of Object.entries(CONFIG.SECURITY_HEADERS)) {
    responseHeaders.set(key, value);
  }

  // Ensure content-type matches the request if available
  if (requestContentType && !responseHeaders.has('Content-Type')) {
    responseHeaders.set('Content-Type', requestContentType);
  }

  // Apply cache control
  applyCacheControl(responseHeaders, response.url);

  // Determine if we should stream the response
  const contentLength = parseInt(responseHeaders.get('Content-Length'), 10);
  const shouldStream = isNaN(contentLength) || contentLength > CONFIG.STREAM_THRESHOLD;

  if (shouldStream) {
    return new Response(response.body, {
      status: response.status,
      statusText: response.statusText,
      headers: responseHeaders,
    });
  } else {
    const responseBody = await response.arrayBuffer();
    return new Response(responseBody, {
      status: response.status,
      statusText: response.statusText,
      headers: responseHeaders,
    });
  }
}

function generateCorsHeaders(origin) {
  const headers = new Headers();
  const allowedOrigin = isAllowedOrigin(origin) ? origin : '*';

  headers.set('Access-Control-Allow-Origin', allowedOrigin);
  headers.set('Access-Control-Allow-Credentials', 'true');
  headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH');
  headers.set('Access-Control-Allow-Headers', '*');
  headers.set('Access-Control-Expose-Headers', '*');
  headers.set('Access-Control-Max-Age', '86400');

  return headers;
}

function handlePreflightRequest(request) {
  const origin = request.headers.get('Origin') || '';
  const corsHeaders = generateCorsHeaders(origin);

  // Add Vary header to ensure proper caching
  corsHeaders.set('Vary', 'Origin');

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

function handleError(error, origin) {
  const status = error instanceof ProxyError ? error.status : 500;
  const message = error.message || 'Internal Server Error';

  logError(error);

  const headers = new Headers({
    'Content-Type': 'application/json',
    ...CONFIG.SECURITY_HEADERS,
    ...generateCorsHeaders(origin || '*'),
  });

  const customErrorResponse = CONFIG.CUSTOM_ERROR_RESPONSES[status];
  if (customErrorResponse) {
    return new Response(JSON.stringify(customErrorResponse), { status, headers });
  }

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

function logError(error) {
  const logLevel = CONFIG.LOGGING_LEVEL.toLowerCase();
  const logMessage = [${new Date().toISOString()}] ${error.name}: ${error.message};

  switch (logLevel) {
    case 'error':
      console.error(logMessage);
      break;
    case 'warn':
      console.warn(logMessage);
      break;
    case 'info':
      console.info(logMessage);
      break;
    case 'debug':
      console.log(logMessage, error.stack);
      break;
  }
}

async function handleConfigUpdate(request) {
  const authHeader = request.headers.get('Authorization');
  if (!authHeader || authHeader !== Bearer ${CONFIG.AUTH_KEY}) {
    return new Response('Unauthorized', { status: 401 });
  }

  try {
    const updatedConfig = await request.json();
    updateConfig(updatedConfig);
    return new Response(JSON.stringify({ message: 'Configuration updated successfully' }), {
      status: 200,
      headers: { 'Content-Type': 'application/json' },
    });
  } catch (error) {
    return new Response(JSON.stringify({ error: 'Invalid configuration data' }), {
      status: 400,
      headers: { 'Content-Type': 'application/json' },
    });
  }
}

function updateConfig(newConfig) {
  for (const [key, value] of Object.entries(newConfig)) {
    if (key in CONFIG) {
      if (value instanceof Array) {
        CONFIG[key] = new Set(value);
      } else if (typeof value === 'object' && value !== null) {
        CONFIG[key] = { ...CONFIG[key], ...value };
      } else {
        CONFIG[key] = value;
      }
    }
  }

  // Ensure TIMEOUT doesn't exceed Cloudflare's limits (30 seconds)
  CONFIG.TIMEOUT = Math.min(CONFIG.TIMEOUT, 30000);
}

async function checkRateLimit(request) {
  const clientIP = request.headers.get('CF-Connecting-IP');
  const rateLimitKey = ratelimit:${clientIP};
  const now = Math.floor(Date.now() / 60000); // Current minute as timestamp
  const key = ${rateLimitKey}:${now};

  let currentCount = parseInt(await RATELIMIT_KV.get(key), 10);
  if (isNaN(currentCount)) {
    currentCount = 0;
  }

  if (currentCount >= CONFIG.RATE_LIMIT.REQUESTS_PER_MINUTE) {
    return false;
  }

  currentCount += 1;
  await RATELIMIT_KV.put(key, currentCount.toString(), { expirationTtl: 120 });

  return true;
}

function applyCacheControl(headers, url) {
  const parsedUrl = new URL(url);
  const customRule = CONFIG.CACHE_CONTROL.CUSTOM_RULES[parsedUrl.pathname];

  if (customRule) {
    headers.set('Cache-Control', customRule);
  } else {
    headers.set('Cache-Control', public, max-age=${CONFIG.CACHE_CONTROL.DEFAULT_MAX_AGE});
  }
}

// Helper function to reset configuration to default
function resetConfig() {
  CONFIG = { ...DEFAULT_CONFIG };
}

// Workers KV namespace binding required for rate limiting
const RATELIMIT_KV = {
  get: async (key) => {
    return await RATE_LIMIT_NAMESPACE.get(key);
  },
  put: async (key, value, options) => {
    await RATE_LIMIT_NAMESPACE.put(key, value, options);
  },
};