Scamming Bug Hot Fix

A temporary workaround for a bug in the scamming page of Torn.

// ==UserScript==
// @name        Scamming Bug Hot Fix
// @namespace   https://github.com/tobytorn
// @description A temporary workaround for a bug in the scamming page of Torn.
// @author      tobytorn [1617955]
// @match       https://www.torn.com/loader.php?sid=crimes*
// @version     1.0.0
// @grant       unsafeWindow
// @run-at      document-start
// @license     MIT
// ==/UserScript==

(function () {
  'use strict';

  // Avoid duplicate injection in TornPDA
  if (window.SCAMMING_HOT_FIX) {
    return;
  }
  window.SCAMMING_HOT_FIX = true;
  console.log('Scamming Hot Fix starts');

  async function hotFix(rsp) {
    const data = await rsp.json();
    const targets = data.DB?.crimesByType?.targets;
    let count = 0;
    if (targets) {
      for (const target of targets) {
        if (typeof target.subID === 'number') {
          target.subID = String(target.subID);
          count++;
        }
      }
      console.log('Scamming Hot Fix: fix type', count);
    }
    rsp.text = () => {
      return Promise.resolve(JSON.stringify(data));
    };
  }

  function interceptFetch() {
    const targetWindow = typeof unsafeWindow !== 'undefined' ? unsafeWindow : window;
    const origFetch = targetWindow.fetch;
    targetWindow.fetch = async (...args) => {
      const rsp = await origFetch(...args);

      try {
        const url = new URL(args[0], location.origin);
        const params = new URLSearchParams(url.search);
        if (url.pathname === '/loader.php' && params.get('sid') === 'crimesData' && params.get('typeID') === '12') {
          await hotFix(rsp);
        }
      } catch {
        // ignore
      }

      return rsp;
    };
  }

  interceptFetch();
})();