import { promises } from 'node:fs';
import { createApp, eventHandler, toNodeListener, lazyEventHandler } from './index2.mjs';
import { listen } from './index.mjs';
import { d as defu } from '../shared/nuxi.a685c563.mjs';
import { l as loadKit } from '../shared/nuxi.60154167.mjs';
import { a as clearDir } from '../shared/nuxi.04a0178b.mjs';
import { o as overrideEnv } from '../shared/nuxi.d21ab543.mjs';
import { d as defineNuxtCommand } from '../shared/nuxi.c68ce99d.mjs';
import { r as resolve, j as join } from '../shared/nuxi.ffb4843d.mjs';
import '../shared/nuxi.f03591c1.mjs';
import 'node:module';
import 'node:url';
import 'node:assert';
import 'node:process';
import 'node:path';
import 'node:v8';
import 'node:util';
import 'node:http';
import 'node:https';
import 'node:os';
import '../shared/nuxi.a3b9dacd.mjs';
import 'tty';
import 'node:net';
import '../shared/nuxi.24198af3.mjs';
import 'http';
import 'https';
import 'node:child_process';
import '../shared/nuxi.bd22f1f6.mjs';
import '../shared/nuxi.114b1a98.mjs';

const analyze = defineNuxtCommand({
  meta: {
    name: "analyze",
    usage: "npx nuxi analyze [--log-level] [--name] [--no-serve] [rootDir]",
    description: "Build nuxt and analyze production bundle (experimental)"
  },
  async invoke(args, options = {}) {
    overrideEnv("production");
    const name = args.name || "default";
    const slug = name.trim().replace(/[^a-z0-9_-]/gi, "_");
    const rootDir = resolve(args._[0] || ".");
    let analyzeDir = join(rootDir, ".nuxt/analyze", slug);
    let buildDir = join(analyzeDir, ".nuxt");
    let outDir = join(analyzeDir, ".output");
    const startTime = Date.now();
    const { loadNuxt, buildNuxt } = await loadKit(rootDir);
    const nuxt = await loadNuxt({
      rootDir,
      overrides: defu(options.overrides, {
        build: {
          analyze: true
        },
        analyzeDir,
        buildDir,
        nitro: {
          output: {
            dir: outDir
          }
        },
        logLevel: args["log-level"]
      })
    });
    analyzeDir = nuxt.options.analyzeDir;
    buildDir = nuxt.options.buildDir;
    outDir = nuxt.options.nitro.output?.dir || outDir;
    await clearDir(analyzeDir);
    await buildNuxt(nuxt);
    const endTime = Date.now();
    const meta = {
      name,
      slug,
      startTime,
      endTime,
      analyzeDir,
      buildDir,
      outDir
    };
    await nuxt.callHook("build:analyze:done", meta);
    await promises.writeFile(join(analyzeDir, "meta.json"), JSON.stringify(meta, null, 2), "utf-8");
    console.info("Analyze results are available at: `" + analyzeDir + "`");
    console.warn("Do not deploy analyze results! Use `nuxi build` before deploying.");
    if (args.serve !== false && !process.env.CI) {
      const app = createApp();
      const serveFile = (filePath) => lazyEventHandler(async () => {
        const contents = await promises.readFile(filePath, "utf-8");
        return eventHandler((event) => {
          event.node.res.end(contents);
        });
      });
      console.info("Starting stats server...");
      app.use("/client", serveFile(join(analyzeDir, "client.html")));
      app.use("/nitro", serveFile(join(analyzeDir, "nitro.html")));
      app.use(eventHandler(() => `<!DOCTYPE html>
        <html lang="en">
        <head>
        <meta charset="utf-8">
        <title>Nuxt Bundle Stats (experimental)</title>
        </head>
          <h1>Nuxt Bundle Stats (experimental)</h1>
          <ul>
            <li>
              <a href="/nitro">Nitro server bundle stats</a>
            </li>
            <li>
              <a href="/client">Client bundle stats</a>
            </li>
          </ul>
        </html>
      `));
      await listen(toNodeListener(app));
      return "wait";
    }
  }
});

export { analyze as default };
