UNPKG

@nuxt/cli

Version:
521 lines (520 loc) • 19.8 kB
import { c as profileArgs, h as defineCommand, i as extendsArgs, l as rootDirArgs, n as dotEnvArgs, r as envNameArgs, s as logLevelArgs, u as targetArgs } from "./_shared-B9W-9akb.mjs"; import { n as resolveDotenvFileNames } from "./args-CAT9qhaw.mjs"; import { r as showBanner } from "./banner-CxN-2rtX.mjs"; import { t as PhaseTimeline } from "./progress-snapshot-BVUmkNu7.mjs"; import { n as formatBytes, r as formatDuration } from "./formatting-CCN_OARd.mjs"; import { D as ActionableError, g as outro, h as logger, p as intro } from "./startup-clock-SyYej6uN.mjs"; import { n as MUTED } from "./terminal-theme-jW0dFyAX.mjs"; import { n as configureProjectConsola, s as reportThroughClack } from "./console-CHdXO7dG.mjs"; import { t as overrideEnv } from "./env-COCHPJ0D.mjs"; import { t as clearBuildDir } from "./fs-BerxlAZq.mjs"; import { t as loadKit } from "./kit-CAB8i9G1.mjs"; import { a as formatLockError, n as acquireOutputLock, t as acquireLock } from "./lockfile-BCHJc48m.mjs"; import { i as resolveRootDir } from "./paths-BipyohVL.mjs"; import { a as stopCpuProfile, i as startCpuProfile, n as formatPhaseBreakdown, r as formatPhaseTable, t as createPhaseReporter } from "./phase-reporter-CgRWH-JB.mjs"; import { r as resolveServerBuild } from "./server-build-DwN4T0qt.mjs"; import process from "node:process"; import { styleText } from "node:util"; import { isCI } from "std-env"; import { join, relative } from "pathe"; import { readFile } from "node:fs/promises"; import { gzip } from "node:zlib"; // src/utils/build-progress.ts /** * The phases that run one after the other before anything is bundled. The last * one covers the rest of the build, in which bundles and prerendering are * tracked as tasks of their own, since they can overlap. */ const BUILD_PHASES = [ { id: "config", message: "Loading Nuxt config" }, { id: "modules", message: "Setting up modules" }, { id: "app", message: "Preparing app" }, { id: "types", message: "Generating types" }, { id: "build", message: "Building" } ]; const HOOK_PHASES = { "modules:before": "modules", "builder:generateApp": "app", "prepare:types": "types", "build:before": "build" }; const BUILD_PHASE = "build"; const PRERENDER_TASK = "prerender"; function listLabels(labels) { return labels.length > 1 ? `${labels.slice(0, -1).join(", ")} and ${labels.at(-1)}` : labels[0]; } /** * Tracks how far a production build has got, so the same transient phase line * `nuxt dev` shows can report `nuxt build`, and the completion summary can list * where the time went. */ var BuildProgress = class extends PhaseTimeline { #message = BUILD_PHASES[0].message; #finished = false; #tasks = /* @__PURE__ */ new Map(); #active = []; #key = BUILD_PHASE; #prerender = { done: 0, total: 0 }; #phaseTimings = []; constructor() { super(BUILD_PHASES); } get snapshot() { const snapshot = { ...super.snapshot, phase: this.#key, message: this.#message }; return this.#prerendering ? { ...snapshot, meter: { ...this.#prerender } } : snapshot; } onUpdate(listener) { const off = super.onUpdate(listener); listener(this.snapshot); return off; } setPhase(id) { if (this.#finished || !this.enter(id)) return; this.#key = id; this.#setMessage(BUILD_PHASES[this.index].message); } /** Start bundling `label`, such as `client`, alongside anything else in flight. */ startBundle(label) { this.#startTask(label); } endBundle(label) { this.#endTask(label); } /** Start prerendering the `total` routes known up front. */ startPrerender(total = 0) { this.#prerender = { done: 0, total }; this.#startTask(PRERENDER_TASK); } /** Count a route as done, out of the `total` known so far. */ prerenderRoute(route, total = 0) { if (this.#finished) return; const done = this.#prerender.done + 1; this.#prerender = { done, total: Math.max(total, this.#prerender.total, done), detail: route }; if (this.#prerendering) this.emit(); } endPrerender() { this.#endTask(PRERENDER_TASK); } /** * Close the phase in flight and stop accepting updates, so its duration makes * it into the breakdown. Nothing is emitted: whoever reports the build owns * what is said about it finishing. */ finish() { if (this.#finished) return; const now = Date.now(); const building = BUILD_PHASES[this.index].id === BUILD_PHASE; this.closePhase(); this.#finished = true; this.#phaseTimings = [...this.timings]; if (!building || !this.#tasks.size) return; this.timings.pop(); const tasks = [...this.#tasks].map(([id, task]) => ({ phase: id, message: id, start: task.start - this.startedAt, duration: (task.end ?? now) - task.start })); this.timings.push(...tasks.sort((a, b) => a.start - b.start)); } /** * The phases alone once the build has finished, with bundling and * prerendering as the one `build` span they ran in. */ get phaseTimings() { return this.#phaseTimings; } /** * Derive phases from the hooks Nuxt calls, so the timeline follows the * project's own build rather than a schedule guessed by the CLI. */ attachNuxt(nuxt) { nuxt.hooks?.beforeEach?.(({ name }) => { const phase = HOOK_PHASES[name]; if (phase) this.setPhase(phase); }); } get #prerendering() { return !this.#finished && this.#active.includes(PRERENDER_TASK); } #startTask(id) { if (this.#finished) return; if (this.enter(BUILD_PHASE)) this.#key = BUILD_PHASE; this.#tasks.set(id, { start: Date.now() }); this.#active = [...this.#active.filter((active) => active !== id), id]; this.#update(); } #endTask(id) { const task = this.#tasks.get(id); if (this.#finished || !task || task.end !== void 0) return; task.end = Date.now(); this.#active = this.#active.filter((active) => active !== id); this.#update(); } #update() { if (this.#finished || !this.#active.length) { this.#setMessage(BUILD_PHASES.at(-1).message); return; } if (this.#active.includes(PRERENDER_TASK)) { this.#key = PRERENDER_TASK; this.#setMessage("Prerendering routes"); return; } this.#key = `bundle:${this.#active.join("+")}`; this.#setMessage(`Bundling ${listLabels(this.#active)}`); } #setMessage(message) { if (this.#finished || message === this.#message) return; this.#message = message; this.emit(); } }; // src/utils/build-report.ts /** How many prerendered routes a local build lists before pointing at verbose output. */ const PRERENDER_ROUTE_LIMIT = 20; /** How many linking pages a local build names for each failed route. */ const LINKED_FROM_LIMIT = 3; /** Source maps, which some builders write as `*.map.json`. */ const SOURCE_MAP_RE = /\.map(?:\.json)?$/; const GZIP_CONCURRENCY = 8; const LABELS = { client: "Client", server: "Server", ssr: "Server", nitro: "Nitro" }; /** What a bundle is called on the progress line and in the breakdown. */ function bundleLabel(environment) { return LABELS[environment.name]?.toLowerCase() ?? environment.name; } function displayLabel(environment) { return LABELS[environment.name] ?? environment.name; } /** * Follow a production build through the hooks Nuxt reports it with, driving the * progress line and collecting what the summary prints once it is done. */ function createBuildReport(nuxt, options) { const hook = nuxt.hook; const { progress } = options; const entries = []; const bundles = []; const routes = []; const gzipFile = createLimiter(GZIP_CONCURRENCY); const starts = /* @__PURE__ */ new Map(); let prerenderStart = 0; hook("build:environment:start", (environment) => { starts.set(environment.name, Date.now()); progress.startBundle(bundleLabel(environment)); }); hook("build:environment:done", (environment, result) => { progress.endBundle(bundleLabel(environment)); const files = result.files.filter((file) => !SOURCE_MAP_RE.test(file.path)); const bundle = { environment, result, files, size: files.reduce((sum, file) => sum + file.size, 0), gzip: environment.consumer === "client" ? Promise.all(files.map((file) => gzipFile(() => gzipSize(join(result.outDir, file.path))))).catch(() => void 0) : Promise.resolve(void 0) }; bundles.push(bundle); entries.push({ start: starts.get(environment.name) ?? Date.now() - result.duration, render: (verbose) => formatBundle(bundle, verbose) }); }); hook("build:prerender:start", (info) => { prerenderStart = Date.now(); routes.length = 0; progress.startPrerender(info.routes); }); hook("build:prerender:route", (route) => { routes.push(route); progress.prerenderRoute(route.route, route.total); }); hook("build:prerender:done", (result) => { progress.endPrerender(); if (result.failed.length) logger.error(`Failed to prerender ${result.failed.length} route${result.failed.length === 1 ? "" : "s"}:\n${result.failed.map((route) => formatFailedRoute(route, isCI || nuxt.options.logLevel === "verbose")).join("\n")}`); if (!result.written) return; const command = nuxtCommand(nuxt, options.command); const written = [...routes]; entries.push({ start: prerenderStart || Date.now() - result.duration, render: async (verbose) => [`Prerendered ${result.written} route${result.written === 1 ? "" : "s"} in ${formatDuration(result.duration)}`, ...formatPrerenderedRoutes(written, command, verbose)].join("\n") }); }); /** Whether a server bundle was written into the build output, and so something to run. */ function hasServerOutput(serverBuild) { return bundles.some((bundle) => bundle.environment.consumer === "server" && !relative(serverBuild.dir, bundle.result.outDir).startsWith("..")); } return { async summary(verbose) { const sorted = [...entries].sort((a, b) => a.start - b.start); const lines = await Promise.all(sorted.map((entry) => entry.render(verbose))); return lines.length ? lines.join("\n") : void 0; }, commands(serverBuild) { const commands = []; if (hasServerOutput(serverBuild)) commands.push(`You can preview this build using ${styleText("cyan", nuxtCommand(nuxt, "preview"))}`); const deploy = deployCommand(nuxt, serverBuild); if (deploy) commands.push(`You can deploy this build using ${styleText("cyan", deploy)}`); return commands; }, staticCommands(serverBuild) { const target = serverBuild.target; const publicDir = relative(process.cwd(), serverBuild.publicDir) || "."; if (!target || target === "static") return [`You can now deploy ${styleText("cyan", publicDir)} to any static hosting`]; const deploy = deployCommand(nuxt, serverBuild); if (deploy) return [`You can deploy this build using ${styleText("cyan", deploy)}`]; const dir = relative(process.cwd(), serverBuild.dir) || "."; return [`You can now deploy ${styleText("cyan", dir)} to ${styleText("cyan", target)}`]; } }; } /** The deploy command, which runs from the project root, prefixed with a `cd` there when that is not the current directory. */ function deployCommand(nuxt, serverBuild) { const command = serverBuild.deployCommand; const dir = relative(process.cwd(), nuxt.options.rootDir || process.cwd()); return command && dir ? `cd ${quote(dir)} && ${command}` : command; } function quote(path) { return /\s/.test(path) ? JSON.stringify(path) : path; } async function formatBundle(bundle, verbose) { const { environment, result, files } = bundle; const gzip = await bundle.gzip; const total = gzip?.reduce((sum, size) => sum + size, 0); const size = `${formatBytes(bundle.size)}${total === void 0 ? "" : ` (${formatBytes(total)} gzip)`}`; const line = `${displayLabel(environment)} ${styleText(MUTED, `(${environment.builder})`)} built in ${formatDuration(result.duration)}${styleText(MUTED, ` \u00B7 ${size}`)}`; if (!verbose || !files.length) return line; const rows = files.map((file, index) => ({ path: relative(process.cwd(), join(result.outDir, file.path)), size: formatBytes(file.size), gzip: gzip && formatBytes(gzip[index]), bytes: file.size })).sort((a, b) => b.bytes - a.bytes); const pathWidth = rows.reduce((max, row) => Math.max(max, row.path.length), 0); const sizeWidth = rows.reduce((max, row) => Math.max(max, row.size.length), 0); const gzipWidth = rows.reduce((max, row) => Math.max(max, row.gzip?.length ?? 0), 0); return [line, ...rows.map((row) => ` ${row.path.padEnd(pathWidth)} ${styleText(MUTED, `${row.size.padStart(sizeWidth)}${row.gzip ? ` ${row.gzip.padStart(gzipWidth)} gzip` : ""}`)}`)].join("\n"); } /** `npx nuxt <command>`, naming the project when it is not the current directory. */ function nuxtCommand(nuxt, command) { const dir = relative(process.cwd(), nuxt.options.rootDir || process.cwd()); return `npx nuxt ${command}${dir ? ` ${quote(dir)}` : ""}`; } function routePath(route) { const query = route.indexOf("?"); return query === -1 ? route : route.slice(0, query); } function isPayloadRoute(route) { return routePath(route.route).endsWith("/_payload.json"); } /** * The routes a build wrote. CI logs are read after the fact to check what was * deployed, so they list every route, skipped ones too, as does verbose output; * a terminal lists a sample of the pages and says how to see the rest. */ function formatPrerenderedRoutes(routes, command, verbose) { const all = isCI || verbose; const listed = routes.filter((route) => !route.error && (all || !route.skipped)); if (all) { const width = Math.min(listed.reduce((max, route) => Math.max(max, route.route.length), 0), 60); const times = listed.map((route) => route.skipped ? "skipped" : formatRouteTime(route.duration)); const timeWidth = times.reduce((max, time) => Math.max(max, time.length), 0); return listed.map((route, index) => `${route.route.padEnd(width)} ${styleText(MUTED, times[index].padStart(timeWidth))}`.trimEnd()); } const shown = listed.filter((route) => !isPayloadRoute(route)).sort((a, b) => a.route.localeCompare(b.route, "en", { numeric: true })).slice(0, PRERENDER_ROUTE_LIMIT); const lines = shown.length ? [styleText(MUTED, "Routes:"), ...shown.map((route) => route.route)] : []; const hidden = listed.length - shown.length; if (hidden) lines.push(styleText(MUTED, `\u2026 and ${hidden} more. Run ${styleText("cyan", `${command} --logLevel=verbose`)} to see all prerendered routes.`)); return lines; } /** Whole milliseconds until a route takes seconds. */ function formatRouteTime(ms) { return ms < 1e3 ? `${Math.round(ms)}ms` : formatDuration(ms); } function formatFailedRoute(route, all) { const detail = [route.status, route.message].filter(Boolean).join(" "); const line = `${route.route}${detail ? styleText(MUTED, ` (${detail})`) : ""}`; const parents = route.linkedFrom ?? []; if (!parents.length) return line; const shown = all ? parents : parents.slice(0, LINKED_FROM_LIMIT); const hidden = parents.length - shown.length; return `${line}\n${styleText(MUTED, ` linked from ${shown.join(", ")}${hidden ? ` and ${hidden} more` : ""}`)}`; } async function gzipSize(path) { const content = await readFile(path); return new Promise((resolve, reject) => gzip(content, (error, result) => error ? reject(error) : resolve(result.byteLength))); } function createLimiter(concurrency) { let running = 0; const queue = []; return (task) => new Promise((resolve, reject) => { const run = () => { running++; task().then(resolve, reject).finally(() => { running--; queue.shift()?.(); }); }; if (running < concurrency) run(); else queue.push(run); }); } // src/commands/build.ts /** How often a phase repeats itself where there is no animated line. */ const HEARTBEAT_INTERVAL = 5e3; var build_default = defineCommand({ meta: { name: "build", description: "Build Nuxt for production deployment" }, args: { ...rootDirArgs, ...logLevelArgs, prerender: { type: "boolean", description: "Build Nuxt and prerender static routes" }, ...targetArgs, ...dotEnvArgs, ...envNameArgs, ...extendsArgs, ...profileArgs }, async run(ctx) { overrideEnv("production"); const start = Date.now(); const cwd = resolveRootDir(ctx.args); const profileArg = ctx.args.profile; const profiling = profileArg !== void 0; const perfValue = profileArg === "verbose" ? true : profiling ? "quiet" : void 0; if (profiling) await startCpuProfile(); const releaseLocks = []; const progress = new BuildProgress(); let stopReporting = () => {}; let stopClackReporting = () => {}; try { intro(styleText("cyan", "Building Nuxt for production...")); stopClackReporting = reportThroughClack(); if (ctx.args.logLevel !== "silent") { const reporter = createPhaseReporter({ heartbeat: HEARTBEAT_INTERVAL }); let unsubscribe; stopReporting = () => { unsubscribe?.(); reporter.stop(); }; unsubscribe = progress.onUpdate(reporter.update); } const kit = await loadKit(cwd); await configureProjectConsola(cwd); const nuxt = await kit.loadNuxt({ cwd, ready: false, dotenv: { cwd, fileName: resolveDotenvFileNames(ctx.args.dotenv) }, envName: ctx.args.envName, overrides: { logLevel: ctx.args.logLevel, _generate: ctx.args.prerender, nitro: { static: ctx.args.prerender, preset: ctx.args.target || ctx.args.preset || process.env.NITRO_PRESET || process.env.SERVER_PRESET }, ...ctx.args.extends.length > 0 && { extends: ctx.args.extends }, ...ctx.data?.overrides, ...(perfValue || ctx.data?.overrides?.debug) && { debug: { ...ctx.data?.overrides?.debug, ...perfValue && { perf: perfValue } } } } }); progress.attachNuxt(nuxt); const report = createBuildReport(nuxt, { progress, command: ctx.args.prerender ? "generate" : "build" }); showBanner(nuxt); await nuxt.ready(); const lock = acquireLock(nuxt.options.buildDir, { command: "build", cwd }); if (lock.existing) throw new ActionableError(formatLockError(lock.existing)); releaseLocks.push(lock.release); const serverBuild = resolveServerBuild(kit, nuxt); const target = serverBuild.target; if (target) logger.info(`Deploy target: ${styleText("cyan", target)}`); const outputDir = serverBuild.dir; const outputLock = acquireOutputLock(nuxt.options.rootDir, outputDir, { command: "build", cwd }); if (outputLock.existing) throw new ActionableError(formatLockError(outputLock.existing, { outputDir: relative(process.cwd(), outputDir) })); releaseLocks.push(outputLock.release); await clearBuildDir(nuxt.options.buildDir); await kit.writeTypes(nuxt); await kit.buildNuxt(nuxt); stopReporting(); progress.finish(); const elapsed = Date.now() - start; const verbose = nuxt.options.logLevel === "verbose"; const summary = nuxt.options.logLevel === "silent" ? void 0 : await report.summary(verbose); if (summary) logger.success(summary); if (ctx.args.prerender && !nuxt.options.ssr) { logger.warn(`HTML content not prerendered because ${styleText("cyan", "ssr: false")} was set.`); logger.info(`You can read more in ${styleText("cyan", "https://nuxt.com/docs/getting-started/deployment#static-hosting")}.`); } const breakdown = verbose ? formatPhaseTable(progress.timings) : formatPhaseBreakdown(progress.phaseTimings); const total = `Build complete in ${styleText("cyan", formatDuration(elapsed))}`; const complete = breakdown ? `${total}\n${verbose ? breakdown : styleText(MUTED, breakdown)}` : total; const next = ctx.args.prerender ? report.staticCommands(serverBuild) : report.commands(serverBuild); if (next.length) { logger.success(complete); outro(next.join("\n")); } else outro(complete); } finally { stopReporting(); stopClackReporting(); for (const release of releaseLocks.reverse()) release(); if (profiling) await stopCpuProfile(cwd, "build"); } } }); export { build_default as default };