UNPKG

@nuxt/cli

Version:
460 lines (458 loc) • 18.1 kB
import { h as defineCommand, i as extendsArgs, l as rootDirArgs, n as dotEnvArgs, s as logLevelArgs } from "./_shared-B9W-9akb.mjs"; import { r as formatDuration } from "./formatting-CCN_OARd.mjs"; import { f as debug, h as logger } from "./startup-clock-SyYej6uN.mjs"; import { i as resolveRootDir } from "./paths-BipyohVL.mjs"; import { c as withNodePath } from "./terminal-theme-jW0dFyAX.mjs"; import { t as createSpinner } from "./spinner-BQYqwsYE.mjs"; import process from "node:process"; import { styleText } from "node:util"; import { hasTTY } from "std-env"; import { cancel, confirm, isCancel, select } from "@clack/prompts"; import { resolveModulePath } from "exsolve"; import { dirname, resolve } from "pathe"; import { existsSync, readFileSync } from "node:fs"; import { mkdir, readFile, rm, utimes, writeFile } from "node:fs/promises"; import os from "node:os"; import { readPackageJSON, readTSConfig } from "pkg-types"; import { x } from "tinyexec"; import v8 from "node:v8"; import { parseJSONC } from "confbox/jsonc"; // src/utils/typecheck-cache.ts const STAMP_FILE = "checker.stamp"; /** * Builds a cache key such as `vue-tsc@3.3.10+typescript@6.0.3` from the resolved entry files of the * packages that affect type-checking output. Returns `undefined` if any version cannot be read. */ function resolveCacheKey(entries) { const ids = []; for (const entry of entries) { const id = entry && readPackageId(entry); if (!id) return; ids.push(id); } return ids.join("+"); } /** * Returns `['--incremental']` if every project referenced by the solution-style `tsconfig.json` in * `cwd` sets its own `tsBuildInfoFile`, after discarding build info written for a different cache key * and marking the referenced configs as newer than their build info. */ async function resolveIncrementalArgs(cwd, key) { try { const { configs, buildInfoFiles } = await resolveProjects(cwd); if (configs.length === 0 || buildInfoFiles.length < configs.length) return []; await discardStaleBuildInfo(buildInfoFiles, key); const now = /* @__PURE__ */ new Date(); await Promise.all(configs.map((config) => utimes(config, now, now))); return ["--incremental"]; } catch (error) { debug("Skipping incremental type-checking:", error); return []; } } /** Removes the build info of the projects referenced by the solution-style `tsconfig.json` in `cwd`. */ async function discardBuildInfo(cwd) { try { const { buildInfoFiles } = await resolveProjects(cwd); await Promise.all(buildInfoFiles.map((file) => rm(file, { force: true }))); } catch (error) { debug("Could not remove build info:", error); } } async function resolveProjects(cwd) { const rootConfig = resolve(cwd, "tsconfig.json"); const configs = (await readConfig(rootConfig)).references?.map((reference) => resolveReference(dirname(rootConfig), reference.path)) ?? []; const buildInfoFiles = []; for (const config of configs) { const tsBuildInfoFile = (await readConfig(config)).compilerOptions?.tsBuildInfoFile; if (typeof tsBuildInfoFile === "string") buildInfoFiles.push(resolve(dirname(config), tsBuildInfoFile)); } return { configs, buildInfoFiles }; } async function discardStaleBuildInfo(buildInfoFiles, key) { const dirs = new Set(buildInfoFiles.map((file) => dirname(file))); for (const dir of dirs) { const stamp = resolve(dir, STAMP_FILE); if (await readFile(stamp, "utf8").catch(() => void 0) === key) continue; await Promise.all(buildInfoFiles.filter((file) => dirname(file) === dir).map((file) => rm(file, { force: true }))); await mkdir(dir, { recursive: true }); await writeFile(stamp, key); } } function resolveReference(dir, path) { const resolved = resolve(dir, path); return resolved.endsWith(".json") ? resolved : resolve(resolved, "tsconfig.json"); } async function readConfig(path) { return parseJSONC(await readFile(path, "utf8"), { allowTrailingComma: true }) ?? {}; } function readPackageId(entry) { let dir = dirname(entry); while (true) { const manifest = resolve(dir, "package.json"); if (existsSync(manifest)) try { const { name, version } = JSON.parse(readFileSync(manifest, "utf8")); if (name && version) return `${name}@${version}`; } catch { return; } const parent = dirname(dir); if (parent === dir) return; dir = parent; } } // src/commands/typecheck.ts const GOLAR_CONFIG_FILES = [ "golar.config.js", "golar.config.ts", "golar.config.mjs", "golar.config.mts", "golar.config.cjs", "golar.config.cts" ]; const GOLAR_CONFIG_TEMPLATE = `import { defineConfig } from 'golar/unstable' import '@golar/vue' export default defineConfig({}) `; const TYPE_CHECKERS = { "vue-tsc": { label: "vue-tsc", hint: "Vue's official TypeScript checker", packages: ["typescript", "vue-tsc"], resolve(cwd, { cache = true } = {}) { const from = withNodePath(cwd); const typescript = resolveModulePath("typescript", { from, try: true, cache }); const bin = resolveModulePath("vue-tsc/bin/vue-tsc.js", { from, try: true, cache }); return { bin: bin ?? void 0, missing: [...!typescript ? ["typescript"] : [], ...!bin ? ["vue-tsc"] : []] }; }, args: (supportsProjects) => supportsProjects ? ["-b", "--noEmit"] : ["--noEmit"], cachePackages: (_cwd, bin) => [bin, resolveModulePath("typescript", { from: bin, try: true })] }, "golar": { label: "Golar", hint: "Native-speed type-checking powered by typescript-go", packages: ["golar", "@golar/vue"], docs: "https://golar.dev/languages/vue/", configFiles: GOLAR_CONFIG_FILES, configNote: `Golar also requires a ${styleText("cyan", "golar.config.ts")} file. One will be created automatically the first time Golar is used.`, resolve(cwd, { cache = true } = {}) { const bin = resolveGolarBin(cwd, cache); const vuePlugin = resolveModulePath("@golar/vue", { from: withNodePath(cwd), try: true, cache }); return { bin, missing: [...!bin ? ["golar"] : [], ...!vuePlugin ? ["@golar/vue"] : []] }; }, args: (supportsProjects) => supportsProjects ? [ "tsc", "--build", "--noEmit" ] : ["tsc", "--noEmit"], cachePackages: (cwd, bin) => [bin, resolveModulePath("@golar/vue", { from: withNodePath(cwd), try: true })], ensureConfig: ensureGolarConfig } }; const CHECKER_PRIORITY = Object.keys(TYPE_CHECKERS); var typecheck_default = defineCommand({ meta: { name: "typecheck", description: "Runs type-checking throughout your app using `vue-tsc` or Golar." }, args: { ...rootDirArgs, ...logLevelArgs, ...dotEnvArgs, ...extendsArgs, checker: { type: "string", description: "Type checker to use", valueHint: CHECKER_PRIORITY.join("|") }, build: { type: "boolean", alias: "b", description: "Type-check in build mode, using TypeScript project references (detected automatically by default)", negativeDescription: "Type-check without TypeScript project references" }, incremental: { type: "boolean", description: "Reuse type information from previous runs", negativeDescription: "Type-check from scratch, without reusing type information from previous runs", default: true } }, async run(ctx) { process.env.NODE_ENV = process.env.NODE_ENV || "production"; const cwd = resolveRootDir(ctx.args); const checkerArg = ctx.args.checker; if (checkerArg && !Object.hasOwn(TYPE_CHECKERS, checkerArg)) { logger.error(`Unknown type checker ${styleText("cyan", checkerArg)}. Expected one of: ${CHECKER_PRIORITY.join(", ")}.`); process.exitCode = 1; return; } const typechecker = await resolveTypeChecker(cwd, checkerArg); if (!typechecker) { process.exitCode = 1; return; } const hasOverrides = Object.keys(ctx.data?.overrides ?? {}).length > 0; const { writeTypes, writeTypesInChild } = await import("./write-types-DHvUnnQN.mjs").then((n) => n.n); const [tsConfig] = await Promise.all([readTSConfig(cwd).catch(() => ({})), (hasOverrides ? writeTypes : writeTypesInChild)({ cwd, dotenv: ctx.args.dotenv, logLevel: ctx.args.logLevel, overrides: { ...ctx.data?.overrides, ...ctx.args.extends.length > 0 && { extends: ctx.args.extends } } })]); const useProjectReferences = ctx.args.build ?? supportsProjectReferences(tsConfig); if (ctx.args.build === void 0 && !useProjectReferences && hasNuxtProjectReferences(tsConfig)) logger.warn(`Your ${styleText("cyan", "tsconfig.json")} references Nuxt's generated project configs but also includes source files of its own, so type-checking will not run in build mode. Add ${styleText("cyan", "\"files\": []")} to your ${styleText("cyan", "tsconfig.json")}, or pass ${styleText("cyan", "--build")} to override.`); const backend = TYPE_CHECKERS[typechecker.checker]; const args = backend.args(useProjectReferences); if (useProjectReferences && supportsProjectReferences(tsConfig)) { if (!ctx.args.incremental) await discardBuildInfo(cwd); else { const cacheKey = resolveCacheKey(backend.cachePackages(cwd, typechecker.bin)); if (cacheKey) args.push(...await resolveIncrementalArgs(cwd, cacheKey)); } } const heap = typechecker.checker === "vue-tsc" ? resolveCheckerHeap() : void 0; const start = Date.now(); const proc = x(typechecker.bin, args, { nodeOptions: { stdio: "inherit", cwd, ...heap?.nodeOptions && { env: { NODE_OPTIONS: heap.nodeOptions } } } }); const result = await proc; const duration = formatDuration(Date.now() - start); const signal = proc.signalCode ?? (process.platform === "win32" && result.exitCode === 134 ? "SIGABRT" : null); if (signal) { const exitCode = reportKilledChecker(signal, duration, heap?.limit); process.exitCode = result.exitCode ?? exitCode; return; } if (result.exitCode === 0) { if (hasTTY) logger.success(`Type check passed in ${styleText("cyan", duration)}.`); return; } if (hasTTY) logger.error(`Type check failed in ${styleText("cyan", duration)}.`); process.exitCode = result.exitCode ?? 1; } }); const NUXT_PROJECT_REFERENCE_RE = /(?:^|[/\\])tsconfig\.(?:app|server|shared|node)\.json$/; const MAX_OLD_SPACE_SIZE_RE = /--max[-_]old[-_]space[-_]size[=\s]+(\d+)/; const MAX_CHECKER_HEAP_MB = 8192; const MB = 1048576; /** * Report a checker killed by a signal, even without a TTY, and return the exit code to use: * `128 + signal number`, following the shell convention. */ function reportKilledChecker(signal, duration, heapLimit) { const outOfMemory = signal === "SIGKILL" || signal === "SIGABRT" ? ", which usually means it ran out of memory" : ""; const heapHint = signal === "SIGABRT" && heapLimit ? ` Its heap was limited to ${styleText("cyan", `${heapLimit} MB`)}. Set ${styleText("bold", "NODE_OPTIONS=--max-old-space-size=<MB>")} to raise it.` : ""; logger.error(`Type-checking was killed by ${styleText("bold", signal)} after ${styleText("cyan", duration)}${outOfMemory}.${heapHint}`); const signalNumber = os.constants.signals[signal]; return signalNumber ? 128 + signalNumber : 1; } /** * Heap limit of the checker in MB, with the `NODE_OPTIONS` that set it if they differ from the inherited ones. * * Unless set by the user, this is half of the memory of the machine or container, bounded by the memory * currently available and by `MAX_CHECKER_HEAP_MB`, and never below V8's default. */ function resolveCheckerHeap() { const nodeOptions = process.env.NODE_OPTIONS; const inherited = nodeOptions?.match(MAX_OLD_SPACE_SIZE_RE); if (inherited) return { limit: Number(inherited[1]) }; const withLimit = (limit) => ({ limit, nodeOptions: [nodeOptions, `--max-old-space-size=${limit}`].filter(Boolean).join(" ") }); const own = process.execArgv.join(" ").match(MAX_OLD_SPACE_SIZE_RE); if (own) return withLimit(Number(own[1])); const defaultLimit = Math.round(v8.getHeapStatistics().heap_size_limit / MB); const total = os.totalmem(); const constrained = process.constrainedMemory(); const limit = Math.floor(Math.min((constrained > 0 && constrained < total ? constrained : total) / 2, process.availableMemory(), MAX_CHECKER_HEAP_MB * MB) / MB); return limit > defaultLimit ? withLimit(limit) : { limit: defaultLimit }; } /** * Whether a tsconfig is a solution-style config, as used by Nuxt's project references setup. * * Building a config that has input files of its own alongside references makes TypeScript apply * `--noEmit` to every referenced project, which fails with `TS6310` for emitting projects. */ function supportsProjectReferences(config) { if (!config.references?.length) return false; return config.files?.length === 0 && !config.include?.length; } function hasNuxtProjectReferences(config) { return !!config.references?.some((reference) => reference.path && NUXT_PROJECT_REFERENCE_RE.test(reference.path)); } async function resolveTypeChecker(cwd, preferred) { const priority = preferred ? [preferred] : detectCheckerPriority(cwd); for (const checker of priority) { const resolved = TYPE_CHECKERS[checker].resolve(cwd); if (resolved.bin && resolved.missing.length === 0) { await TYPE_CHECKERS[checker].ensureConfig?.(cwd); return { checker, bin: resolved.bin }; } } return await promptTypeCheckerInstall(cwd, preferred); } function detectCheckerPriority(cwd) { const configured = CHECKER_PRIORITY.filter((checker) => hasCheckerConfig(checker, cwd)); return [...configured, ...CHECKER_PRIORITY.filter((checker) => !configured.includes(checker))]; } function hasCheckerConfig(checker, cwd) { return TYPE_CHECKERS[checker].configFiles?.some((file) => existsSync(resolve(cwd, file))) ?? false; } function resolveGolarBin(cwd, cache = true) { const entry = resolveModulePath("golar/unstable", { from: withNodePath(cwd), try: true, cache }); if (!entry) return; let dir = dirname(entry); while (true) { const manifest = resolve(dir, "package.json"); if (existsSync(manifest)) { const { name, bin } = JSON.parse(readFileSync(manifest, "utf8")); if (name === "golar") { const relativeBin = typeof bin === "string" ? bin : bin?.golar; return relativeBin ? resolve(dir, relativeBin) : void 0; } } const parent = dirname(dir); if (parent === dir) return; dir = parent; } } async function ensureGolarConfig(cwd) { if (hasCheckerConfig("golar", cwd)) return; const filename = (await readPackageJSON(cwd).catch(() => null))?.type === "module" ? "golar.config.ts" : "golar.config.mts"; await writeFile(resolve(cwd, filename), GOLAR_CONFIG_TEMPLATE); logger.info(`Created ${styleText("cyan", filename)}`); } async function promptTypeCheckerInstall(cwd, preferred) { const { defaultPackageManager, detectPackageManager } = await import("./package-managers-sbHBcaEH.mjs").then((n) => n.s); const packageManager = await detectPackageManager(cwd) ?? defaultPackageManager; const pmName = packageManager.name; const devFlag = pmName === "bun" ? "-d" : "-D"; if (!hasTTY) { printInstallInstructions(pmName, devFlag, preferred ? [preferred] : CHECKER_PRIORITY); return; } let selected = preferred; if (!selected) { logger.warn(`No type checker found for ${styleText("cyan", "nuxt typecheck")}.`); const answer = await select({ message: "Which type checker would you like to use?", options: CHECKER_PRIORITY.map((name) => ({ value: name, label: TYPE_CHECKERS[name].label, hint: TYPE_CHECKERS[name].hint })), initialValue: "vue-tsc" }); if (isCancel(answer)) { cancel("Skipping installation."); return; } selected = answer; } const installCommand = formatInstallCommand(selected, pmName, devFlag); const { missing } = TYPE_CHECKERS[selected].resolve(cwd); if (missing.length > 0) { if (!await installMissingPackages({ cwd, packageManager, pmName, packages: missing, installCommand })) return; } const resolved = TYPE_CHECKERS[selected].resolve(cwd, { cache: false }); if (!resolved.bin || resolved.missing.length > 0) { logger.error(`Failed to resolve ${styleText("cyan", resolved.missing.join(" and ") || selected)} after installation. Please check your installation.`); return; } await TYPE_CHECKERS[selected].ensureConfig?.(cwd); return { checker: selected, bin: resolved.bin }; } function printInstallInstructions(pmCommand, devFlag, checkers) { logger.error(`A type checker is required for ${styleText("cyan", "nuxt typecheck")}. Install ${checkers.length > 1 ? "one of the following" : "it as a devDependency"}:\n`); for (const checker of checkers) { const meta = TYPE_CHECKERS[checker]; const command = formatInstallCommand(checker, pmCommand, devFlag); const docs = meta.docs ? ` (see ${styleText("cyan", meta.docs)})` : ""; logger.info(`${styleText("cyan", meta.label)}${docs}:\n\n ${styleText("bold", command)}\n`); if (meta.configNote) logger.info(`${meta.configNote}\n`); } } function formatInstallCommand(checker, pmCommand, devFlag) { return `${pmCommand} add ${devFlag} ${TYPE_CHECKERS[checker].packages.join(" ")}`; } async function installMissingPackages(options) { const { cwd, packageManager, pmName, packages, installCommand } = options; const list = packages.map((name) => styleText("cyan", name)).join(" and "); const plural = packages.length > 1; const shouldInstall = await confirm({ message: `Install ${list} as ${plural ? "devDependencies" : "a devDependency"}?`, initialValue: true }); if (isCancel(shouldInstall) || !shouldInstall) { cancel(`Skipping installation. Run ${styleText("bold", installCommand)} to install manually.`); return false; } const spin = createSpinner(); spin.start(`Installing ${list} with ${styleText("cyan", pmName)}`); const { runInstall } = await import("./install-B88XgWmK.mjs").then((n) => n.n); const result = await runInstall({ cwd, packageManager, dependencies: packages, dev: true }); if (result.success) { spin.stop(`Installed ${list}`); return true; } spin.error(`Failed to install ${list}`); logger.error(result.error ?? result.output); logger.info(`You can install ${plural ? "them" : "it"} manually with:\n\n ${styleText("bold", installCommand)}\n`); return false; } export { typecheck_default as default };