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.

17. **Final Deliverable**:
    - Send the fully working, fully updated code without any duplication or issues.
    - Ensure the code is fully improved without breaking anything.
    ----
 // 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([
    'content-type',
    'user-agent',
    'accept',
    'accept-language',
    'x-requested-with',
    'if-modified-since',
    'cache-control',
    'authorization',
  ]),
  REMOVE_HEADERS: new Set([
    'cf-connecting-ip',
    'x-forwarded-for',
    'x-real-ip',
    'cookie',
    'proxy-authorization',
    'from',
    'via',
    'X-Forwarded-For',
    'x-forwarded-proto',
    'x-forwarded-protocol',
    'x-forwarded-ssl',
    'x-url-scheme',
    'x-request-id',
    'referer',
    'From',
  ]),
  TIMEOUT: 30000,
  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 await 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 = url.pathname.slice(1) + url.search;

  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 },
  };

  // Forward only specified headers
  for (const header of CONFIG.FORWARD_HEADERS) {
    if (request.headers.has(header)) {
      init.headers.set(header, request.headers.get(header));
    }
  }

  if (!['GET', 'HEAD'].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);

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

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

  // Ensure content-type matches the request
  if (requestContentType) {
    responseHeaders.set('content-type', requestContentType);
  }

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

  // Check if we should stream the response
  const contentLength = parseInt(responseHeaders.get('content-length'), 10);
  if (!isNaN(contentLength) && contentLength > CONFIG.STREAM_THRESHOLD) {
    return new Response(streamResponse(response), {
      status: response.status,
      statusText: response.statusText,
      headers: responseHeaders,
    });
  }

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

async function* streamResponse(response) {
  const reader = response.body.getReader();
  try {
    while (true) {
      const { done, value } = await reader.read();
      if (done) break;
      yield value;
    }
  } finally {
    reader.releaseLock();
  }
}

function generateCorsHeaders(origin) {
  const headers = new Headers();
  headers.set('Access-Control-Allow-Origin', isAllowedOrigin(origin) ? origin : '*');
  headers.set('Access-Control-Allow-Credentials', 'true');
  headers.set('Access-Control-Allow-Methods', '*');
  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 headers = generateCorsHeaders(request.headers.get('Origin'));
  headers.set('Access-Control-Allow-Methods', request.headers.get('Access-Control-Request-Method') || '*');
  headers.set('Access-Control-Allow-Headers', request.headers.get('Access-Control-Request-Headers') || '*');
  return new Response(null, { status: 204, headers });
}

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 Set) {
        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 limit
  CONFIG.TIMEOUT = Math.min(CONFIG.TIMEOUT, 30000);
}

async function checkRateLimit(request) {
  const clientIP = request.headers.get('CF-Connecting-IP');
  const rateLimitKey = `ratelimit:${clientIP}`;

  const currentCount = await getOrSetKV(rateLimitKey, 0);
  
  if (currentCount >= CONFIG.RATE_LIMIT.REQUESTS_PER_MINUTE) {
    return false;
  }

  await incrementKV(rateLimitKey);
  return true;
}

async function getOrSetKV(key, defaultValue) {
  let value = await KV.get(key);
  if (value === null) {
    await KV.put(key, defaultValue.toString(), { expirationTtl: 60 });
    return defaultValue;
  }
  return parseInt(value, 10);
}

async function incrementKV(key) {
  await KV.put(key, (await getOrSetKV(key, 0) + 1).toString(), { expirationTtl: 60 });
}

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 };
}