// K-Meleon CCF -- autoinject.js
//
// Loaded ONCE by the app at startup and injected as a <script> into every
// content document (http/https/file) at "document-element-inserted" -- BEFORE
// the page's own scripts run. See CMfcEmbedApp::InjectAutoScript in
// app/mfcembed.cpp. The script is left in the DOM after appending; removing
// it at parser mid-parse cancels execution.
//
// Edit this file freely; restart the browser to pick up changes.

(function(){
  // (1) Intl.ListFormat polyfill. Missing in Goanna; English-only fallback.
  if (typeof Intl !== 'undefined' && !Intl.ListFormat) {
    function LF(locale, opts){
      opts = opts || {};
      var t = opts.type || 'conjunction';
      this.format = function(a){
        a = Array.prototype.slice.call(a || []).map(String);
        if (!a.length) return '';
        if (a.length === 1) return a[0];
        var c = (t === 'disjunction') ? ' or ' : ' and ';
        if (a.length === 2) return a[0] + c + a[1];
        return a.slice(0, -1).join(', ') + ',' + c + a[a.length - 1];
      };
      this.formatToParts = function(a){ return [{ type:'literal', value:this.format(a) }]; };
      this.resolvedOptions = function(){ return { locale: locale||'en', type: t, style: opts.style||'long' }; };
    }
    LF.supportedLocalesOf = function(){ return []; };
    try { Intl.ListFormat = LF; } catch(e) {}
  }

  // (2) Fetch stub for IPv6-only Cloudflare probe endpoints (ipv6-check-perf,
  //     *.ipv6-only.*). They have only AAAA records; on IPv4-only networks the
  //     fetch rejects with NetworkError, which radar.cloudflare.com doesn't catch.
  if (typeof window !== 'undefined' && window.fetch && !window.__kmFetchStubbed) {
    var origFetch = window.fetch;
    window.fetch = function(input, init){
      var u = (typeof input === 'string') ? input : (input && input.url) || '';
      if (/ipv6-check-perf|\.ipv6-only\./i.test(u)) {
        try {
          return Promise.resolve(new Response('{"ok":true}', {
            status: 200, headers: { 'content-type': 'application/json' }
          }));
        } catch(e) {
          return Promise.resolve({ ok:true, status:200,
            json: function(){ return Promise.resolve({ok:true}); },
            text: function(){ return Promise.resolve('{"ok":true}'); }});
        }
      }
      return origFetch.apply(this, arguments);
    };
    window.__kmFetchStubbed = true;
  }

  // (3) Swallow unhandled promise rejections so a single bad async doesn't tear
  //     down an entire React tree.
  if (typeof window !== 'undefined' && !window.__kmRejCaught) {
    window.__kmRejCaught = true;
    window.addEventListener('unhandledrejection', function(e){
      try { e.preventDefault(); } catch(_) {}
    });
  }
})();
