bennyp / NPM UNPKG Links

// ==UserScript==
// @name         NPM UNPKG Links
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  Add links to UNPKG on npmjs.com
// @author       Benny Powers <web@bennypowers.com>
// @match        https://www.npmjs.com/package/*
// @grant        GM_xmlhttpRequest
// @grant        xmlhttpRequest
// @connect      unpkg.com
// @license      MIT
// ==/UserScript==

(async function() {
    'use strict';
    const handleAsJson = response => response.json();
    const { pathname } = location
    const packageName = pathname.replace('/package/', '');
    const unpkgUrl = `https://unpkg.com/${packageName}`
    const packageJsonUrl = `${unpkgUrl}/package.json`;

    console.log(packageJsonUrl);

    const json = await new Promise((resolve, onerror) => GM_xmlhttpRequest({
      method: "GET",
      url: packageJsonUrl,
      responseType: 'json',
      onload: ({ response }) => resolve(response),
      onerror,
    }));

    const { main, module, type, types } = json

    const isTypesPackage = packageName.startsWith('@types')
    const isModule = type === "module" || module;

    const linkHref = `${unpkgUrl}${(isTypesPackage ? `/${types.replace('.d.ts', '') + '.d.ts'}` : isModule ? '?module' : '')}`;

    const sidebar = document.querySelector('.w-third-l.mt3.w-100.ph3.ph4-m.pv3.pv0-l.order-1-ns.order-0')
    const repository = sidebar.querySelectorAll('.dib.pr2')[5]
    const unpkg = repository.cloneNode(true);
    const link = unpkg.querySelector('a');
    const iconContainer = link.querySelector('span');
    const linkText = unpkg.querySelector('span:last-child');

    iconContainer.innerHTML = `<img src="https://unpkg.com/favicon.ico" alt="unpkg logo"/.>`;
    link.href = linkHref;
    linkText.textContent= unpkgUrl.replace('https://', '');
    repository.after(unpkg);
})();