nikolay-borzov / SCHE-DIGI dev env links fixer

// ==UserScript==
// @name         SCHE-DIGI dev env links fixer
// @namespace    sche
// @version      1.0.11
// @description  Replaces all production/pre-production links by environment specific
// @author       nikolay-borzov
// @include      http://fe*.sche-digi.projects.epam.com/*
// @include      http://www-sqepes.ecom.schneider-electric.com/*
// @include      http://lpesipo1001cppr.schneider-electric.com*
// @include      http://localhost:*
// @grant        none
// @license      MIT
// ==/UserScript==

(function () {
  'use strict';

  const hostRegionPartMap = {
    'www.schneider-electric.us': '/US',
    'www.schneider-electric.com': '/WW',
    'www.schneider-electric.fr': '/FR'
  };

  const internalHostRegExes = [
    /fe.*-app.sche-digi\.projects\.epam\.com/,
    /www-sqepes\.ecom\.schneider-electric\.com/,
    /www-sqe1\.schneider-electric\.com/,
    /lpesipo1001cppr\.schneider-electric\.com/,
    /www-prd\.amer1\.sdl\.schneider-electric\.com/,
    /www-(pre)?prdpes\.ecom\.schneider-electric\.com/,
    /www\.schneider-electric\./,
    /www\.se\.com/
  ];

  const host = location.host;
  const regionLangPart = location.pathname.substr(0, 7); // e.g. '/FR/fr/';
  const regionLangRegExp = new RegExp(regionLangPart, 'i');
  const allLinks = document.querySelectorAll('a[href]');

  for (const link of allLinks) {
    const linkHost = link.host;

    if (linkHost === host) {
      continue;
    }

    // ignore external links
    if (!internalHostRegExes.some(regEx => regEx.test(linkHost))) {
      continue;
    }

    const replaceWith = host + (hostRegionPartMap[linkHost] || '');

    const sameHostURL = link.href
      .replace(linkHost, replaceWith)
      .replace('https:', 'http:') // Dev envs are HTTP
      .replace(regionLangRegExp, regionLangPart); // Make sure region-lang path is in the same case

    link.setAttribute('href', sameHostURL);
  }
})();