/* -  This is a javascript snippet to be used with
      http://mcdlr.com/js-inject/             - */


/* -  GitHub - https://github.com/any-repo/package.json  - *\
|* -  Link package dependencies on a package.json to npm - *|
\* -  v1.0                                               - */


const findParentBySelector = (elem, selector) => {
  const parent = elem.parentNode;
  if (parent.matches(selector)) {
    return parent;
  } else {
    return findParentBySelector(parent, selector);
  }
};

const isEndOfObject = (row) => {
  return /}/.test(row.textContent);
};

const linkToNMP = (tr) => {
  const packageEl = tr.querySelector('.pl-s:first-child');
  const packageText = packageEl.textContent;
  const packageName = packageEl.textContent.replace(/["']*/g, '');
  packageEl.innerHTML = `<a href='https://www.npmjs.com/package/${packageName}' style='text-decoration: underline'>${packageText}</a>`;
};

const traverseTrs = (dep) => {
  const trFather = dep.matches('tr') ? dep : findParentBySelector(dep, 'tr');
  const trSibling = trFather.nextElementSibling
  if(!isEndOfObject(trSibling)){
    linkToNMP(trSibling);
    traverseTrs(trSibling);
  }
};

if (window.location.host === 'github.com' && window.location.pathname.endsWith('package.json')) {
  const deps = Array.from(document.querySelectorAll('.pl-s:first-child'))
    .filter((el, i) => /"(dev)?[Dd]ependencies"/.test(el.textContent));
  for(dep of deps){
    traverseTrs(dep)
  };
} else {
  alert('This is not a package.json file on github.com');
}

/* -  /GitHub  - */

@@ -501,19 +501,21 @@
 const is
-End
+Start
 OfObject
@@ -530,18 +530,66 @@
  =%3E 
-%7B%0A  return
+/%7B/.test(row.textContent);%0A%0Aconst isEndOfObject = (row) =%3E
  /%7D/
@@ -611,19 +611,16 @@
 ontent);
-%0A%7D;
 %0A%0Aconst 
@@ -774,29 +774,19 @@
  package
-El.textConten
+Tex
 t.replac
@@ -1098,16 +1098,18 @@
 tSibling
+;%0A
 %0A  if(!i
@@ -1127,19 +1127,98 @@
 t(tr
-Sibling))%7B%0A
+Father))%7B%0A    if(isStartOfObject(trFather))%7B%0A      traverseTrs(trSibling);%0A    %7D else %7B%0A  
     
@@ -1229,26 +1229,27 @@
 ToNMP(tr
-Sibling
+Father
 );%0A
+  
     trav
@@ -1268,20 +1268,27 @@
 bling);%0A
+    %7D%0A
   %7D%0A
+%0A
 %7D;%0A%0Aif (
@@ -1547,16 +1547,16 @@
  deps)%7B%0A
-
     trav
@@ -1567,16 +1567,17 @@
 Trs(dep)
+;
 %0A  %7D;%0A%7D 

Handle empty package list