import * as eslexer from "es-module-lexer";
import fetch from "node-fetch";
import fs from "fs";
import slash from "slash";
import glob from "tiny-glob";
import {fileURLToPath} from "url";
async function scan(cwd, pattern) {
  const results = await glob(pattern, {cwd: fileURLToPath(cwd)});
  return results.map((filepath) => new URL(slash(filepath), cwd));
}
async function profileHTML({cwd}) {
  const sizes = {};
  const html = await scan(cwd, "**/*.html");
  let maxSize = 0;
  await Promise.all(html.map(async (file) => {
    const relPath = file.pathname.replace(cwd.pathname, "");
    const size = (await fs.promises.stat(file)).size;
    sizes[relPath] = size;
    if (size > maxSize)
      maxSize = size;
  }));
  return {
    html: sizes,
    maxSize
  };
}
async function profileJS({cwd, entryHTML}) {
  const sizes = {};
  let htmlSize = 0;
  if (entryHTML) {
    let entryScripts = [];
    let visitedEntry = false;
    let scanPromises = [];
    await Promise.all(entryScripts.map(parseJS));
    async function parseJS(url) {
      const relPath = url.pathname.replace(cwd.pathname, "");
      if (sizes[relPath])
        return;
      try {
        let code = url.protocol === "file:" ? await fs.promises.readFile(url, "utf8") : await fetch(url.href).then((body) => body.text());
        sizes[relPath] = Buffer.byteLength(code);
        const staticImports = eslexer.parse(code)[0].filter(({d}) => {
          if (!visitedEntry)
            return true;
          return d === -1;
        });
        for (const {n} of staticImports) {
          if (!n)
            continue;
          let nextURL;
          if (n.startsWith("http://") || n.startsWith("https://") || n.startsWith("//"))
            nextURL = new URL(n);
          else if (n[0] === ".")
            nextURL = new URL(n, url);
          else if (n[0] === "/")
            nextURL = new URL(`.${n}`, cwd);
          if (!nextURL)
            continue;
          if (sizes[nextURL.pathname.replace(cwd.pathname, "")])
            continue;
          scanPromises.push(parseJS(nextURL));
        }
      } catch (err) {
        console.warn(`Could not access ${url.href} to include in bundle size`);
      }
      visitedEntry = true;
    }
    await Promise.all(scanPromises);
    htmlSize = Object.values(sizes).reduce((sum, next) => sum + next, 0);
  }
  const js = await scan(cwd, "**/*.(js|mjs|wasm)");
  await Promise.all(js.map(async (file) => {
    const relPath = file.pathname.replace(cwd.pathname, "");
    if (!sizes[relPath])
      sizes[relPath] = (await fs.promises.stat(file)).size;
  }));
  return {
    js: sizes,
    entryHTML: htmlSize || void 0,
    total: Object.values(sizes).reduce((sum, acc) => sum + acc, 0)
  };
}
function kb(bytes) {
  if (bytes === 0)
    return `0 kB`;
  return (Math.round(bytes / 1e3) || 1) + " kB";
}
export {
  kb,
  profileHTML,
  profileJS
};
//# sourceMappingURL=data:application/json;base64,ewogICJ2ZXJzaW9uIjogMywKICAic291cmNlcyI6IFsiLi4vLi4vLi4vc3JjL2NvcmUvYnVpbGQvc3RhdHMudHMiXSwKICAibWFwcGluZ3MiOiAiQUFBQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUF5QkEsb0JBQW9CLEtBQVUsU0FBaUM7QUFDN0QsUUFBTSxVQUFVLE1BQU0sS0FBSyxTQUFTLENBQUUsS0FBSyxjQUFjO0FBQ3pELFNBQU8sUUFBUSxJQUFJLENBQUMsYUFBYSxJQUFJLElBQUksTUFBTSxXQUFXO0FBQUE7QUFJNUQsMkJBQWtDLENBQUUsTUFBMEM7QUFDNUUsUUFBTSxRQUFtQjtBQUN6QixRQUFNLE9BQU8sTUFBTSxLQUFLLEtBQUs7QUFDN0IsTUFBSSxVQUFVO0FBQ2QsUUFBTSxRQUFRLElBQ1osS0FBSyxJQUFJLE9BQU8sU0FBUztBQUN2QixVQUFNLFVBQVUsS0FBSyxTQUFTLFFBQVEsSUFBSSxVQUFVO0FBQ3BELFVBQU0sT0FBUSxPQUFNLEdBQUcsU0FBUyxLQUFLLE9BQU87QUFDNUMsVUFBTSxXQUFXO0FBQ2pCLFFBQUksT0FBTztBQUFTLGdCQUFVO0FBQUE7QUFHbEMsU0FBTztBQUFBLElBQ0wsTUFBTTtBQUFBLElBQ047QUFBQTtBQUFBO0FBS0oseUJBQWdDLENBQUUsS0FBSyxZQUErRDtBQUNwRyxRQUFNLFFBQW1CO0FBQ3pCLE1BQUksV0FBVztBQUdmLE1BQUksV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