Website Structure

This commit is contained in:
supalerk-ar66 2026-01-13 10:46:40 +07:00
parent 62812f2090
commit 71f0676a62
22365 changed files with 4265753 additions and 791 deletions

31
Frontend-Learner/node_modules/@nuxt/cli/bin/nuxi.mjs generated vendored Normal file
View file

@ -0,0 +1,31 @@
#!/usr/bin/env node
import nodeModule from 'node:module'
import process from 'node:process'
import { fileURLToPath } from 'node:url'
// https://nodejs.org/api/module.html#moduleenablecompilecachecachedir
// https://github.com/nodejs/node/pull/54501
if (nodeModule.enableCompileCache && !process.env.NODE_DISABLE_COMPILE_CACHE) {
try {
const { directory } = nodeModule.enableCompileCache()
if (directory) {
// allow child process to share the same cache directory
process.env.NODE_COMPILE_CACHE ||= directory
}
}
catch {
// Ignore errors
}
}
globalThis.__nuxt_cli__ = {
startTime: Date.now(),
entry: fileURLToPath(import.meta.url),
devEntry: fileURLToPath(new URL('../dist/dev/index.mjs', import.meta.url)),
}
// eslint-disable-next-line antfu/no-top-level-await
const { runMain } = await import('../dist/index.mjs')
runMain()

View file

@ -0,0 +1,42 @@
//#region ../nuxi/src/commands/_shared.ts
const cwdArgs = { cwd: {
type: "string",
description: "Specify the working directory",
valueHint: "directory",
default: "."
} };
const logLevelArgs = { logLevel: {
type: "string",
description: "Specify build-time log level",
valueHint: "silent|info|verbose"
} };
const envNameArgs = { envName: {
type: "string",
description: "The environment to use when resolving configuration overrides (default is `production` when building, and `development` when running the dev server)"
} };
const dotEnvArgs = { dotenv: {
type: "string",
description: "Path to `.env` file to load, relative to the root directory"
} };
const extendsArgs = { extends: {
type: "string",
description: "Extend from a Nuxt layer",
valueHint: "layer-name",
alias: ["e"]
} };
const legacyRootDirArgs = {
cwd: {
...cwdArgs.cwd,
description: "Specify the working directory, this takes precedence over ROOTDIR (default: `.`)",
default: void 0
},
rootDir: {
type: "positional",
description: "Specifies the working directory (default: `.`)",
required: false,
default: "."
}
};
//#endregion
export { legacyRootDirArgs as a, extendsArgs as i, dotEnvArgs as n, logLevelArgs as o, envNameArgs as r, cwdArgs as t };

View file

@ -0,0 +1,29 @@
import { satisfies } from "semver";
import { $fetch } from "ofetch";
import { parseINI } from "confbox";
//#region ../nuxi/src/commands/module/_utils.ts
async function fetchModules() {
const { modules } = await $fetch(`https://api.nuxt.com/modules?version=all`);
return modules;
}
function checkNuxtCompatibility(module, nuxtVersion) {
if (!module.compatibility?.nuxt) return true;
return satisfies(nuxtVersion, module.compatibility.nuxt, { includePrerelease: true });
}
function getRegistryFromContent(content, scope) {
try {
const npmConfig = parseINI(content);
if (scope) {
const scopeKey = `${scope}:registry`;
if (npmConfig[scopeKey]) return npmConfig[scopeKey].trim();
}
if (npmConfig.registry) return npmConfig.registry.trim();
return null;
} catch {
return null;
}
}
//#endregion
export { fetchModules as n, getRegistryFromContent as r, checkNuxtCompatibility as t };

View file

@ -0,0 +1,10 @@
import "./_shared-BCYCnX0T.mjs";
import "./logger-B4ge7MhP.mjs";
import "./kit-B3S8uoS_.mjs";
import "./versions-Bly87QYZ.mjs";
import "./fs-CQH7NJn6.mjs";
import { t as add_default } from "./add-cOz5A42V.mjs";
import "./_utils-NB3Cn3-G.mjs";
import "./prepare-CUaf6Joj.mjs";
export { add_default as default };

View file

@ -0,0 +1,341 @@
import { o as logLevelArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { r as relativeToProcess, t as loadKit } from "./kit-B3S8uoS_.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { colors } from "consola/utils";
import { cancel, intro, outro } from "@clack/prompts";
import { existsSync, promises } from "node:fs";
import { dirname, extname, resolve } from "pathe";
import { camelCase, pascalCase } from "scule";
//#region ../nuxi/src/utils/templates/api.ts
const httpMethods = [
"connect",
"delete",
"get",
"head",
"options",
"post",
"put",
"trace",
"patch"
];
const api = ({ name, args, nuxtOptions }) => {
return {
path: resolve(nuxtOptions.srcDir, nuxtOptions.serverDir, `api/${name}${applySuffix(args, httpMethods, "method")}.ts`),
contents: `
export default defineEventHandler(event => {
return 'Hello ${name}'
})
`
};
};
//#endregion
//#region ../nuxi/src/utils/templates/app.ts
const app = ({ args, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, "app.vue"),
contents: args.pages ? `
<script setup lang="ts"><\/script>
<template>
<div>
<NuxtLayout>
<NuxtPage/>
</NuxtLayout>
</div>
</template>
<style scoped></style>
` : `
<script setup lang="ts"><\/script>
<template>
<div>
<h1>Hello World!</h1>
</div>
</template>
<style scoped></style>
`
});
//#endregion
//#region ../nuxi/src/utils/templates/app-config.ts
const appConfig = ({ nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, "app.config.ts"),
contents: `
export default defineAppConfig({})
`
});
//#endregion
//#region ../nuxi/src/utils/templates/component.ts
const component = ({ name, args, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, `components/${name}${applySuffix(args, ["client", "server"], "mode")}.vue`),
contents: `
<script setup lang="ts"><\/script>
<template>
<div>
Component: ${name}
</div>
</template>
<style scoped></style>
`
});
//#endregion
//#region ../nuxi/src/utils/templates/composable.ts
const composable = ({ name, nuxtOptions }) => {
const nameWithUsePrefix = `use${pascalCase(name.replace(/^use-?/, ""))}`;
return {
path: resolve(nuxtOptions.srcDir, `composables/${name}.ts`),
contents: `
export const ${nameWithUsePrefix} = () => {
return ref()
}
`
};
};
//#endregion
//#region ../nuxi/src/utils/templates/error.ts
const error = ({ nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, "error.vue"),
contents: `
<script setup lang="ts">
import type { NuxtError } from '#app'
const props = defineProps({
error: Object as () => NuxtError
})
<\/script>
<template>
<div>
<h1>{{ error.statusCode }}</h1>
<NuxtLink to="/">Go back home</NuxtLink>
</div>
</template>
<style scoped></style>
`
});
//#endregion
//#region ../nuxi/src/utils/templates/layer.ts
const layer = ({ name, nuxtOptions }) => {
return {
path: resolve(nuxtOptions.rootDir, `layers/${name}/nuxt.config.ts`),
contents: `
export default defineNuxtConfig({})
`
};
};
//#endregion
//#region ../nuxi/src/utils/templates/layout.ts
const layout = ({ name, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.dir.layouts, `${name}.vue`),
contents: `
<script setup lang="ts"><\/script>
<template>
<div>
Layout: ${name}
<slot />
</div>
</template>
<style scoped></style>
`
});
//#endregion
//#region ../nuxi/src/utils/templates/middleware.ts
const middleware = ({ name, args, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.dir.middleware, `${name}${applySuffix(args, ["global"])}.ts`),
contents: `
export default defineNuxtRouteMiddleware((to, from) => {})
`
});
//#endregion
//#region ../nuxi/src/utils/templates/module.ts
const module = ({ name, nuxtOptions }) => ({
path: resolve(nuxtOptions.rootDir, "modules", `${name}.ts`),
contents: `
import { defineNuxtModule } from 'nuxt/kit'
export default defineNuxtModule({
meta: {
name: '${name}'
},
setup () {}
})
`
});
//#endregion
//#region ../nuxi/src/utils/templates/page.ts
const page = ({ name, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.dir.pages, `${name}.vue`),
contents: `
<script setup lang="ts"><\/script>
<template>
<div>
Page: ${name}
</div>
</template>
<style scoped></style>
`
});
//#endregion
//#region ../nuxi/src/utils/templates/plugin.ts
const plugin = ({ name, args, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.dir.plugins, `${name}${applySuffix(args, ["client", "server"], "mode")}.ts`),
contents: `
export default defineNuxtPlugin(nuxtApp => {})
`
});
//#endregion
//#region ../nuxi/src/utils/templates/server-middleware.ts
const serverMiddleware = ({ name, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.serverDir, "middleware", `${name}.ts`),
contents: `
export default defineEventHandler(event => {})
`
});
//#endregion
//#region ../nuxi/src/utils/templates/server-plugin.ts
const serverPlugin = ({ name, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.serverDir, "plugins", `${name}.ts`),
contents: `
export default defineNitroPlugin(nitroApp => {})
`
});
//#endregion
//#region ../nuxi/src/utils/templates/server-route.ts
const serverRoute = ({ name, args, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.serverDir, args.api ? "api" : "routes", `${name}.ts`),
contents: `
export default defineEventHandler(event => {})
`
});
//#endregion
//#region ../nuxi/src/utils/templates/server-util.ts
const serverUtil = ({ name, nuxtOptions }) => ({
path: resolve(nuxtOptions.srcDir, nuxtOptions.serverDir, "utils", `${name}.ts`),
contents: `
export function ${camelCase(name)}() {}
`
});
//#endregion
//#region ../nuxi/src/utils/templates/index.ts
const templates = {
"api": api,
"app": app,
"app-config": appConfig,
"component": component,
"composable": composable,
"error": error,
"layer": layer,
"layout": layout,
"middleware": middleware,
"module": module,
"page": page,
"plugin": plugin,
"server-middleware": serverMiddleware,
"server-plugin": serverPlugin,
"server-route": serverRoute,
"server-util": serverUtil
};
function applySuffix(args, suffixes, unwrapFrom) {
let suffix = "";
for (const s of suffixes) if (args[s]) suffix += `.${s}`;
if (unwrapFrom && args[unwrapFrom] && suffixes.includes(args[unwrapFrom])) suffix += `.${args[unwrapFrom]}`;
return suffix;
}
//#endregion
//#region ../nuxi/src/commands/add.ts
const templateNames = Object.keys(templates);
var add_default = defineCommand({
meta: {
name: "add",
description: "Create a new template file."
},
args: {
...cwdArgs,
...logLevelArgs,
force: {
type: "boolean",
description: "Force override file if it already exists",
default: false
},
template: {
type: "positional",
required: true,
valueHint: templateNames.join("|"),
description: `Specify which template to generate`
},
name: {
type: "positional",
required: true,
description: "Specify name of the generated file"
}
},
async run(ctx) {
const cwd = resolve(ctx.args.cwd);
intro(colors.cyan("Adding template..."));
const templateName = ctx.args.template;
if (!templateNames.includes(templateName)) {
const templateNames$1 = Object.keys(templates).map((name$1) => colors.cyan(name$1));
const lastTemplateName = templateNames$1.pop();
logger.error(`Template ${colors.cyan(templateName)} is not supported.`);
logger.info(`Possible values are ${templateNames$1.join(", ")} or ${lastTemplateName}.`);
process.exit(1);
}
const ext = extname(ctx.args.name);
const name = ext === ".vue" || ext === ".ts" ? ctx.args.name.replace(ext, "") : ctx.args.name;
if (!name) {
cancel("name argument is missing!");
process.exit(1);
}
const config = await (await loadKit(cwd)).loadNuxtConfig({ cwd });
const template = templates[templateName];
const res = template({
name,
args: ctx.args,
nuxtOptions: config
});
if (!ctx.args.force && existsSync(res.path)) {
logger.error(`File exists at ${colors.cyan(relativeToProcess(res.path))}.`);
logger.info(`Use ${colors.cyan("--force")} to override or use a different name.`);
process.exit(1);
}
const parentDir = dirname(res.path);
if (!existsSync(parentDir)) {
logger.step(`Creating directory ${colors.cyan(relativeToProcess(parentDir))}.`);
if (templateName === "page") logger.info("This enables vue-router functionality!");
await promises.mkdir(parentDir, { recursive: true });
}
await promises.writeFile(res.path, `${res.contents.trim()}\n`);
logger.success(`Created ${colors.cyan(relativeToProcess(res.path))}.`);
outro(`Generated a new ${colors.cyan(templateName)}!`);
}
});
//#endregion
export { add_default as default };

View file

@ -0,0 +1,309 @@
import { o as logLevelArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { r as relativeToProcess } from "./kit-B3S8uoS_.mjs";
import { t as getNuxtVersion } from "./versions-Bly87QYZ.mjs";
import { n as fetchModules, r as getRegistryFromContent, t as checkNuxtCompatibility } from "./_utils-NB3Cn3-G.mjs";
import { t as prepare_default } from "./prepare-CUaf6Joj.mjs";
import { join } from "node:path";
import process from "node:process";
import { defineCommand, runCommand } from "citty";
import { colors } from "consola/utils";
import { confirm, isCancel, select } from "@clack/prompts";
import { fileURLToPath } from "node:url";
import * as fs from "node:fs";
import { existsSync } from "node:fs";
import { joinURL } from "ufo";
import { resolve as resolve$1 } from "pathe";
import { readPackageJSON } from "pkg-types";
import { satisfies } from "semver";
import { homedir } from "node:os";
import { addDependency, detectPackageManager } from "nypm";
import { $fetch } from "ofetch";
import { updateConfig } from "c12/update";
//#region ../nuxi/src/commands/_utils.ts
const nuxiCommands = [
"add",
"analyze",
"build",
"cleanup",
"_dev",
"dev",
"devtools",
"generate",
"info",
"init",
"module",
"prepare",
"preview",
"start",
"test",
"typecheck",
"upgrade"
];
function isNuxiCommand(command) {
return nuxiCommands.includes(command);
}
//#endregion
//#region ../nuxi/src/run.ts
globalThis.__nuxt_cli__ = globalThis.__nuxt_cli__ || {
startTime: Date.now(),
entry: fileURLToPath(new URL("../../bin/nuxi.mjs", import.meta.url)),
devEntry: fileURLToPath(new URL("../dev/index.mjs", import.meta.url))
};
async function runCommand$1(command, argv = process.argv.slice(2), data = {}) {
argv.push("--no-clear");
if (command.meta && "name" in command.meta && typeof command.meta.name === "string") {
const name = command.meta.name;
if (!isNuxiCommand(name)) throw new Error(`Invalid command ${name}`);
} else throw new Error(`Invalid command, must be named`);
return await runCommand(command, {
rawArgs: argv,
data: { overrides: data.overrides || {} }
});
}
//#endregion
//#region ../nuxi/src/commands/module/add.ts
var add_default = defineCommand({
meta: {
name: "add",
description: "Add Nuxt modules"
},
args: {
...cwdArgs,
...logLevelArgs,
moduleName: {
type: "positional",
description: "Specify one or more modules to install by name, separated by spaces"
},
skipInstall: {
type: "boolean",
description: "Skip npm install"
},
skipConfig: {
type: "boolean",
description: "Skip nuxt.config.ts update"
},
dev: {
type: "boolean",
description: "Install modules as dev dependencies"
}
},
async setup(ctx) {
const cwd = resolve$1(ctx.args.cwd);
const modules = ctx.args._.map((e) => e.trim()).filter(Boolean);
const projectPkg = await readPackageJSON(cwd).catch(() => ({}));
if (!projectPkg.dependencies?.nuxt && !projectPkg.devDependencies?.nuxt) {
logger.warn(`No ${colors.cyan("nuxt")} dependency detected in ${colors.cyan(relativeToProcess(cwd))}.`);
const shouldContinue = await confirm({
message: `Do you want to continue anyway?`,
initialValue: false
});
if (isCancel(shouldContinue) || shouldContinue !== true) process.exit(1);
}
const resolvedModules = (await Promise.all(modules.map((moduleName) => resolveModule(moduleName, cwd)))).filter((x) => x != null);
logger.info(`Resolved ${resolvedModules.map((x) => colors.cyan(x.pkgName)).join(", ")}, adding module${resolvedModules.length > 1 ? "s" : ""}...`);
await addModules(resolvedModules, {
...ctx.args,
cwd
}, projectPkg);
if (!ctx.args.skipInstall) await runCommand$1(prepare_default, Object.entries(ctx.args).filter(([k]) => k in cwdArgs || k in logLevelArgs).map(([k, v]) => `--${k}=${v}`));
}
});
async function addModules(modules, { skipInstall, skipConfig, cwd, dev }, projectPkg) {
if (!skipInstall) {
const installedModules = [];
const notInstalledModules = [];
const dependencies = new Set([...Object.keys(projectPkg.dependencies || {}), ...Object.keys(projectPkg.devDependencies || {})]);
for (const module of modules) if (dependencies.has(module.pkgName)) installedModules.push(module);
else notInstalledModules.push(module);
if (installedModules.length > 0) {
const installedModulesList = installedModules.map((module) => colors.cyan(module.pkgName)).join(", ");
const are = installedModules.length > 1 ? "are" : "is";
logger.info(`${installedModulesList} ${are} already installed`);
}
if (notInstalledModules.length > 0) {
const isDev = Boolean(projectPkg.devDependencies?.nuxt) || dev;
const notInstalledModulesList = notInstalledModules.map((module) => colors.cyan(module.pkg)).join(", ");
const dependency = notInstalledModules.length > 1 ? "dependencies" : "dependency";
const a = notInstalledModules.length > 1 ? "" : " a";
logger.info(`Installing ${notInstalledModulesList} as${a}${isDev ? " development" : ""} ${dependency}`);
const packageManager = await detectPackageManager(cwd);
if (await addDependency(notInstalledModules.map((module) => module.pkg), {
cwd,
dev: isDev,
installPeerDependencies: true,
packageManager,
workspace: packageManager?.name === "pnpm" && existsSync(resolve$1(cwd, "pnpm-workspace.yaml"))
}).then(() => true).catch(async (error) => {
logger.error(error);
const result = await confirm({
message: `Install failed for ${notInstalledModules.map((module) => colors.cyan(module.pkg)).join(", ")}. Do you want to continue adding the module${notInstalledModules.length > 1 ? "s" : ""} to ${colors.cyan("nuxt.config")}?`,
initialValue: false
});
if (isCancel(result)) return false;
return result;
}) !== true) return;
}
}
if (!skipConfig) await updateConfig({
cwd,
configFile: "nuxt.config",
async onCreate() {
logger.info(`Creating ${colors.cyan("nuxt.config.ts")}`);
return getDefaultNuxtConfig();
},
async onUpdate(config) {
if (!config.modules) config.modules = [];
for (const resolved of modules) {
if (config.modules.includes(resolved.pkgName)) {
logger.info(`${colors.cyan(resolved.pkgName)} is already in the ${colors.cyan("modules")}`);
continue;
}
logger.info(`Adding ${colors.cyan(resolved.pkgName)} to the ${colors.cyan("modules")}`);
config.modules.push(resolved.pkgName);
}
}
}).catch((error) => {
logger.error(`Failed to update ${colors.cyan("nuxt.config")}: ${error.message}`);
logger.error(`Please manually add ${colors.cyan(modules.map((module) => module.pkgName).join(", "))} to the ${colors.cyan("modules")} in ${colors.cyan("nuxt.config.ts")}`);
return null;
});
}
function getDefaultNuxtConfig() {
return `
// https://nuxt.com/docs/api/configuration/nuxt-config
export default defineNuxtConfig({
modules: []
})`;
}
const packageRegex = /^(@[a-z0-9-~][a-z0-9-._~]*\/)?([a-z0-9-~][a-z0-9-._~]*)(@[^@]+)?$/;
async function resolveModule(moduleName, cwd) {
let pkgName = moduleName;
let pkgVersion;
const reMatch = moduleName.match(packageRegex);
if (reMatch) {
if (reMatch[3]) {
pkgName = `${reMatch[1] || ""}${reMatch[2] || ""}`;
pkgVersion = reMatch[3].slice(1);
}
} else {
logger.error(`Invalid package name ${colors.cyan(pkgName)}.`);
return false;
}
const matchedModule = (await fetchModules().catch((err) => {
logger.warn(`Cannot search in the Nuxt Modules database: ${err}`);
return [];
})).find((module) => module.name === moduleName || pkgVersion && module.name === pkgName || module.npm === pkgName || module.aliases?.includes(pkgName));
if (matchedModule?.npm) pkgName = matchedModule.npm;
if (matchedModule && matchedModule.compatibility.nuxt) {
const nuxtVersion = await getNuxtVersion(cwd);
if (!checkNuxtCompatibility(matchedModule, nuxtVersion)) {
logger.warn(`The module ${colors.cyan(pkgName)} is not compatible with Nuxt ${colors.cyan(nuxtVersion)} (requires ${colors.cyan(matchedModule.compatibility.nuxt)})`);
const shouldContinue = await confirm({
message: "Do you want to continue installing incompatible version?",
initialValue: false
});
if (isCancel(shouldContinue) || !shouldContinue) return false;
}
const versionMap = matchedModule.compatibility.versionMap;
if (versionMap) {
for (const [_nuxtVersion, _moduleVersion] of Object.entries(versionMap)) if (satisfies(nuxtVersion, _nuxtVersion)) {
if (!pkgVersion) pkgVersion = _moduleVersion;
else {
logger.warn(`Recommended version of ${colors.cyan(pkgName)} for Nuxt ${colors.cyan(nuxtVersion)} is ${colors.cyan(_moduleVersion)} but you have requested ${colors.cyan(pkgVersion)}.`);
const result = await select({
message: "Choose a version:",
options: [{
value: _moduleVersion,
label: _moduleVersion
}, {
value: pkgVersion,
label: pkgVersion
}]
});
if (isCancel(result)) return false;
pkgVersion = result;
}
break;
}
}
}
let version = pkgVersion || "latest";
const meta = await detectNpmRegistry(pkgName.startsWith("@") ? pkgName.split("/")[0] : null);
const headers = {};
if (meta.authToken) headers.Authorization = `Bearer ${meta.authToken}`;
const pkgDetails = await $fetch(joinURL(meta.registry, `${pkgName}`), { headers });
if (pkgDetails["dist-tags"]?.[version]) version = pkgDetails["dist-tags"][version];
else version = Object.keys(pkgDetails.versions)?.findLast((v) => satisfies(v, version)) || version;
const pkg = pkgDetails.versions[version];
const pkgDependencies = Object.assign(pkg.dependencies || {}, pkg.devDependencies || {});
if (!pkgDependencies.nuxt && !pkgDependencies["nuxt-edge"] && !pkgDependencies["@nuxt/kit"]) {
logger.warn(`It seems that ${colors.cyan(pkgName)} is not a Nuxt module.`);
const shouldContinue = await confirm({
message: `Do you want to continue installing ${colors.cyan(pkgName)} anyway?`,
initialValue: false
});
if (isCancel(shouldContinue) || !shouldContinue) return false;
}
return {
nuxtModule: matchedModule,
pkg: `${pkgName}@${version}`,
pkgName,
pkgVersion: version
};
}
function getNpmrcPaths() {
const userNpmrcPath = join(homedir(), ".npmrc");
return [join(process.cwd(), ".npmrc"), userNpmrcPath];
}
async function getAuthToken(registry) {
const paths = getNpmrcPaths();
const authTokenRegex = new RegExp(`^//${registry.replace(/^https?:\/\//, "").replace(/\/$/, "")}/:_authToken=(.+)$`, "m");
for (const npmrcPath of paths) {
let fd;
try {
fd = await fs.promises.open(npmrcPath, "r");
if (await fd.stat().then((r) => r.isFile())) {
const authTokenMatch = (await fd.readFile("utf-8")).match(authTokenRegex)?.[1];
if (authTokenMatch) return authTokenMatch.trim();
}
} catch {} finally {
await fd?.close();
}
}
return null;
}
async function detectNpmRegistry(scope) {
const registry = await getRegistry(scope);
return {
registry,
authToken: await getAuthToken(registry)
};
}
async function getRegistry(scope) {
if (process.env.COREPACK_NPM_REGISTRY) return process.env.COREPACK_NPM_REGISTRY;
const registry = await getRegistryFromFile(getNpmrcPaths(), scope);
if (registry) process.env.COREPACK_NPM_REGISTRY = registry;
return registry || "https://registry.npmjs.org";
}
async function getRegistryFromFile(paths, scope) {
for (const npmrcPath of paths) {
let fd;
try {
fd = await fs.promises.open(npmrcPath, "r");
if (await fd.stat().then((r) => r.isFile())) {
const registry = getRegistryFromContent(await fd.readFile("utf-8"), scope);
if (registry) return registry;
}
} catch {} finally {
await fd?.close();
}
}
return null;
}
//#endregion
export { runCommand$1 as n, add_default as t };

View file

@ -0,0 +1,821 @@
import { a as legacyRootDirArgs, i as extendsArgs, n as dotEnvArgs, o as logLevelArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { t as overrideEnv } from "./env-DV8TWRZt.mjs";
import { r as relativeToProcess, t as loadKit } from "./kit-B3S8uoS_.mjs";
import { n as clearDir } from "./fs-CQH7NJn6.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { colors } from "consola/utils";
import { intro, note, outro, taskLog } from "@clack/prompts";
import { defu as defu$1 } from "defu";
import { promises } from "node:fs";
import { join, resolve } from "pathe";
import { FastResponse, FastURL, serve } from "srvx";
//#region ../../node_modules/.pnpm/rou3@0.7.10/node_modules/rou3/dist/index.mjs
const NullProtoObj = /* @__PURE__ */ (() => {
const e = function() {};
return e.prototype = Object.create(null), Object.freeze(e.prototype), e;
})();
/**
* Create a new router context.
*/
function createRouter() {
return {
root: { key: "" },
static: new NullProtoObj()
};
}
function splitPath(path) {
const [_, ...s] = path.split("/");
return s[s.length - 1] === "" ? s.slice(0, -1) : s;
}
function getMatchParams(segments, paramsMap) {
const params = new NullProtoObj();
for (const [index, name] of paramsMap) {
const segment = index < 0 ? segments.slice(-1 * index).join("/") : segments[index];
if (typeof name === "string") params[name] = segment;
else {
const match = segment.match(name);
if (match) for (const key in match.groups) params[key] = match.groups[key];
}
}
return params;
}
/**
* Add a route to the router context.
*/
function addRoute(ctx, method = "", path, data) {
method = method.toUpperCase();
if (path.charCodeAt(0) !== 47) path = `/${path}`;
const segments = splitPath(path);
let node = ctx.root;
let _unnamedParamIndex = 0;
const paramsMap = [];
const paramsRegexp = [];
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
if (segment.startsWith("**")) {
if (!node.wildcard) node.wildcard = { key: "**" };
node = node.wildcard;
paramsMap.push([
-i,
segment.split(":")[1] || "_",
segment.length === 2
]);
break;
}
if (segment === "*" || segment.includes(":")) {
if (!node.param) node.param = { key: "*" };
node = node.param;
if (segment === "*") paramsMap.push([
i,
`_${_unnamedParamIndex++}`,
true
]);
else if (segment.includes(":", 1)) {
const regexp = getParamRegexp(segment);
paramsRegexp[i] = regexp;
node.hasRegexParam = true;
paramsMap.push([
i,
regexp,
false
]);
} else paramsMap.push([
i,
segment.slice(1),
false
]);
continue;
}
const child = node.static?.[segment];
if (child) node = child;
else {
const staticNode = { key: segment };
if (!node.static) node.static = new NullProtoObj();
node.static[segment] = staticNode;
node = staticNode;
}
}
const hasParams = paramsMap.length > 0;
if (!node.methods) node.methods = new NullProtoObj();
node.methods[method] ??= [];
node.methods[method].push({
data: data || null,
paramsRegexp,
paramsMap: hasParams ? paramsMap : void 0
});
if (!hasParams) ctx.static[path] = node;
}
function getParamRegexp(segment) {
const regex = segment.replace(/:(\w+)/g, (_, id) => `(?<${id}>[^/]+)`).replace(/\./g, "\\.");
return /* @__PURE__ */ new RegExp(`^${regex}$`);
}
/**
* Find a route by path.
*/
function findRoute(ctx, method = "", path, opts) {
if (path.charCodeAt(path.length - 1) === 47) path = path.slice(0, -1);
const staticNode = ctx.static[path];
if (staticNode && staticNode.methods) {
const staticMatch = staticNode.methods[method] || staticNode.methods[""];
if (staticMatch !== void 0) return staticMatch[0];
}
const segments = splitPath(path);
const match = _lookupTree(ctx, ctx.root, method, segments, 0)?.[0];
if (match === void 0) return;
if (opts?.params === false) return match;
return {
data: match.data,
params: match.paramsMap ? getMatchParams(segments, match.paramsMap) : void 0
};
}
function _lookupTree(ctx, node, method, segments, index) {
if (index === segments.length) {
if (node.methods) {
const match = node.methods[method] || node.methods[""];
if (match) return match;
}
if (node.param && node.param.methods) {
const match = node.param.methods[method] || node.param.methods[""];
if (match) {
const pMap = match[0].paramsMap;
if (pMap?.[pMap?.length - 1]?.[2]) return match;
}
}
if (node.wildcard && node.wildcard.methods) {
const match = node.wildcard.methods[method] || node.wildcard.methods[""];
if (match) {
const pMap = match[0].paramsMap;
if (pMap?.[pMap?.length - 1]?.[2]) return match;
}
}
return;
}
const segment = segments[index];
if (node.static) {
const staticChild = node.static[segment];
if (staticChild) {
const match = _lookupTree(ctx, staticChild, method, segments, index + 1);
if (match) return match;
}
}
if (node.param) {
const match = _lookupTree(ctx, node.param, method, segments, index + 1);
if (match) {
if (node.param.hasRegexParam) {
const exactMatch = match.find((m) => m.paramsRegexp[index]?.test(segment)) || match.find((m) => !m.paramsRegexp[index]);
return exactMatch ? [exactMatch] : void 0;
}
return match;
}
}
if (node.wildcard && node.wildcard.methods) return node.wildcard.methods[method] || node.wildcard.methods[""];
}
function routeToRegExp(route = "/") {
const reSegments = [];
let idCtr = 0;
for (const segment of route.split("/")) {
if (!segment) continue;
if (segment === "*") reSegments.push(`(?<_${idCtr++}>[^/]*)`);
else if (segment.startsWith("**")) reSegments.push(segment === "**" ? "?(?<_>.*)" : `?(?<${segment.slice(3)}>.+)`);
else if (segment.includes(":")) reSegments.push(segment.replace(/:(\w+)/g, (_, id) => `(?<${id}>[^/]+)`).replace(/\./g, "\\."));
else reSegments.push(segment);
}
return /* @__PURE__ */ new RegExp(`^/${reSegments.join("/")}/?$`);
}
//#endregion
//#region ../../node_modules/.pnpm/h3@2.0.1-rc.6_crossws@0.4.1_srvx@0.9.8_/node_modules/h3/dist/h3.mjs
const kEventNS = "h3.internal.event.";
const kEventRes = /* @__PURE__ */ Symbol.for(`${kEventNS}res`);
const kEventResHeaders = /* @__PURE__ */ Symbol.for(`${kEventNS}res.headers`);
var H3Event = class {
app;
req;
url;
context;
static __is_event__ = true;
constructor(req, context, app) {
this.context = context || req.context || new NullProtoObj();
this.req = req;
this.app = app;
const _url = req._url;
this.url = _url && _url instanceof URL ? _url : new FastURL(req.url);
}
get res() {
return this[kEventRes] ||= new H3EventResponse();
}
get runtime() {
return this.req.runtime;
}
waitUntil(promise) {
this.req.waitUntil?.(promise);
}
toString() {
return `[${this.req.method}] ${this.req.url}`;
}
toJSON() {
return this.toString();
}
get node() {
return this.req.runtime?.node;
}
get headers() {
return this.req.headers;
}
get path() {
return this.url.pathname + this.url.search;
}
get method() {
return this.req.method;
}
};
var H3EventResponse = class {
status;
statusText;
get headers() {
return this[kEventResHeaders] ||= new Headers();
}
};
const DISALLOWED_STATUS_CHARS = /[^\u0009\u0020-\u007E]/g;
function sanitizeStatusMessage(statusMessage = "") {
return statusMessage.replace(DISALLOWED_STATUS_CHARS, "");
}
function sanitizeStatusCode(statusCode, defaultStatusCode = 200) {
if (!statusCode) return defaultStatusCode;
if (typeof statusCode === "string") statusCode = +statusCode;
if (statusCode < 100 || statusCode > 599) return defaultStatusCode;
return statusCode;
}
var HTTPError = class HTTPError$1 extends Error {
get name() {
return "HTTPError";
}
status;
statusText;
headers;
cause;
data;
body;
unhandled;
static isError(input) {
return input instanceof Error && input?.name === "HTTPError";
}
static status(status, statusText, details) {
return new HTTPError$1({
...details,
statusText,
status
});
}
constructor(arg1, arg2) {
let messageInput;
let details;
if (typeof arg1 === "string") {
messageInput = arg1;
details = arg2;
} else details = arg1;
const status = sanitizeStatusCode(details?.status || (details?.cause)?.status || details?.status || details?.statusCode, 500);
const statusText = sanitizeStatusMessage(details?.statusText || (details?.cause)?.statusText || details?.statusText || details?.statusMessage);
const message = messageInput || details?.message || (details?.cause)?.message || details?.statusText || details?.statusMessage || [
"HTTPError",
status,
statusText
].filter(Boolean).join(" ");
super(message, { cause: details });
this.cause = details;
Error.captureStackTrace?.(this, this.constructor);
this.status = status;
this.statusText = statusText || void 0;
const rawHeaders = details?.headers || (details?.cause)?.headers;
this.headers = rawHeaders ? new Headers(rawHeaders) : void 0;
this.unhandled = details?.unhandled ?? (details?.cause)?.unhandled ?? void 0;
this.data = details?.data;
this.body = details?.body;
}
get statusCode() {
return this.status;
}
get statusMessage() {
return this.statusText;
}
toJSON() {
const unhandled = this.unhandled;
return {
status: this.status,
statusText: this.statusText,
unhandled,
message: unhandled ? "HTTPError" : this.message,
data: unhandled ? void 0 : this.data,
...unhandled ? void 0 : this.body
};
}
};
function isJSONSerializable(value, _type) {
if (value === null || value === void 0) return true;
if (_type !== "object") return _type === "boolean" || _type === "number" || _type === "string";
if (typeof value.toJSON === "function") return true;
if (Array.isArray(value)) return true;
if (typeof value.pipe === "function" || typeof value.pipeTo === "function") return false;
if (value instanceof NullProtoObj) return true;
const proto = Object.getPrototypeOf(value);
return proto === Object.prototype || proto === null;
}
const kNotFound = /* @__PURE__ */ Symbol.for("h3.notFound");
const kHandled = /* @__PURE__ */ Symbol.for("h3.handled");
function toResponse(val, event, config = {}) {
if (typeof val?.then === "function") return (val.catch?.((error) => error) || Promise.resolve(val)).then((resolvedVal) => toResponse(resolvedVal, event, config));
const response = prepareResponse(val, event, config);
if (typeof response?.then === "function") return toResponse(response, event, config);
const { onResponse: onResponse$1 } = config;
return onResponse$1 ? Promise.resolve(onResponse$1(response, event)).then(() => response) : response;
}
var HTTPResponse = class {
#headers;
#init;
body;
constructor(body, init) {
this.body = body;
this.#init = init;
}
get status() {
return this.#init?.status || 200;
}
get statusText() {
return this.#init?.statusText || "OK";
}
get headers() {
return this.#headers ||= new Headers(this.#init?.headers);
}
};
function prepareResponse(val, event, config, nested) {
if (val === kHandled) return new FastResponse(null);
if (val === kNotFound) val = new HTTPError({
status: 404,
message: `Cannot find any route matching [${event.req.method}] ${event.url}`
});
if (val && val instanceof Error) {
const isHTTPError = HTTPError.isError(val);
const error = isHTTPError ? val : new HTTPError(val);
if (!isHTTPError) {
error.unhandled = true;
if (val?.stack) error.stack = val.stack;
}
if (error.unhandled && !config.silent) console.error(error);
const { onError: onError$1 } = config;
return onError$1 && !nested ? Promise.resolve(onError$1(error, event)).catch((error$1) => error$1).then((newVal) => prepareResponse(newVal ?? val, event, config, true)) : errorResponse(error, config.debug);
}
const preparedRes = event[kEventRes];
const preparedHeaders = preparedRes?.[kEventResHeaders];
event[kEventRes] = void 0;
if (!(val instanceof Response)) {
const res = prepareResponseBody(val, event, config);
const status = res.status || preparedRes?.status;
return new FastResponse(nullBody(event.req.method, status) ? null : res.body, {
status,
statusText: res.statusText || preparedRes?.statusText,
headers: res.headers && preparedHeaders ? mergeHeaders$1(res.headers, preparedHeaders) : res.headers || preparedHeaders
});
}
if (!preparedHeaders || nested || !val.ok) return val;
try {
mergeHeaders$1(val.headers, preparedHeaders, val.headers);
return val;
} catch {
return new FastResponse(nullBody(event.req.method, val.status) ? null : val.body, {
status: val.status,
statusText: val.statusText,
headers: mergeHeaders$1(val.headers, preparedHeaders)
});
}
}
function mergeHeaders$1(base, overrides, target = new Headers(base)) {
for (const [name, value] of overrides) if (name === "set-cookie") target.append(name, value);
else target.set(name, value);
return target;
}
const frozenHeaders = () => {
throw new Error("Headers are frozen");
};
var FrozenHeaders = class extends Headers {
constructor(init) {
super(init);
this.set = this.append = this.delete = frozenHeaders;
}
};
const emptyHeaders = /* @__PURE__ */ new FrozenHeaders({ "content-length": "0" });
const jsonHeaders = /* @__PURE__ */ new FrozenHeaders({ "content-type": "application/json;charset=UTF-8" });
function prepareResponseBody(val, event, config) {
if (val === null || val === void 0) return {
body: "",
headers: emptyHeaders
};
const valType = typeof val;
if (valType === "string") return { body: val };
if (val instanceof Uint8Array) {
event.res.headers.set("content-length", val.byteLength.toString());
return { body: val };
}
if (val instanceof HTTPResponse || val?.constructor?.name === "HTTPResponse") return val;
if (isJSONSerializable(val, valType)) return {
body: JSON.stringify(val, void 0, config.debug ? 2 : void 0),
headers: jsonHeaders
};
if (valType === "bigint") return {
body: val.toString(),
headers: jsonHeaders
};
if (val instanceof Blob) {
const headers = new Headers({
"content-type": val.type,
"content-length": val.size.toString()
});
let filename = val.name;
if (filename) {
filename = encodeURIComponent(filename);
headers.set("content-disposition", `filename="${filename}"; filename*=UTF-8''${filename}`);
}
return {
body: val.stream(),
headers
};
}
if (valType === "symbol") return { body: val.toString() };
if (valType === "function") return { body: `${val.name}()` };
return { body: val };
}
function nullBody(method, status) {
return method === "HEAD" || status === 100 || status === 101 || status === 102 || status === 204 || status === 205 || status === 304;
}
function errorResponse(error, debug) {
return new FastResponse(JSON.stringify({
...error.toJSON(),
stack: debug && error.stack ? error.stack.split("\n").map((l) => l.trim()) : void 0
}, void 0, debug ? 2 : void 0), {
status: error.status,
statusText: error.statusText,
headers: error.headers ? mergeHeaders$1(jsonHeaders, error.headers) : new Headers(jsonHeaders)
});
}
function normalizeMiddleware(input, opts = {}) {
const matcher = createMatcher(opts);
if (!matcher && (input.length > 1 || input.constructor?.name === "AsyncFunction")) return input;
return (event, next) => {
if (matcher && !matcher(event)) return next();
const res = input(event, next);
return res === void 0 || res === kNotFound ? next() : res;
};
}
function createMatcher(opts) {
if (!opts.route && !opts.method && !opts.match) return;
const routeMatcher = opts.route ? routeToRegExp(opts.route) : void 0;
const method = opts.method?.toUpperCase();
return function _middlewareMatcher(event) {
if (method && event.req.method !== method) return false;
if (opts.match && !opts.match(event)) return false;
if (!routeMatcher) return true;
const match = event.url.pathname.match(routeMatcher);
if (!match) return false;
if (match.groups) event.context.middlewareParams = {
...event.context.middlewareParams,
...match.groups
};
return true;
};
}
function callMiddleware(event, middleware, handler, index = 0) {
if (index === middleware.length) return handler(event);
const fn = middleware[index];
let nextCalled;
let nextResult;
const next = () => {
if (nextCalled) return nextResult;
nextCalled = true;
nextResult = callMiddleware(event, middleware, handler, index + 1);
return nextResult;
};
const ret = fn(event, next);
return isUnhandledResponse(ret) ? next() : typeof ret?.then === "function" ? ret.then((resolved) => isUnhandledResponse(resolved) ? next() : resolved) : ret;
}
function isUnhandledResponse(val) {
return val === void 0 || val === kNotFound;
}
function toRequest(input, options) {
if (typeof input === "string") {
let url = input;
if (url[0] === "/") {
const headers = options?.headers ? new Headers(options.headers) : void 0;
const host = headers?.get("host") || "localhost";
url = `${headers?.get("x-forwarded-proto") === "https" ? "https" : "http"}://${host}${url}`;
}
return new Request(url, options);
} else if (options || input instanceof URL) return new Request(input, options);
return input;
}
function defineHandler(input) {
if (typeof input === "function") return handlerWithFetch(input);
const handler = input.handler || (input.fetch ? function _fetchHandler(event) {
return input.fetch(event.req);
} : NoHandler);
return Object.assign(handlerWithFetch(input.middleware?.length ? function _handlerMiddleware(event) {
return callMiddleware(event, input.middleware, handler);
} : handler), input);
}
function handlerWithFetch(handler) {
if ("fetch" in handler) return handler;
return Object.assign(handler, { fetch: (req) => {
if (typeof req === "string") req = new URL(req, "http://_");
if (req instanceof URL) req = new Request(req);
const event = new H3Event(req);
try {
return Promise.resolve(toResponse(handler(event), event));
} catch (error) {
return Promise.resolve(toResponse(error, event));
}
} });
}
function defineLazyEventHandler(loader) {
let handler;
let promise;
const resolveLazyHandler = () => {
if (handler) return Promise.resolve(handler);
return promise ??= Promise.resolve(loader()).then((r) => {
handler = toEventHandler(r) || toEventHandler(r.default);
if (typeof handler !== "function") throw new TypeError("Invalid lazy handler", { cause: { resolved: r } });
return handler;
});
};
return defineHandler(function lazyHandler(event) {
return handler ? handler(event) : resolveLazyHandler().then((r) => r(event));
});
}
function toEventHandler(handler) {
if (typeof handler === "function") return handler;
if (typeof handler?.handler === "function") return handler.handler;
if (typeof handler?.fetch === "function") return function _fetchHandler(event) {
return handler.fetch(event.req);
};
}
const NoHandler = () => kNotFound;
var H3Core = class {
config;
"~middleware";
"~routes" = [];
constructor(config = {}) {
this["~middleware"] = [];
this.config = config;
this.fetch = this.fetch.bind(this);
this.handler = this.handler.bind(this);
}
fetch(request) {
return this["~request"](request);
}
handler(event) {
const route = this["~findRoute"](event);
if (route) {
event.context.params = route.params;
event.context.matchedRoute = route.data;
}
const routeHandler = route?.data.handler || NoHandler;
const middleware = this["~getMiddleware"](event, route);
return middleware.length > 0 ? callMiddleware(event, middleware, routeHandler) : routeHandler(event);
}
"~request"(request, context) {
const event = new H3Event(request, context, this);
let handlerRes;
try {
if (this.config.onRequest) {
const hookRes = this.config.onRequest(event);
handlerRes = typeof hookRes?.then === "function" ? hookRes.then(() => this.handler(event)) : this.handler(event);
} else handlerRes = this.handler(event);
} catch (error) {
handlerRes = Promise.reject(error);
}
return toResponse(handlerRes, event, this.config);
}
"~findRoute"(_event) {}
"~addRoute"(_route) {
this["~routes"].push(_route);
}
"~getMiddleware"(_event, route) {
const routeMiddleware = route?.data.middleware;
const globalMiddleware = this["~middleware"];
return routeMiddleware ? [...globalMiddleware, ...routeMiddleware] : globalMiddleware;
}
};
const H3 = /* @__PURE__ */ (() => {
class H3$1 extends H3Core {
"~rou3";
constructor(config = {}) {
super(config);
this["~rou3"] = createRouter();
this.request = this.request.bind(this);
config.plugins?.forEach((plugin) => plugin(this));
}
register(plugin) {
plugin(this);
return this;
}
request(_req, _init, context) {
return this["~request"](toRequest(_req, _init), context);
}
mount(base, input) {
if ("handler" in input) {
if (input["~middleware"].length > 0) this["~middleware"].push((event, next) => {
const originalPathname = event.url.pathname;
if (!originalPathname.startsWith(base)) return next();
event.url.pathname = event.url.pathname.slice(base.length) || "/";
return callMiddleware(event, input["~middleware"], () => {
event.url.pathname = originalPathname;
return next();
});
});
for (const r of input["~routes"]) this["~addRoute"]({
...r,
route: base + r.route
});
} else {
const fetchHandler = "fetch" in input ? input.fetch : input;
this.all(`${base}/**`, function _mountedMiddleware(event) {
const url = new URL(event.url);
url.pathname = url.pathname.slice(base.length) || "/";
return fetchHandler(new Request(url, event.req));
});
}
return this;
}
on(method, route, handler, opts) {
const _method = (method || "").toUpperCase();
route = new URL(route, "http://_").pathname;
this["~addRoute"]({
method: _method,
route,
handler: toEventHandler(handler),
middleware: opts?.middleware,
meta: {
...handler.meta,
...opts?.meta
}
});
return this;
}
all(route, handler, opts) {
return this.on("", route, handler, opts);
}
"~findRoute"(_event) {
return findRoute(this["~rou3"], _event.req.method, _event.url.pathname);
}
"~addRoute"(_route) {
addRoute(this["~rou3"], _route.method, _route.route, _route);
super["~addRoute"](_route);
}
use(arg1, arg2, arg3) {
let route;
let fn;
let opts;
if (typeof arg1 === "string") {
route = arg1;
fn = arg2;
opts = arg3;
} else {
fn = arg1;
opts = arg2;
}
this["~middleware"].push(normalizeMiddleware(fn, {
...opts,
route
}));
return this;
}
}
for (const method of [
"GET",
"POST",
"PUT",
"DELETE",
"PATCH",
"HEAD",
"OPTIONS",
"CONNECT",
"TRACE"
]) H3Core.prototype[method.toLowerCase()] = function(route, handler, opts) {
return this.on(method, route, handler, opts);
};
return H3$1;
})();
const lazyEventHandler = defineLazyEventHandler;
//#endregion
//#region ../nuxi/src/commands/analyze.ts
const indexHtml = `
<!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>
`.trim();
var analyze_default = defineCommand({
meta: {
name: "analyze",
description: "Build nuxt and analyze production bundle (experimental)"
},
args: {
...cwdArgs,
...logLevelArgs,
...legacyRootDirArgs,
...dotEnvArgs,
...extendsArgs,
name: {
type: "string",
description: "Name of the analysis",
default: "default",
valueHint: "name"
},
serve: {
type: "boolean",
description: "Serve the analysis results",
negativeDescription: "Skip serving the analysis results",
default: true
}
},
async run(ctx) {
overrideEnv("production");
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const name = ctx.args.name || "default";
const slug = name.trim().replace(/[^\w-]/g, "_");
intro(colors.cyan("Analyzing bundle size..."));
const startTime = Date.now();
const { loadNuxt, buildNuxt } = await loadKit(cwd);
const nuxt = await loadNuxt({
cwd,
dotenv: {
cwd,
fileName: ctx.args.dotenv
},
overrides: defu$1(ctx.data?.overrides, {
...ctx.args.extends && { extends: ctx.args.extends },
build: { analyze: { enabled: true } },
vite: { build: { rollupOptions: { output: {
chunkFileNames: "_nuxt/[name].js",
entryFileNames: "_nuxt/[name].js"
} } } },
logLevel: ctx.args.logLevel
})
});
const analyzeDir = nuxt.options.analyzeDir;
const buildDir = nuxt.options.buildDir;
const outDir = nuxt.options.nitro.output?.dir || join(nuxt.options.rootDir, ".output");
nuxt.options.build.analyze = defu$1(nuxt.options.build.analyze, { filename: join(analyzeDir, "client.html") });
const tasklog = taskLog({
title: "Building Nuxt with analysis enabled",
retainLog: false,
limit: 1
});
tasklog.message("Clearing analyze directory...");
await clearDir(analyzeDir);
tasklog.message("Building Nuxt...");
await buildNuxt(nuxt);
tasklog.success("Build complete");
const meta = {
name,
slug,
startTime,
endTime: Date.now(),
analyzeDir,
buildDir,
outDir
};
await nuxt.callHook("build:analyze:done", meta);
await promises.writeFile(join(analyzeDir, "meta.json"), JSON.stringify(meta, null, 2), "utf-8");
note(`${relativeToProcess(analyzeDir)}\n\nDo not deploy analyze results! Use ${colors.cyan("nuxt build")} before deploying.`, "Build location");
if (ctx.args.serve !== false && !process.env.CI) {
const app = new H3();
const opts = { headers: { "content-type": "text/html" } };
const serveFile = (filePath) => lazyEventHandler(async () => {
const contents = await promises.readFile(filePath, "utf-8");
return () => new Response(contents, opts);
});
logger.step("Starting stats server...");
app.use("/client", serveFile(join(analyzeDir, "client.html")));
app.use("/nitro", serveFile(join(analyzeDir, "nitro.html")));
app.use(() => new Response(indexHtml, opts));
await serve(app).serve();
} else outro("✨ Analysis build complete!");
}
});
//#endregion
export { analyze_default as default };

View file

@ -0,0 +1,42 @@
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { n as getPkgJSON, r as getPkgVersion } from "./versions-Bly87QYZ.mjs";
import { colors } from "consola/utils";
//#region ../nuxi/src/utils/banner.ts
function getBuilder(cwd, builder) {
switch (builder) {
case "rspack":
case "@nuxt/rspack-builder": return {
name: "Rspack",
version: getPkgVersion(cwd, "@rspack/core")
};
case "webpack":
case "@nuxt/webpack-builder": return {
name: "Webpack",
version: getPkgVersion(cwd, "webpack")
};
case "vite":
case "@nuxt/vite-builder":
default: {
const pkgJSON = getPkgJSON(cwd, "vite");
return {
name: pkgJSON.name.includes("rolldown") ? "Rolldown-Vite" : "Vite",
version: pkgJSON.version
};
}
}
}
function showVersionsFromConfig(cwd, config) {
const { bold, gray, green } = colors;
const nuxtVersion = getPkgVersion(cwd, "nuxt") || getPkgVersion(cwd, "nuxt-nightly") || getPkgVersion(cwd, "nuxt3") || getPkgVersion(cwd, "nuxt-edge");
const nitroVersion = getPkgVersion(cwd, "nitropack") || getPkgVersion(cwd, "nitro") || getPkgVersion(cwd, "nitropack-nightly") || getPkgVersion(cwd, "nitropack-edge");
const builder = getBuilder(cwd, config.builder);
const vueVersion = getPkgVersion(cwd, "vue") || null;
logger.info(green(`Nuxt ${bold(nuxtVersion)}`) + gray(" (with ") + (nitroVersion ? gray(`Nitro ${bold(nitroVersion)}`) : "") + gray(`, ${builder.name} ${bold(builder.version)}`) + (vueVersion ? gray(` and Vue ${bold(vueVersion)}`) : "") + gray(")"));
}
async function showVersions(cwd, kit) {
return showVersionsFromConfig(cwd, await kit.loadNuxtConfig({ cwd }));
}
//#endregion
export { showVersions as n, showVersionsFromConfig as r, getBuilder as t };

View file

@ -0,0 +1,85 @@
import { a as legacyRootDirArgs, i as extendsArgs, n as dotEnvArgs, o as logLevelArgs, r as envNameArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { t as overrideEnv } from "./env-DV8TWRZt.mjs";
import { t as loadKit } from "./kit-B3S8uoS_.mjs";
import "./versions-Bly87QYZ.mjs";
import { n as showVersions } from "./banner-DMgRAl0q.mjs";
import { t as clearBuildDir } from "./fs-CQH7NJn6.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { colors } from "consola/utils";
import { intro, outro } from "@clack/prompts";
import { relative, resolve } from "pathe";
//#region ../nuxi/src/commands/build.ts
var build_default = defineCommand({
meta: {
name: "build",
description: "Build Nuxt for production deployment"
},
args: {
...cwdArgs,
...logLevelArgs,
prerender: {
type: "boolean",
description: "Build Nuxt and prerender static routes"
},
preset: {
type: "string",
description: "Nitro server preset"
},
...dotEnvArgs,
...envNameArgs,
...extendsArgs,
...legacyRootDirArgs
},
async run(ctx) {
overrideEnv("production");
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
intro(colors.cyan("Building Nuxt for production..."));
const kit = await loadKit(cwd);
await showVersions(cwd, kit);
const nuxt = await kit.loadNuxt({
cwd,
dotenv: {
cwd,
fileName: ctx.args.dotenv
},
envName: ctx.args.envName,
overrides: {
logLevel: ctx.args.logLevel,
_generate: ctx.args.prerender,
nitro: {
static: ctx.args.prerender,
preset: ctx.args.preset || process.env.NITRO_PRESET || process.env.SERVER_PRESET
},
...ctx.args.extends && { extends: ctx.args.extends },
...ctx.data?.overrides
}
});
let nitro;
try {
nitro = kit.useNitro?.();
if (nitro) logger.info(`Nitro preset: ${colors.cyan(nitro.options.preset)}`);
} catch {}
await clearBuildDir(nuxt.options.buildDir);
await kit.writeTypes(nuxt);
nuxt.hook("build:error", (err) => {
logger.error(`Nuxt build error: ${err}`);
process.exit(1);
});
await kit.buildNuxt(nuxt);
if (ctx.args.prerender) {
if (!nuxt.options.ssr) {
logger.warn(`HTML content not prerendered because ${colors.cyan("ssr: false")} was set.`);
logger.info(`You can read more in ${colors.cyan("https://nuxt.com/docs/getting-started/deployment#static-hosting")}.`);
}
const dir = nitro?.options.output.publicDir;
const publicDir = dir ? relative(process.cwd(), dir) : ".output/public";
outro(`✨ You can now deploy ${colors.cyan(publicDir)} to any static hosting!`);
} else outro("✨ Build complete!");
}
});
//#endregion
export { build_default as default };

View file

@ -0,0 +1,32 @@
import { a as legacyRootDirArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { t as loadKit } from "./kit-B3S8uoS_.mjs";
import "./fs-CQH7NJn6.mjs";
import { t as cleanupNuxtDirs } from "./nuxt-B1NSR4xh.mjs";
import { defineCommand } from "citty";
import { resolve } from "pathe";
//#region ../nuxi/src/commands/cleanup.ts
var cleanup_default = defineCommand({
meta: {
name: "cleanup",
description: "Clean up generated Nuxt files and caches"
},
args: {
...cwdArgs,
...legacyRootDirArgs
},
async run(ctx) {
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const { loadNuxtConfig } = await loadKit(cwd);
const nuxtOptions = await loadNuxtConfig({
cwd,
overrides: { dev: true }
});
await cleanupNuxtDirs(nuxtOptions.rootDir, nuxtOptions.buildDir);
logger.success("Cleanup complete!");
}
});
//#endregion
export { cleanup_default as default };

View file

@ -0,0 +1,713 @@
import { t as overrideEnv } from "./env-DV8TWRZt.mjs";
import { i as withNodePath, t as loadKit } from "./kit-B3S8uoS_.mjs";
import { r as showVersionsFromConfig } from "./banner-DMgRAl0q.mjs";
import { t as clearBuildDir } from "./fs-CQH7NJn6.mjs";
import { a as writeNuxtManifest, i as resolveNuxtManifest, n as loadNuxtManifest } from "./nuxt-B1NSR4xh.mjs";
import process from "node:process";
import { provider } from "std-env";
import { pathToFileURL } from "node:url";
import defu, { defu as defu$1 } from "defu";
import EventEmitter from "node:events";
import { existsSync, readdirSync, statSync, watch } from "node:fs";
import { mkdir } from "node:fs/promises";
import { resolveModulePath } from "exsolve";
import { joinURL } from "ufo";
import { listen } from "listhen";
import { join, resolve } from "pathe";
import { debounce } from "perfect-debounce";
import { toNodeHandler } from "srvx/node";
import { Youch } from "youch";
//#region ../../node_modules/.pnpm/h3@1.15.4/node_modules/h3/dist/index.mjs
function hasProp(obj, prop) {
try {
return prop in obj;
} catch {
return false;
}
}
var H3Error = class extends Error {
static __h3_error__ = true;
statusCode = 500;
fatal = false;
unhandled = false;
statusMessage;
data;
cause;
constructor(message, opts = {}) {
super(message, opts);
if (opts.cause && !this.cause) this.cause = opts.cause;
}
toJSON() {
const obj = {
message: this.message,
statusCode: sanitizeStatusCode(this.statusCode, 500)
};
if (this.statusMessage) obj.statusMessage = sanitizeStatusMessage(this.statusMessage);
if (this.data !== void 0) obj.data = this.data;
return obj;
}
};
function createError(input) {
if (typeof input === "string") return new H3Error(input);
if (isError(input)) return input;
const err = new H3Error(input.message ?? input.statusMessage ?? "", { cause: input.cause || input });
if (hasProp(input, "stack")) try {
Object.defineProperty(err, "stack", { get() {
return input.stack;
} });
} catch {
try {
err.stack = input.stack;
} catch {}
}
if (input.data) err.data = input.data;
if (input.statusCode) err.statusCode = sanitizeStatusCode(input.statusCode, err.statusCode);
else if (input.status) err.statusCode = sanitizeStatusCode(input.status, err.statusCode);
if (input.statusMessage) err.statusMessage = input.statusMessage;
else if (input.statusText) err.statusMessage = input.statusText;
if (err.statusMessage) {
const originalMessage = err.statusMessage;
if (sanitizeStatusMessage(err.statusMessage) !== originalMessage) console.warn("[h3] Please prefer using `message` for longer error messages instead of `statusMessage`. In the future, `statusMessage` will be sanitized by default.");
}
if (input.fatal !== void 0) err.fatal = input.fatal;
if (input.unhandled !== void 0) err.unhandled = input.unhandled;
return err;
}
function sendError(event, error, debug) {
if (event.handled) return;
const h3Error = isError(error) ? error : createError(error);
const responseBody = {
statusCode: h3Error.statusCode,
statusMessage: h3Error.statusMessage,
stack: [],
data: h3Error.data
};
if (debug) responseBody.stack = (h3Error.stack || "").split("\n").map((l) => l.trim());
if (event.handled) return;
setResponseStatus(event, Number.parseInt(h3Error.statusCode), h3Error.statusMessage);
event.node.res.setHeader("content-type", MIMES.json);
event.node.res.end(JSON.stringify(responseBody, void 0, 2));
}
function isError(input) {
return input?.constructor?.__h3_error__ === true;
}
const RawBodySymbol = Symbol.for("h3RawBody");
const ParsedBodySymbol = Symbol.for("h3ParsedBody");
const MIMES = {
html: "text/html",
json: "application/json"
};
const DISALLOWED_STATUS_CHARS = /[^\u0009\u0020-\u007E]/g;
function sanitizeStatusMessage(statusMessage = "") {
return statusMessage.replace(DISALLOWED_STATUS_CHARS, "");
}
function sanitizeStatusCode(statusCode, defaultStatusCode = 200) {
if (!statusCode) return defaultStatusCode;
if (typeof statusCode === "string") statusCode = Number.parseInt(statusCode, 10);
if (statusCode < 100 || statusCode > 999) return defaultStatusCode;
return statusCode;
}
function splitCookiesString(cookiesString) {
if (Array.isArray(cookiesString)) return cookiesString.flatMap((c) => splitCookiesString(c));
if (typeof cookiesString !== "string") return [];
const cookiesStrings = [];
let pos = 0;
let start$1;
let ch;
let lastComma;
let nextStart;
let cookiesSeparatorFound;
const skipWhitespace = () => {
while (pos < cookiesString.length && /\s/.test(cookiesString.charAt(pos))) pos += 1;
return pos < cookiesString.length;
};
const notSpecialChar = () => {
ch = cookiesString.charAt(pos);
return ch !== "=" && ch !== ";" && ch !== ",";
};
while (pos < cookiesString.length) {
start$1 = pos;
cookiesSeparatorFound = false;
while (skipWhitespace()) {
ch = cookiesString.charAt(pos);
if (ch === ",") {
lastComma = pos;
pos += 1;
skipWhitespace();
nextStart = pos;
while (pos < cookiesString.length && notSpecialChar()) pos += 1;
if (pos < cookiesString.length && cookiesString.charAt(pos) === "=") {
cookiesSeparatorFound = true;
pos = nextStart;
cookiesStrings.push(cookiesString.slice(start$1, lastComma));
start$1 = pos;
} else pos = lastComma + 1;
} else pos += 1;
}
if (!cookiesSeparatorFound || pos >= cookiesString.length) cookiesStrings.push(cookiesString.slice(start$1));
}
return cookiesStrings;
}
function setResponseStatus(event, code, text) {
if (code) event.node.res.statusCode = sanitizeStatusCode(code, event.node.res.statusCode);
if (text) event.node.res.statusMessage = sanitizeStatusMessage(text);
}
function sendStream(event, stream) {
if (!stream || typeof stream !== "object") throw new Error("[h3] Invalid stream provided.");
event.node.res._data = stream;
if (!event.node.res.socket) {
event._handled = true;
return Promise.resolve();
}
if (hasProp(stream, "pipeTo") && typeof stream.pipeTo === "function") return stream.pipeTo(new WritableStream({ write(chunk) {
event.node.res.write(chunk);
} })).then(() => {
event.node.res.end();
});
if (hasProp(stream, "pipe") && typeof stream.pipe === "function") return new Promise((resolve$1, reject) => {
stream.pipe(event.node.res);
if (stream.on) {
stream.on("end", () => {
event.node.res.end();
resolve$1();
});
stream.on("error", (error) => {
reject(error);
});
}
event.node.res.on("close", () => {
if (stream.abort) stream.abort();
});
});
throw new Error("[h3] Invalid or incompatible stream provided.");
}
function sendWebResponse(event, response) {
for (const [key, value] of response.headers) if (key === "set-cookie") event.node.res.appendHeader(key, splitCookiesString(value));
else event.node.res.setHeader(key, value);
if (response.status) event.node.res.statusCode = sanitizeStatusCode(response.status, event.node.res.statusCode);
if (response.statusText) event.node.res.statusMessage = sanitizeStatusMessage(response.statusText);
if (response.redirected) event.node.res.setHeader("location", response.url);
if (!response.body) {
event.node.res.end();
return;
}
return sendStream(event, response.body);
}
var H3Event = class {
"__is_event__" = true;
node;
web;
context = {};
_method;
_path;
_headers;
_requestBody;
_handled = false;
_onBeforeResponseCalled;
_onAfterResponseCalled;
constructor(req, res) {
this.node = {
req,
res
};
}
get method() {
if (!this._method) this._method = (this.node.req.method || "GET").toUpperCase();
return this._method;
}
get path() {
return this._path || this.node.req.url || "/";
}
get headers() {
if (!this._headers) this._headers = _normalizeNodeHeaders(this.node.req.headers);
return this._headers;
}
get handled() {
return this._handled || this.node.res.writableEnded || this.node.res.headersSent;
}
respondWith(response) {
return Promise.resolve(response).then((_response) => sendWebResponse(this, _response));
}
toString() {
return `[${this.method}] ${this.path}`;
}
toJSON() {
return this.toString();
}
/** @deprecated Please use `event.node.req` instead. */
get req() {
return this.node.req;
}
/** @deprecated Please use `event.node.res` instead. */
get res() {
return this.node.res;
}
};
function createEvent(req, res) {
return new H3Event(req, res);
}
function _normalizeNodeHeaders(nodeHeaders) {
const headers = new Headers();
for (const [name, value] of Object.entries(nodeHeaders)) if (Array.isArray(value)) for (const item of value) headers.append(name, item);
else if (value) headers.set(name, value);
return headers;
}
const H3Headers = globalThis.Headers;
const H3Response = globalThis.Response;
function toNodeListener(app) {
const toNodeHandle = async function(req, res) {
const event = createEvent(req, res);
try {
await app.handler(event);
} catch (_error) {
const error = createError(_error);
if (!isError(_error)) error.unhandled = true;
setResponseStatus(event, error.statusCode, error.statusMessage);
if (app.options.onError) await app.options.onError(error, event);
if (event.handled) return;
if (error.unhandled || error.fatal) console.error("[h3]", error.fatal ? "[fatal]" : "[unhandled]", error);
if (app.options.onBeforeResponse && !event._onBeforeResponseCalled) await app.options.onBeforeResponse(event, { body: error });
await sendError(event, error, !!app.options.debug);
if (app.options.onAfterResponse && !event._onAfterResponseCalled) await app.options.onAfterResponse(event, { body: error });
}
};
return toNodeHandle;
}
//#endregion
//#region ../nuxi/src/dev/error.ts
async function renderError(req, res, error) {
if (res.headersSent) {
if (!res.writableEnded) res.end();
return;
}
const youch = new Youch();
res.statusCode = 500;
res.setHeader("Content-Type", "text/html");
res.setHeader("Cache-Control", "no-store");
res.setHeader("Refresh", "3");
const html = await youch.toHTML(error, { request: {
url: req.url,
method: req.method,
headers: req.headers
} });
res.end(html);
}
//#endregion
//#region ../nuxi/src/dev/utils.ts
const RESTART_RE = /^(?:nuxt\.config\.[a-z0-9]+|\.nuxtignore|\.nuxtrc|\.config\/nuxt(?:\.config)?\.[a-z0-9]+)$/;
var FileChangeTracker = class {
mtimes = /* @__PURE__ */ new Map();
shouldEmitChange(filePath) {
const resolved = resolve(filePath);
try {
const currentMtime = statSync(resolved).mtimeMs;
const lastMtime = this.mtimes.get(resolved);
this.mtimes.set(resolved, currentMtime);
return lastMtime === void 0 || currentMtime !== lastMtime;
} catch {
this.mtimes.delete(resolved);
return true;
}
}
prime(filePath, recursive = false) {
const resolved = resolve(filePath);
const stat = statSync(resolved);
this.mtimes.set(resolved, stat.mtimeMs);
if (stat.isDirectory()) {
const entries = readdirSync(resolved);
for (const entry of entries) {
const fullPath = resolve(resolved, entry);
try {
const stats = statSync(fullPath);
this.mtimes.set(fullPath, stats.mtimeMs);
if (recursive && stats.isDirectory()) this.prime(fullPath, recursive);
} catch {}
}
}
}
};
var NuxtDevServer = class extends EventEmitter {
#handler;
#distWatcher;
#configWatcher;
#currentNuxt;
#loadingMessage;
#loadingError;
#fileChangeTracker = new FileChangeTracker();
#cwd;
#websocketConnections = /* @__PURE__ */ new Set();
loadDebounced;
handler;
listener;
constructor(options) {
super();
this.options = options;
this.loadDebounced = debounce(this.load);
let _initResolve;
const _initPromise = new Promise((resolve$1) => {
_initResolve = resolve$1;
});
this.once("ready", () => {
_initResolve();
});
this.#cwd = options.cwd;
this.handler = async (req, res) => {
if (this.#loadingError) {
renderError(req, res, this.#loadingError);
return;
}
await _initPromise;
if (this.#handler) this.#handler(req, res);
else this.#renderLoadingScreen(req, res);
};
}
async #renderLoadingScreen(req, res) {
if (res.headersSent) {
if (!res.writableEnded) res.end();
return;
}
res.statusCode = 503;
res.setHeader("Content-Type", "text/html");
const loadingTemplate = this.options.loadingTemplate || this.#currentNuxt?.options.devServer.loadingTemplate || await resolveLoadingTemplate(this.#cwd);
res.end(loadingTemplate({ loading: this.#loadingMessage || "Loading..." }));
}
async init() {
this.#loadingMessage = `Starting Nuxt...`;
this.#handler = void 0;
this.emit("loading", this.#loadingMessage);
await this.#loadNuxtInstance();
if (this.options.showBanner) showVersionsFromConfig(this.options.cwd, this.#currentNuxt.options);
await this.#createListener();
await this.#initializeNuxt(false);
this.#watchConfig();
}
closeWatchers() {
this.#distWatcher?.close();
this.#configWatcher?.();
}
async load(reload, reason) {
try {
this.closeWatchers();
await this.#load(reload, reason);
this.#loadingError = void 0;
} catch (error) {
console.error(`Cannot ${reload ? "restart" : "start"} nuxt: `, error);
this.#handler = void 0;
this.#loadingError = error;
this.#loadingMessage = "Error while loading Nuxt. Please check console and fix errors.";
this.emit("loading:error", error);
}
this.#watchConfig();
}
async #loadNuxtInstance(urls) {
const kit = await loadKit(this.options.cwd);
const loadOptions = {
cwd: this.options.cwd,
dev: true,
ready: false,
envName: this.options.envName,
dotenv: {
cwd: this.options.cwd,
fileName: this.options.dotenv.fileName
},
overrides: {
logLevel: this.options.logLevel,
...this.options.overrides,
vite: {
clearScreen: this.options.clear,
...this.options.overrides.vite
}
}
};
if (urls) {
const overrides = this.options.listenOverrides || {};
const hostname = overrides.hostname;
const https = overrides.https;
loadOptions.defaults = resolveDevServerDefaults({
hostname,
https
}, urls);
}
this.#currentNuxt = await kit.loadNuxt(loadOptions);
}
async #createListener() {
if (!this.#currentNuxt) throw new Error("Nuxt must be loaded before creating listener");
const listenOptions = this.#resolveListenOptions();
this.listener = await listen(this.handler, listenOptions);
if (listenOptions.public) {
this.#currentNuxt.options.devServer.cors = { origin: "*" };
if (this.#currentNuxt.options.vite?.server) this.#currentNuxt.options.vite.server.allowedHosts = true;
return;
}
const urls = await this.listener.getURLs().then((r) => r.map((r$1) => r$1.url));
if (urls && urls.length > 0) this.#currentNuxt.options.vite = defu(this.#currentNuxt.options.vite, { server: { allowedHosts: urls.map((u) => new URL(u).hostname) } });
}
#resolveListenOptions() {
if (!this.#currentNuxt) throw new Error("Nuxt must be loaded before resolving listen options");
const nuxtConfig = this.#currentNuxt.options;
const overrides = this.options.listenOverrides || {};
const port = overrides.port ?? nuxtConfig.devServer?.port;
const hostname = overrides.hostname ?? nuxtConfig.devServer?.host;
const isPublic = provider === "codesandbox" || (overrides.public ?? (isPublicHostname(hostname) ? true : void 0));
const httpsFromConfig = typeof nuxtConfig.devServer?.https !== "boolean" && nuxtConfig.devServer?.https ? nuxtConfig.devServer.https : {};
overrides._https ??= !!nuxtConfig.devServer?.https;
const httpsOptions = overrides.https && defu(typeof overrides.https === "object" ? overrides.https : {}, httpsFromConfig);
const baseURL = nuxtConfig.app?.baseURL?.startsWith?.("./") ? nuxtConfig.app.baseURL.slice(1) : nuxtConfig.app?.baseURL;
return {
...overrides,
port,
hostname,
public: isPublic,
https: httpsOptions || void 0,
baseURL
};
}
async #initializeNuxt(reload) {
if (!this.#currentNuxt) throw new Error("Nuxt must be loaded before configuration");
if (!process.env.NUXI_DISABLE_VITE_HMR) this.#currentNuxt.hooks.hook("vite:extend", ({ config }) => {
if (config.server) config.server.hmr = {
protocol: void 0,
...config.server.hmr,
port: void 0,
host: void 0,
server: this.listener.server
};
});
this.#currentNuxt.hooks.hookOnce("close", () => {
this.#closeWebSocketConnections();
this.listener.server.removeAllListeners("upgrade");
});
if (!reload) {
const previousManifest = await loadNuxtManifest(this.#currentNuxt.options.buildDir);
const newManifest = resolveNuxtManifest(this.#currentNuxt);
const promise = writeNuxtManifest(this.#currentNuxt, newManifest);
this.#currentNuxt.hooks.hookOnce("ready", async () => {
await promise;
});
if (previousManifest && newManifest && previousManifest._hash !== newManifest._hash) await clearBuildDir(this.#currentNuxt.options.buildDir);
}
await this.#currentNuxt.ready();
const unsub = this.#currentNuxt.hooks.hook("restart", async (options) => {
unsub();
if (options?.hard) {
this.emit("restart");
return;
}
await this.load(true);
});
if (this.#currentNuxt.server && "upgrade" in this.#currentNuxt.server) this.listener.server.on("upgrade", (req, socket, head) => {
const nuxt = this.#currentNuxt;
if (!nuxt || !nuxt.server) return;
const viteHmrPath = joinURL(nuxt.options.app.baseURL.startsWith("./") ? nuxt.options.app.baseURL.slice(1) : nuxt.options.app.baseURL, nuxt.options.app.buildAssetsDir);
if (req.url?.startsWith(viteHmrPath)) return;
nuxt.server.upgrade(req, socket, head);
this.#websocketConnections.add(socket);
socket.on("close", () => {
this.#websocketConnections.delete(socket);
});
});
await this.#currentNuxt.hooks.callHook("listen", this.listener.server, this.listener);
const addr = this.listener.address;
this.#currentNuxt.options.devServer.host = addr.address;
this.#currentNuxt.options.devServer.port = addr.port;
this.#currentNuxt.options.devServer.url = getAddressURL(addr, !!this.listener.https);
this.#currentNuxt.options.devServer.https = this.listener.https;
if (this.listener.https && !process.env.NODE_TLS_REJECT_UNAUTHORIZED) console.warn("You might need `NODE_TLS_REJECT_UNAUTHORIZED=0` environment variable to make https work.");
const kit = await loadKit(this.options.cwd);
const typesPromise = existsSync(join(this.#currentNuxt.options.buildDir, "tsconfig.json")) ? kit.writeTypes(this.#currentNuxt).catch(console.error) : await kit.writeTypes(this.#currentNuxt).catch(console.error);
await Promise.all([typesPromise, kit.buildNuxt(this.#currentNuxt)]);
if (!this.#currentNuxt.server) throw new Error("Nitro server has not been initialized.");
const distDir = join(this.#currentNuxt.options.buildDir, "dist");
await mkdir(distDir, { recursive: true });
this.#fileChangeTracker.prime(distDir);
this.#distWatcher = watch(distDir);
this.#distWatcher.on("change", (_event, file) => {
if (!this.#fileChangeTracker.shouldEmitChange(resolve(distDir, file || ""))) return;
this.loadDebounced(true, ".nuxt/dist directory has been removed");
});
if ("fetch" in this.#currentNuxt.server) this.#handler = toNodeHandler(this.#currentNuxt.server.fetch);
else this.#handler = toNodeListener(this.#currentNuxt.server.app);
const proto = this.listener.https ? "https" : "http";
this.emit("ready", `${proto}://127.0.0.1:${addr.port}`);
}
async close() {
if (this.#currentNuxt) await this.#currentNuxt.close();
}
#closeWebSocketConnections() {
for (const socket of this.#websocketConnections) socket.destroy();
this.#websocketConnections.clear();
}
async #load(reload, reason) {
const action = reload ? "Restarting" : "Starting";
this.#loadingMessage = `${reason ? `${reason}. ` : ""}${action} Nuxt...`;
this.#handler = void 0;
this.emit("loading", this.#loadingMessage);
if (reload) console.info(this.#loadingMessage);
await this.close();
const urls = await this.listener.getURLs().then((r) => r.map((r$1) => r$1.url));
await this.#loadNuxtInstance(urls);
await this.#initializeNuxt(!!reload);
}
#watchConfig() {
this.#configWatcher = createConfigWatcher(this.#cwd, this.options.dotenv.fileName, () => this.emit("restart"), (file) => this.loadDebounced(true, `${file} updated`));
}
};
function getAddressURL(addr, https) {
const proto = https ? "https" : "http";
let host = addr.address.includes(":") ? `[${addr.address}]` : addr.address;
if (host === "[::]") host = "localhost";
const port = addr.port || 3e3;
return `${proto}://${host}:${port}/`;
}
function resolveDevServerDefaults(listenOptions, urls = []) {
const defaultConfig = {};
if (urls && urls.length > 0) defaultConfig.vite = { server: { allowedHosts: urls.map((u) => new URL(u).hostname) } };
if (listenOptions.hostname) {
defaultConfig.devServer = { cors: { origin: [`${listenOptions.https ? "https" : "http"}://${listenOptions.hostname}`, ...urls] } };
defaultConfig.vite = defu(defaultConfig.vite, { server: { allowedHosts: [listenOptions.hostname] } });
}
return defaultConfig;
}
function createConfigWatcher(cwd, dotenvFileName = ".env", onRestart, onReload) {
const fileWatcher = new FileChangeTracker();
fileWatcher.prime(cwd);
const configWatcher = watch(cwd);
let configDirWatcher = existsSync(join(cwd, ".config")) ? createConfigDirWatcher(cwd, onReload) : void 0;
const dotenvFileNames = new Set(Array.isArray(dotenvFileName) ? dotenvFileName : [dotenvFileName]);
configWatcher.on("change", (_event, file) => {
if (!fileWatcher.shouldEmitChange(resolve(cwd, file))) return;
if (dotenvFileNames.has(file)) onRestart();
if (RESTART_RE.test(file)) onReload(file);
if (file === ".config") configDirWatcher ||= createConfigDirWatcher(cwd, onReload);
});
return () => {
configWatcher.close();
configDirWatcher?.();
};
}
function createConfigDirWatcher(cwd, onReload) {
const configDir = join(cwd, ".config");
const fileWatcher = new FileChangeTracker();
fileWatcher.prime(configDir);
const configDirWatcher = watch(configDir);
configDirWatcher.on("change", (_event, file) => {
if (!fileWatcher.shouldEmitChange(resolve(configDir, file))) return;
if (RESTART_RE.test(file)) onReload(file);
});
return () => configDirWatcher.close();
}
async function resolveLoadingTemplate(cwd) {
return (await import(pathToFileURL(resolveModulePath("@nuxt/ui-templates", { from: withNodePath(resolveModulePath("nuxt", {
from: withNodePath(cwd),
try: true
}) || cwd) })).href)).loading || ((params) => `<h2>${params.loading}</h2>`);
}
function isPublicHostname(hostname) {
return !!hostname && ![
"localhost",
"127.0.0.1",
"::1"
].includes(hostname);
}
//#endregion
//#region ../nuxi/src/dev/index.ts
const start = Date.now();
var IPC = class {
enabled = !!process.send && !process.title?.includes("vitest") && process.env.__NUXT__FORK;
constructor() {
if (this.enabled) process.once("unhandledRejection", (reason) => {
this.send({
type: "nuxt:internal:dev:rejection",
message: reason instanceof Error ? reason.toString() : "Unhandled Rejection"
});
process.exit();
});
process.on("message", (message) => {
if (message.type === "nuxt:internal:dev:context") initialize(message.context, { listenOverrides: message.listenOverrides });
});
this.send({ type: "nuxt:internal:dev:fork-ready" });
}
send(message) {
if (this.enabled) process.send?.(message);
}
};
const ipc = new IPC();
async function initialize(devContext, ctx = {}) {
overrideEnv("development");
const devServer = new NuxtDevServer({
cwd: devContext.cwd,
overrides: defu(ctx.data?.overrides, { extends: devContext.args.extends }),
logLevel: devContext.args.logLevel,
clear: devContext.args.clear,
dotenv: {
cwd: devContext.cwd,
fileName: devContext.args.dotenv
},
envName: devContext.args.envName,
showBanner: ctx.showBanner !== false && !ipc.enabled,
listenOverrides: ctx.listenOverrides
});
let address;
if (ipc.enabled) {
devServer.on("loading:error", (_error) => {
ipc.send({
type: "nuxt:internal:dev:loading:error",
error: {
message: _error.message,
stack: _error.stack,
name: _error.name,
code: "code" in _error ? _error.code : void 0
}
});
});
devServer.on("loading", (message) => {
ipc.send({
type: "nuxt:internal:dev:loading",
message
});
});
devServer.on("restart", () => {
ipc.send({ type: "nuxt:internal:dev:restart" });
});
devServer.on("ready", (payload) => {
ipc.send({
type: "nuxt:internal:dev:ready",
address: payload
});
});
} else devServer.on("ready", (payload) => {
address = payload;
});
await devServer.init();
if (process.env.DEBUG) console.debug(`Dev server (internal) initialized in ${Date.now() - start}ms`);
return {
listener: devServer.listener,
close: async () => {
devServer.closeWatchers();
await Promise.all([devServer.listener.close(), devServer.close()]);
},
onReady: (callback) => {
if (address) callback(address);
else devServer.once("ready", (payload) => callback(payload));
},
onRestart: (callback) => {
let restarted = false;
function restart() {
if (!restarted) {
restarted = true;
callback(devServer);
}
}
devServer.once("restart", restart);
process.once("uncaughtException", restart);
process.once("unhandledRejection", restart);
}
};
}
//#endregion
export { initialize as t };

View file

@ -0,0 +1,282 @@
import { a as legacyRootDirArgs, i as extendsArgs, n as dotEnvArgs, o as logLevelArgs, r as envNameArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger, t as debug } from "./logger-B4ge7MhP.mjs";
import "./env-DV8TWRZt.mjs";
import { t as initialize } from "./dev-BKPehGZf.mjs";
import "./kit-B3S8uoS_.mjs";
import "./versions-Bly87QYZ.mjs";
import "./banner-DMgRAl0q.mjs";
import "./fs-CQH7NJn6.mjs";
import "./nuxt-B1NSR4xh.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { isBun, isDeno, isTest } from "std-env";
import { colors } from "consola/utils";
import { resolve } from "pathe";
import { satisfies } from "semver";
import { getArgs, parseArgs } from "listhen/cli";
import { fork } from "node:child_process";
//#region ../nuxi/src/dev/pool.ts
var ForkPool = class {
pool = [];
poolSize;
rawArgs;
listenOverrides;
warming = false;
constructor(options) {
this.rawArgs = options.rawArgs;
this.poolSize = options.poolSize ?? 2;
this.listenOverrides = options.listenOverrides;
for (const signal of [
"exit",
"SIGTERM",
"SIGINT",
"SIGQUIT"
]) process.once(signal, () => {
this.killAll(signal === "exit" ? 0 : signal);
});
}
startWarming() {
if (this.warming) return;
this.warming = true;
for (let i = 0; i < this.poolSize; i++) this.warmFork();
}
async getFork(context, onMessage) {
const readyFork = this.pool.find((f) => f.state === "ready");
if (readyFork) {
readyFork.state = "active";
if (onMessage) this.attachMessageHandler(readyFork.process, onMessage);
await this.sendContext(readyFork.process, context);
if (this.warming) this.warmFork();
return () => this.killFork(readyFork);
}
const warmingFork = this.pool.find((f) => f.state === "warming");
if (warmingFork) {
await warmingFork.ready;
warmingFork.state = "active";
if (onMessage) this.attachMessageHandler(warmingFork.process, onMessage);
await this.sendContext(warmingFork.process, context);
if (this.warming) this.warmFork();
return () => this.killFork(warmingFork);
}
debug("No pre-warmed forks available, starting cold fork");
const coldFork = this.createFork();
await coldFork.ready;
coldFork.state = "active";
if (onMessage) this.attachMessageHandler(coldFork.process, onMessage);
await this.sendContext(coldFork.process, context);
return () => this.killFork(coldFork);
}
attachMessageHandler(childProc, onMessage) {
childProc.on("message", (message) => {
if (message.type !== "nuxt:internal:dev:fork-ready") onMessage(message);
});
}
warmFork() {
const fork$1 = this.createFork();
fork$1.ready.then(() => {
if (fork$1.state === "warming") fork$1.state = "ready";
}).catch(() => {
this.removeFork(fork$1);
});
this.pool.push(fork$1);
}
createFork() {
const childProc = fork(globalThis.__nuxt_cli__.devEntry, this.rawArgs, {
execArgv: ["--enable-source-maps", process.argv.find((a) => a.includes("--inspect"))].filter(Boolean),
env: {
...process.env,
__NUXT__FORK: "true"
}
});
let readyResolve;
let readyReject;
const pooledFork = {
process: childProc,
ready: new Promise((resolve$1, reject) => {
readyResolve = resolve$1;
readyReject = reject;
}),
state: "warming"
};
childProc.on("message", (message) => {
if (message.type === "nuxt:internal:dev:fork-ready") readyResolve();
});
childProc.on("error", (err) => {
readyReject(err);
this.removeFork(pooledFork);
});
childProc.on("close", (errorCode) => {
if (pooledFork.state === "active" && errorCode) process.exit(errorCode);
this.removeFork(pooledFork);
});
return pooledFork;
}
async sendContext(childProc, context) {
childProc.send({
type: "nuxt:internal:dev:context",
listenOverrides: this.listenOverrides,
context
});
}
killFork(fork$1, signal = "SIGTERM") {
fork$1.state = "dead";
if (fork$1.process) fork$1.process.kill(signal === 0 && isDeno ? "SIGTERM" : signal);
this.removeFork(fork$1);
}
removeFork(fork$1) {
const index = this.pool.indexOf(fork$1);
if (index > -1) this.pool.splice(index, 1);
}
killAll(signal) {
for (const fork$1 of this.pool) this.killFork(fork$1, signal);
}
getStats() {
return {
total: this.pool.length,
warming: this.pool.filter((f) => f.state === "warming").length,
ready: this.pool.filter((f) => f.state === "ready").length,
active: this.pool.filter((f) => f.state === "active").length
};
}
};
//#endregion
//#region ../nuxi/src/commands/dev.ts
const startTime = Date.now();
const forkSupported = !isTest && (!isBun || isBunForkSupported());
const listhenArgs = getArgs();
const command = defineCommand({
meta: {
name: "dev",
description: "Run Nuxt development server"
},
args: {
...cwdArgs,
...logLevelArgs,
...dotEnvArgs,
...legacyRootDirArgs,
...envNameArgs,
...extendsArgs,
clear: {
type: "boolean",
description: "Clear console on restart",
default: false
},
fork: {
type: "boolean",
description: forkSupported ? "Disable forked mode" : "Enable forked mode",
negativeDescription: "Disable forked mode",
default: forkSupported,
alias: ["f"]
},
...listhenArgs,
port: {
...listhenArgs.port,
description: "Port to listen on (default: `NUXT_PORT || NITRO_PORT || PORT || nuxtOptions.devServer.port`)",
alias: ["p"]
},
open: {
...listhenArgs.open,
alias: ["o"],
default: false
},
host: {
...listhenArgs.host,
alias: ["h"],
description: "Host to listen on (default: `NUXT_HOST || NITRO_HOST || HOST || nuxtOptions.devServer?.host`)"
},
clipboard: {
...listhenArgs.clipboard,
default: false
},
sslCert: {
type: "string",
description: "(DEPRECATED) Use `--https.cert` instead."
},
sslKey: {
type: "string",
description: "(DEPRECATED) Use `--https.key` instead."
}
},
async run(ctx) {
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const listenOverrides = resolveListenOverrides(ctx.args);
const { listener, close, onRestart, onReady } = await initialize({
cwd,
args: ctx.args
}, {
data: ctx.data,
listenOverrides,
showBanner: true
});
if (!ctx.args.fork) return {
listener,
close
};
const pool = new ForkPool({
rawArgs: ctx.rawArgs,
poolSize: 2,
listenOverrides
});
onReady((_address) => {
pool.startWarming();
if (startTime) debug(`Dev server ready for connections in ${Date.now() - startTime}ms`);
});
let cleanupCurrentFork;
async function restartWithFork() {
const context = {
cwd,
args: ctx.args
};
cleanupCurrentFork?.();
cleanupCurrentFork = await pool.getFork(context, (message) => {
if (message.type === "nuxt:internal:dev:ready") {
if (startTime) debug(`Dev server ready for connections in ${Date.now() - startTime}ms`);
} else if (message.type === "nuxt:internal:dev:restart") restartWithFork();
else if (message.type === "nuxt:internal:dev:rejection") {
logger.info(`Restarting Nuxt due to error: ${colors.cyan(message.message)}`);
restartWithFork();
}
});
}
onRestart(async () => {
await close();
await restartWithFork();
});
return { async close() {
cleanupCurrentFork?.();
await Promise.all([listener.close(), close()]);
} };
}
});
var dev_default = command;
function resolveListenOverrides(args) {
if (process.env._PORT) return {
port: process.env._PORT || 0,
hostname: "127.0.0.1",
showURL: false
};
const options = parseArgs({
...args,
"host": args.host || process.env.NUXT_HOST || process.env.NITRO_HOST || process.env.HOST,
"port": args.port || process.env.NUXT_PORT || process.env.NITRO_PORT || process.env.PORT,
"https": args.https !== false,
"https.cert": args["https.cert"] || args.sslCert || process.env.NUXT_SSL_CERT || process.env.NITRO_SSL_CERT,
"https.key": args["https.key"] || args.sslKey || process.env.NUXT_SSL_KEY || process.env.NITRO_SSL_KEY
});
return {
...options,
_https: args.https,
get https() {
return this._https ? options.https : false;
}
};
}
function isBunForkSupported() {
const bunVersion = globalThis.Bun.version;
return satisfies(bunVersion, ">=1.2");
}
//#endregion
export { dev_default as default };

View file

@ -0,0 +1,37 @@
import { a as legacyRootDirArgs, n as dotEnvArgs, o as logLevelArgs, r as envNameArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { isTest } from "std-env";
import { resolve } from "pathe";
//#region ../nuxi/src/commands/dev-child.ts
var dev_child_default = defineCommand({
meta: {
name: "_dev",
description: "Run Nuxt development server (internal command to start child process)"
},
args: {
...cwdArgs,
...logLevelArgs,
...envNameArgs,
...dotEnvArgs,
...legacyRootDirArgs,
clear: {
type: "boolean",
description: "Clear console on restart",
negativeDescription: "Disable clear console on restart"
}
},
async run(ctx) {
if (!process.send && !isTest) console.warn("`nuxi _dev` is an internal command and should not be used directly. Please use `nuxi dev` instead.");
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const { initialize } = await import("./dev-fNXtL_VP.mjs");
await initialize({
cwd,
args: ctx.args
}, ctx);
}
});
//#endregion
export { dev_child_default as default };

View file

@ -0,0 +1,10 @@
import "./logger-B4ge7MhP.mjs";
import "./env-DV8TWRZt.mjs";
import { t as initialize } from "./dev-BKPehGZf.mjs";
import "./kit-B3S8uoS_.mjs";
import "./versions-Bly87QYZ.mjs";
import "./banner-DMgRAl0q.mjs";
import "./fs-CQH7NJn6.mjs";
import "./nuxt-B1NSR4xh.mjs";
export { initialize };

View file

@ -0,0 +1,69 @@
import EventEmitter from "node:events";
import { ListenOptions, Listener } from "listhen";
import { DotenvOptions } from "c12";
import { NuxtConfig } from "@nuxt/schema";
import { RequestListener } from "node:http";
//#region ../nuxi/src/dev/utils.d.ts
interface NuxtDevContext {
cwd: string;
args: {
clear: boolean;
logLevel: string;
dotenv: string;
envName: string;
extends?: string;
};
}
interface NuxtDevServerOptions {
cwd: string;
logLevel?: "silent" | "info" | "verbose";
dotenv: DotenvOptions;
envName?: string;
clear?: boolean;
overrides: NuxtConfig;
loadingTemplate?: ({
loading
}: {
loading: string;
}) => string;
showBanner?: boolean;
listenOverrides?: Partial<ListenOptions>;
}
interface DevServerEventMap {
"loading:error": [error: Error];
"loading": [loadingMessage: string];
"ready": [address: string];
"restart": [];
}
declare class NuxtDevServer extends EventEmitter<DevServerEventMap> {
#private;
private options;
loadDebounced: (reload?: boolean, reason?: string) => void;
handler: RequestListener;
listener: Listener;
constructor(options: NuxtDevServerOptions);
init(): Promise<void>;
closeWatchers(): void;
load(reload?: boolean, reason?: string): Promise<void>;
close(): Promise<void>;
}
//#endregion
//#region ../nuxi/src/dev/index.d.ts
interface InitializeOptions {
data?: {
overrides?: NuxtConfig;
};
listenOverrides?: Partial<ListenOptions>;
showBanner?: boolean;
}
interface InitializeReturn {
listener: Listener;
close: () => Promise<void>;
onReady: (callback: (address: string) => void) => void;
onRestart: (callback: (devServer: NuxtDevServer) => void) => void;
}
declare function initialize(devContext: NuxtDevContext, ctx?: InitializeOptions): Promise<InitializeReturn>;
//#endregion
export { initialize };

View file

@ -0,0 +1,10 @@
import "../logger-B4ge7MhP.mjs";
import "../env-DV8TWRZt.mjs";
import { t as initialize } from "../dev-BKPehGZf.mjs";
import "../kit-B3S8uoS_.mjs";
import "../versions-Bly87QYZ.mjs";
import "../banner-DMgRAl0q.mjs";
import "../fs-CQH7NJn6.mjs";
import "../nuxt-B1NSR4xh.mjs";
export { initialize };

View file

@ -0,0 +1,45 @@
import { a as legacyRootDirArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { colors } from "consola/utils";
import { resolve } from "pathe";
import { x } from "tinyexec";
//#region ../nuxi/src/commands/devtools.ts
var devtools_default = defineCommand({
meta: {
name: "devtools",
description: "Enable or disable devtools in a Nuxt project"
},
args: {
...cwdArgs,
command: {
type: "positional",
description: "Command to run",
valueHint: "enable|disable"
},
...legacyRootDirArgs
},
async run(ctx) {
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
if (!["enable", "disable"].includes(ctx.args.command)) {
logger.error(`Unknown command ${colors.cyan(ctx.args.command)}.`);
process.exit(1);
}
await x("npx", [
"@nuxt/devtools-wizard@latest",
ctx.args.command,
cwd
], {
throwOnError: true,
nodeOptions: {
stdio: "inherit",
cwd
}
});
}
});
//#endregion
export { devtools_default as default };

View file

@ -0,0 +1,13 @@
import { n as logger } from "./logger-B4ge7MhP.mjs";
import process from "node:process";
import { colors } from "consola/utils";
//#region ../nuxi/src/utils/env.ts
function overrideEnv(targetEnv) {
const currentEnv = process.env.NODE_ENV;
if (currentEnv && currentEnv !== targetEnv) logger.warn(`Changing ${colors.cyan("NODE_ENV")} from ${colors.cyan(currentEnv)} to ${colors.cyan(targetEnv)}, to avoid unintended behavior.`);
process.env.NODE_ENV = targetEnv;
}
//#endregion
export { overrideEnv as t };

View file

@ -0,0 +1,56 @@
import process from "node:process";
import { colors } from "consola/utils";
import { stripVTControlCharacters } from "node:util";
//#region ../nuxi/src/utils/formatting.ts
function getStringWidth(str) {
const stripped = stripVTControlCharacters(str);
let width = 0;
for (const char of stripped) {
const code = char.codePointAt(0);
if (!code) continue;
if (code >= 65024 && code <= 65039) continue;
if (code >= 127744 && code <= 129535 || code >= 128512 && code <= 128591 || code >= 128640 && code <= 128767 || code >= 9728 && code <= 9983 || code >= 9984 && code <= 10175 || code >= 129280 && code <= 129535 || code >= 129648 && code <= 129791) width += 2;
else width += 1;
}
return width;
}
function formatInfoBox(infoObj) {
let firstColumnLength = 0;
let ansiFirstColumnLength = 0;
const entries = Object.entries(infoObj).map(([label, val]) => {
if (label.length > firstColumnLength) {
ansiFirstColumnLength = colors.bold(colors.whiteBright(label)).length + 6;
firstColumnLength = label.length + 6;
}
return [label, val || "-"];
});
const terminalWidth = Math.max(process.stdout.columns || 80, firstColumnLength) - 8;
let boxStr = "";
for (const [label, value] of entries) {
const formattedValue = value.replace(/\b@([^, ]+)/g, (_, r) => colors.gray(` ${r}`)).replace(/`([^`]*)`/g, (_, r) => r);
boxStr += `${colors.bold(colors.whiteBright(label))}`.padEnd(ansiFirstColumnLength);
let boxRowLength = firstColumnLength;
const words = formattedValue.split(" ");
let currentLine = "";
for (const word of words) {
const wordLength = getStringWidth(word);
const spaceLength = currentLine ? 1 : 0;
if (boxRowLength + wordLength + spaceLength > terminalWidth) {
if (currentLine) boxStr += colors.cyan(currentLine);
boxStr += `\n${" ".repeat(firstColumnLength)}`;
currentLine = word;
boxRowLength = firstColumnLength + wordLength;
} else {
currentLine += (currentLine ? " " : "") + word;
boxRowLength += wordLength + spaceLength;
}
}
if (currentLine) boxStr += colors.cyan(currentLine);
boxStr += "\n";
}
return boxStr;
}
//#endregion
export { formatInfoBox as t };

View file

@ -0,0 +1,40 @@
import { t as debug } from "./logger-B4ge7MhP.mjs";
import { existsSync, promises } from "node:fs";
import { join } from "pathe";
//#region ../nuxi/src/utils/fs.ts
async function clearDir(path, exclude) {
if (!exclude) await promises.rm(path, {
recursive: true,
force: true
});
else if (existsSync(path)) {
const files = await promises.readdir(path);
await Promise.all(files.map(async (name) => {
if (!exclude.includes(name)) await promises.rm(join(path, name), {
recursive: true,
force: true
});
}));
}
await promises.mkdir(path, { recursive: true });
}
function clearBuildDir(path) {
return clearDir(path, [
"cache",
"analyze",
"nuxt.json"
]);
}
async function rmRecursive(paths) {
await Promise.all(paths.filter((p) => typeof p === "string").map(async (path) => {
debug(`Removing recursive path: ${path}`);
await promises.rm(path, {
recursive: true,
force: true
}).catch(() => {});
}));
}
//#endregion
export { clearDir as n, rmRecursive as r, clearBuildDir as t };

View file

@ -0,0 +1,36 @@
import { a as legacyRootDirArgs, i as extendsArgs, n as dotEnvArgs, o as logLevelArgs, r as envNameArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import "./logger-B4ge7MhP.mjs";
import "./env-DV8TWRZt.mjs";
import "./kit-B3S8uoS_.mjs";
import "./versions-Bly87QYZ.mjs";
import "./banner-DMgRAl0q.mjs";
import "./fs-CQH7NJn6.mjs";
import build_default from "./build-1TjVJ-UC.mjs";
import { defineCommand } from "citty";
//#region ../nuxi/src/commands/generate.ts
var generate_default = defineCommand({
meta: {
name: "generate",
description: "Build Nuxt and prerender all routes"
},
args: {
...cwdArgs,
...logLevelArgs,
preset: {
type: "string",
description: "Nitro server preset"
},
...dotEnvArgs,
...envNameArgs,
...extendsArgs,
...legacyRootDirArgs
},
async run(ctx) {
ctx.args.prerender = true;
await build_default.run(ctx);
}
});
//#endregion
export { generate_default as default };

View file

@ -0,0 +1,14 @@
import { CommandDef } from "citty";
//#region src/main.d.ts
declare const main: CommandDef<any>;
//#endregion
//#region src/run.d.ts
declare function runMain(): Promise<void>;
declare function runCommand(name: string, argv?: string[], data?: {
overrides?: Record<string, any>;
}): Promise<{
result: unknown;
}>;
//#endregion
export { main, runCommand, runMain };

252
Frontend-Learner/node_modules/@nuxt/cli/dist/index.mjs generated vendored Normal file
View file

@ -0,0 +1,252 @@
import { t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { t as templates } from "./templates-C0gAD--n.mjs";
import { resolve } from "node:path";
import process from "node:process";
import { defineCommand, runCommand as runCommand$1, runMain as runMain$1 } from "citty";
import { provider } from "std-env";
import { consola } from "consola";
import { colors } from "consola/utils";
import { fileURLToPath } from "node:url";
import tab from "@bomb.sh/tab/citty";
//#region ../nuxi/src/commands/index.ts
const _rDefault = (r) => r.default || r;
const commands = {
add: () => import("./add-Dy11jAJ1.mjs").then(_rDefault),
analyze: () => import("./analyze-BckIrOKp.mjs").then(_rDefault),
build: () => import("./build-1TjVJ-UC.mjs").then(_rDefault),
cleanup: () => import("./cleanup-BhQbCstD.mjs").then(_rDefault),
_dev: () => import("./dev-child-DfGhbYXE.mjs").then(_rDefault),
dev: () => import("./dev-HhMgIfMX.mjs").then(_rDefault),
devtools: () => import("./devtools-ChsGaImC.mjs").then(_rDefault),
generate: () => import("./generate-cGaHTpaK.mjs").then(_rDefault),
info: () => import("./info-B3eKD75o.mjs").then(_rDefault),
init: () => import("./init-jiA9OW7h.mjs").then(_rDefault),
module: () => import("./module-CZNTz7xr.mjs").then(_rDefault),
prepare: () => import("./prepare-DCPPpZ3e.mjs").then(_rDefault),
preview: () => import("./preview-CbUSteIx.mjs").then(_rDefault),
start: () => import("./preview-CbUSteIx.mjs").then(_rDefault),
test: () => import("./test-pxuzy0gI.mjs").then(_rDefault),
typecheck: () => import("./typecheck-DNhVOVc6.mjs").then(_rDefault),
upgrade: () => import("./upgrade-CXj1pphH.mjs").then(_rDefault)
};
//#endregion
//#region ../nuxi/src/utils/console.ts
function wrapReporter(reporter) {
return { log(logObj, ctx) {
if (!logObj.args || !logObj.args.length) return;
const msg = logObj.args[0];
if (typeof msg === "string" && !process.env.DEBUG) {
if (msg.startsWith("[Vue Router warn]: No match found for location with path")) return;
if (msg.includes("ExperimentalWarning: The Fetch API is an experimental feature")) return;
if (msg.startsWith("Sourcemap") && msg.includes("node_modules")) return;
}
return reporter.log(logObj, ctx);
} };
}
function setupGlobalConsole(opts = {}) {
consola.options.reporters = consola.options.reporters.map(wrapReporter);
if (opts.dev) consola.wrapAll();
else consola.wrapConsole();
process.on("unhandledRejection", (err) => consola.error("[unhandledRejection]", err));
process.on("uncaughtException", (err) => consola.error("[uncaughtException]", err));
}
//#endregion
//#region ../nuxi/src/utils/engines.ts
async function checkEngines() {
const satisfies = await import("semver/functions/satisfies.js").then((r) => r.default || r);
const currentNode = process.versions.node;
const nodeRange = ">= 18.0.0";
if (!satisfies(currentNode, nodeRange)) logger.warn(`Current version of Node.js (${colors.cyan(currentNode)}) is unsupported and might cause issues.\n Please upgrade to a compatible version ${colors.cyan(nodeRange)}.`);
}
//#endregion
//#region package.json
var name = "@nuxt/cli";
var version = "3.31.3";
var description = "Nuxt CLI";
//#endregion
//#region src/main.ts
const _main = defineCommand({
meta: {
name: name.endsWith("nightly") ? name : "nuxi",
version,
description
},
args: {
...cwdArgs,
command: {
type: "positional",
required: false
}
},
subCommands: commands,
async setup(ctx) {
const command = ctx.args._[0];
setupGlobalConsole({ dev: command === "dev" });
let backgroundTasks;
if (command !== "_dev" && provider !== "stackblitz") backgroundTasks = Promise.all([checkEngines()]).catch((err) => logger.error(err));
if (command === "init") await backgroundTasks;
if (ctx.args.command && !(ctx.args.command in commands)) {
const cwd = resolve(ctx.args.cwd);
try {
const { x } = await import("tinyexec");
await x(`nuxt-${ctx.args.command}`, ctx.rawArgs.slice(1), {
nodeOptions: {
stdio: "inherit",
cwd
},
throwOnError: true
});
} catch (err) {
if (err instanceof Error && "code" in err && err.code === "ENOENT") return;
}
process.exit();
}
}
});
const main = _main;
//#endregion
//#region ../nuxi/src/data/nitro-presets.ts
const nitroPresets = [
"alwaysdata",
"aws-amplify",
"aws-lambda",
"azure-functions",
"azure-swa",
"bun",
"cleavr",
"cli",
"cloudflare-dev",
"cloudflare-durable",
"cloudflare-module",
"cloudflare-module-legacy",
"cloudflare-pages",
"cloudflare-pages-static",
"cloudflare-worker",
"deno-deploy",
"deno-server",
"deno-server-legacy",
"digital-ocean",
"edgio",
"firebase",
"firebase-app-hosting",
"flight-control",
"genezio",
"github-pages",
"gitlab-pages",
"heroku",
"iis-handler",
"iis-node",
"koyeb",
"netlify",
"netlify-builder",
"netlify-edge",
"netlify-legacy",
"netlify-static",
"node-cluster",
"node-listener",
"node-server",
"platform-sh",
"render-com",
"service-worker",
"static",
"stormkit",
"vercel",
"vercel-edge",
"vercel-static",
"winterjs",
"zeabur",
"zeabur-static",
"zerops",
"zerops-static"
];
//#endregion
//#region ../nuxi/src/completions.ts
async function initCompletions(command) {
const completion = await tab(command);
const devCommand = completion.commands.get("dev");
if (devCommand) {
const portOption = devCommand.options.get("port");
if (portOption) portOption.handler = (complete) => {
complete("3000", "Default development port");
complete("3001", "Alternative port");
complete("8080", "Common alternative port");
};
const hostOption = devCommand.options.get("host");
if (hostOption) hostOption.handler = (complete) => {
complete("localhost", "Local development");
complete("0.0.0.0", "Listen on all interfaces");
complete("127.0.0.1", "Loopback address");
};
}
const buildCommand = completion.commands.get("build");
if (buildCommand) {
const presetOption = buildCommand.options.get("preset");
if (presetOption) presetOption.handler = (complete) => {
for (const preset of nitroPresets) complete(preset, "");
};
}
const initCommand = completion.commands.get("init");
if (initCommand) {
const templateOption = initCommand.options.get("template");
if (templateOption) templateOption.handler = (complete) => {
for (const template in templates) complete(template, templates[template]?.description || "");
};
}
const addCommand = completion.commands.get("add");
if (addCommand) {
const cwdOption = addCommand.options.get("cwd");
if (cwdOption) cwdOption.handler = (complete) => {
complete(".", "Current directory");
};
}
for (const cmdName of [
"dev",
"build",
"generate",
"preview",
"prepare",
"init"
]) {
const cmd = completion.commands.get(cmdName);
if (cmd) {
const logLevelOption = cmd.options.get("logLevel");
if (logLevelOption) logLevelOption.handler = (complete) => {
complete("silent", "No logs");
complete("info", "Standard logging");
complete("verbose", "Detailed logging");
};
}
}
return completion;
}
//#endregion
//#region src/run.ts
globalThis.__nuxt_cli__ = globalThis.__nuxt_cli__ || {
startTime: Date.now(),
entry: fileURLToPath(new URL("../../bin/nuxi.mjs", import.meta.url)),
devEntry: fileURLToPath(new URL("../dev/index.mjs", import.meta.url))
};
async function runMain() {
await initCompletions(main);
return runMain$1(main);
}
async function runCommand(name$1, argv = process.argv.slice(2), data = {}) {
argv.push("--no-clear");
if (!(name$1 in commands)) throw new Error(`Invalid command ${name$1}`);
return await runCommand$1(await commands[name$1](), {
rawArgs: argv,
data: { overrides: data.overrides || {} }
});
}
//#endregion
export { main, runCommand, runMain };

View file

@ -0,0 +1,139 @@
import { a as legacyRootDirArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { n as tryResolveNuxt } from "./kit-B3S8uoS_.mjs";
import "./versions-Bly87QYZ.mjs";
import { t as getBuilder } from "./banner-DMgRAl0q.mjs";
import { t as formatInfoBox } from "./formatting-V2rnOEP4.mjs";
import { t as getPackageManagerVersion } from "./packageManagers-BKxN4oEl.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { isBun, isDeno, isMinimal } from "std-env";
import { colors } from "consola/utils";
import { box } from "@clack/prompts";
import { resolve } from "pathe";
import { readPackageJSON } from "pkg-types";
import os from "node:os";
import { copy } from "copy-paste";
import { detectPackageManager } from "nypm";
//#region ../nuxi/package.json
var version = "3.31.3";
//#endregion
//#region ../nuxi/src/commands/info.ts
var info_default = defineCommand({
meta: {
name: "info",
description: "Get information about Nuxt project"
},
args: {
...cwdArgs,
...legacyRootDirArgs
},
async run(ctx) {
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const nuxtConfig = await getNuxtConfig(cwd);
const { dependencies = {}, devDependencies = {} } = await readPackageJSON(cwd).catch(() => ({}));
const nuxtPath = tryResolveNuxt(cwd);
async function getDepVersion(name) {
for (const url of [cwd, nuxtPath]) {
if (!url) continue;
const pkg = await readPackageJSON(name, { url }).catch(() => null);
if (pkg) return pkg.version;
}
return dependencies[name] || devDependencies[name];
}
async function listModules(arr = []) {
const info = [];
for (let m of arr) {
if (Array.isArray(m)) m = m[0];
const name = normalizeConfigModule(m, cwd);
if (name) {
const v = await getDepVersion(name.split("/").splice(0, 2).join("/"));
info.push(`\`${v ? `${name}@${v}` : name}\``);
}
}
return info.join(", ");
}
const nuxtVersion = await getDepVersion("nuxt") || await getDepVersion("nuxt-nightly") || await getDepVersion("nuxt-edge") || await getDepVersion("nuxt3") || "-";
const isLegacy = nuxtVersion.startsWith("2");
const builder = !isLegacy ? nuxtConfig.builder || "vite" : nuxtConfig.bridge?.vite ? "vite" : nuxtConfig.buildModules?.includes("nuxt-vite") ? "vite" : "webpack";
let packageManager = (await detectPackageManager(cwd))?.name;
if (packageManager) packageManager += `@${getPackageManagerVersion(packageManager)}`;
const osType = os.type();
const builderInfo = typeof builder === "string" ? getBuilder(cwd, builder) : {
name: "custom",
version: "0.0.0"
};
const infoObj = {
"Operating system": osType === "Darwin" ? `macOS ${os.release()}` : osType === "Windows_NT" ? `Windows ${os.release()}` : `${osType} ${os.release()}`,
"CPU": `${os.cpus()[0]?.model || "unknown"} (${os.cpus().length} cores)`,
...isBun ? { "Bun version": Bun?.version } : isDeno ? { "Deno version": Deno?.version.deno } : { "Node.js version": process.version },
"nuxt/cli version": version,
"Package manager": packageManager ?? "unknown",
"Nuxt version": nuxtVersion,
"Nitro version": await getDepVersion("nitropack") || await getDepVersion("nitro"),
"Builder": builderInfo.name === "custom" ? "custom" : `${builderInfo.name.toLowerCase()}@${builderInfo.version}`,
"Config": Object.keys(nuxtConfig).map((key) => `\`${key}\``).sort().join(", "),
"Modules": await listModules(nuxtConfig.modules),
...isLegacy ? { "Build modules": await listModules(nuxtConfig.buildModules || []) } : {}
};
logger.info(`Nuxt root directory: ${colors.cyan(nuxtConfig.rootDir || cwd)}\n`);
const boxStr = formatInfoBox(infoObj);
let firstColumnLength = 0;
let secondColumnLength = 0;
const entries = Object.entries(infoObj).map(([label, val]) => {
if (label.length > firstColumnLength) firstColumnLength = label.length + 4;
if ((val || "").length > secondColumnLength) secondColumnLength = (val || "").length + 2;
return [label, val || "-"];
});
let copyStr = `| ${" ".repeat(firstColumnLength)} | ${" ".repeat(secondColumnLength)} |\n| ${"-".repeat(firstColumnLength)} | ${"-".repeat(secondColumnLength)} |\n`;
for (const [label, value] of entries) if (!isMinimal) copyStr += `| ${`**${label}**`.padEnd(firstColumnLength)} | ${(value.includes("`") ? value : `\`${value}\``).padEnd(secondColumnLength)} |\n`;
if (!isMinimal && await new Promise((resolve$1) => copy(copyStr, (err) => resolve$1(!err)))) box(`\n${boxStr}`, ` Nuxt project info ${colors.gray("(copied to clipboard) ")}`, {
contentAlign: "left",
titleAlign: "left",
width: "auto",
titlePadding: 2,
contentPadding: 2,
rounded: true
});
else logger.info(`Nuxt project info:\n${copyStr}`, { withGuide: false });
const isNuxt3 = !isLegacy;
const isBridge = !isNuxt3 && infoObj["Build modules"]?.includes("bridge");
const repo = isBridge ? "nuxt/bridge" : "nuxt/nuxt";
const docsURL = isNuxt3 || isBridge ? "https://nuxt.com" : "https://v2.nuxt.com";
logger.info(`👉 Read documentation: ${colors.cyan(docsURL)}`);
if (isNuxt3 || isBridge) {
logger.info(`👉 Report an issue: ${colors.cyan(`https://github.com/${repo}/issues/new?template=bug-report.yml`)}`, { spacing: 0 });
logger.info(`👉 Suggest an improvement: ${colors.cyan(`https://github.com/${repo}/discussions/new`)}`, { spacing: 0 });
}
}
});
function normalizeConfigModule(module, rootDir) {
if (!module) return null;
if (typeof module === "string") return module.split(rootDir).pop().split("node_modules").pop().replace(/^\//, "");
if (typeof module === "function") return `${module.name}()`;
if (Array.isArray(module)) return normalizeConfigModule(module[0], rootDir);
return null;
}
async function getNuxtConfig(rootDir) {
try {
const { createJiti } = await import("jiti");
const jiti = createJiti(rootDir, {
interopDefault: true,
alias: {
"~": rootDir,
"@": rootDir
}
});
globalThis.defineNuxtConfig = (c) => c;
const result = await jiti.import("./nuxt.config", { default: true });
delete globalThis.defineNuxtConfig;
return result;
} catch {
return {};
}
}
//#endregion
export { info_default as default };

View file

@ -0,0 +1,490 @@
import { o as logLevelArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { r as relativeToProcess } from "./kit-B3S8uoS_.mjs";
import { t as getNuxtVersion } from "./versions-Bly87QYZ.mjs";
import "./fs-CQH7NJn6.mjs";
import { n as runCommand$1, t as add_default } from "./add-cOz5A42V.mjs";
import { n as fetchModules, t as checkNuxtCompatibility } from "./_utils-NB3Cn3-G.mjs";
import "./prepare-CUaf6Joj.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { hasTTY } from "std-env";
import { colors } from "consola/utils";
import { box, cancel, confirm, intro, isCancel, multiselect, outro, select, spinner, tasks, text } from "@clack/prompts";
import { existsSync } from "node:fs";
import { basename, join, relative, resolve } from "pathe";
import { findFile, readPackageJSON, writePackageJSON } from "pkg-types";
import { x } from "tinyexec";
import { installDependencies } from "nypm";
import { downloadTemplate, startShell } from "giget";
import { $fetch } from "ofetch";
//#region ../nuxi/src/utils/ascii.ts
/**
* Thank you to IndyJoenz for this ASCII art
* https://bsky.app/profile/durdraw.org/post/3liadod3gv22a
*/
const themeColor = "\x1B[38;2;0;220;130m";
const icon = [
` .d$b.`,
` i$$A$$L .d$b`,
` .$$F\` \`$$L.$$A$$.`,
` j$$' \`4$$:\` \`$$.`,
` j$$' .4$: \`$$.`,
` j$$\` .$$: \`4$L`,
` :$$:____.d$$: _____.:$$:`,
` \`4$$$$$$$$P\` .i$$$$$$$$P\``
];
const nuxtIcon = icon.map((line) => line.split("").join(themeColor)).join("\n");
//#endregion
//#region ../nuxi/src/utils/starter-templates.ts
const hiddenTemplates = [
"doc-driven",
"v4",
"v4-compat",
"v2-bridge",
"v3",
"ui-vue",
"module-devtools",
"layer",
"hub"
];
const fetchOptions = {
timeout: 3e3,
responseType: "json",
headers: {
"user-agent": "@nuxt/cli",
...process.env.GITHUB_TOKEN ? { authorization: `token ${process.env.GITHUB_TOKEN}` } : {}
}
};
let templatesCache = null;
async function getTemplates() {
templatesCache ||= fetchTemplates();
return templatesCache;
}
async function fetchTemplates() {
const templates = {};
const files = await $fetch("https://api.github.com/repos/nuxt/starter/contents/templates?ref=templates", fetchOptions);
await Promise.all(files.map(async (file) => {
if (!file.download_url || file.type !== "file" || !file.name.endsWith(".json")) return;
const templateName = file.name.replace(".json", "");
if (hiddenTemplates.includes(templateName)) return;
templates[templateName] = void 0;
templates[templateName] = await $fetch(file.download_url, fetchOptions);
}));
return templates;
}
//#endregion
//#region ../nuxi/src/commands/init.ts
const DEFAULT_REGISTRY = "https://raw.githubusercontent.com/nuxt/starter/templates/templates";
const DEFAULT_TEMPLATE_NAME = "minimal";
const packageManagerOptions = Object.keys({
npm: void 0,
pnpm: void 0,
yarn: void 0,
bun: void 0,
deno: void 0
});
var init_default = defineCommand({
meta: {
name: "init",
description: "Initialize a fresh project"
},
args: {
...cwdArgs,
...logLevelArgs,
dir: {
type: "positional",
description: "Project directory",
default: ""
},
template: {
type: "string",
alias: "t",
description: "Template name"
},
force: {
type: "boolean",
alias: "f",
description: "Override existing directory"
},
offline: {
type: "boolean",
description: "Force offline mode"
},
preferOffline: {
type: "boolean",
description: "Prefer offline mode"
},
install: {
type: "boolean",
default: true,
description: "Skip installing dependencies"
},
gitInit: {
type: "boolean",
description: "Initialize git repository"
},
shell: {
type: "boolean",
description: "Start shell after installation in project directory"
},
packageManager: {
type: "string",
description: "Package manager choice (npm, pnpm, yarn, bun)"
},
modules: {
type: "string",
required: false,
description: "Nuxt modules to install (comma separated without spaces)",
negativeDescription: "Skip module installation prompt",
alias: "M"
},
nightly: {
type: "string",
description: "Use Nuxt nightly release channel (3x or latest)"
}
},
async run(ctx) {
if (!ctx.args.offline && !ctx.args.preferOffline && !ctx.args.template) getTemplates().catch(() => null);
if (hasTTY) process.stdout.write(`\n${nuxtIcon}\n\n`);
intro(colors.bold(`Welcome to Nuxt!`.split("").map((m) => `${themeColor}${m}`).join("")));
let availableTemplates = {};
if (!ctx.args.template || !ctx.args.dir) {
const defaultTemplates = await import("./templates-FddTjK4U.mjs").then((r) => r.templates);
if (ctx.args.offline || ctx.args.preferOffline) availableTemplates = defaultTemplates;
else {
const templatesSpinner = spinner();
templatesSpinner.start("Loading available templates");
try {
availableTemplates = await getTemplates();
templatesSpinner.stop("Templates loaded");
} catch {
availableTemplates = defaultTemplates;
templatesSpinner.stop("Templates loaded from cache");
}
}
}
let templateName = ctx.args.template;
if (!templateName) {
const result = await select({
message: "Which template would you like to use?",
options: Object.entries(availableTemplates).map(([name, data]) => {
return {
value: name,
label: data ? `${colors.whiteBright(name)} ${data.description}` : name,
hint: name === DEFAULT_TEMPLATE_NAME ? "recommended" : void 0
};
}),
initialValue: DEFAULT_TEMPLATE_NAME
});
if (isCancel(result)) {
cancel("Operation cancelled.");
process.exit(1);
}
templateName = result;
}
templateName ||= DEFAULT_TEMPLATE_NAME;
if (typeof templateName !== "string") {
logger.error("Please specify a template!");
process.exit(1);
}
if (ctx.args.dir === "") {
const defaultDir = availableTemplates[templateName]?.defaultDir || "nuxt-app";
const result = await text({
message: "Where would you like to create your project?",
placeholder: `./${defaultDir}`,
defaultValue: defaultDir
});
if (isCancel(result)) {
cancel("Operation cancelled.");
process.exit(1);
}
ctx.args.dir = result;
}
const cwd = resolve(ctx.args.cwd);
let templateDownloadPath = resolve(cwd, ctx.args.dir);
logger.step(`Creating project in ${colors.cyan(relativeToProcess(templateDownloadPath))}`);
let shouldForce = Boolean(ctx.args.force);
if (!shouldForce && existsSync(templateDownloadPath)) {
const selectedAction = await select({
message: `The directory ${colors.cyan(relativeToProcess(templateDownloadPath))} already exists. What would you like to do?`,
options: [
{
value: "override",
label: "Override its contents"
},
{
value: "different",
label: "Select different directory"
},
{
value: "abort",
label: "Abort"
}
]
});
if (isCancel(selectedAction)) {
cancel("Operation cancelled.");
process.exit(1);
}
switch (selectedAction) {
case "override":
shouldForce = true;
break;
case "different": {
const result = await text({ message: "Please specify a different directory:" });
if (isCancel(result)) {
cancel("Operation cancelled.");
process.exit(1);
}
templateDownloadPath = resolve(cwd, result);
break;
}
case "abort":
default: process.exit(1);
}
}
let template;
const downloadSpinner = spinner();
downloadSpinner.start(`Downloading ${colors.cyan(templateName)} template`);
try {
template = await downloadTemplate(templateName, {
dir: templateDownloadPath,
force: shouldForce,
offline: Boolean(ctx.args.offline),
preferOffline: Boolean(ctx.args.preferOffline),
registry: process.env.NUXI_INIT_REGISTRY || DEFAULT_REGISTRY
});
if (ctx.args.dir.length > 0) {
const path = await findFile("package.json", {
startingFrom: join(templateDownloadPath, "package.json"),
reverse: true
});
if (path) {
const pkg = await readPackageJSON(path, { try: true });
if (pkg && pkg.name) {
const slug = basename(templateDownloadPath).replace(/[^\w-]/g, "-").replace(/-{2,}/g, "-").replace(/^-|-$/g, "");
if (slug) {
pkg.name = slug;
await writePackageJSON(path, pkg);
}
}
}
}
downloadSpinner.stop(`Downloaded ${colors.cyan(template.name)} template`);
} catch (err) {
downloadSpinner.error("Template download failed");
if (process.env.DEBUG) throw err;
logger.error(err.toString());
process.exit(1);
}
if (ctx.args.nightly !== void 0 && !ctx.args.offline && !ctx.args.preferOffline) {
const nightlySpinner = spinner();
nightlySpinner.start("Fetching nightly version info");
const response = await $fetch("https://registry.npmjs.org/nuxt-nightly");
const nightlyChannelTag = ctx.args.nightly || "latest";
if (!nightlyChannelTag) {
nightlySpinner.error("Failed to get nightly channel tag");
logger.error(`Error getting nightly channel tag.`);
process.exit(1);
}
const nightlyChannelVersion = response["dist-tags"][nightlyChannelTag];
if (!nightlyChannelVersion) {
nightlySpinner.error("Nightly version not found");
logger.error(`Nightly channel version for tag ${colors.cyan(nightlyChannelTag)} not found.`);
process.exit(1);
}
const nightlyNuxtPackageJsonVersion = `npm:nuxt-nightly@${nightlyChannelVersion}`;
const packageJsonPath = resolve(cwd, ctx.args.dir);
const packageJson = await readPackageJSON(packageJsonPath);
if (packageJson.dependencies && "nuxt" in packageJson.dependencies) packageJson.dependencies.nuxt = nightlyNuxtPackageJsonVersion;
else if (packageJson.devDependencies && "nuxt" in packageJson.devDependencies) packageJson.devDependencies.nuxt = nightlyNuxtPackageJsonVersion;
await writePackageJSON(join(packageJsonPath, "package.json"), packageJson);
nightlySpinner.stop(`Updated to nightly version ${colors.cyan(nightlyChannelVersion)}`);
}
const currentPackageManager = detectCurrentPackageManager();
const packageManagerArg = ctx.args.packageManager;
const packageManagerSelectOptions = packageManagerOptions.map((pm) => ({
label: pm,
value: pm,
hint: currentPackageManager === pm ? "current" : void 0
}));
let selectedPackageManager;
if (packageManagerOptions.includes(packageManagerArg)) selectedPackageManager = packageManagerArg;
else {
const result = await select({
message: "Which package manager would you like to use?",
options: packageManagerSelectOptions,
initialValue: currentPackageManager
});
if (isCancel(result)) {
cancel("Operation cancelled.");
process.exit(1);
}
selectedPackageManager = result;
}
if (ctx.args.gitInit === void 0) {
const result = await confirm({ message: "Initialize git repository?" });
if (isCancel(result)) {
cancel("Operation cancelled.");
process.exit(1);
}
ctx.args.gitInit = result;
}
if (ctx.args.install === false) logger.info("Skipping install dependencies step.");
else {
const setupTasks = [{
title: `Installing dependencies with ${colors.cyan(selectedPackageManager)}`,
task: async () => {
await installDependencies({
cwd: template.dir,
packageManager: {
name: selectedPackageManager,
command: selectedPackageManager
}
});
return "Dependencies installed";
}
}];
if (ctx.args.gitInit) setupTasks.push({
title: "Initializing git repository",
task: async () => {
try {
await x("git", ["init", template.dir], {
throwOnError: true,
nodeOptions: { stdio: "inherit" }
});
return "Git repository initialized";
} catch (err) {
return `Git initialization failed: ${err}`;
}
}
});
try {
await tasks(setupTasks);
} catch (err) {
if (process.env.DEBUG) throw err;
logger.error(err.toString());
process.exit(1);
}
}
const modulesToAdd = [];
if (ctx.args.modules !== void 0) for (const segment of (ctx.args.modules || "").split(",")) {
const mod = segment.trim();
if (mod) modulesToAdd.push(mod);
}
else if (!ctx.args.offline && !ctx.args.preferOffline) {
const modulesPromise = fetchModules();
const wantsUserModules = await confirm({
message: `Would you like to install any of the official modules?`,
initialValue: false
});
if (isCancel(wantsUserModules)) {
cancel("Operation cancelled.");
process.exit(1);
}
if (wantsUserModules) {
const modulesSpinner = spinner();
modulesSpinner.start("Fetching available modules");
const [response, templateDeps, nuxtVersion] = await Promise.all([
modulesPromise,
getTemplateDependencies(template.dir),
getNuxtVersion(template.dir)
]);
modulesSpinner.stop("Modules loaded");
const officialModules = response.filter((module) => module.type === "official" && module.npm !== "@nuxt/devtools" && !templateDeps.includes(module.npm) && (!module.compatibility.nuxt || checkNuxtCompatibility(module, nuxtVersion)));
if (officialModules.length === 0) logger.info("All official modules are already included in this template.");
else {
const selectedOfficialModules = await multiselect({
message: "Pick the modules to install:",
options: officialModules.map((module) => ({
label: `${colors.bold(colors.greenBright(module.npm))} ${module.description.replace(/\.$/, "")}`,
value: module.npm
})),
required: false
});
if (isCancel(selectedOfficialModules)) process.exit(1);
if (selectedOfficialModules.length > 0) {
const modules = selectedOfficialModules;
const { toInstall, skipped } = filterModules(modules, Object.fromEntries(await Promise.all(modules.map(async (module) => [module, await getModuleDependencies(module)]))));
if (skipped.length) logger.info(`The following modules are already included as dependencies of another module and will not be installed: ${skipped.map((m) => colors.cyan(m)).join(", ")}`);
modulesToAdd.push(...toInstall);
}
}
}
}
if (modulesToAdd.length > 0) await runCommand$1(add_default, [
...modulesToAdd,
`--cwd=${templateDownloadPath}`,
ctx.args.install ? "" : "--skipInstall",
ctx.args.logLevel ? `--logLevel=${ctx.args.logLevel}` : ""
].filter(Boolean));
outro(`✨ Nuxt project has been created with the ${colors.cyan(template.name)} template.`);
const relativeTemplateDir = relative(process.cwd(), template.dir) || ".";
const runCmd = selectedPackageManager === "deno" ? "task" : "run";
box(`\n${[!ctx.args.shell && relativeTemplateDir.length > 1 && colors.cyan(`cd ${relativeTemplateDir}`), colors.cyan(`${selectedPackageManager} ${runCmd} dev`)].filter(Boolean).map((step) => ` ${step}`).join("\n")}\n`, ` 👉 Next steps `, {
contentAlign: "left",
titleAlign: "left",
width: "auto",
titlePadding: 2,
contentPadding: 2,
rounded: true,
withGuide: false,
formatBorder: (text$1) => `${themeColor + text$1}\x1B[0m`
});
if (ctx.args.shell) startShell(template.dir);
}
});
async function getModuleDependencies(moduleName) {
try {
const dependencies = (await $fetch(`https://registry.npmjs.org/${moduleName}/latest`)).dependencies || {};
return Object.keys(dependencies);
} catch (err) {
logger.warn(`Could not get dependencies for ${colors.cyan(moduleName)}: ${err}`);
return [];
}
}
function filterModules(modules, allDependencies) {
const result = {
toInstall: [],
skipped: []
};
for (const module of modules) if (modules.some((otherModule) => {
if (otherModule === module) return false;
return (allDependencies[otherModule] || []).includes(module);
})) result.skipped.push(module);
else result.toInstall.push(module);
return result;
}
async function getTemplateDependencies(templateDir) {
try {
const packageJsonPath = join(templateDir, "package.json");
if (!existsSync(packageJsonPath)) return [];
const packageJson = await readPackageJSON(packageJsonPath);
const directDeps = {
...packageJson.dependencies,
...packageJson.devDependencies
};
const directDepNames = Object.keys(directDeps);
const allDeps = new Set(directDepNames);
(await Promise.all(directDepNames.map((dep) => getModuleDependencies(dep)))).forEach((deps) => {
deps.forEach((dep) => allDeps.add(dep));
});
return Array.from(allDeps);
} catch (err) {
logger.warn(`Could not read template dependencies: ${err}`);
return [];
}
}
function detectCurrentPackageManager() {
const userAgent = process.env.npm_config_user_agent;
if (!userAgent) return;
const [name] = userAgent.split("/");
if (packageManagerOptions.includes(name)) return name;
}
//#endregion
export { init_default as default };

View file

@ -0,0 +1,49 @@
import process from "node:process";
import { pathToFileURL } from "node:url";
import { resolveModulePath } from "exsolve";
import { relative } from "pathe";
//#region ../nuxi/src/utils/paths.ts
const cwd = process.cwd();
function relativeToProcess(path) {
return relative(cwd, path) || path;
}
function withNodePath(path) {
return [path, process.env.NODE_PATH].filter((i) => !!i);
}
//#endregion
//#region ../nuxi/src/utils/kit.ts
async function loadKit(rootDir) {
try {
let kit = await import(pathToFileURL(resolveModulePath("@nuxt/kit", { from: tryResolveNuxt(rootDir) || rootDir })).href);
if (!kit.writeTypes) kit = {
...kit,
writeTypes: () => {
throw new Error("`writeTypes` is not available in this version of `@nuxt/kit`. Please upgrade to v3.7 or newer.");
}
};
return kit;
} catch (e) {
if (e.toString().includes("Cannot find module '@nuxt/kit'")) throw new Error("nuxi requires `@nuxt/kit` to be installed in your project. Try installing `nuxt` v3+ or `@nuxt/bridge` first.");
throw e;
}
}
function tryResolveNuxt(rootDir) {
for (const pkg of [
"nuxt-nightly",
"nuxt",
"nuxt3",
"nuxt-edge"
]) {
const path = resolveModulePath(pkg, {
from: withNodePath(rootDir),
try: true
});
if (path) return path;
}
return null;
}
//#endregion
export { withNodePath as i, tryResolveNuxt as n, relativeToProcess as r, loadKit as t };

View file

@ -0,0 +1,9 @@
import { log } from "@clack/prompts";
import createDebug from "debug";
//#region ../nuxi/src/utils/logger.ts
const logger = log;
const debug = createDebug("nuxi");
//#endregion
export { logger as n, debug as t };

View file

@ -0,0 +1,17 @@
import { defineCommand } from "citty";
//#region ../nuxi/src/commands/module/index.ts
var module_default = defineCommand({
meta: {
name: "module",
description: "Manage Nuxt modules"
},
args: {},
subCommands: {
add: () => import("./add-CbHKQ2Kq.mjs").then((r) => r.default || r),
search: () => import("./search-CKbK1-IC.mjs").then((r) => r.default || r)
}
});
//#endregion
export { module_default as default };

View file

@ -0,0 +1,44 @@
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { r as rmRecursive } from "./fs-CQH7NJn6.mjs";
import { promises } from "node:fs";
import { dirname, resolve } from "pathe";
import { hash } from "ohash";
//#region ../nuxi/src/utils/nuxt.ts
async function cleanupNuxtDirs(rootDir, buildDir) {
logger.info("Cleaning up generated Nuxt files and caches...");
await rmRecursive([
buildDir,
".output",
"dist",
"node_modules/.vite",
"node_modules/.cache"
].map((dir) => resolve(rootDir, dir)));
}
function nuxtVersionToGitIdentifier(version) {
const id = /\.([0-9a-f]{7,8})$/.exec(version);
if (id?.[1]) return id[1];
return `v${version}`;
}
function resolveNuxtManifest(nuxt) {
const manifest = {
_hash: null,
project: { rootDir: nuxt.options.rootDir },
versions: { nuxt: nuxt._version }
};
manifest._hash = hash(manifest);
return manifest;
}
async function writeNuxtManifest(nuxt, manifest = resolveNuxtManifest(nuxt)) {
const manifestPath = resolve(nuxt.options.buildDir, "nuxt.json");
await promises.mkdir(dirname(manifestPath), { recursive: true });
await promises.writeFile(manifestPath, JSON.stringify(manifest, null, 2), "utf-8");
return manifest;
}
async function loadNuxtManifest(buildDir) {
const manifestPath = resolve(buildDir, "nuxt.json");
return await promises.readFile(manifestPath, "utf-8").then((data) => JSON.parse(data)).catch(() => null);
}
//#endregion
export { writeNuxtManifest as a, resolveNuxtManifest as i, loadNuxtManifest as n, nuxtVersionToGitIdentifier as r, cleanupNuxtDirs as t };

View file

@ -0,0 +1,9 @@
import { execSync } from "node:child_process";
//#region ../nuxi/src/utils/packageManagers.ts
function getPackageManagerVersion(name) {
return execSync(`${name} --version`).toString("utf8").trim();
}
//#endregion
export { getPackageManagerVersion as t };

View file

@ -0,0 +1,50 @@
import { a as legacyRootDirArgs, i as extendsArgs, n as dotEnvArgs, o as logLevelArgs, r as envNameArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { r as relativeToProcess, t as loadKit } from "./kit-B3S8uoS_.mjs";
import { t as clearBuildDir } from "./fs-CQH7NJn6.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { colors } from "consola/utils";
import { resolve } from "pathe";
//#region ../nuxi/src/commands/prepare.ts
var prepare_default = defineCommand({
meta: {
name: "prepare",
description: "Prepare Nuxt for development/build"
},
args: {
...dotEnvArgs,
...cwdArgs,
...logLevelArgs,
...envNameArgs,
...extendsArgs,
...legacyRootDirArgs
},
async run(ctx) {
process.env.NODE_ENV = process.env.NODE_ENV || "production";
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const { loadNuxt, buildNuxt, writeTypes } = await loadKit(cwd);
const nuxt = await loadNuxt({
cwd,
dotenv: {
cwd,
fileName: ctx.args.dotenv
},
envName: ctx.args.envName,
overrides: {
_prepare: true,
logLevel: ctx.args.logLevel,
...ctx.args.extends && { extends: ctx.args.extends },
...ctx.data?.overrides
}
});
await clearBuildDir(nuxt.options.buildDir);
await buildNuxt(nuxt);
await writeTypes(nuxt);
logger.success(`Types generated in ${colors.cyan(relativeToProcess(nuxt.options.buildDir))}.`);
}
});
//#endregion
export { prepare_default as t };

View file

@ -0,0 +1,7 @@
import "./_shared-BCYCnX0T.mjs";
import "./logger-B4ge7MhP.mjs";
import "./kit-B3S8uoS_.mjs";
import "./fs-CQH7NJn6.mjs";
import { t as prepare_default } from "./prepare-CUaf6Joj.mjs";
export { prepare_default as default };

View file

@ -0,0 +1,119 @@
import { a as legacyRootDirArgs, i as extendsArgs, n as dotEnvArgs, o as logLevelArgs, r as envNameArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { r as relativeToProcess, t as loadKit } from "./kit-B3S8uoS_.mjs";
import { dirname } from "node:path";
import process from "node:process";
import { defineCommand } from "citty";
import { colors } from "consola/utils";
import { box, outro } from "@clack/prompts";
import { existsSync, promises } from "node:fs";
import { resolve as resolve$1 } from "pathe";
import { x } from "tinyexec";
import { setupDotenv } from "c12";
//#region ../nuxi/src/commands/preview.ts
const command = defineCommand({
meta: {
name: "preview",
description: "Launches Nitro server for local testing after `nuxi build`."
},
args: {
...cwdArgs,
...logLevelArgs,
...envNameArgs,
...extendsArgs,
...legacyRootDirArgs,
port: {
type: "string",
description: "Port to listen on",
alias: ["p"]
},
...dotEnvArgs
},
async run(ctx) {
process.env.NODE_ENV = process.env.NODE_ENV || "production";
const cwd = resolve$1(ctx.args.cwd || ctx.args.rootDir);
const { loadNuxt } = await loadKit(cwd);
const nitroJSONPaths = [await new Promise((res) => {
loadNuxt({
cwd,
dotenv: {
cwd,
fileName: ctx.args.dotenv
},
envName: ctx.args.envName,
ready: true,
overrides: {
...ctx.args.extends && { extends: ctx.args.extends },
modules: [function(_, nuxt) {
nuxt.hook("nitro:init", (nitro) => {
res(resolve$1(nuxt.options.srcDir || cwd, nitro.options.output.dir || ".output", "nitro.json"));
});
}]
}
}).then((nuxt) => nuxt.close()).catch(() => "");
}), resolve$1(cwd, ".output", "nitro.json")].filter(Boolean);
const nitroJSONPath = nitroJSONPaths.find((p) => existsSync(p));
if (!nitroJSONPath) {
logger.error(`Cannot find ${colors.cyan("nitro.json")}. Did you run ${colors.cyan("nuxi build")} first? Search path:\n${nitroJSONPaths.join("\n")}`);
process.exit(1);
}
const outputPath = dirname(nitroJSONPath);
const nitroJSON = JSON.parse(await promises.readFile(nitroJSONPath, "utf-8"));
if (!nitroJSON.commands.preview) {
logger.error("Preview is not supported for this build.");
process.exit(1);
}
const info = [
["Node.js:", `v${process.versions.node}`],
["Nitro preset:", nitroJSON.preset],
["Working directory:", relativeToProcess(outputPath)]
];
const _infoKeyLen = Math.max(...info.map(([label]) => label.length));
logger.message("");
box([
"",
"You are previewing a Nuxt app. In production, do not use this CLI. ",
`Instead, run ${colors.cyan(nitroJSON.commands.preview)} directly.`,
"",
...info.map(([label, value]) => `${label.padEnd(_infoKeyLen, " ")} ${colors.cyan(value)}`),
""
].join("\n"), colors.yellow(" Previewing Nuxt app "), {
contentAlign: "left",
titleAlign: "left",
width: "auto",
titlePadding: 2,
contentPadding: 2,
rounded: true,
withGuide: true,
formatBorder: (text$1) => colors.yellow(text$1)
});
const envFileName = ctx.args.dotenv || ".env";
if (existsSync(resolve$1(cwd, envFileName))) {
logger.info(`Loading ${colors.cyan(envFileName)}. This will not be loaded when running the server in production.`);
await setupDotenv({
cwd,
fileName: envFileName
});
} else if (ctx.args.dotenv) logger.error(`Cannot find ${colors.cyan(envFileName)}.`);
const port = ctx.args.port ?? process.env.NUXT_PORT ?? process.env.NITRO_PORT ?? process.env.PORT;
outro(`Running ${colors.cyan(nitroJSON.commands.preview)} in ${colors.cyan(relativeToProcess(outputPath))}`);
const [command$1, ...commandArgs] = nitroJSON.commands.preview.split(" ");
await x(command$1, commandArgs, {
throwOnError: true,
nodeOptions: {
stdio: "inherit",
cwd: outputPath,
env: {
...process.env,
NUXT_PORT: port,
NITRO_PORT: port
}
}
});
}
});
var preview_default = command;
//#endregion
export { preview_default as default };

View file

@ -0,0 +1,120 @@
import { t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import "./kit-B3S8uoS_.mjs";
import { t as getNuxtVersion } from "./versions-Bly87QYZ.mjs";
import { t as formatInfoBox } from "./formatting-V2rnOEP4.mjs";
import { n as fetchModules, t as checkNuxtCompatibility } from "./_utils-NB3Cn3-G.mjs";
import { defineCommand } from "citty";
import { colors } from "consola/utils";
import { box } from "@clack/prompts";
import { kebabCase, upperFirst } from "scule";
import Fuse from "fuse.js";
//#region ../nuxi/src/commands/module/search.ts
const { format: formatNumber } = Intl.NumberFormat("en-GB", {
notation: "compact",
maximumFractionDigits: 1
});
var search_default = defineCommand({
meta: {
name: "search",
description: "Search in Nuxt modules"
},
args: {
...cwdArgs,
query: {
type: "positional",
description: "keywords to search for",
required: true
},
nuxtVersion: {
type: "string",
description: "Filter by Nuxt version and list compatible modules only (auto detected by default)",
required: false,
valueHint: "2|3"
}
},
async setup(ctx) {
const nuxtVersion = await getNuxtVersion(ctx.args.cwd);
return findModuleByKeywords(ctx.args._.join(" "), nuxtVersion);
}
});
async function findModuleByKeywords(query, nuxtVersion) {
const results = new Fuse((await fetchModules()).filter((m) => checkNuxtCompatibility(m, nuxtVersion)), {
threshold: .1,
keys: [
{
name: "name",
weight: 1
},
{
name: "npm",
weight: 1
},
{
name: "repo",
weight: 1
},
{
name: "tags",
weight: 1
},
{
name: "category",
weight: 1
},
{
name: "description",
weight: .5
},
{
name: "maintainers.name",
weight: .5
},
{
name: "maintainers.github",
weight: .5
}
]
}).search(query).map((result) => {
const res = {
name: result.item.name,
package: result.item.npm,
homepage: colors.cyan(result.item.website),
compatibility: `nuxt: ${result.item.compatibility?.nuxt || "*"}`,
repository: result.item.github,
description: result.item.description,
install: `npx nuxt module add ${result.item.name}`,
stars: colors.yellow(formatNumber(result.item.stats.stars)),
monthlyDownloads: colors.yellow(formatNumber(result.item.stats.downloads))
};
if (result.item.github === result.item.website) delete res.homepage;
if (result.item.name === result.item.npm) delete res.packageName;
return res;
});
if (!results.length) {
logger.info(`No Nuxt modules found matching query ${colors.magenta(query)} for Nuxt ${colors.cyan(nuxtVersion)}`);
return;
}
logger.success(`Found ${results.length} Nuxt ${results.length > 1 ? "modules" : "module"} matching ${colors.cyan(query)} ${nuxtVersion ? `for Nuxt ${colors.cyan(nuxtVersion)}` : ""}:\n`);
for (const foundModule of results) {
const formattedModule = {};
for (const [key, val] of Object.entries(foundModule)) {
const label = upperFirst(kebabCase(key)).replace(/-/g, " ");
formattedModule[label] = val;
}
const title = formattedModule.Name || formattedModule.Package;
delete formattedModule.Name;
box(`\n${formatInfoBox(formattedModule)}`, ` ${title} `, {
contentAlign: "left",
titleAlign: "left",
width: "auto",
titlePadding: 2,
contentPadding: 2,
rounded: true
});
}
}
//#endregion
export { search_default as default };

View file

@ -0,0 +1,34 @@
//#region ../nuxi/src/data/templates.ts
const templates = {
"content": {
"name": "content",
"description": "Content-driven website",
"defaultDir": "nuxt-app",
"url": "https://content.nuxt.com",
"tar": "https://codeload.github.com/nuxt/starter/tar.gz/refs/heads/content"
},
"minimal": {
"name": "minimal",
"description": "Minimal setup for Nuxt 4",
"defaultDir": "nuxt-app",
"url": "https://nuxt.com",
"tar": "https://codeload.github.com/nuxt/starter/tar.gz/refs/heads/v4"
},
"module": {
"name": "module",
"description": "Nuxt module",
"defaultDir": "nuxt-module",
"url": "https://nuxt.com",
"tar": "https://codeload.github.com/nuxt/starter/tar.gz/refs/heads/module"
},
"ui": {
"name": "ui",
"description": "App using Nuxt UI",
"defaultDir": "nuxt-app",
"url": "https://ui.nuxt.com",
"tar": "https://codeload.github.com/nuxt-ui-templates/starter/tar.gz/refs/heads/main"
}
};
//#endregion
export { templates as t };

View file

@ -0,0 +1,3 @@
import { t as templates } from "./templates-C0gAD--n.mjs";
export { templates };

View file

@ -0,0 +1,55 @@
import { a as legacyRootDirArgs, o as logLevelArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { resolve } from "pathe";
//#region ../nuxi/src/commands/test.ts
var test_default = defineCommand({
meta: {
name: "test",
description: "Run tests"
},
args: {
...cwdArgs,
...logLevelArgs,
...legacyRootDirArgs,
dev: {
type: "boolean",
description: "Run in dev mode"
},
watch: {
type: "boolean",
description: "Watch mode"
}
},
async run(ctx) {
process.env.NODE_ENV = process.env.NODE_ENV || "test";
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const { runTests } = await importTestUtils();
await runTests({
rootDir: cwd,
dev: ctx.args.dev,
watch: ctx.args.watch
});
}
});
async function importTestUtils() {
let err;
for (const pkg of [
"@nuxt/test-utils-nightly",
"@nuxt/test-utils-edge",
"@nuxt/test-utils"
]) try {
const exports = await import(pkg);
if (!exports.runTests) throw new Error("Invalid version of `@nuxt/test-utils` is installed!");
return exports;
} catch (_err) {
err = _err;
}
logger.error(err);
throw new Error("`@nuxt/test-utils` seems missing. Run `npm i -D @nuxt/test-utils` or `yarn add -D @nuxt/test-utils` to install.");
}
//#endregion
export { test_default as default };

View file

@ -0,0 +1,102 @@
import { a as legacyRootDirArgs, i as extendsArgs, n as dotEnvArgs, o as logLevelArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { t as loadKit } from "./kit-B3S8uoS_.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { isBun } from "std-env";
import { resolveModulePath } from "exsolve";
import { resolve } from "pathe";
import { readTSConfig } from "pkg-types";
import { x } from "tinyexec";
//#region ../nuxi/src/commands/typecheck.ts
var typecheck_default = defineCommand({
meta: {
name: "typecheck",
description: "Runs `vue-tsc` to check types throughout your app."
},
args: {
...cwdArgs,
...logLevelArgs,
...dotEnvArgs,
...extendsArgs,
...legacyRootDirArgs
},
async run(ctx) {
process.env.NODE_ENV = process.env.NODE_ENV || "production";
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
const [supportsProjects, resolvedTypeScript, resolvedVueTsc] = await Promise.all([
readTSConfig(cwd).then((r) => !!r.references?.length),
resolveModulePath("typescript", { try: true }),
resolveModulePath("vue-tsc/bin/vue-tsc.js", { try: true }),
writeTypes(cwd, ctx.args.dotenv, ctx.args.logLevel, {
...ctx.data?.overrides,
...ctx.args.extends && { extends: ctx.args.extends }
})
]);
const typeCheckArgs = supportsProjects ? ["-b", "--noEmit"] : ["--noEmit"];
if (resolvedTypeScript && resolvedVueTsc) return await x(resolvedVueTsc, typeCheckArgs, {
throwOnError: true,
nodeOptions: {
stdio: "inherit",
cwd
}
});
if (isBun) {
await x("bun", [
"install",
"typescript",
"vue-tsc",
"--global",
"--silent"
], {
throwOnError: true,
nodeOptions: {
stdio: "inherit",
cwd
}
});
return await x("bunx", ["vue-tsc", ...typeCheckArgs], {
throwOnError: true,
nodeOptions: {
stdio: "inherit",
cwd
}
});
}
await x("npx", [
"-p",
"vue-tsc",
"-p",
"typescript",
"vue-tsc",
...typeCheckArgs
], {
throwOnError: true,
nodeOptions: {
stdio: "inherit",
cwd
}
});
}
});
async function writeTypes(cwd, dotenv, logLevel, overrides) {
const { loadNuxt, buildNuxt, writeTypes: writeTypes$1 } = await loadKit(cwd);
const nuxt = await loadNuxt({
cwd,
dotenv: {
cwd,
fileName: dotenv
},
overrides: {
_prepare: true,
logLevel,
...overrides
}
});
await writeTypes$1(nuxt);
await buildNuxt(nuxt);
await nuxt.close();
}
//#endregion
export { typecheck_default as default };

View file

@ -0,0 +1,226 @@
import { a as legacyRootDirArgs, o as logLevelArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { r as relativeToProcess, t as loadKit } from "./kit-B3S8uoS_.mjs";
import { t as getNuxtVersion } from "./versions-Bly87QYZ.mjs";
import "./fs-CQH7NJn6.mjs";
import { r as nuxtVersionToGitIdentifier, t as cleanupNuxtDirs } from "./nuxt-B1NSR4xh.mjs";
import { t as getPackageManagerVersion } from "./packageManagers-BKxN4oEl.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { colors } from "consola/utils";
import { cancel, intro, isCancel, note, outro, select, spinner, tasks } from "@clack/prompts";
import { existsSync } from "node:fs";
import { resolve } from "pathe";
import { findWorkspaceDir, readPackageJSON } from "pkg-types";
import { addDependency, dedupeDependencies, detectPackageManager } from "nypm";
//#region ../nuxi/src/commands/upgrade.ts
function checkNuxtDependencyType(pkg) {
if (pkg.dependencies?.nuxt) return "dependencies";
if (pkg.devDependencies?.nuxt) return "devDependencies";
return "dependencies";
}
const nuxtVersionTags = {
"3.x": "3x",
"4.x": "latest"
};
function getNightlyDependency(dep, nuxtVersion) {
return `${dep}@npm:${dep}-nightly@${nuxtVersionTags[nuxtVersion]}`;
}
async function getNightlyVersion(packageNames) {
const nuxtVersion = await select({
message: "Which nightly Nuxt release channel do you want to install?",
options: [{
value: "3.x",
label: "3.x"
}, {
value: "4.x",
label: "4.x"
}],
initialValue: "4.x"
});
if (isCancel(nuxtVersion)) {
cancel("Operation cancelled.");
process.exit(1);
}
return {
npmPackages: packageNames.map((p) => getNightlyDependency(p, nuxtVersion)),
nuxtVersion
};
}
async function getRequiredNewVersion(packageNames, channel) {
switch (channel) {
case "nightly": return getNightlyVersion(packageNames);
case "v3": return {
npmPackages: packageNames.map((p) => `${p}@3`),
nuxtVersion: "3.x"
};
case "v3-nightly": return {
npmPackages: packageNames.map((p) => getNightlyDependency(p, "3.x")),
nuxtVersion: "3.x"
};
case "v4": return {
npmPackages: packageNames.map((p) => `${p}@4`),
nuxtVersion: "4.x"
};
case "v4-nightly": return {
npmPackages: packageNames.map((p) => getNightlyDependency(p, "4.x")),
nuxtVersion: "4.x"
};
case "stable":
default: return {
npmPackages: packageNames.map((p) => `${p}@latest`),
nuxtVersion: "4.x"
};
}
}
var upgrade_default = defineCommand({
meta: {
name: "upgrade",
description: "Upgrade Nuxt"
},
args: {
...cwdArgs,
...logLevelArgs,
...legacyRootDirArgs,
dedupe: {
type: "boolean",
description: "Dedupe dependencies after upgrading"
},
force: {
type: "boolean",
alias: "f",
description: "Force upgrade to recreate lockfile and node_modules"
},
channel: {
type: "string",
alias: "ch",
default: "stable",
description: "Specify a channel to install from (default: stable)",
valueHint: "stable|nightly|v3|v4|v4-nightly|v3-nightly"
}
},
async run(ctx) {
const cwd = resolve(ctx.args.cwd || ctx.args.rootDir);
intro(colors.cyan("Upgrading Nuxt ..."));
const [packageManager, workspaceDir = cwd] = await Promise.all([detectPackageManager(cwd), findWorkspaceDir(cwd, { try: true })]);
if (!packageManager) {
logger.error(`Unable to determine the package manager used by this project.\n\nNo lock files found in ${colors.cyan(relativeToProcess(cwd))}, and no ${colors.cyan("packageManager")} field specified in ${colors.cyan("package.json")}.`);
logger.info(`Please either add the ${colors.cyan("packageManager")} field to ${colors.cyan("package.json")} or execute the installation command for your package manager. For example, you can use ${colors.cyan("pnpm i")}, ${colors.cyan("npm i")}, ${colors.cyan("bun i")}, or ${colors.cyan("yarn i")}, and then try again.`);
process.exit(1);
}
const { name: packageManagerName, lockFile: lockFileCandidates } = packageManager;
const packageManagerVersion = getPackageManagerVersion(packageManagerName);
logger.step(`Package manager: ${colors.cyan(packageManagerName)} ${packageManagerVersion}`);
const currentVersion = await getNuxtVersion(cwd, false) || "[unknown]";
logger.step(`Current Nuxt version: ${colors.cyan(currentVersion)}`);
const pkg = await readPackageJSON(cwd).catch(() => null);
const nuxtDependencyType = pkg ? checkNuxtDependencyType(pkg) : "dependencies";
const { npmPackages, nuxtVersion } = await getRequiredNewVersion(["nuxt", ...pkg ? [
"@nuxt/kit",
"@nuxt/schema",
"@nuxt/vite-builder",
"@nuxt/webpack-builder",
"@nuxt/rspack-builder"
].filter((p) => pkg.dependencies?.[p] || pkg.devDependencies?.[p]) : []], ctx.args.channel);
const toRemove = ["node_modules"];
const lockFile = normaliseLockFile(workspaceDir, lockFileCandidates);
if (lockFile) toRemove.push(lockFile);
const forceRemovals = toRemove.map((p) => colors.cyan(p)).join(" and ");
let method = ctx.args.force ? "force" : ctx.args.dedupe ? "dedupe" : void 0;
if (!method) {
const result = await select({
message: `Would you like to dedupe your lockfile, or recreate ${forceRemovals}? This can fix problems with hoisted dependency versions and ensure you have the most up-to-date dependencies.`,
options: [
{
label: "dedupe lockfile",
value: "dedupe",
hint: "recommended"
},
{
label: `recreate ${forceRemovals}`,
value: "force"
},
{
label: "skip",
value: "skip"
}
],
initialValue: "dedupe"
});
if (isCancel(result)) {
cancel("Operation cancelled.");
process.exit(1);
}
method = result;
}
const versionType = ctx.args.channel === "nightly" ? "nightly" : `latest ${ctx.args.channel}`;
const spin = spinner();
spin.start("Upgrading Nuxt");
await tasks([
{
title: `Installing ${versionType} Nuxt ${nuxtVersion} release`,
task: async () => {
await addDependency(npmPackages, {
cwd,
packageManager,
dev: nuxtDependencyType === "devDependencies",
workspace: packageManager?.name === "pnpm" && existsSync(resolve(cwd, "pnpm-workspace.yaml"))
});
return "Nuxt packages installed";
}
},
...method === "force" ? [{
title: `Recreating ${forceRemovals}`,
task: async () => {
await dedupeDependencies({ recreateLockfile: true });
return "Lockfile recreated";
}
}] : [],
...method === "dedupe" ? [{
title: "Deduping dependencies",
task: async () => {
await dedupeDependencies();
return "Dependencies deduped";
}
}] : [],
{
title: "Cleaning up build directories",
task: async () => {
let buildDir = ".nuxt";
try {
const { loadNuxtConfig } = await loadKit(cwd);
buildDir = (await loadNuxtConfig({ cwd })).buildDir;
} catch {}
await cleanupNuxtDirs(cwd, buildDir);
return "Build directories cleaned";
}
}
]);
spin.stop();
if (method === "force") logger.info(`If you encounter any issues, revert the changes and try with ${colors.cyan("--no-force")}`);
const upgradedVersion = await getNuxtVersion(cwd, false) || "[unknown]";
if (upgradedVersion === "[unknown]") return;
if (upgradedVersion === currentVersion) outro(`You were already using the latest version of Nuxt (${colors.green(currentVersion)})`);
else {
logger.success(`Successfully upgraded Nuxt from ${colors.cyan(currentVersion)} to ${colors.green(upgradedVersion)}`);
if (currentVersion === "[unknown]") return;
const commitA = nuxtVersionToGitIdentifier(currentVersion);
const commitB = nuxtVersionToGitIdentifier(upgradedVersion);
if (commitA && commitB) note(`https://github.com/nuxt/nuxt/compare/${commitA}...${commitB}`, "Changelog");
outro("✨ Upgrade complete!");
}
}
});
function normaliseLockFile(cwd, lockFiles) {
if (typeof lockFiles === "string") lockFiles = [lockFiles];
const lockFile = lockFiles?.find((file) => existsSync(resolve(cwd, file)));
if (lockFile === void 0) {
logger.error(`Unable to find any lock files in ${colors.cyan(relativeToProcess(cwd))}.`);
return;
}
return lockFile;
}
//#endregion
export { upgrade_default as default };

View file

@ -0,0 +1,35 @@
import { n as tryResolveNuxt } from "./kit-B3S8uoS_.mjs";
import { readFileSync } from "node:fs";
import { resolveModulePath } from "exsolve";
import { readPackageJSON } from "pkg-types";
import { coerce } from "semver";
//#region ../nuxi/src/utils/versions.ts
async function getNuxtVersion(cwd, cache = true) {
const nuxtPkg = await readPackageJSON("nuxt", {
url: cwd,
try: true,
cache
});
if (nuxtPkg) return nuxtPkg.version;
const pkg = await readPackageJSON(cwd);
const pkgDep = pkg?.dependencies?.nuxt || pkg?.devDependencies?.nuxt;
return pkgDep && coerce(pkgDep)?.version || "3.0.0";
}
function getPkgVersion(cwd, pkg) {
return getPkgJSON(cwd, pkg)?.version ?? "";
}
function getPkgJSON(cwd, pkg) {
for (const url of [cwd, tryResolveNuxt(cwd)]) {
if (!url) continue;
const p = resolveModulePath(`${pkg}/package.json`, {
from: url,
try: true
});
if (p) return JSON.parse(readFileSync(p, "utf-8"));
}
return null;
}
//#endregion
export { getPkgJSON as n, getPkgVersion as r, getNuxtVersion as t };

83
Frontend-Learner/node_modules/@nuxt/cli/package.json generated vendored Normal file
View file

@ -0,0 +1,83 @@
{
"name": "@nuxt/cli",
"type": "module",
"version": "3.31.3",
"description": "Nuxt CLI",
"license": "MIT",
"repository": {
"type": "git",
"url": "git+https://github.com/nuxt/cli.git",
"directory": "packages/nuxt-cli"
},
"exports": {
".": "./dist/index.mjs",
"./cli": "./bin/nuxi.mjs"
},
"types": "./dist/index.d.ts",
"bin": {
"nuxi": "bin/nuxi.mjs",
"nuxi-ng": "bin/nuxi.mjs",
"nuxt": "bin/nuxi.mjs",
"nuxt-cli": "bin/nuxi.mjs"
},
"files": [
"bin",
"dist"
],
"engines": {
"node": "^16.10.0 || >=18.0.0"
},
"scripts": {
"build": "tsdown",
"dev:prepare": "tsdown --watch",
"prepack": "tsdown"
},
"dependencies": {
"@bomb.sh/tab": "^0.0.10",
"@clack/prompts": "1.0.0-alpha.8",
"c12": "^3.3.2",
"citty": "^0.1.6",
"confbox": "^0.2.2",
"consola": "^3.4.2",
"copy-paste": "^2.2.0",
"debug": "^4.4.3",
"defu": "^6.1.4",
"exsolve": "^1.0.8",
"fuse.js": "^7.1.0",
"giget": "^2.0.0",
"jiti": "^2.6.1",
"listhen": "^1.9.0",
"nypm": "^0.6.2",
"ofetch": "^1.5.1",
"ohash": "^2.0.11",
"pathe": "^2.0.3",
"perfect-debounce": "^2.0.0",
"pkg-types": "^2.3.0",
"scule": "^1.3.0",
"semver": "^7.7.3",
"srvx": "^0.9.8",
"std-env": "^3.10.0",
"tinyexec": "^1.0.2",
"ufo": "^1.6.1",
"youch": "^4.1.0-beta.13"
},
"devDependencies": {
"@nuxt/kit": "^4.2.2",
"@nuxt/schema": "^4.2.2",
"@types/debug": "^4.1.12",
"@types/node": "^24.10.4",
"get-port-please": "^3.2.0",
"h3": "^1.15.4",
"h3-next": "npm:h3@^2.0.1-rc.6",
"nitro": "^3.0.1-alpha.1",
"nitropack": "^2.12.9",
"rollup": "^4.53.4",
"rollup-plugin-visualizer": "^6.0.5",
"tsdown": "^0.18.0",
"typescript": "^5.9.3",
"undici": "^7.16.0",
"unplugin-purge-polyfills": "^0.1.0",
"vitest": "^3.2.4",
"youch": "^4.1.0-beta.13"
}
}

7
Frontend-Learner/node_modules/@nuxt/devalue/LICENSE generated vendored Normal file
View file

@ -0,0 +1,7 @@
Copyright (c) 2018-19 [these people](https://github.com/nuxt-contrib/devalue/graphs/contributors)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

146
Frontend-Learner/node_modules/@nuxt/devalue/README.md generated vendored Normal file
View file

@ -0,0 +1,146 @@
# @nuxt/devalue
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![codecov][codecov-src]][codecov-href]
[![package phobia][package-phobia-src]][package-phobia-href]
[![bundle phobia][bundle-phobia-src]][bundle-phobia-href]
> Forked from [devalue](https://github.com/Rich-Harris/devalue) to log errors on non-serializable properties rather than throwing `Error`.
Like `JSON.stringify`, but handles
* cyclical references (`obj.self = obj`)
* repeated references (`[value, value]`)
* `undefined`, `Infinity`, `NaN`, `-0`
* regular expressions
* dates
* `Map` and `Set`
* `.toJSON()` method for non-POJOs
Try it out on [runkit.com](https://npm.runkit.com/@nuxt/devalue).
## Goals:
* Performance
* Security (see [XSS mitigation](#xss-mitigation))
* Compact output
## Non-goals:
* Human-readable output
* Stringifying functions or arbritary non-POJOs
## Usage
```js
import devalue from '@nuxt/devalue';
let obj = { a: 1, b: 2 };
obj.c = 3;
devalue(obj); // '{a:1,b:2,c:3}'
obj.self = obj;
devalue(obj); // '(function(a){a.a=1;a.b=2;a.c=3;a.self=a;return a}({}))'
```
If `devalue` encounters a function or a non-POJO, it will throw an error.
## XSS mitigation
Say you're server-rendering a page and want to serialize some state, which could include user input. `JSON.stringify` doesn't protect against XSS attacks:
```js
const state = {
userinput: `</script><script src='https://evil.com/mwahaha.js'>`
};
const template = `
<script>
// NEVER DO THIS
var preloaded = ${JSON.stringify(state)};
</script>`;
```
Which would result in this:
```html
<script>
// NEVER DO THIS
var preloaded = {"userinput":"</script><script src='https://evil.com/mwahaha.js'>"};
</script>
```
Using `devalue`, we're protected against that attack:
```js
const template = `
<script>
var preloaded = ${devalue(state)};
</script>`;
```
```html
<script>
var preloaded = {userinput:"\\u003C\\u002Fscript\\u003E\\u003Cscript src=\'https:\\u002F\\u002Fevil.com\\u002Fmwahaha.js\'\\u003E"};
</script>
```
This, along with the fact that `devalue` bails on functions and non-POJOs, stops attackers from executing arbitrary code. Strings generated by `devalue` can be safely deserialized with `eval` or `new Function`:
```js
const value = (0,eval)('(' + str + ')');
```
## Other security considerations
While `devalue` prevents the XSS vulnerability shown above, meaning you can use it to send data from server to client, **you should not send user data from client to server** using the same method. Since it has to be evaluated, an attacker that successfully submitted data that bypassed `devalue` would have access to your system.
When using `eval`, ensure that you call it *indirectly* so that the evaluated code doesn't have access to the surrounding scope:
```js
{
const sensitiveData = 'Setec Astronomy';
eval('sendToEvilServer(sensitiveData)'); // pwned :(
(0,eval)('sendToEvilServer(sensitiveData)'); // nice try, evildoer!
}
```
Using `new Function(code)` is akin to using indirect eval.
## See also
* [lave](https://github.com/jed/lave) by Jed Schmidt
* [arson](https://github.com/benjamn/arson) by Ben Newman
* [tosource](https://github.com/marcello3d/node-tosource) by Marcello Bastéa-Forte
* [serialize-javascript](https://github.com/yahoo/serialize-javascript) by Eric Ferraiuolo
## License
[MIT](LICENSE)
<!-- Refs -->
[npm-version-src]: https://flat.badgen.net/npm/v/@nuxt/devalue/latest
[npm-version-href]: https://www.npmjs.com/package/@nuxt/devalue
[npm-downloads-src]: https://flat.badgen.net/npm/dm/@nuxt/devalue
[npm-downloads-href]: https://www.npmjs.com/package/@nuxt/devalue
[circleci-src]: https://flat.badgen.net/circleci/github/nuxt-contrib/devalue
[circleci-href]: https://circleci.com/gh/nuxt-contrib/devalue
[package-phobia-src]: https://flat.badgen.net/packagephobia/install/@nuxt/devalue
[package-phobia-href]: https://packagephobia.now.sh/result?p=@nuxt/devalue
[bundle-phobia-src]: https://flat.badgen.net/bundlephobia/minzip/@nuxt/devalue
[bundle-phobia-href]: https://bundlephobia.com/result?p=@nuxt/devalue
[codecov-src]: https://flat.badgen.net/codecov/c/github/nuxt-contrib/devalue/master
[codecov-href]: https://codecov.io/gh/nuxt-contrib/devalue

View file

@ -0,0 +1,236 @@
'use strict';
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$";
const unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
const reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
const escaped = {
"<": "\\u003C",
">": "\\u003E",
"/": "\\u002F",
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
" ": "\\t",
"\0": "\\0",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
const objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function devalue(value) {
const counts = /* @__PURE__ */ new Map();
let logNum = 0;
function log(message) {
if (logNum < 100) {
console.warn(message);
logNum += 1;
}
}
function walk(thing) {
if (typeof thing === "function") {
log(`Cannot stringify a function ${thing.name}`);
return;
}
if (counts.has(thing)) {
counts.set(thing, counts.get(thing) + 1);
return;
}
counts.set(thing, 1);
if (!isPrimitive(thing)) {
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
case "Date":
case "RegExp":
return;
case "Array":
thing.forEach(walk);
break;
case "Set":
case "Map":
Array.from(thing).forEach(walk);
break;
default:
const proto = Object.getPrototypeOf(thing);
if (proto !== Object.prototype && proto !== null && Object.getOwnPropertyNames(proto).sort().join("\0") !== objectProtoOwnPropertyNames) {
if (typeof thing.toJSON !== "function") {
log(`Cannot stringify arbitrary non-POJOs ${thing.constructor.name}`);
}
} else if (Object.getOwnPropertySymbols(thing).length > 0) {
log(`Cannot stringify POJOs with symbolic keys ${Object.getOwnPropertySymbols(thing).map((symbol) => symbol.toString())}`);
} else {
Object.keys(thing).forEach((key) => walk(thing[key]));
}
}
}
}
walk(value);
const names = /* @__PURE__ */ new Map();
Array.from(counts).filter((entry) => entry[1] > 1).sort((a, b) => b[1] - a[1]).forEach((entry, i) => {
names.set(entry[0], getName(i));
});
function stringify(thing) {
if (names.has(thing)) {
return names.get(thing);
}
if (isPrimitive(thing)) {
return stringifyPrimitive(thing);
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
return `Object(${stringify(thing.valueOf())})`;
case "RegExp":
return thing.toString();
case "Date":
return `new Date(${thing.getTime()})`;
case "Array":
const members = thing.map((v, i) => i in thing ? stringify(v) : "");
const tail = thing.length === 0 || thing.length - 1 in thing ? "" : ",";
return `[${members.join(",")}${tail}]`;
case "Set":
case "Map":
return `new ${type}([${Array.from(thing).map(stringify).join(",")}])`;
default:
if (thing.toJSON) {
let json = thing.toJSON();
if (getType(json) === "String") {
try {
json = JSON.parse(json);
} catch (e) {
}
}
return stringify(json);
}
if (Object.getPrototypeOf(thing) === null) {
if (Object.keys(thing).length === 0) {
return "Object.create(null)";
}
return `Object.create(null,{${Object.keys(thing).map((key) => `${safeKey(key)}:{writable:true,enumerable:true,value:${stringify(thing[key])}}`).join(",")}})`;
}
return `{${Object.keys(thing).map((key) => `${safeKey(key)}:${stringify(thing[key])}`).join(",")}}`;
}
}
const str = stringify(value);
if (names.size) {
const params = [];
const statements = [];
const values = [];
names.forEach((name, thing) => {
params.push(name);
if (isPrimitive(thing)) {
values.push(stringifyPrimitive(thing));
return;
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
values.push(`Object(${stringify(thing.valueOf())})`);
break;
case "RegExp":
values.push(thing.toString());
break;
case "Date":
values.push(`new Date(${thing.getTime()})`);
break;
case "Array":
values.push(`Array(${thing.length})`);
thing.forEach((v, i) => {
statements.push(`${name}[${i}]=${stringify(v)}`);
});
break;
case "Set":
values.push("new Set");
statements.push(`${name}.${Array.from(thing).map((v) => `add(${stringify(v)})`).join(".")}`);
break;
case "Map":
values.push("new Map");
statements.push(`${name}.${Array.from(thing).map(([k, v]) => `set(${stringify(k)}, ${stringify(v)})`).join(".")}`);
break;
default:
values.push(Object.getPrototypeOf(thing) === null ? "Object.create(null)" : "{}");
Object.keys(thing).forEach((key) => {
statements.push(`${name}${safeProp(key)}=${stringify(thing[key])}`);
});
}
});
statements.push(`return ${str}`);
return `(function(${params.join(",")}){${statements.join(";")}}(${values.join(",")}))`;
} else {
return str;
}
}
function getName(num) {
let name = "";
do {
name = chars[num % chars.length] + name;
num = ~~(num / chars.length) - 1;
} while (num >= 0);
return reserved.test(name) ? `${name}0` : name;
}
function isPrimitive(thing) {
return Object(thing) !== thing;
}
function stringifyPrimitive(thing) {
if (typeof thing === "string") {
return stringifyString(thing);
}
if (thing === void 0) {
return "void 0";
}
if (thing === 0 && 1 / thing < 0) {
return "-0";
}
const str = String(thing);
if (typeof thing === "number") {
return str.replace(/^(-)?0\./, "$1.");
}
return str;
}
function getType(thing) {
return Object.prototype.toString.call(thing).slice(8, -1);
}
function escapeUnsafeChar(c) {
return escaped[c] || c;
}
function escapeUnsafeChars(str) {
return str.replace(unsafeChars, escapeUnsafeChar);
}
function safeKey(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
}
function safeProp(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? `.${key}` : `[${escapeUnsafeChars(JSON.stringify(key))}]`;
}
function stringifyString(str) {
let result = '"';
for (let i = 0; i < str.length; i += 1) {
const char = str.charAt(i);
const code = char.charCodeAt(0);
if (char === '"') {
result += '\\"';
} else if (char in escaped) {
result += escaped[char];
} else if (code >= 55296 && code <= 57343) {
const next = str.charCodeAt(i + 1);
if (code <= 56319 && (next >= 56320 && next <= 57343)) {
result += char + str[++i];
} else {
result += `\\u${code.toString(16).toUpperCase()}`;
}
} else {
result += char;
}
}
result += '"';
return result;
}
module.exports = devalue;

View file

@ -0,0 +1,234 @@
const chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_$";
const unsafeChars = /[<>\b\f\n\r\t\0\u2028\u2029]/g;
const reserved = /^(?:do|if|in|for|int|let|new|try|var|byte|case|char|else|enum|goto|long|this|void|with|await|break|catch|class|const|final|float|short|super|throw|while|yield|delete|double|export|import|native|return|switch|throws|typeof|boolean|default|extends|finally|package|private|abstract|continue|debugger|function|volatile|interface|protected|transient|implements|instanceof|synchronized)$/;
const escaped = {
"<": "\\u003C",
">": "\\u003E",
"/": "\\u002F",
"\\": "\\\\",
"\b": "\\b",
"\f": "\\f",
"\n": "\\n",
"\r": "\\r",
" ": "\\t",
"\0": "\\0",
"\u2028": "\\u2028",
"\u2029": "\\u2029"
};
const objectProtoOwnPropertyNames = Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
function devalue(value) {
const counts = /* @__PURE__ */ new Map();
let logNum = 0;
function log(message) {
if (logNum < 100) {
console.warn(message);
logNum += 1;
}
}
function walk(thing) {
if (typeof thing === "function") {
log(`Cannot stringify a function ${thing.name}`);
return;
}
if (counts.has(thing)) {
counts.set(thing, counts.get(thing) + 1);
return;
}
counts.set(thing, 1);
if (!isPrimitive(thing)) {
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
case "Date":
case "RegExp":
return;
case "Array":
thing.forEach(walk);
break;
case "Set":
case "Map":
Array.from(thing).forEach(walk);
break;
default:
const proto = Object.getPrototypeOf(thing);
if (proto !== Object.prototype && proto !== null && Object.getOwnPropertyNames(proto).sort().join("\0") !== objectProtoOwnPropertyNames) {
if (typeof thing.toJSON !== "function") {
log(`Cannot stringify arbitrary non-POJOs ${thing.constructor.name}`);
}
} else if (Object.getOwnPropertySymbols(thing).length > 0) {
log(`Cannot stringify POJOs with symbolic keys ${Object.getOwnPropertySymbols(thing).map((symbol) => symbol.toString())}`);
} else {
Object.keys(thing).forEach((key) => walk(thing[key]));
}
}
}
}
walk(value);
const names = /* @__PURE__ */ new Map();
Array.from(counts).filter((entry) => entry[1] > 1).sort((a, b) => b[1] - a[1]).forEach((entry, i) => {
names.set(entry[0], getName(i));
});
function stringify(thing) {
if (names.has(thing)) {
return names.get(thing);
}
if (isPrimitive(thing)) {
return stringifyPrimitive(thing);
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
return `Object(${stringify(thing.valueOf())})`;
case "RegExp":
return thing.toString();
case "Date":
return `new Date(${thing.getTime()})`;
case "Array":
const members = thing.map((v, i) => i in thing ? stringify(v) : "");
const tail = thing.length === 0 || thing.length - 1 in thing ? "" : ",";
return `[${members.join(",")}${tail}]`;
case "Set":
case "Map":
return `new ${type}([${Array.from(thing).map(stringify).join(",")}])`;
default:
if (thing.toJSON) {
let json = thing.toJSON();
if (getType(json) === "String") {
try {
json = JSON.parse(json);
} catch (e) {
}
}
return stringify(json);
}
if (Object.getPrototypeOf(thing) === null) {
if (Object.keys(thing).length === 0) {
return "Object.create(null)";
}
return `Object.create(null,{${Object.keys(thing).map((key) => `${safeKey(key)}:{writable:true,enumerable:true,value:${stringify(thing[key])}}`).join(",")}})`;
}
return `{${Object.keys(thing).map((key) => `${safeKey(key)}:${stringify(thing[key])}`).join(",")}}`;
}
}
const str = stringify(value);
if (names.size) {
const params = [];
const statements = [];
const values = [];
names.forEach((name, thing) => {
params.push(name);
if (isPrimitive(thing)) {
values.push(stringifyPrimitive(thing));
return;
}
const type = getType(thing);
switch (type) {
case "Number":
case "String":
case "Boolean":
values.push(`Object(${stringify(thing.valueOf())})`);
break;
case "RegExp":
values.push(thing.toString());
break;
case "Date":
values.push(`new Date(${thing.getTime()})`);
break;
case "Array":
values.push(`Array(${thing.length})`);
thing.forEach((v, i) => {
statements.push(`${name}[${i}]=${stringify(v)}`);
});
break;
case "Set":
values.push("new Set");
statements.push(`${name}.${Array.from(thing).map((v) => `add(${stringify(v)})`).join(".")}`);
break;
case "Map":
values.push("new Map");
statements.push(`${name}.${Array.from(thing).map(([k, v]) => `set(${stringify(k)}, ${stringify(v)})`).join(".")}`);
break;
default:
values.push(Object.getPrototypeOf(thing) === null ? "Object.create(null)" : "{}");
Object.keys(thing).forEach((key) => {
statements.push(`${name}${safeProp(key)}=${stringify(thing[key])}`);
});
}
});
statements.push(`return ${str}`);
return `(function(${params.join(",")}){${statements.join(";")}}(${values.join(",")}))`;
} else {
return str;
}
}
function getName(num) {
let name = "";
do {
name = chars[num % chars.length] + name;
num = ~~(num / chars.length) - 1;
} while (num >= 0);
return reserved.test(name) ? `${name}0` : name;
}
function isPrimitive(thing) {
return Object(thing) !== thing;
}
function stringifyPrimitive(thing) {
if (typeof thing === "string") {
return stringifyString(thing);
}
if (thing === void 0) {
return "void 0";
}
if (thing === 0 && 1 / thing < 0) {
return "-0";
}
const str = String(thing);
if (typeof thing === "number") {
return str.replace(/^(-)?0\./, "$1.");
}
return str;
}
function getType(thing) {
return Object.prototype.toString.call(thing).slice(8, -1);
}
function escapeUnsafeChar(c) {
return escaped[c] || c;
}
function escapeUnsafeChars(str) {
return str.replace(unsafeChars, escapeUnsafeChar);
}
function safeKey(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? key : escapeUnsafeChars(JSON.stringify(key));
}
function safeProp(key) {
return /^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(key) ? `.${key}` : `[${escapeUnsafeChars(JSON.stringify(key))}]`;
}
function stringifyString(str) {
let result = '"';
for (let i = 0; i < str.length; i += 1) {
const char = str.charAt(i);
const code = char.charCodeAt(0);
if (char === '"') {
result += '\\"';
} else if (char in escaped) {
result += escaped[char];
} else if (code >= 55296 && code <= 57343) {
const next = str.charCodeAt(i + 1);
if (code <= 56319 && (next >= 56320 && next <= 57343)) {
result += char + str[++i];
} else {
result += `\\u${code.toString(16).toUpperCase()}`;
}
} else {
result += char;
}
}
result += '"';
return result;
}
export { devalue as default };

View file

@ -0,0 +1,3 @@
declare function devalue(value: any): string;
export { devalue as default };

View file

@ -0,0 +1,39 @@
{
"name": "@nuxt/devalue",
"version": "2.0.2",
"description": "Gets the job done when JSON.stringify can't",
"repository": "nuxt/devalue",
"license": "MIT",
"exports": {
".": {
"types": "./dist/index.d.ts",
"require": "./dist/devalue.js",
"import": "./dist/devalue.mjs"
}
},
"main": "./dist/devalue.js",
"module": "./dist/devalue.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist"
],
"scripts": {
"build": "unbuild",
"prepack": "yarn build",
"lint": "eslint --ext .ts,.js .",
"test": "yarn lint && jest",
"release": "yarn test && standard-version && git push --follow-tags && npm publish"
},
"devDependencies": {
"@nuxtjs/eslint-config-typescript": "^6.0.0",
"@types/jest": "^26.0.23",
"@types/mocha": "^8.2.2",
"@types/node": "^15.3.0",
"eslint": "^7.26.0",
"jest": "^26.6.3",
"standard-version": "^9.3.0",
"ts-jest": "^26.5.6",
"typescript": "^4.2.4",
"unbuild": "^1.2.1"
}
}

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022-PRESENT Nuxt Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,110 @@
'use strict';
const kit = require('@nuxt/kit');
const execa = require('execa');
function addCustomTab(tab, nuxt = kit.useNuxt()) {
nuxt.hook("devtools:customTabs", async (tabs) => {
if (typeof tab === "function")
tab = await tab();
tabs.push(tab);
});
}
function refreshCustomTabs(nuxt = kit.useNuxt()) {
return nuxt.callHook("devtools:customTabs:refresh");
}
function startSubprocess(execaOptions, tabOptions, nuxt = kit.useNuxt()) {
const id = tabOptions.id;
let restarting = false;
function start() {
const process2 = execa.execa(
execaOptions.command,
execaOptions.args,
{
reject: false,
...execaOptions,
env: {
COLORS: "true",
FORCE_COLOR: "true",
...execaOptions.env,
// Force disable Nuxi CLI override
__CLI_ARGV__: void 0
}
}
);
nuxt.callHook("devtools:terminal:write", { id, data: `> ${[execaOptions.command, ...execaOptions.args || []].join(" ")}
` });
process2.stdout.on("data", (data) => {
nuxt.callHook("devtools:terminal:write", { id, data: data.toString() });
});
process2.stderr.on("data", (data) => {
nuxt.callHook("devtools:terminal:write", { id, data: data.toString() });
});
process2.on("exit", (code) => {
if (!restarting) {
nuxt.callHook("devtools:terminal:write", { id, data: `
> process terminalated with ${code}
` });
nuxt.callHook("devtools:terminal:exit", { id, code: code || 0 });
}
});
return process2;
}
register();
nuxt.hook("close", () => {
terminate();
});
let process = start();
function restart() {
restarting = true;
process?.kill();
clear();
process = start();
restarting = false;
}
function clear() {
tabOptions.buffer = "";
register();
}
function terminate() {
restarting = false;
try {
process?.kill();
} catch {
}
nuxt.callHook("devtools:terminal:remove", { id });
}
function register() {
nuxt.callHook("devtools:terminal:register", {
onActionRestart: tabOptions.restartable === false ? void 0 : restart,
onActionTerminate: tabOptions.terminatable === false ? void 0 : terminate,
isTerminated: false,
...tabOptions
});
}
return {
getProcess: () => process,
terminate,
restart,
clear
};
}
function extendServerRpc(namespace, functions, nuxt = kit.useNuxt()) {
const ctx = _getContext(nuxt);
if (!ctx)
throw new Error("[Nuxt DevTools] Failed to get devtools context.");
return ctx.extendServerRpc(namespace, functions);
}
function onDevToolsInitialized(fn, nuxt = kit.useNuxt()) {
nuxt.hook("devtools:initialized", fn);
}
function _getContext(nuxt = kit.useNuxt()) {
return nuxt?.devtools;
}
exports.addCustomTab = addCustomTab;
exports.extendServerRpc = extendServerRpc;
exports.onDevToolsInitialized = onDevToolsInitialized;
exports.refreshCustomTabs = refreshCustomTabs;
exports.startSubprocess = startSubprocess;

View file

@ -0,0 +1,35 @@
import * as _nuxt_schema from '@nuxt/schema';
import { BirpcGroup } from 'birpc';
import { ExecaChildProcess } from 'execa';
import { M as ModuleCustomTab, S as SubprocessOptions, T as TerminalState, N as NuxtDevtoolsInfo } from './shared/devtools-kit.r2McQC71.cjs';
import 'vue';
import 'nuxt/schema';
import 'unimport';
import 'vue-router';
import 'nitropack';
import 'unstorage';
import 'vite';
/**
* Hooks to extend a custom tab in devtools.
*
* Provide a function to pass a factory that can be updated dynamically.
*/
declare function addCustomTab(tab: ModuleCustomTab | (() => ModuleCustomTab | Promise<ModuleCustomTab>), nuxt?: _nuxt_schema.Nuxt): void;
/**
* Retrigger update for custom tabs, `devtools:customTabs` will be called again.
*/
declare function refreshCustomTabs(nuxt?: _nuxt_schema.Nuxt): Promise<any>;
/**
* Create a subprocess that handled by the DevTools.
*/
declare function startSubprocess(execaOptions: SubprocessOptions, tabOptions: TerminalState, nuxt?: _nuxt_schema.Nuxt): {
getProcess: () => ExecaChildProcess<string>;
terminate: () => void;
restart: () => void;
clear: () => void;
};
declare function extendServerRpc<ClientFunctions = Record<string, never>, ServerFunctions = Record<string, never>>(namespace: string, functions: ServerFunctions, nuxt?: _nuxt_schema.Nuxt): BirpcGroup<ClientFunctions, ServerFunctions>;
declare function onDevToolsInitialized(fn: (info: NuxtDevtoolsInfo) => void, nuxt?: _nuxt_schema.Nuxt): void;
export { addCustomTab, extendServerRpc, onDevToolsInitialized, refreshCustomTabs, startSubprocess };

View file

@ -0,0 +1,35 @@
import * as _nuxt_schema from '@nuxt/schema';
import { BirpcGroup } from 'birpc';
import { ExecaChildProcess } from 'execa';
import { M as ModuleCustomTab, S as SubprocessOptions, T as TerminalState, N as NuxtDevtoolsInfo } from './shared/devtools-kit.r2McQC71.mjs';
import 'vue';
import 'nuxt/schema';
import 'unimport';
import 'vue-router';
import 'nitropack';
import 'unstorage';
import 'vite';
/**
* Hooks to extend a custom tab in devtools.
*
* Provide a function to pass a factory that can be updated dynamically.
*/
declare function addCustomTab(tab: ModuleCustomTab | (() => ModuleCustomTab | Promise<ModuleCustomTab>), nuxt?: _nuxt_schema.Nuxt): void;
/**
* Retrigger update for custom tabs, `devtools:customTabs` will be called again.
*/
declare function refreshCustomTabs(nuxt?: _nuxt_schema.Nuxt): Promise<any>;
/**
* Create a subprocess that handled by the DevTools.
*/
declare function startSubprocess(execaOptions: SubprocessOptions, tabOptions: TerminalState, nuxt?: _nuxt_schema.Nuxt): {
getProcess: () => ExecaChildProcess<string>;
terminate: () => void;
restart: () => void;
clear: () => void;
};
declare function extendServerRpc<ClientFunctions = Record<string, never>, ServerFunctions = Record<string, never>>(namespace: string, functions: ServerFunctions, nuxt?: _nuxt_schema.Nuxt): BirpcGroup<ClientFunctions, ServerFunctions>;
declare function onDevToolsInitialized(fn: (info: NuxtDevtoolsInfo) => void, nuxt?: _nuxt_schema.Nuxt): void;
export { addCustomTab, extendServerRpc, onDevToolsInitialized, refreshCustomTabs, startSubprocess };

View file

@ -0,0 +1,35 @@
import * as _nuxt_schema from '@nuxt/schema';
import { BirpcGroup } from 'birpc';
import { ExecaChildProcess } from 'execa';
import { M as ModuleCustomTab, S as SubprocessOptions, T as TerminalState, N as NuxtDevtoolsInfo } from './shared/devtools-kit.r2McQC71.js';
import 'vue';
import 'nuxt/schema';
import 'unimport';
import 'vue-router';
import 'nitropack';
import 'unstorage';
import 'vite';
/**
* Hooks to extend a custom tab in devtools.
*
* Provide a function to pass a factory that can be updated dynamically.
*/
declare function addCustomTab(tab: ModuleCustomTab | (() => ModuleCustomTab | Promise<ModuleCustomTab>), nuxt?: _nuxt_schema.Nuxt): void;
/**
* Retrigger update for custom tabs, `devtools:customTabs` will be called again.
*/
declare function refreshCustomTabs(nuxt?: _nuxt_schema.Nuxt): Promise<any>;
/**
* Create a subprocess that handled by the DevTools.
*/
declare function startSubprocess(execaOptions: SubprocessOptions, tabOptions: TerminalState, nuxt?: _nuxt_schema.Nuxt): {
getProcess: () => ExecaChildProcess<string>;
terminate: () => void;
restart: () => void;
clear: () => void;
};
declare function extendServerRpc<ClientFunctions = Record<string, never>, ServerFunctions = Record<string, never>>(namespace: string, functions: ServerFunctions, nuxt?: _nuxt_schema.Nuxt): BirpcGroup<ClientFunctions, ServerFunctions>;
declare function onDevToolsInitialized(fn: (info: NuxtDevtoolsInfo) => void, nuxt?: _nuxt_schema.Nuxt): void;
export { addCustomTab, extendServerRpc, onDevToolsInitialized, refreshCustomTabs, startSubprocess };

View file

@ -0,0 +1,104 @@
import { useNuxt } from '@nuxt/kit';
import { execa } from 'execa';
function addCustomTab(tab, nuxt = useNuxt()) {
nuxt.hook("devtools:customTabs", async (tabs) => {
if (typeof tab === "function")
tab = await tab();
tabs.push(tab);
});
}
function refreshCustomTabs(nuxt = useNuxt()) {
return nuxt.callHook("devtools:customTabs:refresh");
}
function startSubprocess(execaOptions, tabOptions, nuxt = useNuxt()) {
const id = tabOptions.id;
let restarting = false;
function start() {
const process2 = execa(
execaOptions.command,
execaOptions.args,
{
reject: false,
...execaOptions,
env: {
COLORS: "true",
FORCE_COLOR: "true",
...execaOptions.env,
// Force disable Nuxi CLI override
__CLI_ARGV__: void 0
}
}
);
nuxt.callHook("devtools:terminal:write", { id, data: `> ${[execaOptions.command, ...execaOptions.args || []].join(" ")}
` });
process2.stdout.on("data", (data) => {
nuxt.callHook("devtools:terminal:write", { id, data: data.toString() });
});
process2.stderr.on("data", (data) => {
nuxt.callHook("devtools:terminal:write", { id, data: data.toString() });
});
process2.on("exit", (code) => {
if (!restarting) {
nuxt.callHook("devtools:terminal:write", { id, data: `
> process terminalated with ${code}
` });
nuxt.callHook("devtools:terminal:exit", { id, code: code || 0 });
}
});
return process2;
}
register();
nuxt.hook("close", () => {
terminate();
});
let process = start();
function restart() {
restarting = true;
process?.kill();
clear();
process = start();
restarting = false;
}
function clear() {
tabOptions.buffer = "";
register();
}
function terminate() {
restarting = false;
try {
process?.kill();
} catch {
}
nuxt.callHook("devtools:terminal:remove", { id });
}
function register() {
nuxt.callHook("devtools:terminal:register", {
onActionRestart: tabOptions.restartable === false ? void 0 : restart,
onActionTerminate: tabOptions.terminatable === false ? void 0 : terminate,
isTerminated: false,
...tabOptions
});
}
return {
getProcess: () => process,
terminate,
restart,
clear
};
}
function extendServerRpc(namespace, functions, nuxt = useNuxt()) {
const ctx = _getContext(nuxt);
if (!ctx)
throw new Error("[Nuxt DevTools] Failed to get devtools context.");
return ctx.extendServerRpc(namespace, functions);
}
function onDevToolsInitialized(fn, nuxt = useNuxt()) {
nuxt.hook("devtools:initialized", fn);
}
function _getContext(nuxt = useNuxt()) {
return nuxt?.devtools;
}
export { addCustomTab, extendServerRpc, onDevToolsInitialized, refreshCustomTabs, startSubprocess };

View file

@ -0,0 +1,4 @@
import type { NuxtDevtoolsHostClient } from '@nuxt/devtools-kit/types';
import type { Ref } from 'vue';
export declare function onDevtoolsHostClientConnected(fn: (client: NuxtDevtoolsHostClient) => void): (() => void) | undefined;
export declare function useDevtoolsHostClient(): Ref<NuxtDevtoolsHostClient | undefined>;

View file

@ -0,0 +1,34 @@
import { shallowRef } from "vue";
let clientRef;
const fns = [];
export function onDevtoolsHostClientConnected(fn) {
fns.push(fn);
if (typeof window === "undefined")
return;
if (window.__NUXT_DEVTOOLS_HOST__) {
fns.forEach((fn2) => fn2(window.__NUXT_DEVTOOLS_HOST__));
}
Object.defineProperty(window, "__NUXT_DEVTOOLS_HOST__", {
set(value) {
if (value)
fns.forEach((fn2) => fn2(value));
},
get() {
return clientRef.value;
},
configurable: true
});
return () => {
fns.splice(fns.indexOf(fn), 1);
};
}
export function useDevtoolsHostClient() {
if (!clientRef) {
clientRef = shallowRef();
onDevtoolsHostClientConnected(setup);
}
function setup(client) {
clientRef.value = client;
}
return clientRef;
}

View file

@ -0,0 +1,4 @@
import type { Ref } from 'vue';
import type { NuxtDevtoolsIframeClient } from '../types';
export declare function onDevtoolsClientConnected(fn: (client: NuxtDevtoolsIframeClient) => void): (() => void) | undefined;
export declare function useDevtoolsClient(): Ref<NuxtDevtoolsIframeClient | undefined, NuxtDevtoolsIframeClient | undefined>;

View file

@ -0,0 +1,44 @@
import { shallowRef, triggerRef } from "vue";
let clientRef;
const hasSetup = false;
const fns = [];
export function onDevtoolsClientConnected(fn) {
fns.push(fn);
if (hasSetup)
return;
if (typeof window === "undefined")
return;
if (window.__NUXT_DEVTOOLS__) {
fns.forEach((fn2) => fn2(window.__NUXT_DEVTOOLS__));
}
Object.defineProperty(window, "__NUXT_DEVTOOLS__", {
set(value) {
if (value)
fns.forEach((fn2) => fn2(value));
},
get() {
return clientRef.value;
},
configurable: true
});
return () => {
fns.splice(fns.indexOf(fn), 1);
};
}
export function useDevtoolsClient() {
if (!clientRef) {
clientRef = shallowRef();
onDevtoolsClientConnected(setup);
}
function onUpdateReactivity() {
if (clientRef) {
triggerRef(clientRef);
}
}
function setup(client) {
clientRef.value = client;
if (client.host)
client.host.hooks.hook("host:update:reactivity", onUpdateReactivity);
}
return clientRef;
}

View file

@ -0,0 +1,797 @@
import { VNode, MaybeRefOrGetter } from 'vue';
import { BirpcGroup } from 'birpc';
import { Component, NuxtOptions, NuxtPage, NuxtLayout, NuxtApp, NuxtDebugModuleMutationRecord, Nuxt } from 'nuxt/schema';
import { Import, UnimportMeta } from 'unimport';
import { RouteRecordNormalized } from 'vue-router';
import { Nitro, StorageMounts } from 'nitropack';
import { StorageValue } from 'unstorage';
import { ResolvedConfig } from 'vite';
import { NuxtAnalyzeMeta } from '@nuxt/schema';
import { Options } from 'execa';
type TabCategory = 'pinned' | 'app' | 'vue-devtools' | 'analyze' | 'server' | 'modules' | 'documentation' | 'advanced';
interface ModuleCustomTab {
/**
* The name of the tab, must be unique
*/
name: string;
/**
* Icon of the tab, support any Iconify icons, or a url to an image
*/
icon?: string;
/**
* Title of the tab
*/
title: string;
/**
* Main view of the tab
*/
view: ModuleView;
/**
* Category of the tab
* @default 'app'
*/
category?: TabCategory;
/**
* Insert static vnode to the tab entry
*
* Advanced options. You don't usually need this.
*/
extraTabVNode?: VNode;
/**
* Require local authentication to access the tab
* It's highly recommended to enable this if the tab have sensitive information or have access to the OS
*
* @default false
*/
requireAuth?: boolean;
}
interface ModuleLaunchView {
/**
* A view for module to lazy launch some actions
*/
type: 'launch';
title?: string;
icon?: string;
description: string;
/**
* Action buttons
*/
actions: ModuleLaunchAction[];
}
interface ModuleIframeView {
/**
* Iframe view
*/
type: 'iframe';
/**
* Url of the iframe
*/
src: string;
/**
* Persist the iframe instance even if the tab is not active
*
* @default true
*/
persistent?: boolean;
/**
* Additional permissions to allow in the iframe
* These will be merged with the default permissions (clipboard-write, clipboard-read)
*
* @example ['camera', 'microphone', 'geolocation']
*/
permissions?: string[];
}
interface ModuleVNodeView {
/**
* Vue's VNode view
*/
type: 'vnode';
/**
* Send vnode to the client, they must be static and serializable
*
* Call `nuxt.hook('devtools:customTabs:refresh')` to trigger manual refresh
*/
vnode: VNode;
}
interface ModuleLaunchAction {
/**
* Label of the action button
*/
label: string;
/**
* Additional HTML attributes to the action button
*/
attrs?: Record<string, string>;
/**
* Indicate if the action is pending, will show a loading indicator and disable the button
*/
pending?: boolean;
/**
* Function to handle the action, this is executed on the server side.
* Will automatically refresh the tabs after the action is resolved.
*/
handle?: () => void | Promise<void>;
/**
* Treat the action as a link, will open the link in a new tab
*/
src?: string;
}
type ModuleView = ModuleIframeView | ModuleLaunchView | ModuleVNodeView;
interface ModuleIframeTabLazyOptions {
description?: string;
onLoad?: () => Promise<void>;
}
interface ModuleBuiltinTab {
name: string;
icon?: string;
title?: string;
path?: string;
category?: TabCategory;
show?: () => MaybeRefOrGetter<any>;
badge?: () => MaybeRefOrGetter<number | string | undefined>;
onClick?: () => void;
}
type ModuleTabInfo = ModuleCustomTab | ModuleBuiltinTab;
type CategorizedTabs = [TabCategory, (ModuleCustomTab | ModuleBuiltinTab)[]][];
interface HookInfo {
name: string;
start: number;
end?: number;
duration?: number;
listeners: number;
executions: number[];
}
interface ImageMeta {
width: number;
height: number;
orientation?: number;
type?: string;
mimeType?: string;
}
interface PackageUpdateInfo {
name: string;
current: string;
latest: string;
needsUpdate: boolean;
}
type PackageManagerName = 'npm' | 'yarn' | 'pnpm' | 'bun';
type NpmCommandType = 'install' | 'uninstall' | 'update';
interface NpmCommandOptions {
dev?: boolean;
global?: boolean;
}
interface AutoImportsWithMetadata {
imports: Import[];
metadata?: UnimportMeta;
dirs: string[];
}
interface RouteInfo extends Pick<RouteRecordNormalized, 'name' | 'path' | 'meta' | 'props' | 'children'> {
file?: string;
}
interface ServerRouteInfo {
route: string;
filepath: string;
method?: string;
type: 'api' | 'route' | 'runtime' | 'collection';
routes?: ServerRouteInfo[];
}
type ServerRouteInputType = 'string' | 'number' | 'boolean' | 'file' | 'date' | 'time' | 'datetime-local';
interface ServerRouteInput {
active: boolean;
key: string;
value: any;
type?: ServerRouteInputType;
}
interface Payload {
url: string;
time: number;
data?: Record<string, any>;
state?: Record<string, any>;
functions?: Record<string, any>;
}
interface ServerTaskInfo {
name: string;
handler: string;
description: string;
type: 'collection' | 'task';
tasks?: ServerTaskInfo[];
}
interface ScannedNitroTasks {
tasks: {
[name: string]: {
handler: string;
description: string;
};
};
scheduledTasks: {
[cron: string]: string[];
};
}
interface PluginInfoWithMetic {
src: string;
mode?: 'client' | 'server' | 'all';
ssr?: boolean;
metric?: PluginMetric;
}
interface PluginMetric {
src: string;
start: number;
end: number;
duration: number;
}
interface LoadingTimeMetric {
ssrStart?: number;
appInit?: number;
appLoad?: number;
pageStart?: number;
pageEnd?: number;
pluginInit?: number;
hmrStart?: number;
hmrEnd?: number;
}
interface BasicModuleInfo {
entryPath?: string;
meta?: {
name?: string;
};
}
interface InstalledModuleInfo {
name?: string;
isPackageModule: boolean;
isUninstallable: boolean;
info?: ModuleStaticInfo;
entryPath?: string;
timings?: Record<string, number | undefined>;
meta?: {
name?: string;
};
}
interface ModuleStaticInfo {
name: string;
description: string;
repo: string;
npm: string;
icon?: string;
github: string;
website: string;
learn_more: string;
category: string;
type: ModuleType;
stats: ModuleStats;
maintainers: MaintainerInfo[];
contributors: GitHubContributor[];
compatibility: ModuleCompatibility;
}
interface ModuleCompatibility {
nuxt: string;
requires: {
bridge?: boolean | 'optional';
};
}
interface ModuleStats {
downloads: number;
stars: number;
publishedAt: number;
createdAt: number;
}
type CompatibilityStatus = 'working' | 'wip' | 'unknown' | 'not-working';
type ModuleType = 'community' | 'official' | '3rd-party';
interface MaintainerInfo {
name: string;
github: string;
twitter?: string;
}
interface GitHubContributor {
login: string;
name?: string;
avatar_url?: string;
}
interface VueInspectorClient {
enabled: boolean;
position: {
x: number;
y: number;
};
linkParams: {
file: string;
line: number;
column: number;
};
enable: () => void;
disable: () => void;
toggleEnabled: () => void;
openInEditor: (url: URL) => void;
onUpdated: () => void;
}
type VueInspectorData = VueInspectorClient['linkParams'] & Partial<VueInspectorClient['position']>;
type AssetType = 'image' | 'font' | 'video' | 'audio' | 'text' | 'json' | 'other';
interface AssetInfo {
path: string;
type: AssetType;
publicPath: string;
filePath: string;
size: number;
mtime: number;
layer?: string;
}
interface AssetEntry {
path: string;
content: string;
encoding?: BufferEncoding;
override?: boolean;
}
interface CodeSnippet {
code: string;
lang: string;
name: string;
docs?: string;
}
interface ComponentRelationship {
id: string;
deps: string[];
}
interface ComponentWithRelationships {
component: Component;
dependencies?: string[];
dependents?: string[];
}
interface CodeServerOptions {
codeBinary: string;
launchArg: string;
licenseTermsArg: string;
connectionTokenArg: string;
}
type CodeServerType = 'ms-code-cli' | 'ms-code-server' | 'coder-code-server';
interface ModuleOptions {
/**
* Enable DevTools
*
* @default true
*/
enabled?: boolean;
/**
* Custom tabs
*
* This is in static format, for dynamic injection, call `nuxt.hook('devtools:customTabs')` instead
*/
customTabs?: ModuleCustomTab[];
/**
* VS Code Server integration options.
*/
vscode?: VSCodeIntegrationOptions;
/**
* Enable Vue Component Inspector
*
* @default true
*/
componentInspector?: boolean;
/**
* Enable Vue DevTools integration
*/
vueDevTools?: boolean;
/**
* Enable vite-plugin-inspect
*
* @default true
*/
viteInspect?: boolean;
/**
* Enable Vite DevTools integration
*
* @experimental
* @default false
*/
viteDevTools?: boolean;
/**
* Disable dev time authorization check.
*
* **NOT RECOMMENDED**, only use this if you know what you are doing.
*
* @see https://github.com/nuxt/devtools/pull/257
* @default false
*/
disableAuthorization?: boolean;
/**
* Props for the iframe element, useful for environment with stricter CSP
*/
iframeProps?: Record<string, string | boolean>;
/**
* Experimental features
*/
experimental?: {
/**
* Timeline tab
* @deprecated Use `timeline.enable` instead
*/
timeline?: boolean;
};
/**
* Options for the timeline tab
*/
timeline?: {
/**
* Enable timeline tab
*
* @default false
*/
enabled?: boolean;
/**
* Track on function calls
*/
functions?: {
include?: (string | RegExp | ((item: Import) => boolean))[];
/**
* Include from specific modules
*
* @default ['#app', '@unhead/vue']
*/
includeFrom?: string[];
exclude?: (string | RegExp | ((item: Import) => boolean))[];
};
};
/**
* Options for assets tab
*/
assets?: {
/**
* Allowed file extensions for assets tab to upload.
* To security concern.
*
* Set to '*' to disbale this limitation entirely
*
* @default Common media and txt files
*/
uploadExtensions?: '*' | string[];
};
/**
* Enable anonymous telemetry, helping us improve Nuxt DevTools.
*
* By default it will respect global Nuxt telemetry settings.
*/
telemetry?: boolean;
}
interface ModuleGlobalOptions {
/**
* List of projects to enable devtools for. Only works when devtools is installed globally.
*/
projects?: string[];
}
interface VSCodeIntegrationOptions {
/**
* Enable VS Code Server integration
*/
enabled?: boolean;
/**
* Start VS Code Server on boot
*
* @default false
*/
startOnBoot?: boolean;
/**
* Port to start VS Code Server
*
* @default 3080
*/
port?: number;
/**
* Reuse existing server if available (same port)
*/
reuseExistingServer?: boolean;
/**
* Determine whether to use code-server or vs code tunnel
*
* @default 'local-serve'
*/
mode?: 'local-serve' | 'tunnel';
/**
* Options for VS Code tunnel
*/
tunnel?: VSCodeTunnelOptions;
/**
* Determines which binary and arguments to use for VS Code.
*
* By default, uses the MS Code Server (ms-code-server).
* Can alternatively use the open source Coder code-server (coder-code-server),
* or the MS VS Code CLI (ms-code-cli)
* @default 'ms-code-server'
*/
codeServer?: CodeServerType;
/**
* Host address to listen on. Unspecified by default.
*/
host?: string;
}
interface VSCodeTunnelOptions {
/**
* the machine name for port forwarding service
*
* default: device hostname
*/
name?: string;
}
interface NuxtDevToolsOptions {
behavior: {
telemetry: boolean | null;
openInEditor: string | undefined;
};
ui: {
componentsGraphShowGlobalComponents: boolean;
componentsGraphShowLayouts: boolean;
componentsGraphShowNodeModules: boolean;
componentsGraphShowPages: boolean;
componentsGraphShowWorkspace: boolean;
componentsView: 'list' | 'graph';
hiddenTabCategories: string[];
hiddenTabs: string[];
interactionCloseOnOutsideClick: boolean;
minimizePanelInactive: number;
pinnedTabs: string[];
scale: number;
showExperimentalFeatures: boolean;
showHelpButtons: boolean;
showPanel: boolean | null;
sidebarExpanded: boolean;
sidebarScrollable: boolean;
};
serverRoutes: {
selectedRoute: ServerRouteInfo | null;
view: 'tree' | 'list';
inputDefaults: Record<string, ServerRouteInput[]>;
sendFrom: 'app' | 'devtools';
};
serverTasks: {
enabled: boolean;
selectedTask: ServerTaskInfo | null;
view: 'tree' | 'list';
inputDefaults: Record<string, ServerRouteInput[]>;
};
assets: {
view: 'grid' | 'list';
};
}
interface AnalyzeBuildMeta extends NuxtAnalyzeMeta {
features: {
bundleClient: boolean;
bundleNitro: boolean;
viteInspect: boolean;
};
size: {
clientBundle?: number;
nitroBundle?: number;
};
}
interface AnalyzeBuildsInfo {
isBuilding: boolean;
builds: AnalyzeBuildMeta[];
}
interface TerminalBase {
id: string;
name: string;
description?: string;
icon?: string;
}
type TerminalAction = 'restart' | 'terminate' | 'clear' | 'remove';
interface SubprocessOptions extends Options {
command: string;
args?: string[];
}
interface TerminalInfo extends TerminalBase {
/**
* Whether the terminal can be restarted
*/
restartable?: boolean;
/**
* Whether the terminal can be terminated
*/
terminatable?: boolean;
/**
* Whether the terminal is terminated
*/
isTerminated?: boolean;
/**
* Content buffer
*/
buffer?: string;
}
interface TerminalState extends TerminalInfo {
/**
* User action to restart the terminal, when not provided, this action will be disabled
*/
onActionRestart?: () => Promise<void> | void;
/**
* User action to terminate the terminal, when not provided, this action will be disabled
*/
onActionTerminate?: () => Promise<void> | void;
}
interface WizardFunctions {
enablePages: (nuxt: any) => Promise<void>;
}
type WizardActions = keyof WizardFunctions;
type GetWizardArgs<T extends WizardActions> = WizardFunctions[T] extends (nuxt: any, ...args: infer A) => any ? A : never;
interface ServerFunctions {
getServerConfig: () => NuxtOptions;
getServerDebugContext: () => Promise<ServerDebugContext | undefined>;
getServerData: (token: string) => Promise<NuxtServerData>;
getServerRuntimeConfig: () => Record<string, any>;
getModuleOptions: () => ModuleOptions;
getComponents: () => Component[];
getComponentsRelationships: () => Promise<ComponentRelationship[]>;
getAutoImports: () => AutoImportsWithMetadata;
getServerPages: () => NuxtPage[];
getCustomTabs: () => ModuleCustomTab[];
getServerHooks: () => HookInfo[];
getServerLayouts: () => NuxtLayout[];
getStaticAssets: () => Promise<AssetInfo[]>;
getServerRoutes: () => ServerRouteInfo[];
getServerTasks: () => ScannedNitroTasks | null;
getServerApp: () => NuxtApp | undefined;
getOptions: <T extends keyof NuxtDevToolsOptions>(tab: T) => Promise<NuxtDevToolsOptions[T]>;
updateOptions: <T extends keyof NuxtDevToolsOptions>(tab: T, settings: Partial<NuxtDevToolsOptions[T]>) => Promise<void>;
clearOptions: () => Promise<void>;
checkForUpdateFor: (name: string) => Promise<PackageUpdateInfo | undefined>;
getNpmCommand: (command: NpmCommandType, packageName: string, options?: NpmCommandOptions) => Promise<string[] | undefined>;
runNpmCommand: (token: string, command: NpmCommandType, packageName: string, options?: NpmCommandOptions) => Promise<{
processId: string;
} | undefined>;
getTerminals: () => TerminalInfo[];
getTerminalDetail: (token: string, id: string) => Promise<TerminalInfo | undefined>;
runTerminalAction: (token: string, id: string, action: TerminalAction) => Promise<boolean>;
getStorageMounts: () => Promise<StorageMounts>;
getStorageKeys: (base?: string) => Promise<string[]>;
getStorageItem: (token: string, key: string) => Promise<StorageValue>;
setStorageItem: (token: string, key: string, value: StorageValue) => Promise<void>;
removeStorageItem: (token: string, key: string) => Promise<void>;
getAnalyzeBuildInfo: () => Promise<AnalyzeBuildsInfo>;
generateAnalyzeBuildName: () => Promise<string>;
startAnalyzeBuild: (token: string, name: string) => Promise<string>;
clearAnalyzeBuilds: (token: string, names?: string[]) => Promise<void>;
getImageMeta: (token: string, filepath: string) => Promise<ImageMeta | undefined>;
getTextAssetContent: (token: string, filepath: string, limit?: number) => Promise<string | undefined>;
writeStaticAssets: (token: string, file: AssetEntry[], folder: string) => Promise<string[]>;
deleteStaticAsset: (token: string, filepath: string) => Promise<void>;
renameStaticAsset: (token: string, oldPath: string, newPath: string) => Promise<void>;
telemetryEvent: (payload: object, immediate?: boolean) => void;
customTabAction: (name: string, action: number) => Promise<boolean>;
runWizard: <T extends WizardActions>(token: string, name: T, ...args: GetWizardArgs<T>) => Promise<void>;
openInEditor: (filepath: string) => Promise<boolean>;
restartNuxt: (token: string, hard?: boolean) => Promise<void>;
installNuxtModule: (token: string, name: string, dry?: boolean) => Promise<InstallModuleReturn>;
uninstallNuxtModule: (token: string, name: string, dry?: boolean) => Promise<InstallModuleReturn>;
enableTimeline: (dry: boolean) => Promise<[string, string]>;
requestForAuth: (info?: string, origin?: string) => Promise<void>;
verifyAuthToken: (token: string) => Promise<boolean>;
}
interface ClientFunctions {
refresh: (event: ClientUpdateEvent) => void;
callHook: (hook: string, ...args: any[]) => Promise<void>;
navigateTo: (path: string) => void;
onTerminalData: (_: {
id: string;
data: string;
}) => void;
onTerminalExit: (_: {
id: string;
code?: number;
}) => void;
}
interface NuxtServerData {
nuxt: NuxtOptions;
nitro?: Nitro['options'];
vite: {
server?: ResolvedConfig;
client?: ResolvedConfig;
};
}
type ClientUpdateEvent = keyof ServerFunctions;
/**
* @internal
*/
interface NuxtDevtoolsServerContext {
nuxt: Nuxt;
options: ModuleOptions;
rpc: BirpcGroup<ClientFunctions, ServerFunctions>;
/**
* Hook to open file in editor
*/
openInEditorHooks: ((filepath: string) => boolean | void | Promise<boolean | void>)[];
/**
* Invalidate client cache for a function and ask for re-fetching
*/
refresh: (event: keyof ServerFunctions) => void;
/**
* Ensure dev auth token is valid, throw if not
*/
ensureDevAuthToken: (token: string) => Promise<void>;
extendServerRpc: <ClientFunctions = Record<string, never>, ServerFunctions = Record<string, never>>(name: string, functions: ServerFunctions) => BirpcGroup<ClientFunctions, ServerFunctions>;
}
interface NuxtDevtoolsInfo {
version: string;
packagePath: string;
isGlobalInstall: boolean;
}
interface InstallModuleReturn {
configOriginal: string;
configGenerated: string;
commands: string[];
processId: string;
}
type ServerDebugModuleMutationRecord = (Omit<NuxtDebugModuleMutationRecord, 'module'> & {
name: string;
});
interface ServerDebugContext {
moduleMutationRecords: ServerDebugModuleMutationRecord[];
}
declare module '@nuxt/schema' {
interface NuxtHooks {
/**
* Called before devtools starts. Useful to detect if devtools is enabled.
*/
'devtools:before': () => void;
/**
* Called after devtools is initialized.
*/
'devtools:initialized': (info: NuxtDevtoolsInfo) => void;
/**
* Hooks to extend devtools tabs.
*/
'devtools:customTabs': (tabs: ModuleCustomTab[]) => void;
/**
* Retrigger update for custom tabs, `devtools:customTabs` will be called again.
*/
'devtools:customTabs:refresh': () => void;
/**
* Register a terminal.
*/
'devtools:terminal:register': (terminal: TerminalState) => void;
/**
* Write to a terminal.
*
* Returns true if terminal is found.
*/
'devtools:terminal:write': (_: {
id: string;
data: string;
}) => void;
/**
* Remove a terminal from devtools.
*
* Returns true if terminal is found and deleted.
*/
'devtools:terminal:remove': (_: {
id: string;
}) => void;
/**
* Mark a terminal as terminated.
*/
'devtools:terminal:exit': (_: {
id: string;
code?: number;
}) => void;
}
}
declare module '@nuxt/schema' {
/**
* Runtime Hooks
*/
interface RuntimeNuxtHooks {
/**
* On terminal data.
*/
'devtools:terminal:data': (payload: {
id: string;
data: string;
}) => void;
}
}
export type { CodeServerType as $, AnalyzeBuildMeta as A, BasicModuleInfo as B, ClientFunctions as C, ModuleCompatibility as D, ModuleStats as E, CompatibilityStatus as F, ModuleType as G, HookInfo as H, ImageMeta as I, MaintainerInfo as J, GitHubContributor as K, LoadingTimeMetric as L, ModuleCustomTab as M, NuxtDevtoolsInfo as N, VueInspectorData as O, PluginMetric as P, AssetType as Q, RouteInfo as R, SubprocessOptions as S, TerminalState as T, AssetInfo as U, VueInspectorClient as V, AssetEntry as W, CodeSnippet as X, ComponentRelationship as Y, ComponentWithRelationships as Z, CodeServerOptions as _, ServerFunctions as a, ModuleOptions as a0, ModuleGlobalOptions as a1, VSCodeIntegrationOptions as a2, VSCodeTunnelOptions as a3, NuxtDevToolsOptions as a4, NuxtServerData as a5, ClientUpdateEvent as a6, NuxtDevtoolsServerContext as a7, InstallModuleReturn as a8, ServerDebugModuleMutationRecord as a9, ServerDebugContext as aa, TerminalBase as ab, TerminalAction as ac, TerminalInfo as ad, WizardFunctions as ae, WizardActions as af, GetWizardArgs as ag, AnalyzeBuildsInfo as b, TabCategory as c, ModuleLaunchView as d, ModuleIframeView as e, ModuleVNodeView as f, ModuleLaunchAction as g, ModuleView as h, ModuleIframeTabLazyOptions as i, ModuleBuiltinTab as j, ModuleTabInfo as k, CategorizedTabs as l, PackageUpdateInfo as m, PackageManagerName as n, NpmCommandType as o, NpmCommandOptions as p, AutoImportsWithMetadata as q, ServerRouteInfo as r, ServerRouteInputType as s, ServerRouteInput as t, Payload as u, ServerTaskInfo as v, ScannedNitroTasks as w, PluginInfoWithMetic as x, InstalledModuleInfo as y, ModuleStaticInfo as z };

View file

@ -0,0 +1,797 @@
import { VNode, MaybeRefOrGetter } from 'vue';
import { BirpcGroup } from 'birpc';
import { Component, NuxtOptions, NuxtPage, NuxtLayout, NuxtApp, NuxtDebugModuleMutationRecord, Nuxt } from 'nuxt/schema';
import { Import, UnimportMeta } from 'unimport';
import { RouteRecordNormalized } from 'vue-router';
import { Nitro, StorageMounts } from 'nitropack';
import { StorageValue } from 'unstorage';
import { ResolvedConfig } from 'vite';
import { NuxtAnalyzeMeta } from '@nuxt/schema';
import { Options } from 'execa';
type TabCategory = 'pinned' | 'app' | 'vue-devtools' | 'analyze' | 'server' | 'modules' | 'documentation' | 'advanced';
interface ModuleCustomTab {
/**
* The name of the tab, must be unique
*/
name: string;
/**
* Icon of the tab, support any Iconify icons, or a url to an image
*/
icon?: string;
/**
* Title of the tab
*/
title: string;
/**
* Main view of the tab
*/
view: ModuleView;
/**
* Category of the tab
* @default 'app'
*/
category?: TabCategory;
/**
* Insert static vnode to the tab entry
*
* Advanced options. You don't usually need this.
*/
extraTabVNode?: VNode;
/**
* Require local authentication to access the tab
* It's highly recommended to enable this if the tab have sensitive information or have access to the OS
*
* @default false
*/
requireAuth?: boolean;
}
interface ModuleLaunchView {
/**
* A view for module to lazy launch some actions
*/
type: 'launch';
title?: string;
icon?: string;
description: string;
/**
* Action buttons
*/
actions: ModuleLaunchAction[];
}
interface ModuleIframeView {
/**
* Iframe view
*/
type: 'iframe';
/**
* Url of the iframe
*/
src: string;
/**
* Persist the iframe instance even if the tab is not active
*
* @default true
*/
persistent?: boolean;
/**
* Additional permissions to allow in the iframe
* These will be merged with the default permissions (clipboard-write, clipboard-read)
*
* @example ['camera', 'microphone', 'geolocation']
*/
permissions?: string[];
}
interface ModuleVNodeView {
/**
* Vue's VNode view
*/
type: 'vnode';
/**
* Send vnode to the client, they must be static and serializable
*
* Call `nuxt.hook('devtools:customTabs:refresh')` to trigger manual refresh
*/
vnode: VNode;
}
interface ModuleLaunchAction {
/**
* Label of the action button
*/
label: string;
/**
* Additional HTML attributes to the action button
*/
attrs?: Record<string, string>;
/**
* Indicate if the action is pending, will show a loading indicator and disable the button
*/
pending?: boolean;
/**
* Function to handle the action, this is executed on the server side.
* Will automatically refresh the tabs after the action is resolved.
*/
handle?: () => void | Promise<void>;
/**
* Treat the action as a link, will open the link in a new tab
*/
src?: string;
}
type ModuleView = ModuleIframeView | ModuleLaunchView | ModuleVNodeView;
interface ModuleIframeTabLazyOptions {
description?: string;
onLoad?: () => Promise<void>;
}
interface ModuleBuiltinTab {
name: string;
icon?: string;
title?: string;
path?: string;
category?: TabCategory;
show?: () => MaybeRefOrGetter<any>;
badge?: () => MaybeRefOrGetter<number | string | undefined>;
onClick?: () => void;
}
type ModuleTabInfo = ModuleCustomTab | ModuleBuiltinTab;
type CategorizedTabs = [TabCategory, (ModuleCustomTab | ModuleBuiltinTab)[]][];
interface HookInfo {
name: string;
start: number;
end?: number;
duration?: number;
listeners: number;
executions: number[];
}
interface ImageMeta {
width: number;
height: number;
orientation?: number;
type?: string;
mimeType?: string;
}
interface PackageUpdateInfo {
name: string;
current: string;
latest: string;
needsUpdate: boolean;
}
type PackageManagerName = 'npm' | 'yarn' | 'pnpm' | 'bun';
type NpmCommandType = 'install' | 'uninstall' | 'update';
interface NpmCommandOptions {
dev?: boolean;
global?: boolean;
}
interface AutoImportsWithMetadata {
imports: Import[];
metadata?: UnimportMeta;
dirs: string[];
}
interface RouteInfo extends Pick<RouteRecordNormalized, 'name' | 'path' | 'meta' | 'props' | 'children'> {
file?: string;
}
interface ServerRouteInfo {
route: string;
filepath: string;
method?: string;
type: 'api' | 'route' | 'runtime' | 'collection';
routes?: ServerRouteInfo[];
}
type ServerRouteInputType = 'string' | 'number' | 'boolean' | 'file' | 'date' | 'time' | 'datetime-local';
interface ServerRouteInput {
active: boolean;
key: string;
value: any;
type?: ServerRouteInputType;
}
interface Payload {
url: string;
time: number;
data?: Record<string, any>;
state?: Record<string, any>;
functions?: Record<string, any>;
}
interface ServerTaskInfo {
name: string;
handler: string;
description: string;
type: 'collection' | 'task';
tasks?: ServerTaskInfo[];
}
interface ScannedNitroTasks {
tasks: {
[name: string]: {
handler: string;
description: string;
};
};
scheduledTasks: {
[cron: string]: string[];
};
}
interface PluginInfoWithMetic {
src: string;
mode?: 'client' | 'server' | 'all';
ssr?: boolean;
metric?: PluginMetric;
}
interface PluginMetric {
src: string;
start: number;
end: number;
duration: number;
}
interface LoadingTimeMetric {
ssrStart?: number;
appInit?: number;
appLoad?: number;
pageStart?: number;
pageEnd?: number;
pluginInit?: number;
hmrStart?: number;
hmrEnd?: number;
}
interface BasicModuleInfo {
entryPath?: string;
meta?: {
name?: string;
};
}
interface InstalledModuleInfo {
name?: string;
isPackageModule: boolean;
isUninstallable: boolean;
info?: ModuleStaticInfo;
entryPath?: string;
timings?: Record<string, number | undefined>;
meta?: {
name?: string;
};
}
interface ModuleStaticInfo {
name: string;
description: string;
repo: string;
npm: string;
icon?: string;
github: string;
website: string;
learn_more: string;
category: string;
type: ModuleType;
stats: ModuleStats;
maintainers: MaintainerInfo[];
contributors: GitHubContributor[];
compatibility: ModuleCompatibility;
}
interface ModuleCompatibility {
nuxt: string;
requires: {
bridge?: boolean | 'optional';
};
}
interface ModuleStats {
downloads: number;
stars: number;
publishedAt: number;
createdAt: number;
}
type CompatibilityStatus = 'working' | 'wip' | 'unknown' | 'not-working';
type ModuleType = 'community' | 'official' | '3rd-party';
interface MaintainerInfo {
name: string;
github: string;
twitter?: string;
}
interface GitHubContributor {
login: string;
name?: string;
avatar_url?: string;
}
interface VueInspectorClient {
enabled: boolean;
position: {
x: number;
y: number;
};
linkParams: {
file: string;
line: number;
column: number;
};
enable: () => void;
disable: () => void;
toggleEnabled: () => void;
openInEditor: (url: URL) => void;
onUpdated: () => void;
}
type VueInspectorData = VueInspectorClient['linkParams'] & Partial<VueInspectorClient['position']>;
type AssetType = 'image' | 'font' | 'video' | 'audio' | 'text' | 'json' | 'other';
interface AssetInfo {
path: string;
type: AssetType;
publicPath: string;
filePath: string;
size: number;
mtime: number;
layer?: string;
}
interface AssetEntry {
path: string;
content: string;
encoding?: BufferEncoding;
override?: boolean;
}
interface CodeSnippet {
code: string;
lang: string;
name: string;
docs?: string;
}
interface ComponentRelationship {
id: string;
deps: string[];
}
interface ComponentWithRelationships {
component: Component;
dependencies?: string[];
dependents?: string[];
}
interface CodeServerOptions {
codeBinary: string;
launchArg: string;
licenseTermsArg: string;
connectionTokenArg: string;
}
type CodeServerType = 'ms-code-cli' | 'ms-code-server' | 'coder-code-server';
interface ModuleOptions {
/**
* Enable DevTools
*
* @default true
*/
enabled?: boolean;
/**
* Custom tabs
*
* This is in static format, for dynamic injection, call `nuxt.hook('devtools:customTabs')` instead
*/
customTabs?: ModuleCustomTab[];
/**
* VS Code Server integration options.
*/
vscode?: VSCodeIntegrationOptions;
/**
* Enable Vue Component Inspector
*
* @default true
*/
componentInspector?: boolean;
/**
* Enable Vue DevTools integration
*/
vueDevTools?: boolean;
/**
* Enable vite-plugin-inspect
*
* @default true
*/
viteInspect?: boolean;
/**
* Enable Vite DevTools integration
*
* @experimental
* @default false
*/
viteDevTools?: boolean;
/**
* Disable dev time authorization check.
*
* **NOT RECOMMENDED**, only use this if you know what you are doing.
*
* @see https://github.com/nuxt/devtools/pull/257
* @default false
*/
disableAuthorization?: boolean;
/**
* Props for the iframe element, useful for environment with stricter CSP
*/
iframeProps?: Record<string, string | boolean>;
/**
* Experimental features
*/
experimental?: {
/**
* Timeline tab
* @deprecated Use `timeline.enable` instead
*/
timeline?: boolean;
};
/**
* Options for the timeline tab
*/
timeline?: {
/**
* Enable timeline tab
*
* @default false
*/
enabled?: boolean;
/**
* Track on function calls
*/
functions?: {
include?: (string | RegExp | ((item: Import) => boolean))[];
/**
* Include from specific modules
*
* @default ['#app', '@unhead/vue']
*/
includeFrom?: string[];
exclude?: (string | RegExp | ((item: Import) => boolean))[];
};
};
/**
* Options for assets tab
*/
assets?: {
/**
* Allowed file extensions for assets tab to upload.
* To security concern.
*
* Set to '*' to disbale this limitation entirely
*
* @default Common media and txt files
*/
uploadExtensions?: '*' | string[];
};
/**
* Enable anonymous telemetry, helping us improve Nuxt DevTools.
*
* By default it will respect global Nuxt telemetry settings.
*/
telemetry?: boolean;
}
interface ModuleGlobalOptions {
/**
* List of projects to enable devtools for. Only works when devtools is installed globally.
*/
projects?: string[];
}
interface VSCodeIntegrationOptions {
/**
* Enable VS Code Server integration
*/
enabled?: boolean;
/**
* Start VS Code Server on boot
*
* @default false
*/
startOnBoot?: boolean;
/**
* Port to start VS Code Server
*
* @default 3080
*/
port?: number;
/**
* Reuse existing server if available (same port)
*/
reuseExistingServer?: boolean;
/**
* Determine whether to use code-server or vs code tunnel
*
* @default 'local-serve'
*/
mode?: 'local-serve' | 'tunnel';
/**
* Options for VS Code tunnel
*/
tunnel?: VSCodeTunnelOptions;
/**
* Determines which binary and arguments to use for VS Code.
*
* By default, uses the MS Code Server (ms-code-server).
* Can alternatively use the open source Coder code-server (coder-code-server),
* or the MS VS Code CLI (ms-code-cli)
* @default 'ms-code-server'
*/
codeServer?: CodeServerType;
/**
* Host address to listen on. Unspecified by default.
*/
host?: string;
}
interface VSCodeTunnelOptions {
/**
* the machine name for port forwarding service
*
* default: device hostname
*/
name?: string;
}
interface NuxtDevToolsOptions {
behavior: {
telemetry: boolean | null;
openInEditor: string | undefined;
};
ui: {
componentsGraphShowGlobalComponents: boolean;
componentsGraphShowLayouts: boolean;
componentsGraphShowNodeModules: boolean;
componentsGraphShowPages: boolean;
componentsGraphShowWorkspace: boolean;
componentsView: 'list' | 'graph';
hiddenTabCategories: string[];
hiddenTabs: string[];
interactionCloseOnOutsideClick: boolean;
minimizePanelInactive: number;
pinnedTabs: string[];
scale: number;
showExperimentalFeatures: boolean;
showHelpButtons: boolean;
showPanel: boolean | null;
sidebarExpanded: boolean;
sidebarScrollable: boolean;
};
serverRoutes: {
selectedRoute: ServerRouteInfo | null;
view: 'tree' | 'list';
inputDefaults: Record<string, ServerRouteInput[]>;
sendFrom: 'app' | 'devtools';
};
serverTasks: {
enabled: boolean;
selectedTask: ServerTaskInfo | null;
view: 'tree' | 'list';
inputDefaults: Record<string, ServerRouteInput[]>;
};
assets: {
view: 'grid' | 'list';
};
}
interface AnalyzeBuildMeta extends NuxtAnalyzeMeta {
features: {
bundleClient: boolean;
bundleNitro: boolean;
viteInspect: boolean;
};
size: {
clientBundle?: number;
nitroBundle?: number;
};
}
interface AnalyzeBuildsInfo {
isBuilding: boolean;
builds: AnalyzeBuildMeta[];
}
interface TerminalBase {
id: string;
name: string;
description?: string;
icon?: string;
}
type TerminalAction = 'restart' | 'terminate' | 'clear' | 'remove';
interface SubprocessOptions extends Options {
command: string;
args?: string[];
}
interface TerminalInfo extends TerminalBase {
/**
* Whether the terminal can be restarted
*/
restartable?: boolean;
/**
* Whether the terminal can be terminated
*/
terminatable?: boolean;
/**
* Whether the terminal is terminated
*/
isTerminated?: boolean;
/**
* Content buffer
*/
buffer?: string;
}
interface TerminalState extends TerminalInfo {
/**
* User action to restart the terminal, when not provided, this action will be disabled
*/
onActionRestart?: () => Promise<void> | void;
/**
* User action to terminate the terminal, when not provided, this action will be disabled
*/
onActionTerminate?: () => Promise<void> | void;
}
interface WizardFunctions {
enablePages: (nuxt: any) => Promise<void>;
}
type WizardActions = keyof WizardFunctions;
type GetWizardArgs<T extends WizardActions> = WizardFunctions[T] extends (nuxt: any, ...args: infer A) => any ? A : never;
interface ServerFunctions {
getServerConfig: () => NuxtOptions;
getServerDebugContext: () => Promise<ServerDebugContext | undefined>;
getServerData: (token: string) => Promise<NuxtServerData>;
getServerRuntimeConfig: () => Record<string, any>;
getModuleOptions: () => ModuleOptions;
getComponents: () => Component[];
getComponentsRelationships: () => Promise<ComponentRelationship[]>;
getAutoImports: () => AutoImportsWithMetadata;
getServerPages: () => NuxtPage[];
getCustomTabs: () => ModuleCustomTab[];
getServerHooks: () => HookInfo[];
getServerLayouts: () => NuxtLayout[];
getStaticAssets: () => Promise<AssetInfo[]>;
getServerRoutes: () => ServerRouteInfo[];
getServerTasks: () => ScannedNitroTasks | null;
getServerApp: () => NuxtApp | undefined;
getOptions: <T extends keyof NuxtDevToolsOptions>(tab: T) => Promise<NuxtDevToolsOptions[T]>;
updateOptions: <T extends keyof NuxtDevToolsOptions>(tab: T, settings: Partial<NuxtDevToolsOptions[T]>) => Promise<void>;
clearOptions: () => Promise<void>;
checkForUpdateFor: (name: string) => Promise<PackageUpdateInfo | undefined>;
getNpmCommand: (command: NpmCommandType, packageName: string, options?: NpmCommandOptions) => Promise<string[] | undefined>;
runNpmCommand: (token: string, command: NpmCommandType, packageName: string, options?: NpmCommandOptions) => Promise<{
processId: string;
} | undefined>;
getTerminals: () => TerminalInfo[];
getTerminalDetail: (token: string, id: string) => Promise<TerminalInfo | undefined>;
runTerminalAction: (token: string, id: string, action: TerminalAction) => Promise<boolean>;
getStorageMounts: () => Promise<StorageMounts>;
getStorageKeys: (base?: string) => Promise<string[]>;
getStorageItem: (token: string, key: string) => Promise<StorageValue>;
setStorageItem: (token: string, key: string, value: StorageValue) => Promise<void>;
removeStorageItem: (token: string, key: string) => Promise<void>;
getAnalyzeBuildInfo: () => Promise<AnalyzeBuildsInfo>;
generateAnalyzeBuildName: () => Promise<string>;
startAnalyzeBuild: (token: string, name: string) => Promise<string>;
clearAnalyzeBuilds: (token: string, names?: string[]) => Promise<void>;
getImageMeta: (token: string, filepath: string) => Promise<ImageMeta | undefined>;
getTextAssetContent: (token: string, filepath: string, limit?: number) => Promise<string | undefined>;
writeStaticAssets: (token: string, file: AssetEntry[], folder: string) => Promise<string[]>;
deleteStaticAsset: (token: string, filepath: string) => Promise<void>;
renameStaticAsset: (token: string, oldPath: string, newPath: string) => Promise<void>;
telemetryEvent: (payload: object, immediate?: boolean) => void;
customTabAction: (name: string, action: number) => Promise<boolean>;
runWizard: <T extends WizardActions>(token: string, name: T, ...args: GetWizardArgs<T>) => Promise<void>;
openInEditor: (filepath: string) => Promise<boolean>;
restartNuxt: (token: string, hard?: boolean) => Promise<void>;
installNuxtModule: (token: string, name: string, dry?: boolean) => Promise<InstallModuleReturn>;
uninstallNuxtModule: (token: string, name: string, dry?: boolean) => Promise<InstallModuleReturn>;
enableTimeline: (dry: boolean) => Promise<[string, string]>;
requestForAuth: (info?: string, origin?: string) => Promise<void>;
verifyAuthToken: (token: string) => Promise<boolean>;
}
interface ClientFunctions {
refresh: (event: ClientUpdateEvent) => void;
callHook: (hook: string, ...args: any[]) => Promise<void>;
navigateTo: (path: string) => void;
onTerminalData: (_: {
id: string;
data: string;
}) => void;
onTerminalExit: (_: {
id: string;
code?: number;
}) => void;
}
interface NuxtServerData {
nuxt: NuxtOptions;
nitro?: Nitro['options'];
vite: {
server?: ResolvedConfig;
client?: ResolvedConfig;
};
}
type ClientUpdateEvent = keyof ServerFunctions;
/**
* @internal
*/
interface NuxtDevtoolsServerContext {
nuxt: Nuxt;
options: ModuleOptions;
rpc: BirpcGroup<ClientFunctions, ServerFunctions>;
/**
* Hook to open file in editor
*/
openInEditorHooks: ((filepath: string) => boolean | void | Promise<boolean | void>)[];
/**
* Invalidate client cache for a function and ask for re-fetching
*/
refresh: (event: keyof ServerFunctions) => void;
/**
* Ensure dev auth token is valid, throw if not
*/
ensureDevAuthToken: (token: string) => Promise<void>;
extendServerRpc: <ClientFunctions = Record<string, never>, ServerFunctions = Record<string, never>>(name: string, functions: ServerFunctions) => BirpcGroup<ClientFunctions, ServerFunctions>;
}
interface NuxtDevtoolsInfo {
version: string;
packagePath: string;
isGlobalInstall: boolean;
}
interface InstallModuleReturn {
configOriginal: string;
configGenerated: string;
commands: string[];
processId: string;
}
type ServerDebugModuleMutationRecord = (Omit<NuxtDebugModuleMutationRecord, 'module'> & {
name: string;
});
interface ServerDebugContext {
moduleMutationRecords: ServerDebugModuleMutationRecord[];
}
declare module '@nuxt/schema' {
interface NuxtHooks {
/**
* Called before devtools starts. Useful to detect if devtools is enabled.
*/
'devtools:before': () => void;
/**
* Called after devtools is initialized.
*/
'devtools:initialized': (info: NuxtDevtoolsInfo) => void;
/**
* Hooks to extend devtools tabs.
*/
'devtools:customTabs': (tabs: ModuleCustomTab[]) => void;
/**
* Retrigger update for custom tabs, `devtools:customTabs` will be called again.
*/
'devtools:customTabs:refresh': () => void;
/**
* Register a terminal.
*/
'devtools:terminal:register': (terminal: TerminalState) => void;
/**
* Write to a terminal.
*
* Returns true if terminal is found.
*/
'devtools:terminal:write': (_: {
id: string;
data: string;
}) => void;
/**
* Remove a terminal from devtools.
*
* Returns true if terminal is found and deleted.
*/
'devtools:terminal:remove': (_: {
id: string;
}) => void;
/**
* Mark a terminal as terminated.
*/
'devtools:terminal:exit': (_: {
id: string;
code?: number;
}) => void;
}
}
declare module '@nuxt/schema' {
/**
* Runtime Hooks
*/
interface RuntimeNuxtHooks {
/**
* On terminal data.
*/
'devtools:terminal:data': (payload: {
id: string;
data: string;
}) => void;
}
}
export type { CodeServerType as $, AnalyzeBuildMeta as A, BasicModuleInfo as B, ClientFunctions as C, ModuleCompatibility as D, ModuleStats as E, CompatibilityStatus as F, ModuleType as G, HookInfo as H, ImageMeta as I, MaintainerInfo as J, GitHubContributor as K, LoadingTimeMetric as L, ModuleCustomTab as M, NuxtDevtoolsInfo as N, VueInspectorData as O, PluginMetric as P, AssetType as Q, RouteInfo as R, SubprocessOptions as S, TerminalState as T, AssetInfo as U, VueInspectorClient as V, AssetEntry as W, CodeSnippet as X, ComponentRelationship as Y, ComponentWithRelationships as Z, CodeServerOptions as _, ServerFunctions as a, ModuleOptions as a0, ModuleGlobalOptions as a1, VSCodeIntegrationOptions as a2, VSCodeTunnelOptions as a3, NuxtDevToolsOptions as a4, NuxtServerData as a5, ClientUpdateEvent as a6, NuxtDevtoolsServerContext as a7, InstallModuleReturn as a8, ServerDebugModuleMutationRecord as a9, ServerDebugContext as aa, TerminalBase as ab, TerminalAction as ac, TerminalInfo as ad, WizardFunctions as ae, WizardActions as af, GetWizardArgs as ag, AnalyzeBuildsInfo as b, TabCategory as c, ModuleLaunchView as d, ModuleIframeView as e, ModuleVNodeView as f, ModuleLaunchAction as g, ModuleView as h, ModuleIframeTabLazyOptions as i, ModuleBuiltinTab as j, ModuleTabInfo as k, CategorizedTabs as l, PackageUpdateInfo as m, PackageManagerName as n, NpmCommandType as o, NpmCommandOptions as p, AutoImportsWithMetadata as q, ServerRouteInfo as r, ServerRouteInputType as s, ServerRouteInput as t, Payload as u, ServerTaskInfo as v, ScannedNitroTasks as w, PluginInfoWithMetic as x, InstalledModuleInfo as y, ModuleStaticInfo as z };

View file

@ -0,0 +1,797 @@
import { VNode, MaybeRefOrGetter } from 'vue';
import { BirpcGroup } from 'birpc';
import { Component, NuxtOptions, NuxtPage, NuxtLayout, NuxtApp, NuxtDebugModuleMutationRecord, Nuxt } from 'nuxt/schema';
import { Import, UnimportMeta } from 'unimport';
import { RouteRecordNormalized } from 'vue-router';
import { Nitro, StorageMounts } from 'nitropack';
import { StorageValue } from 'unstorage';
import { ResolvedConfig } from 'vite';
import { NuxtAnalyzeMeta } from '@nuxt/schema';
import { Options } from 'execa';
type TabCategory = 'pinned' | 'app' | 'vue-devtools' | 'analyze' | 'server' | 'modules' | 'documentation' | 'advanced';
interface ModuleCustomTab {
/**
* The name of the tab, must be unique
*/
name: string;
/**
* Icon of the tab, support any Iconify icons, or a url to an image
*/
icon?: string;
/**
* Title of the tab
*/
title: string;
/**
* Main view of the tab
*/
view: ModuleView;
/**
* Category of the tab
* @default 'app'
*/
category?: TabCategory;
/**
* Insert static vnode to the tab entry
*
* Advanced options. You don't usually need this.
*/
extraTabVNode?: VNode;
/**
* Require local authentication to access the tab
* It's highly recommended to enable this if the tab have sensitive information or have access to the OS
*
* @default false
*/
requireAuth?: boolean;
}
interface ModuleLaunchView {
/**
* A view for module to lazy launch some actions
*/
type: 'launch';
title?: string;
icon?: string;
description: string;
/**
* Action buttons
*/
actions: ModuleLaunchAction[];
}
interface ModuleIframeView {
/**
* Iframe view
*/
type: 'iframe';
/**
* Url of the iframe
*/
src: string;
/**
* Persist the iframe instance even if the tab is not active
*
* @default true
*/
persistent?: boolean;
/**
* Additional permissions to allow in the iframe
* These will be merged with the default permissions (clipboard-write, clipboard-read)
*
* @example ['camera', 'microphone', 'geolocation']
*/
permissions?: string[];
}
interface ModuleVNodeView {
/**
* Vue's VNode view
*/
type: 'vnode';
/**
* Send vnode to the client, they must be static and serializable
*
* Call `nuxt.hook('devtools:customTabs:refresh')` to trigger manual refresh
*/
vnode: VNode;
}
interface ModuleLaunchAction {
/**
* Label of the action button
*/
label: string;
/**
* Additional HTML attributes to the action button
*/
attrs?: Record<string, string>;
/**
* Indicate if the action is pending, will show a loading indicator and disable the button
*/
pending?: boolean;
/**
* Function to handle the action, this is executed on the server side.
* Will automatically refresh the tabs after the action is resolved.
*/
handle?: () => void | Promise<void>;
/**
* Treat the action as a link, will open the link in a new tab
*/
src?: string;
}
type ModuleView = ModuleIframeView | ModuleLaunchView | ModuleVNodeView;
interface ModuleIframeTabLazyOptions {
description?: string;
onLoad?: () => Promise<void>;
}
interface ModuleBuiltinTab {
name: string;
icon?: string;
title?: string;
path?: string;
category?: TabCategory;
show?: () => MaybeRefOrGetter<any>;
badge?: () => MaybeRefOrGetter<number | string | undefined>;
onClick?: () => void;
}
type ModuleTabInfo = ModuleCustomTab | ModuleBuiltinTab;
type CategorizedTabs = [TabCategory, (ModuleCustomTab | ModuleBuiltinTab)[]][];
interface HookInfo {
name: string;
start: number;
end?: number;
duration?: number;
listeners: number;
executions: number[];
}
interface ImageMeta {
width: number;
height: number;
orientation?: number;
type?: string;
mimeType?: string;
}
interface PackageUpdateInfo {
name: string;
current: string;
latest: string;
needsUpdate: boolean;
}
type PackageManagerName = 'npm' | 'yarn' | 'pnpm' | 'bun';
type NpmCommandType = 'install' | 'uninstall' | 'update';
interface NpmCommandOptions {
dev?: boolean;
global?: boolean;
}
interface AutoImportsWithMetadata {
imports: Import[];
metadata?: UnimportMeta;
dirs: string[];
}
interface RouteInfo extends Pick<RouteRecordNormalized, 'name' | 'path' | 'meta' | 'props' | 'children'> {
file?: string;
}
interface ServerRouteInfo {
route: string;
filepath: string;
method?: string;
type: 'api' | 'route' | 'runtime' | 'collection';
routes?: ServerRouteInfo[];
}
type ServerRouteInputType = 'string' | 'number' | 'boolean' | 'file' | 'date' | 'time' | 'datetime-local';
interface ServerRouteInput {
active: boolean;
key: string;
value: any;
type?: ServerRouteInputType;
}
interface Payload {
url: string;
time: number;
data?: Record<string, any>;
state?: Record<string, any>;
functions?: Record<string, any>;
}
interface ServerTaskInfo {
name: string;
handler: string;
description: string;
type: 'collection' | 'task';
tasks?: ServerTaskInfo[];
}
interface ScannedNitroTasks {
tasks: {
[name: string]: {
handler: string;
description: string;
};
};
scheduledTasks: {
[cron: string]: string[];
};
}
interface PluginInfoWithMetic {
src: string;
mode?: 'client' | 'server' | 'all';
ssr?: boolean;
metric?: PluginMetric;
}
interface PluginMetric {
src: string;
start: number;
end: number;
duration: number;
}
interface LoadingTimeMetric {
ssrStart?: number;
appInit?: number;
appLoad?: number;
pageStart?: number;
pageEnd?: number;
pluginInit?: number;
hmrStart?: number;
hmrEnd?: number;
}
interface BasicModuleInfo {
entryPath?: string;
meta?: {
name?: string;
};
}
interface InstalledModuleInfo {
name?: string;
isPackageModule: boolean;
isUninstallable: boolean;
info?: ModuleStaticInfo;
entryPath?: string;
timings?: Record<string, number | undefined>;
meta?: {
name?: string;
};
}
interface ModuleStaticInfo {
name: string;
description: string;
repo: string;
npm: string;
icon?: string;
github: string;
website: string;
learn_more: string;
category: string;
type: ModuleType;
stats: ModuleStats;
maintainers: MaintainerInfo[];
contributors: GitHubContributor[];
compatibility: ModuleCompatibility;
}
interface ModuleCompatibility {
nuxt: string;
requires: {
bridge?: boolean | 'optional';
};
}
interface ModuleStats {
downloads: number;
stars: number;
publishedAt: number;
createdAt: number;
}
type CompatibilityStatus = 'working' | 'wip' | 'unknown' | 'not-working';
type ModuleType = 'community' | 'official' | '3rd-party';
interface MaintainerInfo {
name: string;
github: string;
twitter?: string;
}
interface GitHubContributor {
login: string;
name?: string;
avatar_url?: string;
}
interface VueInspectorClient {
enabled: boolean;
position: {
x: number;
y: number;
};
linkParams: {
file: string;
line: number;
column: number;
};
enable: () => void;
disable: () => void;
toggleEnabled: () => void;
openInEditor: (url: URL) => void;
onUpdated: () => void;
}
type VueInspectorData = VueInspectorClient['linkParams'] & Partial<VueInspectorClient['position']>;
type AssetType = 'image' | 'font' | 'video' | 'audio' | 'text' | 'json' | 'other';
interface AssetInfo {
path: string;
type: AssetType;
publicPath: string;
filePath: string;
size: number;
mtime: number;
layer?: string;
}
interface AssetEntry {
path: string;
content: string;
encoding?: BufferEncoding;
override?: boolean;
}
interface CodeSnippet {
code: string;
lang: string;
name: string;
docs?: string;
}
interface ComponentRelationship {
id: string;
deps: string[];
}
interface ComponentWithRelationships {
component: Component;
dependencies?: string[];
dependents?: string[];
}
interface CodeServerOptions {
codeBinary: string;
launchArg: string;
licenseTermsArg: string;
connectionTokenArg: string;
}
type CodeServerType = 'ms-code-cli' | 'ms-code-server' | 'coder-code-server';
interface ModuleOptions {
/**
* Enable DevTools
*
* @default true
*/
enabled?: boolean;
/**
* Custom tabs
*
* This is in static format, for dynamic injection, call `nuxt.hook('devtools:customTabs')` instead
*/
customTabs?: ModuleCustomTab[];
/**
* VS Code Server integration options.
*/
vscode?: VSCodeIntegrationOptions;
/**
* Enable Vue Component Inspector
*
* @default true
*/
componentInspector?: boolean;
/**
* Enable Vue DevTools integration
*/
vueDevTools?: boolean;
/**
* Enable vite-plugin-inspect
*
* @default true
*/
viteInspect?: boolean;
/**
* Enable Vite DevTools integration
*
* @experimental
* @default false
*/
viteDevTools?: boolean;
/**
* Disable dev time authorization check.
*
* **NOT RECOMMENDED**, only use this if you know what you are doing.
*
* @see https://github.com/nuxt/devtools/pull/257
* @default false
*/
disableAuthorization?: boolean;
/**
* Props for the iframe element, useful for environment with stricter CSP
*/
iframeProps?: Record<string, string | boolean>;
/**
* Experimental features
*/
experimental?: {
/**
* Timeline tab
* @deprecated Use `timeline.enable` instead
*/
timeline?: boolean;
};
/**
* Options for the timeline tab
*/
timeline?: {
/**
* Enable timeline tab
*
* @default false
*/
enabled?: boolean;
/**
* Track on function calls
*/
functions?: {
include?: (string | RegExp | ((item: Import) => boolean))[];
/**
* Include from specific modules
*
* @default ['#app', '@unhead/vue']
*/
includeFrom?: string[];
exclude?: (string | RegExp | ((item: Import) => boolean))[];
};
};
/**
* Options for assets tab
*/
assets?: {
/**
* Allowed file extensions for assets tab to upload.
* To security concern.
*
* Set to '*' to disbale this limitation entirely
*
* @default Common media and txt files
*/
uploadExtensions?: '*' | string[];
};
/**
* Enable anonymous telemetry, helping us improve Nuxt DevTools.
*
* By default it will respect global Nuxt telemetry settings.
*/
telemetry?: boolean;
}
interface ModuleGlobalOptions {
/**
* List of projects to enable devtools for. Only works when devtools is installed globally.
*/
projects?: string[];
}
interface VSCodeIntegrationOptions {
/**
* Enable VS Code Server integration
*/
enabled?: boolean;
/**
* Start VS Code Server on boot
*
* @default false
*/
startOnBoot?: boolean;
/**
* Port to start VS Code Server
*
* @default 3080
*/
port?: number;
/**
* Reuse existing server if available (same port)
*/
reuseExistingServer?: boolean;
/**
* Determine whether to use code-server or vs code tunnel
*
* @default 'local-serve'
*/
mode?: 'local-serve' | 'tunnel';
/**
* Options for VS Code tunnel
*/
tunnel?: VSCodeTunnelOptions;
/**
* Determines which binary and arguments to use for VS Code.
*
* By default, uses the MS Code Server (ms-code-server).
* Can alternatively use the open source Coder code-server (coder-code-server),
* or the MS VS Code CLI (ms-code-cli)
* @default 'ms-code-server'
*/
codeServer?: CodeServerType;
/**
* Host address to listen on. Unspecified by default.
*/
host?: string;
}
interface VSCodeTunnelOptions {
/**
* the machine name for port forwarding service
*
* default: device hostname
*/
name?: string;
}
interface NuxtDevToolsOptions {
behavior: {
telemetry: boolean | null;
openInEditor: string | undefined;
};
ui: {
componentsGraphShowGlobalComponents: boolean;
componentsGraphShowLayouts: boolean;
componentsGraphShowNodeModules: boolean;
componentsGraphShowPages: boolean;
componentsGraphShowWorkspace: boolean;
componentsView: 'list' | 'graph';
hiddenTabCategories: string[];
hiddenTabs: string[];
interactionCloseOnOutsideClick: boolean;
minimizePanelInactive: number;
pinnedTabs: string[];
scale: number;
showExperimentalFeatures: boolean;
showHelpButtons: boolean;
showPanel: boolean | null;
sidebarExpanded: boolean;
sidebarScrollable: boolean;
};
serverRoutes: {
selectedRoute: ServerRouteInfo | null;
view: 'tree' | 'list';
inputDefaults: Record<string, ServerRouteInput[]>;
sendFrom: 'app' | 'devtools';
};
serverTasks: {
enabled: boolean;
selectedTask: ServerTaskInfo | null;
view: 'tree' | 'list';
inputDefaults: Record<string, ServerRouteInput[]>;
};
assets: {
view: 'grid' | 'list';
};
}
interface AnalyzeBuildMeta extends NuxtAnalyzeMeta {
features: {
bundleClient: boolean;
bundleNitro: boolean;
viteInspect: boolean;
};
size: {
clientBundle?: number;
nitroBundle?: number;
};
}
interface AnalyzeBuildsInfo {
isBuilding: boolean;
builds: AnalyzeBuildMeta[];
}
interface TerminalBase {
id: string;
name: string;
description?: string;
icon?: string;
}
type TerminalAction = 'restart' | 'terminate' | 'clear' | 'remove';
interface SubprocessOptions extends Options {
command: string;
args?: string[];
}
interface TerminalInfo extends TerminalBase {
/**
* Whether the terminal can be restarted
*/
restartable?: boolean;
/**
* Whether the terminal can be terminated
*/
terminatable?: boolean;
/**
* Whether the terminal is terminated
*/
isTerminated?: boolean;
/**
* Content buffer
*/
buffer?: string;
}
interface TerminalState extends TerminalInfo {
/**
* User action to restart the terminal, when not provided, this action will be disabled
*/
onActionRestart?: () => Promise<void> | void;
/**
* User action to terminate the terminal, when not provided, this action will be disabled
*/
onActionTerminate?: () => Promise<void> | void;
}
interface WizardFunctions {
enablePages: (nuxt: any) => Promise<void>;
}
type WizardActions = keyof WizardFunctions;
type GetWizardArgs<T extends WizardActions> = WizardFunctions[T] extends (nuxt: any, ...args: infer A) => any ? A : never;
interface ServerFunctions {
getServerConfig: () => NuxtOptions;
getServerDebugContext: () => Promise<ServerDebugContext | undefined>;
getServerData: (token: string) => Promise<NuxtServerData>;
getServerRuntimeConfig: () => Record<string, any>;
getModuleOptions: () => ModuleOptions;
getComponents: () => Component[];
getComponentsRelationships: () => Promise<ComponentRelationship[]>;
getAutoImports: () => AutoImportsWithMetadata;
getServerPages: () => NuxtPage[];
getCustomTabs: () => ModuleCustomTab[];
getServerHooks: () => HookInfo[];
getServerLayouts: () => NuxtLayout[];
getStaticAssets: () => Promise<AssetInfo[]>;
getServerRoutes: () => ServerRouteInfo[];
getServerTasks: () => ScannedNitroTasks | null;
getServerApp: () => NuxtApp | undefined;
getOptions: <T extends keyof NuxtDevToolsOptions>(tab: T) => Promise<NuxtDevToolsOptions[T]>;
updateOptions: <T extends keyof NuxtDevToolsOptions>(tab: T, settings: Partial<NuxtDevToolsOptions[T]>) => Promise<void>;
clearOptions: () => Promise<void>;
checkForUpdateFor: (name: string) => Promise<PackageUpdateInfo | undefined>;
getNpmCommand: (command: NpmCommandType, packageName: string, options?: NpmCommandOptions) => Promise<string[] | undefined>;
runNpmCommand: (token: string, command: NpmCommandType, packageName: string, options?: NpmCommandOptions) => Promise<{
processId: string;
} | undefined>;
getTerminals: () => TerminalInfo[];
getTerminalDetail: (token: string, id: string) => Promise<TerminalInfo | undefined>;
runTerminalAction: (token: string, id: string, action: TerminalAction) => Promise<boolean>;
getStorageMounts: () => Promise<StorageMounts>;
getStorageKeys: (base?: string) => Promise<string[]>;
getStorageItem: (token: string, key: string) => Promise<StorageValue>;
setStorageItem: (token: string, key: string, value: StorageValue) => Promise<void>;
removeStorageItem: (token: string, key: string) => Promise<void>;
getAnalyzeBuildInfo: () => Promise<AnalyzeBuildsInfo>;
generateAnalyzeBuildName: () => Promise<string>;
startAnalyzeBuild: (token: string, name: string) => Promise<string>;
clearAnalyzeBuilds: (token: string, names?: string[]) => Promise<void>;
getImageMeta: (token: string, filepath: string) => Promise<ImageMeta | undefined>;
getTextAssetContent: (token: string, filepath: string, limit?: number) => Promise<string | undefined>;
writeStaticAssets: (token: string, file: AssetEntry[], folder: string) => Promise<string[]>;
deleteStaticAsset: (token: string, filepath: string) => Promise<void>;
renameStaticAsset: (token: string, oldPath: string, newPath: string) => Promise<void>;
telemetryEvent: (payload: object, immediate?: boolean) => void;
customTabAction: (name: string, action: number) => Promise<boolean>;
runWizard: <T extends WizardActions>(token: string, name: T, ...args: GetWizardArgs<T>) => Promise<void>;
openInEditor: (filepath: string) => Promise<boolean>;
restartNuxt: (token: string, hard?: boolean) => Promise<void>;
installNuxtModule: (token: string, name: string, dry?: boolean) => Promise<InstallModuleReturn>;
uninstallNuxtModule: (token: string, name: string, dry?: boolean) => Promise<InstallModuleReturn>;
enableTimeline: (dry: boolean) => Promise<[string, string]>;
requestForAuth: (info?: string, origin?: string) => Promise<void>;
verifyAuthToken: (token: string) => Promise<boolean>;
}
interface ClientFunctions {
refresh: (event: ClientUpdateEvent) => void;
callHook: (hook: string, ...args: any[]) => Promise<void>;
navigateTo: (path: string) => void;
onTerminalData: (_: {
id: string;
data: string;
}) => void;
onTerminalExit: (_: {
id: string;
code?: number;
}) => void;
}
interface NuxtServerData {
nuxt: NuxtOptions;
nitro?: Nitro['options'];
vite: {
server?: ResolvedConfig;
client?: ResolvedConfig;
};
}
type ClientUpdateEvent = keyof ServerFunctions;
/**
* @internal
*/
interface NuxtDevtoolsServerContext {
nuxt: Nuxt;
options: ModuleOptions;
rpc: BirpcGroup<ClientFunctions, ServerFunctions>;
/**
* Hook to open file in editor
*/
openInEditorHooks: ((filepath: string) => boolean | void | Promise<boolean | void>)[];
/**
* Invalidate client cache for a function and ask for re-fetching
*/
refresh: (event: keyof ServerFunctions) => void;
/**
* Ensure dev auth token is valid, throw if not
*/
ensureDevAuthToken: (token: string) => Promise<void>;
extendServerRpc: <ClientFunctions = Record<string, never>, ServerFunctions = Record<string, never>>(name: string, functions: ServerFunctions) => BirpcGroup<ClientFunctions, ServerFunctions>;
}
interface NuxtDevtoolsInfo {
version: string;
packagePath: string;
isGlobalInstall: boolean;
}
interface InstallModuleReturn {
configOriginal: string;
configGenerated: string;
commands: string[];
processId: string;
}
type ServerDebugModuleMutationRecord = (Omit<NuxtDebugModuleMutationRecord, 'module'> & {
name: string;
});
interface ServerDebugContext {
moduleMutationRecords: ServerDebugModuleMutationRecord[];
}
declare module '@nuxt/schema' {
interface NuxtHooks {
/**
* Called before devtools starts. Useful to detect if devtools is enabled.
*/
'devtools:before': () => void;
/**
* Called after devtools is initialized.
*/
'devtools:initialized': (info: NuxtDevtoolsInfo) => void;
/**
* Hooks to extend devtools tabs.
*/
'devtools:customTabs': (tabs: ModuleCustomTab[]) => void;
/**
* Retrigger update for custom tabs, `devtools:customTabs` will be called again.
*/
'devtools:customTabs:refresh': () => void;
/**
* Register a terminal.
*/
'devtools:terminal:register': (terminal: TerminalState) => void;
/**
* Write to a terminal.
*
* Returns true if terminal is found.
*/
'devtools:terminal:write': (_: {
id: string;
data: string;
}) => void;
/**
* Remove a terminal from devtools.
*
* Returns true if terminal is found and deleted.
*/
'devtools:terminal:remove': (_: {
id: string;
}) => void;
/**
* Mark a terminal as terminated.
*/
'devtools:terminal:exit': (_: {
id: string;
code?: number;
}) => void;
}
}
declare module '@nuxt/schema' {
/**
* Runtime Hooks
*/
interface RuntimeNuxtHooks {
/**
* On terminal data.
*/
'devtools:terminal:data': (payload: {
id: string;
data: string;
}) => void;
}
}
export type { CodeServerType as $, AnalyzeBuildMeta as A, BasicModuleInfo as B, ClientFunctions as C, ModuleCompatibility as D, ModuleStats as E, CompatibilityStatus as F, ModuleType as G, HookInfo as H, ImageMeta as I, MaintainerInfo as J, GitHubContributor as K, LoadingTimeMetric as L, ModuleCustomTab as M, NuxtDevtoolsInfo as N, VueInspectorData as O, PluginMetric as P, AssetType as Q, RouteInfo as R, SubprocessOptions as S, TerminalState as T, AssetInfo as U, VueInspectorClient as V, AssetEntry as W, CodeSnippet as X, ComponentRelationship as Y, ComponentWithRelationships as Z, CodeServerOptions as _, ServerFunctions as a, ModuleOptions as a0, ModuleGlobalOptions as a1, VSCodeIntegrationOptions as a2, VSCodeTunnelOptions as a3, NuxtDevToolsOptions as a4, NuxtServerData as a5, ClientUpdateEvent as a6, NuxtDevtoolsServerContext as a7, InstallModuleReturn as a8, ServerDebugModuleMutationRecord as a9, ServerDebugContext as aa, TerminalBase as ab, TerminalAction as ac, TerminalInfo as ad, WizardFunctions as ae, WizardActions as af, GetWizardArgs as ag, AnalyzeBuildsInfo as b, TabCategory as c, ModuleLaunchView as d, ModuleIframeView as e, ModuleVNodeView as f, ModuleLaunchAction as g, ModuleView as h, ModuleIframeTabLazyOptions as i, ModuleBuiltinTab as j, ModuleTabInfo as k, CategorizedTabs as l, PackageUpdateInfo as m, PackageManagerName as n, NpmCommandType as o, NpmCommandOptions as p, AutoImportsWithMetadata as q, ServerRouteInfo as r, ServerRouteInputType as s, ServerRouteInput as t, Payload as u, ServerTaskInfo as v, ScannedNitroTasks as w, PluginInfoWithMetic as x, InstalledModuleInfo as y, ModuleStaticInfo as z };

View file

@ -0,0 +1,2 @@
'use strict';

View file

@ -0,0 +1,181 @@
import { H as HookInfo, P as PluginMetric, L as LoadingTimeMetric, a as ServerFunctions, C as ClientFunctions } from './shared/devtools-kit.r2McQC71.cjs';
export { A as AnalyzeBuildMeta, b as AnalyzeBuildsInfo, W as AssetEntry, U as AssetInfo, Q as AssetType, q as AutoImportsWithMetadata, B as BasicModuleInfo, l as CategorizedTabs, a6 as ClientUpdateEvent, _ as CodeServerOptions, $ as CodeServerType, X as CodeSnippet, F as CompatibilityStatus, Y as ComponentRelationship, Z as ComponentWithRelationships, ag as GetWizardArgs, K as GitHubContributor, I as ImageMeta, a8 as InstallModuleReturn, y as InstalledModuleInfo, J as MaintainerInfo, j as ModuleBuiltinTab, D as ModuleCompatibility, M as ModuleCustomTab, a1 as ModuleGlobalOptions, i as ModuleIframeTabLazyOptions, e as ModuleIframeView, g as ModuleLaunchAction, d as ModuleLaunchView, a0 as ModuleOptions, z as ModuleStaticInfo, E as ModuleStats, k as ModuleTabInfo, G as ModuleType, f as ModuleVNodeView, h as ModuleView, p as NpmCommandOptions, o as NpmCommandType, a4 as NuxtDevToolsOptions, N as NuxtDevtoolsInfo, a7 as NuxtDevtoolsServerContext, a5 as NuxtServerData, n as PackageManagerName, m as PackageUpdateInfo, u as Payload, x as PluginInfoWithMetic, R as RouteInfo, w as ScannedNitroTasks, aa as ServerDebugContext, a9 as ServerDebugModuleMutationRecord, r as ServerRouteInfo, t as ServerRouteInput, s as ServerRouteInputType, v as ServerTaskInfo, S as SubprocessOptions, c as TabCategory, ac as TerminalAction, ab as TerminalBase, ad as TerminalInfo, T as TerminalState, a2 as VSCodeIntegrationOptions, a3 as VSCodeTunnelOptions, V as VueInspectorClient, O as VueInspectorData, af as WizardActions, ae as WizardFunctions } from './shared/devtools-kit.r2McQC71.cjs';
import { BirpcReturn } from 'birpc';
import { Hookable } from 'hookable';
import { NuxtApp } from 'nuxt/app';
import { AppConfig } from 'nuxt/schema';
import { $Fetch } from 'ofetch';
import { BuiltinLanguage } from 'shiki';
import { Ref } from 'vue';
import { StackFrame } from 'error-stack-parser-es';
import 'unimport';
import 'vue-router';
import 'nitropack';
import 'unstorage';
import 'vite';
import '@nuxt/schema';
import 'execa';
interface TimelineEventFunction {
type: 'function';
start: number;
end?: number;
name: string;
args?: any[];
result?: any;
stacktrace?: StackFrame[];
isPromise?: boolean;
}
interface TimelineServerState {
timeSsrStart?: number;
}
interface TimelineEventRoute {
type: 'route';
start: number;
end?: number;
from: string;
to: string;
}
interface TimelineOptions {
enabled: boolean;
stacktrace: boolean;
arguments: boolean;
}
type TimelineEvent = TimelineEventFunction | TimelineEventRoute;
interface TimelineMetrics {
events: TimelineEvent[];
nonLiteralSymbol: symbol;
options: TimelineOptions;
}
interface TimelineEventNormalized<T> {
event: T;
segment: TimelineEventsSegment;
relativeStart: number;
relativeWidth: number;
layer: number;
}
interface TimelineEventsSegment {
start: number;
end: number;
events: TimelineEvent[];
functions: TimelineEventNormalized<TimelineEventFunction>[];
route?: TimelineEventNormalized<TimelineEventRoute>;
duration: number;
previousGap?: number;
}
interface DevToolsFrameState {
width: number;
height: number;
top: number;
left: number;
open: boolean;
route: string;
position: 'left' | 'right' | 'bottom' | 'top';
closeOnOutsideClick: boolean;
minimizePanelInactive: number;
}
interface NuxtDevtoolsClientHooks {
/**
* When the DevTools navigates, used for persisting the current tab
*/
'devtools:navigate': (path: string) => void;
/**
* Event emitted when the component inspector is clicked
*/
'host:inspector:click': (path: string) => void;
/**
* Event to close the component inspector
*/
'host:inspector:close': () => void;
/**
* Triggers reactivity manually, since Vue won't be reactive across frames)
*/
'host:update:reactivity': () => void;
/**
* Host action to control the DevTools navigation
*/
'host:action:navigate': (path: string) => void;
/**
* Host action to reload the DevTools
*/
'host:action:reload': () => void;
}
/**
* Host client from the App
*/
interface NuxtDevtoolsHostClient {
nuxt: NuxtApp;
hooks: Hookable<NuxtDevtoolsClientHooks>;
getIframe: () => HTMLIFrameElement | undefined;
inspector?: {
enable: () => void;
disable: () => void;
toggle: () => void;
isEnabled: Ref<boolean>;
isAvailable: Ref<boolean>;
};
devtools: {
close: () => void;
open: () => void;
toggle: () => void;
reload: () => void;
navigate: (path: string) => void;
/**
* Popup the DevTools frame into Picture-in-Picture mode
*
* Requires Chrome 111 with experimental flag enabled.
*
* Function is undefined when not supported.
*
* @see https://developer.chrome.com/docs/web-platform/document-picture-in-picture/
*/
popup?: () => any;
};
app: {
reload: () => void;
navigate: (path: string, hard?: boolean) => void;
appConfig: AppConfig;
colorMode: Ref<'dark' | 'light'>;
frameState: Ref<DevToolsFrameState>;
$fetch: $Fetch;
};
metrics: {
clientHooks: () => HookInfo[];
clientPlugins: () => PluginMetric[] | undefined;
clientTimeline: () => TimelineMetrics | undefined;
loading: () => LoadingTimeMetric;
};
/**
* A counter to trigger reactivity updates
*/
revision: Ref<number>;
/**
* Update client
* @internal
*/
syncClient: () => NuxtDevtoolsHostClient;
}
interface CodeHighlightOptions {
grammarContextCode?: string;
}
interface NuxtDevtoolsClient {
rpc: BirpcReturn<ServerFunctions, ClientFunctions>;
renderCodeHighlight: (code: string, lang?: BuiltinLanguage, options?: CodeHighlightOptions) => {
code: string;
supported: boolean;
};
renderMarkdown: (markdown: string) => string;
colorMode: string;
extendClientRpc: <ServerFunctions = Record<string, never>, ClientFunctions = Record<string, never>>(name: string, functions: ClientFunctions) => BirpcReturn<ServerFunctions, ClientFunctions>;
}
interface NuxtDevtoolsIframeClient {
host: NuxtDevtoolsHostClient;
devtools: NuxtDevtoolsClient;
}
interface NuxtDevtoolsGlobal {
setClient: (client: NuxtDevtoolsHostClient) => void;
}
export { ClientFunctions, HookInfo, LoadingTimeMetric, PluginMetric, ServerFunctions };
export type { CodeHighlightOptions, DevToolsFrameState, NuxtDevtoolsClient, NuxtDevtoolsClientHooks, NuxtDevtoolsGlobal, NuxtDevtoolsHostClient, NuxtDevtoolsIframeClient, TimelineEvent, TimelineEventFunction, TimelineEventNormalized, TimelineEventRoute, TimelineEventsSegment, TimelineMetrics, TimelineOptions, TimelineServerState };

View file

@ -0,0 +1,181 @@
import { H as HookInfo, P as PluginMetric, L as LoadingTimeMetric, a as ServerFunctions, C as ClientFunctions } from './shared/devtools-kit.r2McQC71.mjs';
export { A as AnalyzeBuildMeta, b as AnalyzeBuildsInfo, W as AssetEntry, U as AssetInfo, Q as AssetType, q as AutoImportsWithMetadata, B as BasicModuleInfo, l as CategorizedTabs, a6 as ClientUpdateEvent, _ as CodeServerOptions, $ as CodeServerType, X as CodeSnippet, F as CompatibilityStatus, Y as ComponentRelationship, Z as ComponentWithRelationships, ag as GetWizardArgs, K as GitHubContributor, I as ImageMeta, a8 as InstallModuleReturn, y as InstalledModuleInfo, J as MaintainerInfo, j as ModuleBuiltinTab, D as ModuleCompatibility, M as ModuleCustomTab, a1 as ModuleGlobalOptions, i as ModuleIframeTabLazyOptions, e as ModuleIframeView, g as ModuleLaunchAction, d as ModuleLaunchView, a0 as ModuleOptions, z as ModuleStaticInfo, E as ModuleStats, k as ModuleTabInfo, G as ModuleType, f as ModuleVNodeView, h as ModuleView, p as NpmCommandOptions, o as NpmCommandType, a4 as NuxtDevToolsOptions, N as NuxtDevtoolsInfo, a7 as NuxtDevtoolsServerContext, a5 as NuxtServerData, n as PackageManagerName, m as PackageUpdateInfo, u as Payload, x as PluginInfoWithMetic, R as RouteInfo, w as ScannedNitroTasks, aa as ServerDebugContext, a9 as ServerDebugModuleMutationRecord, r as ServerRouteInfo, t as ServerRouteInput, s as ServerRouteInputType, v as ServerTaskInfo, S as SubprocessOptions, c as TabCategory, ac as TerminalAction, ab as TerminalBase, ad as TerminalInfo, T as TerminalState, a2 as VSCodeIntegrationOptions, a3 as VSCodeTunnelOptions, V as VueInspectorClient, O as VueInspectorData, af as WizardActions, ae as WizardFunctions } from './shared/devtools-kit.r2McQC71.mjs';
import { BirpcReturn } from 'birpc';
import { Hookable } from 'hookable';
import { NuxtApp } from 'nuxt/app';
import { AppConfig } from 'nuxt/schema';
import { $Fetch } from 'ofetch';
import { BuiltinLanguage } from 'shiki';
import { Ref } from 'vue';
import { StackFrame } from 'error-stack-parser-es';
import 'unimport';
import 'vue-router';
import 'nitropack';
import 'unstorage';
import 'vite';
import '@nuxt/schema';
import 'execa';
interface TimelineEventFunction {
type: 'function';
start: number;
end?: number;
name: string;
args?: any[];
result?: any;
stacktrace?: StackFrame[];
isPromise?: boolean;
}
interface TimelineServerState {
timeSsrStart?: number;
}
interface TimelineEventRoute {
type: 'route';
start: number;
end?: number;
from: string;
to: string;
}
interface TimelineOptions {
enabled: boolean;
stacktrace: boolean;
arguments: boolean;
}
type TimelineEvent = TimelineEventFunction | TimelineEventRoute;
interface TimelineMetrics {
events: TimelineEvent[];
nonLiteralSymbol: symbol;
options: TimelineOptions;
}
interface TimelineEventNormalized<T> {
event: T;
segment: TimelineEventsSegment;
relativeStart: number;
relativeWidth: number;
layer: number;
}
interface TimelineEventsSegment {
start: number;
end: number;
events: TimelineEvent[];
functions: TimelineEventNormalized<TimelineEventFunction>[];
route?: TimelineEventNormalized<TimelineEventRoute>;
duration: number;
previousGap?: number;
}
interface DevToolsFrameState {
width: number;
height: number;
top: number;
left: number;
open: boolean;
route: string;
position: 'left' | 'right' | 'bottom' | 'top';
closeOnOutsideClick: boolean;
minimizePanelInactive: number;
}
interface NuxtDevtoolsClientHooks {
/**
* When the DevTools navigates, used for persisting the current tab
*/
'devtools:navigate': (path: string) => void;
/**
* Event emitted when the component inspector is clicked
*/
'host:inspector:click': (path: string) => void;
/**
* Event to close the component inspector
*/
'host:inspector:close': () => void;
/**
* Triggers reactivity manually, since Vue won't be reactive across frames)
*/
'host:update:reactivity': () => void;
/**
* Host action to control the DevTools navigation
*/
'host:action:navigate': (path: string) => void;
/**
* Host action to reload the DevTools
*/
'host:action:reload': () => void;
}
/**
* Host client from the App
*/
interface NuxtDevtoolsHostClient {
nuxt: NuxtApp;
hooks: Hookable<NuxtDevtoolsClientHooks>;
getIframe: () => HTMLIFrameElement | undefined;
inspector?: {
enable: () => void;
disable: () => void;
toggle: () => void;
isEnabled: Ref<boolean>;
isAvailable: Ref<boolean>;
};
devtools: {
close: () => void;
open: () => void;
toggle: () => void;
reload: () => void;
navigate: (path: string) => void;
/**
* Popup the DevTools frame into Picture-in-Picture mode
*
* Requires Chrome 111 with experimental flag enabled.
*
* Function is undefined when not supported.
*
* @see https://developer.chrome.com/docs/web-platform/document-picture-in-picture/
*/
popup?: () => any;
};
app: {
reload: () => void;
navigate: (path: string, hard?: boolean) => void;
appConfig: AppConfig;
colorMode: Ref<'dark' | 'light'>;
frameState: Ref<DevToolsFrameState>;
$fetch: $Fetch;
};
metrics: {
clientHooks: () => HookInfo[];
clientPlugins: () => PluginMetric[] | undefined;
clientTimeline: () => TimelineMetrics | undefined;
loading: () => LoadingTimeMetric;
};
/**
* A counter to trigger reactivity updates
*/
revision: Ref<number>;
/**
* Update client
* @internal
*/
syncClient: () => NuxtDevtoolsHostClient;
}
interface CodeHighlightOptions {
grammarContextCode?: string;
}
interface NuxtDevtoolsClient {
rpc: BirpcReturn<ServerFunctions, ClientFunctions>;
renderCodeHighlight: (code: string, lang?: BuiltinLanguage, options?: CodeHighlightOptions) => {
code: string;
supported: boolean;
};
renderMarkdown: (markdown: string) => string;
colorMode: string;
extendClientRpc: <ServerFunctions = Record<string, never>, ClientFunctions = Record<string, never>>(name: string, functions: ClientFunctions) => BirpcReturn<ServerFunctions, ClientFunctions>;
}
interface NuxtDevtoolsIframeClient {
host: NuxtDevtoolsHostClient;
devtools: NuxtDevtoolsClient;
}
interface NuxtDevtoolsGlobal {
setClient: (client: NuxtDevtoolsHostClient) => void;
}
export { ClientFunctions, HookInfo, LoadingTimeMetric, PluginMetric, ServerFunctions };
export type { CodeHighlightOptions, DevToolsFrameState, NuxtDevtoolsClient, NuxtDevtoolsClientHooks, NuxtDevtoolsGlobal, NuxtDevtoolsHostClient, NuxtDevtoolsIframeClient, TimelineEvent, TimelineEventFunction, TimelineEventNormalized, TimelineEventRoute, TimelineEventsSegment, TimelineMetrics, TimelineOptions, TimelineServerState };

View file

@ -0,0 +1,181 @@
import { H as HookInfo, P as PluginMetric, L as LoadingTimeMetric, a as ServerFunctions, C as ClientFunctions } from './shared/devtools-kit.r2McQC71.js';
export { A as AnalyzeBuildMeta, b as AnalyzeBuildsInfo, W as AssetEntry, U as AssetInfo, Q as AssetType, q as AutoImportsWithMetadata, B as BasicModuleInfo, l as CategorizedTabs, a6 as ClientUpdateEvent, _ as CodeServerOptions, $ as CodeServerType, X as CodeSnippet, F as CompatibilityStatus, Y as ComponentRelationship, Z as ComponentWithRelationships, ag as GetWizardArgs, K as GitHubContributor, I as ImageMeta, a8 as InstallModuleReturn, y as InstalledModuleInfo, J as MaintainerInfo, j as ModuleBuiltinTab, D as ModuleCompatibility, M as ModuleCustomTab, a1 as ModuleGlobalOptions, i as ModuleIframeTabLazyOptions, e as ModuleIframeView, g as ModuleLaunchAction, d as ModuleLaunchView, a0 as ModuleOptions, z as ModuleStaticInfo, E as ModuleStats, k as ModuleTabInfo, G as ModuleType, f as ModuleVNodeView, h as ModuleView, p as NpmCommandOptions, o as NpmCommandType, a4 as NuxtDevToolsOptions, N as NuxtDevtoolsInfo, a7 as NuxtDevtoolsServerContext, a5 as NuxtServerData, n as PackageManagerName, m as PackageUpdateInfo, u as Payload, x as PluginInfoWithMetic, R as RouteInfo, w as ScannedNitroTasks, aa as ServerDebugContext, a9 as ServerDebugModuleMutationRecord, r as ServerRouteInfo, t as ServerRouteInput, s as ServerRouteInputType, v as ServerTaskInfo, S as SubprocessOptions, c as TabCategory, ac as TerminalAction, ab as TerminalBase, ad as TerminalInfo, T as TerminalState, a2 as VSCodeIntegrationOptions, a3 as VSCodeTunnelOptions, V as VueInspectorClient, O as VueInspectorData, af as WizardActions, ae as WizardFunctions } from './shared/devtools-kit.r2McQC71.js';
import { BirpcReturn } from 'birpc';
import { Hookable } from 'hookable';
import { NuxtApp } from 'nuxt/app';
import { AppConfig } from 'nuxt/schema';
import { $Fetch } from 'ofetch';
import { BuiltinLanguage } from 'shiki';
import { Ref } from 'vue';
import { StackFrame } from 'error-stack-parser-es';
import 'unimport';
import 'vue-router';
import 'nitropack';
import 'unstorage';
import 'vite';
import '@nuxt/schema';
import 'execa';
interface TimelineEventFunction {
type: 'function';
start: number;
end?: number;
name: string;
args?: any[];
result?: any;
stacktrace?: StackFrame[];
isPromise?: boolean;
}
interface TimelineServerState {
timeSsrStart?: number;
}
interface TimelineEventRoute {
type: 'route';
start: number;
end?: number;
from: string;
to: string;
}
interface TimelineOptions {
enabled: boolean;
stacktrace: boolean;
arguments: boolean;
}
type TimelineEvent = TimelineEventFunction | TimelineEventRoute;
interface TimelineMetrics {
events: TimelineEvent[];
nonLiteralSymbol: symbol;
options: TimelineOptions;
}
interface TimelineEventNormalized<T> {
event: T;
segment: TimelineEventsSegment;
relativeStart: number;
relativeWidth: number;
layer: number;
}
interface TimelineEventsSegment {
start: number;
end: number;
events: TimelineEvent[];
functions: TimelineEventNormalized<TimelineEventFunction>[];
route?: TimelineEventNormalized<TimelineEventRoute>;
duration: number;
previousGap?: number;
}
interface DevToolsFrameState {
width: number;
height: number;
top: number;
left: number;
open: boolean;
route: string;
position: 'left' | 'right' | 'bottom' | 'top';
closeOnOutsideClick: boolean;
minimizePanelInactive: number;
}
interface NuxtDevtoolsClientHooks {
/**
* When the DevTools navigates, used for persisting the current tab
*/
'devtools:navigate': (path: string) => void;
/**
* Event emitted when the component inspector is clicked
*/
'host:inspector:click': (path: string) => void;
/**
* Event to close the component inspector
*/
'host:inspector:close': () => void;
/**
* Triggers reactivity manually, since Vue won't be reactive across frames)
*/
'host:update:reactivity': () => void;
/**
* Host action to control the DevTools navigation
*/
'host:action:navigate': (path: string) => void;
/**
* Host action to reload the DevTools
*/
'host:action:reload': () => void;
}
/**
* Host client from the App
*/
interface NuxtDevtoolsHostClient {
nuxt: NuxtApp;
hooks: Hookable<NuxtDevtoolsClientHooks>;
getIframe: () => HTMLIFrameElement | undefined;
inspector?: {
enable: () => void;
disable: () => void;
toggle: () => void;
isEnabled: Ref<boolean>;
isAvailable: Ref<boolean>;
};
devtools: {
close: () => void;
open: () => void;
toggle: () => void;
reload: () => void;
navigate: (path: string) => void;
/**
* Popup the DevTools frame into Picture-in-Picture mode
*
* Requires Chrome 111 with experimental flag enabled.
*
* Function is undefined when not supported.
*
* @see https://developer.chrome.com/docs/web-platform/document-picture-in-picture/
*/
popup?: () => any;
};
app: {
reload: () => void;
navigate: (path: string, hard?: boolean) => void;
appConfig: AppConfig;
colorMode: Ref<'dark' | 'light'>;
frameState: Ref<DevToolsFrameState>;
$fetch: $Fetch;
};
metrics: {
clientHooks: () => HookInfo[];
clientPlugins: () => PluginMetric[] | undefined;
clientTimeline: () => TimelineMetrics | undefined;
loading: () => LoadingTimeMetric;
};
/**
* A counter to trigger reactivity updates
*/
revision: Ref<number>;
/**
* Update client
* @internal
*/
syncClient: () => NuxtDevtoolsHostClient;
}
interface CodeHighlightOptions {
grammarContextCode?: string;
}
interface NuxtDevtoolsClient {
rpc: BirpcReturn<ServerFunctions, ClientFunctions>;
renderCodeHighlight: (code: string, lang?: BuiltinLanguage, options?: CodeHighlightOptions) => {
code: string;
supported: boolean;
};
renderMarkdown: (markdown: string) => string;
colorMode: string;
extendClientRpc: <ServerFunctions = Record<string, never>, ClientFunctions = Record<string, never>>(name: string, functions: ClientFunctions) => BirpcReturn<ServerFunctions, ClientFunctions>;
}
interface NuxtDevtoolsIframeClient {
host: NuxtDevtoolsHostClient;
devtools: NuxtDevtoolsClient;
}
interface NuxtDevtoolsGlobal {
setClient: (client: NuxtDevtoolsHostClient) => void;
}
export { ClientFunctions, HookInfo, LoadingTimeMetric, PluginMetric, ServerFunctions };
export type { CodeHighlightOptions, DevToolsFrameState, NuxtDevtoolsClient, NuxtDevtoolsClientHooks, NuxtDevtoolsGlobal, NuxtDevtoolsHostClient, NuxtDevtoolsIframeClient, TimelineEvent, TimelineEventFunction, TimelineEventNormalized, TimelineEventRoute, TimelineEventsSegment, TimelineMetrics, TimelineOptions, TimelineServerState };

View file

@ -0,0 +1 @@

View file

@ -0,0 +1 @@
export * from './dist/runtime/host-client'

View file

@ -0,0 +1 @@
export * from './dist/runtime/host-client.mjs'

View file

@ -0,0 +1 @@
export * from './dist/runtime/iframe-client'

View file

@ -0,0 +1 @@
export * from './dist/runtime/iframe-client.mjs'

View file

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2016-present - Nuxt Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,117 @@
[![Nuxt banner](https://github.com/nuxt/nuxt/blob/main/.github/assets/banner.svg)](https://nuxt.com)
# Nuxt
<p>
<a href="https://www.npmjs.com/package/nuxt"><img src="https://img.shields.io/npm/v/nuxt.svg?style=flat&colorA=18181B&colorB=28CF8D" alt="Version"></a>
<a href="https://www.npmjs.com/package/nuxt"><img src="https://img.shields.io/npm/dm/nuxt.svg?style=flat&colorA=18181B&colorB=28CF8D" alt="Downloads"></a>
<a href="https://github.com/nuxt/nuxt/blob/main/LICENSE"><img src="https://img.shields.io/github/license/nuxt/nuxt.svg?style=flat&colorA=18181B&colorB=28CF8D" alt="License"></a>
<a href="https://nuxt.com"><img src="https://img.shields.io/badge/Nuxt%20Docs-18181B?logo=nuxt" alt="Website"></a>
<a href="https://chat.nuxt.dev"><img src="https://img.shields.io/badge/Nuxt%20Discord-18181B?logo=discord" alt="Discord"></a>
<a href="https://securityscorecards.dev/"><img src="https://api.securityscorecards.dev/projects/github.com/nuxt/nuxt/badge" alt="Nuxt openssf scorecard score"></a>
</p>
Nuxt is a free and open-source framework with an intuitive and extendable way to create type-safe, performant and production-grade full-stack web applications and websites with Vue.js.
It provides a number of features that make it easy to build fast, SEO-friendly, and scalable web applications, including:
- Server-side rendering, static site generation, hybrid rendering and edge-side rendering
- Automatic routing with code-splitting and pre-fetching
- Data fetching and state management
- Search engine optimization and defining meta tags
- Auto imports of components, composables and utils
- TypeScript with zero configuration
- Go full-stack with our server/ directory
- Extensible with [200+ modules](https://nuxt.com/modules)
- Deployment to a variety of [hosting platforms](https://nuxt.com/deploy)
- ...[and much more](https://nuxt.com) 🚀
### Table of Contents
- 🚀 [Getting Started](#getting-started)
- 💻 [ Vue Development](#vue-development)
- 📖 [Documentation](#documentation)
- 🧩 [Modules](#modules)
- ❤️ [Contribute](#contribute)
- 🏠 [Local Development](#local-development)
- 🛟 [Professional Support](#professional-support)
- 🔗 [Follow Us](#follow-us)
- ⚖️ [License](#license)
---
## <a name="getting-started">🚀 Getting Started</a>
Use the following command to create a new starter project. This will create a starter project with all the necessary files and dependencies:
```bash
npm create nuxt@latest <my-project>
```
> [!TIP]
> Discover also [nuxt.new](https://nuxt.new): Open a Nuxt starter on CodeSandbox, StackBlitz or locally to get up and running in a few seconds.
## <a name="vue-development">💻 Vue Development</a>
Simple, intuitive and powerful, Nuxt lets you write Vue components in a way that makes sense. Every repetitive task is automated, so you can focus on writing your full-stack Vue application with confidence.
Example of an `app.vue`:
```vue
<script setup lang="ts">
useSeoMeta({
title: 'Meet Nuxt',
description: 'The Intuitive Vue Framework.',
})
</script>
<template>
<div id="app">
<AppHeader />
<NuxtPage />
<AppFooter />
</div>
</template>
<style scoped>
#app {
background-color: #020420;
color: #00DC82;
}
</style>
```
## <a name="documentation">📖 Documentation</a>
We highly recommend you take a look at the [Nuxt documentation](https://nuxt.com/docs) to level up. Its a great resource for learning more about the framework. It covers everything from getting started to advanced topics.
## <a name="modules">🧩 Modules</a>
Discover our [list of modules](https://nuxt.com/modules) to supercharge your Nuxt project, created by the Nuxt team and community.
## <a name="contribute">❤️ Contribute</a>
We invite you to contribute and help improve Nuxt 💚
Here are a few ways you can get involved:
- **Reporting Bugs:** If you come across any bugs or issues, please check out the [reporting bugs guide](https://nuxt.com/docs/4.x/community/reporting-bugs) to learn how to submit a bug report.
- **Suggestions:** Have ideas to enhance Nuxt? We'd love to hear them! Check out the [contribution guide](https://nuxt.com/docs/4.x/community/contribution) to share your suggestions.
- **Questions:** If you have questions or need assistance, the [getting help guide](https://nuxt.com/docs/4.x/community/getting-help) provides resources to help you out.
## <a name="local-development">🏠 Local Development</a>
Follow the docs to [Set Up Your Local Development Environment](https://nuxt.com/docs/4.x/community/framework-contribution#setup) to contribute to the framework and documentation.
## <a name="professional-support">🛟 Professional Support</a>
- Technical audit & consulting: [Nuxt Experts](https://nuxt.com/enterprise/support)
- Custom development & more: [Nuxt Agencies Partners](https://nuxt.com/enterprise/agencies)
## <a name="follow-us">🔗 Follow Us</a>
<p valign="center">
<a href="https://go.nuxt.com/discord"><img width="20px" src="https://github.com/nuxt/nuxt/blob/main/.github/assets/discord.svg" alt="Discord"></a>&nbsp;&nbsp;<a href="https://go.nuxt.com/x"><img width="20px" src="https://github.com/nuxt/nuxt/blob/main/.github/assets/twitter.svg" alt="Twitter"></a>&nbsp;&nbsp;<a href="https://go.nuxt.com/github"><img width="20px" src="https://github.com/nuxt/nuxt/blob/main/.github/assets/github.svg" alt="GitHub"></a>&nbsp;&nbsp;<a href="https://go.nuxt.com/bluesky"><img width="20px" src="https://github.com/nuxt/nuxt/blob/main/.github/assets/bluesky.svg" alt="Bluesky"></a>
</p>
## <a name="license">⚖️ License</a>
[MIT](https://github.com/nuxt/nuxt/blob/main/LICENSE)

View file

@ -0,0 +1,552 @@
import * as _nuxt_schema from '@nuxt/schema';
import { ModuleOptions, ModuleDefinition, NuxtModule, NuxtConfig, Nuxt, ModuleMeta, NuxtOptions, SchemaDefinition, NuxtAppConfig, NuxtCompatibility, NuxtCompatibilityIssues, Component, ComponentsDir, NuxtTemplate, NuxtMiddleware, NuxtHooks, NuxtPlugin, NuxtPluginTemplate, ResolvedNuxtTemplate, NuxtServerTemplate, NuxtTypeTemplate } from '@nuxt/schema';
import { LoadConfigOptions } from 'c12';
import { Import, InlinePreset } from 'unimport';
import { WebpackPluginInstance, Configuration } from 'webpack';
import { RspackPluginInstance } from '@rspack/core';
import { Plugin, UserConfig } from 'vite';
import * as unctx from 'unctx';
import { NitroRouteConfig, NitroEventHandler, NitroDevEventHandler, Nitro } from 'nitropack/types';
import { GlobOptions } from 'tinyglobby';
import * as consola from 'consola';
import { ConsolaOptions } from 'consola';
/**
* Define a Nuxt module, automatically merging defaults with user provided options, installing
* any hooks that are provided, and calling an optional setup function for full control.
*/
declare function defineNuxtModule<TOptions extends ModuleOptions>(definition: ModuleDefinition<TOptions, Partial<TOptions>, false> | NuxtModule<TOptions, Partial<TOptions>, false>): NuxtModule<TOptions, TOptions, false>;
declare function defineNuxtModule<TOptions extends ModuleOptions>(): {
with: <TOptionsDefaults extends Partial<TOptions>>(definition: ModuleDefinition<TOptions, TOptionsDefaults, true> | NuxtModule<TOptions, TOptionsDefaults, true>) => NuxtModule<TOptions, TOptionsDefaults, true>;
};
type ModuleToInstall = string | NuxtModule<ModuleOptions, Partial<ModuleOptions>, false>;
/**
* Installs a set of modules on a Nuxt instance.
* @internal
*/
declare function installModules(modulesToInstall: Map<ModuleToInstall, Record<string, any>>, resolvedModulePaths: Set<string>, nuxt?: Nuxt): Promise<void>;
/**
* Installs a module on a Nuxt instance.
* @deprecated Use module dependencies.
*/
declare function installModule<T extends string | NuxtModule, Config extends Extract<NonNullable<NuxtConfig['modules']>[number], [T, any]>>(moduleToInstall: T, inlineOptions?: [Config] extends [never] ? any : Config[1], nuxt?: Nuxt): Promise<void>;
declare function resolveModuleWithOptions(definition: NuxtModule<any> | string | false | undefined | null | [(NuxtModule | string)?, Record<string, any>?], nuxt: Nuxt): {
resolvedPath?: string;
module: string | NuxtModule<any>;
options: Record<string, any>;
} | undefined;
declare function loadNuxtModuleInstance(nuxtModule: string | NuxtModule, nuxt?: Nuxt): Promise<{
nuxtModule: NuxtModule<any>;
buildTimeModuleMeta: ModuleMeta;
resolvedModulePath?: string;
}>;
declare function getDirectory(p: string): string;
declare const normalizeModuleTranspilePath: (p: string) => string;
/**
* Check if a Nuxt module is installed by name.
*
* This will check both the installed modules and the modules to be installed. Note
* that it cannot detect if a module is _going to be_ installed programmatically by another module.
*/
declare function hasNuxtModule(moduleName: string, nuxt?: Nuxt): boolean;
/**
* Checks if a Nuxt Module is compatible with a given semver version.
*/
declare function hasNuxtModuleCompatibility(module: string | NuxtModule, semverVersion: string, nuxt?: Nuxt): Promise<boolean>;
/**
* Get the version of a Nuxt module.
*
* Scans installed modules for the version, if it's not found it will attempt to load the module instance and get the version from there.
*/
declare function getNuxtModuleVersion(module: string | NuxtModule, nuxt?: Nuxt | any): Promise<string | false>;
interface LoadNuxtConfigOptions extends Omit<LoadConfigOptions<NuxtConfig>, 'overrides'> {
overrides?: Exclude<LoadConfigOptions<NuxtConfig>['overrides'], Promise<any> | Function>;
}
declare function loadNuxtConfig(opts: LoadNuxtConfigOptions): Promise<NuxtOptions>;
declare function extendNuxtSchema(def: SchemaDefinition | (() => SchemaDefinition)): void;
interface LoadNuxtOptions extends LoadNuxtConfigOptions {
/** Load nuxt with development mode */
dev?: boolean;
/** Use lazy initialization of nuxt if set to false */
ready?: boolean;
}
declare function loadNuxt(opts: LoadNuxtOptions): Promise<Nuxt>;
declare function buildNuxt(nuxt: Nuxt): Promise<any>;
interface LayerDirectories {
/** Nuxt rootDir (`/` by default) */
readonly root: string;
/** Nitro source directory (`/server` by default) */
readonly server: string;
/** Local modules directory (`/modules` by default) */
readonly modules: string;
/** Shared directory (`/shared` by default) */
readonly shared: string;
/** Public directory (`/public` by default) */
readonly public: string;
/** Nuxt srcDir (`/app/` by default) */
readonly app: string;
/** Layouts directory (`/app/layouts` by default) */
readonly appLayouts: string;
/** Middleware directory (`/app/middleware` by default) */
readonly appMiddleware: string;
/** Pages directory (`/app/pages` by default) */
readonly appPages: string;
/** Plugins directory (`/app/plugins` by default) */
readonly appPlugins: string;
}
/**
* Get the resolved directory paths for all layers in a Nuxt application.
*
* Returns an array of LayerDirectories objects, ordered by layer priority:
* - The first layer is the user/project layer (highest priority)
* - Earlier layers override later layers in the array
* - Base layers appear last in the array (lowest priority)
*
* @param nuxt - The Nuxt instance to get layers from. Defaults to the current Nuxt context.
* @returns Array of LayerDirectories objects, ordered by priority (user layer first)
*/
declare function getLayerDirectories(nuxt?: _nuxt_schema.Nuxt): LayerDirectories[];
declare function setGlobalHead(head: NuxtAppConfig['head']): void;
declare function addImports(imports: Import | Import[]): void;
declare function addImportsDir(dirs: string | string[], opts?: {
prepend?: boolean;
}): void;
declare function addImportsSources(presets: InlinePreset | InlinePreset[]): void;
/**
* Access 'resolved' Nuxt runtime configuration, with values updated from environment.
*
* This mirrors the runtime behavior of Nitro.
*/
declare function useRuntimeConfig(): Record<string, any>;
/**
* Update Nuxt runtime configuration.
*/
declare function updateRuntimeConfig(runtimeConfig: Record<string, unknown>): void | Promise<void>;
interface ExtendConfigOptions {
/**
* Install plugin on dev
* @default true
*/
dev?: boolean;
/**
* Install plugin on build
* @default true
*/
build?: boolean;
/**
* Install plugin on server side
* @default true
*/
server?: boolean;
/**
* Install plugin on client side
* @default true
*/
client?: boolean;
/**
* Prepends the plugin to the array with `unshift()` instead of `push()`.
*/
prepend?: boolean;
}
interface ExtendWebpackConfigOptions extends ExtendConfigOptions {
}
interface ExtendViteConfigOptions extends Omit<ExtendConfigOptions, 'server' | 'client'> {
/**
* Extend server Vite configuration
* @default true
* @deprecated calling \`extendViteConfig\` with only server/client environment is deprecated.
* Nuxt 5+ uses the Vite Environment API which shares a configuration between environments.
* You can likely use a Vite plugin to achieve the same result.
*/
server?: boolean;
/**
* Extend client Vite configuration
* @default true
* @deprecated calling \`extendViteConfig\` with only server/client environment is deprecated.
* Nuxt 5+ uses the Vite Environment API which shares a configuration between environments.
* You can likely use a Vite plugin to achieve the same result.
*/
client?: boolean;
}
/**
* Extend webpack config
*
* The fallback function might be called multiple times
* when applying to both client and server builds.
*/
declare const extendWebpackConfig: (fn: ((config: Configuration) => void), options?: ExtendWebpackConfigOptions) => void;
/**
* Extend rspack config
*
* The fallback function might be called multiple times
* when applying to both client and server builds.
*/
declare const extendRspackConfig: (fn: ((config: Configuration) => void), options?: ExtendWebpackConfigOptions) => void;
/**
* Extend Vite config
*/
declare function extendViteConfig(fn: ((config: UserConfig) => void), options?: ExtendViteConfigOptions): (() => void) | undefined;
/**
* Append webpack plugin to the config.
*/
declare function addWebpackPlugin(pluginOrGetter: WebpackPluginInstance | WebpackPluginInstance[] | (() => WebpackPluginInstance | WebpackPluginInstance[]), options?: ExtendWebpackConfigOptions): void;
/**
* Append rspack plugin to the config.
*/
declare function addRspackPlugin(pluginOrGetter: RspackPluginInstance | RspackPluginInstance[] | (() => RspackPluginInstance | RspackPluginInstance[]), options?: ExtendWebpackConfigOptions): void;
/**
* Append Vite plugin to the config.
*/
declare function addVitePlugin(pluginOrGetter: Plugin | Plugin[] | (() => Plugin | Plugin[]), options?: ExtendConfigOptions): void;
interface AddBuildPluginFactory {
vite?: () => Plugin | Plugin[];
webpack?: () => WebpackPluginInstance | WebpackPluginInstance[];
rspack?: () => RspackPluginInstance | RspackPluginInstance[];
}
declare function addBuildPlugin(pluginFactory: AddBuildPluginFactory, options?: ExtendConfigOptions): void;
declare function normalizeSemanticVersion(version: string): string;
/**
* Check version constraints and return incompatibility issues as an array
*/
declare function checkNuxtCompatibility(constraints: NuxtCompatibility, nuxt?: Nuxt): Promise<NuxtCompatibilityIssues>;
/**
* Check version constraints and throw a detailed error if has any, otherwise returns true
*/
declare function assertNuxtCompatibility(constraints: NuxtCompatibility, nuxt?: Nuxt): Promise<true>;
/**
* Check version constraints and return true if passed, otherwise returns false
*/
declare function hasNuxtCompatibility(constraints: NuxtCompatibility, nuxt?: Nuxt): Promise<boolean>;
/**
* Check if current Nuxt instance is of specified major version
*/
declare function isNuxtMajorVersion(majorVersion: 2 | 3 | 4, nuxt?: Nuxt): boolean;
/**
* @deprecated Use `isNuxtMajorVersion(2, nuxt)` instead. This may be removed in \@nuxt/kit v5 or a future major version.
*/
declare function isNuxt2(nuxt?: Nuxt): boolean;
/**
* @deprecated Use `isNuxtMajorVersion(3, nuxt)` instead. This may be removed in \@nuxt/kit v5 or a future major version.
*/
declare function isNuxt3(nuxt?: Nuxt): boolean;
/**
* Get nuxt version
*/
declare function getNuxtVersion(nuxt?: Nuxt | any): string;
/**
* Register a directory to be scanned for components and imported only when used.
*/
declare function addComponentsDir(dir: ComponentsDir, opts?: {
prepend?: boolean;
}): void;
type AddComponentOptions = {
name: string;
filePath: string;
} & Partial<Exclude<Component, 'shortPath' | 'async' | 'level' | 'import' | 'asyncImport'>>;
/**
* This utility takes a file path or npm package that is scanned for named exports, which are get added automatically
*/
declare function addComponentExports(opts: Omit<AddComponentOptions, 'name'> & {
prefix?: string;
}): void;
/**
* Register a component by its name and filePath.
*/
declare function addComponent(opts: AddComponentOptions): void;
/**
* Direct access to the Nuxt global context - see https://github.com/unjs/unctx.
* @deprecated Use `getNuxtCtx` instead
*/
declare const nuxtCtx: unctx.UseContext<Nuxt>;
/** Direct access to the Nuxt context with asyncLocalStorage - see https://github.com/unjs/unctx. */
declare const getNuxtCtx: () => Nuxt | null;
/**
* Get access to Nuxt instance.
*
* Throws an error if Nuxt instance is unavailable.
* @example
* ```js
* const nuxt = useNuxt()
* ```
*/
declare function useNuxt(): Nuxt;
/**
* Get access to Nuxt instance.
*
* Returns null if Nuxt instance is unavailable.
* @example
* ```js
* const nuxt = tryUseNuxt()
* if (nuxt) {
* // Do something
* }
* ```
*/
declare function tryUseNuxt(): Nuxt | null;
declare function runWithNuxtContext<T extends (...args: any[]) => any>(nuxt: Nuxt, fn: T): ReturnType<T>;
declare function createIsIgnored(nuxt?: _nuxt_schema.Nuxt | null): (pathname: string, stats?: unknown) => boolean;
/**
* Return a filter function to filter an array of paths
*/
declare function isIgnored(pathname: string, _stats?: unknown, nuxt?: _nuxt_schema.Nuxt | null): boolean;
declare function resolveIgnorePatterns(relativePath?: string): string[];
declare function addLayout(template: NuxtTemplate | string, name?: string): void;
declare function extendPages(cb: NuxtHooks['pages:extend']): void;
interface ExtendRouteRulesOptions {
/**
* Override route rule config
* @default false
*/
override?: boolean;
}
declare function extendRouteRules(route: string, rule: NitroRouteConfig, options?: ExtendRouteRulesOptions): void;
interface AddRouteMiddlewareOptions {
/**
* Override existing middleware with the same name, if it exists
* @default false
*/
override?: boolean;
/**
* Prepend middleware to the list
* @default false
*/
prepend?: boolean;
}
declare function addRouteMiddleware(input: NuxtMiddleware | NuxtMiddleware[], options?: AddRouteMiddlewareOptions): void;
declare function normalizePlugin(plugin: NuxtPlugin | string): NuxtPlugin;
/**
* Registers a nuxt plugin and to the plugins array.
*
* Note: You can use mode or .client and .server modifiers with fileName option
* to use plugin only in client or server side.
*
* Note: By default plugin is prepended to the plugins array. You can use second argument to append (push) instead.
* @example
* ```js
* import { createResolver } from '@nuxt/kit'
* const resolver = createResolver(import.meta.url)
*
* addPlugin({
* src: resolver.resolve('templates/foo.js'),
* filename: 'foo.server.js' // [optional] only include in server bundle
* })
* ```
*/
interface AddPluginOptions {
append?: boolean;
}
declare function addPlugin(_plugin: NuxtPlugin | string, opts?: AddPluginOptions): NuxtPlugin;
/**
* Adds a template and registers as a nuxt plugin.
*/
declare function addPluginTemplate(plugin: NuxtPluginTemplate | string, opts?: AddPluginOptions): NuxtPlugin;
interface ResolvePathOptions {
/** Base for resolving paths from. Default is Nuxt rootDir. */
cwd?: string;
/** An object of aliases. Default is Nuxt configured aliases. */
alias?: Record<string, string>;
/**
* The file extensions to try.
* Default is Nuxt configured extensions.
*
* Isn't considered when `type` is set to `'dir'`.
*/
extensions?: string[];
/**
* Whether to resolve files that exist in the Nuxt VFS (for example, as a Nuxt template).
* @default false
*/
virtual?: boolean;
/**
* Whether to fallback to the original path if the resolved path does not exist instead of returning the normalized input path.
* @default false
*/
fallbackToOriginal?: boolean;
/**
* The type of the path to be resolved.
* @default 'file'
*/
type?: PathType;
}
/**
* Resolve the full path to a file or a directory (based on the provided type), respecting Nuxt alias and extensions options.
*
* If a path cannot be resolved, normalized input will be returned unless the `fallbackToOriginal` option is set to `true`,
* in which case the original input path will be returned.
*/
declare function resolvePath(path: string, opts?: ResolvePathOptions): Promise<string>;
/**
* Try to resolve first existing file in paths
*/
declare function findPath(paths: string | string[], opts?: ResolvePathOptions, pathType?: PathType): Promise<string | null>;
/**
* Resolve path aliases respecting Nuxt alias options
*/
declare function resolveAlias(path: string, alias?: Record<string, string>): string;
interface Resolver {
resolve(...path: string[]): string;
resolvePath(path: string, opts?: ResolvePathOptions): Promise<string>;
}
/**
* Create a relative resolver
*/
declare function createResolver(base: string | URL): Resolver;
declare function resolveNuxtModule(base: string, paths: string[]): Promise<string[]>;
type PathType = 'file' | 'dir';
/**
* Resolve absolute file paths in the provided directory with respect to `.nuxtignore` and return them sorted.
* @param path path to the directory to resolve files in
* @param pattern glob pattern or an array of glob patterns to match files
* @param opts options for globbing
* @param opts.followSymbolicLinks whether to follow symbolic links, default is `true`
* @param opts.ignore additional glob patterns to ignore
* @returns sorted array of absolute file paths
*/
declare function resolveFiles(path: string, pattern: string | string[], opts?: {
followSymbolicLinks?: boolean;
ignore?: GlobOptions['ignore'];
}): Promise<string[]>;
/**
* Adds a nitro server handler
*
*/
declare function addServerHandler(handler: NitroEventHandler): void;
/**
* Adds a nitro server handler for development-only
*
*/
declare function addDevServerHandler(handler: NitroDevEventHandler): void;
/**
* Adds a Nitro plugin
*/
declare function addServerPlugin(plugin: string): void;
/**
* Adds routes to be prerendered
*/
declare function addPrerenderRoutes(routes: string | string[]): void;
/**
* Access to the Nitro instance
*
* **Note:** You can call `useNitro()` only after `ready` hook.
*
* **Note:** Changes to the Nitro instance configuration are not applied.
* @example
*
* ```ts
* nuxt.hook('ready', () => {
* console.log(useNitro())
* })
* ```
*/
declare function useNitro(): Nitro;
/**
* Add server imports to be auto-imported by Nitro
*/
declare function addServerImports(imports: Import | Import[]): void;
/**
* Add directories to be scanned for auto-imports by Nitro
*/
declare function addServerImportsDir(dirs: string | string[], opts?: {
prepend?: boolean;
}): void;
/**
* Add directories to be scanned by Nitro. It will check for subdirectories,
* which will be registered just like the `~/server` folder is.
*/
declare function addServerScanDir(dirs: string | string[], opts?: {
prepend?: boolean;
}): void;
/**
* Renders given template during build into the virtual file system (and optionally to disk in the project `buildDir`)
*/
declare function addTemplate<T>(_template: NuxtTemplate<T> | string): ResolvedNuxtTemplate<T>;
/**
* Adds a virtual file that can be used within the Nuxt Nitro server build.
*/
declare function addServerTemplate(template: NuxtServerTemplate): NuxtServerTemplate;
/**
* Renders given types during build to disk in the project `buildDir`
* and register them as types.
*
* You can pass a second context object to specify in which context the type should be added.
*
* If no context object is passed, then it will only be added to the nuxt context.
*/
declare function addTypeTemplate<T>(_template: NuxtTypeTemplate<T>, context?: {
nitro?: boolean;
nuxt?: boolean;
node?: boolean;
shared?: boolean;
}): ResolvedNuxtTemplate<T>;
/**
* Normalize a nuxt template object
*/
declare function normalizeTemplate<T>(template: NuxtTemplate<T> | string, buildDir?: string): ResolvedNuxtTemplate<T>;
/**
* Trigger rebuilding Nuxt templates
*
* You can pass a filter within the options to selectively regenerate a subset of templates.
*/
declare function updateTemplates(options?: {
filter?: (template: ResolvedNuxtTemplate<any>) => boolean;
}): Promise<any>;
declare function writeTypes(nuxt: Nuxt): Promise<void>;
declare const logger: consola.ConsolaInstance;
declare function useLogger(tag?: string, options?: Partial<ConsolaOptions>): consola.ConsolaInstance;
interface ResolveModuleOptions {
/** @deprecated use `url` with URLs pointing at a file - never a directory */
paths?: string | string[];
url?: URL | URL[];
/** @default ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'] */
extensions?: string[];
}
declare function directoryToURL(dir: string): URL;
/**
* Resolve a module from a given root path using an algorithm patterned on
* the upcoming `import.meta.resolve`. It returns a file URL
*
* @internal
*/
declare function tryResolveModule(id: string, url: URL | URL[]): Promise<string | undefined>;
/** @deprecated pass URLs pointing at files */
declare function tryResolveModule(id: string, url: string | string[]): Promise<string | undefined>;
declare function resolveModule(id: string, options?: ResolveModuleOptions): string;
interface ImportModuleOptions extends ResolveModuleOptions {
/** Automatically de-default the result of requiring the module. */
interopDefault?: boolean;
}
declare function importModule<T = unknown>(id: string, opts?: ImportModuleOptions): Promise<T>;
declare function tryImportModule<T = unknown>(id: string, opts?: ImportModuleOptions): Promise<T | undefined> | undefined;
/**
* @deprecated Please use `importModule` instead.
*/
declare function requireModule<T = unknown>(id: string, opts?: ImportModuleOptions): T;
/**
* @deprecated Please use `tryImportModule` instead.
*/
declare function tryRequireModule<T = unknown>(id: string, opts?: ImportModuleOptions): T | undefined;
export { addBuildPlugin, addComponent, addComponentExports, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addPrerenderRoutes, addRouteMiddleware, addRspackPlugin, addServerHandler, addServerImports, addServerImportsDir, addServerPlugin, addServerScanDir, addServerTemplate, addTemplate, addTypeTemplate, addVitePlugin, addWebpackPlugin, assertNuxtCompatibility, buildNuxt, checkNuxtCompatibility, createIsIgnored, createResolver, defineNuxtModule, directoryToURL, extendNuxtSchema, extendPages, extendRouteRules, extendRspackConfig, extendViteConfig, extendWebpackConfig, findPath, getDirectory, getLayerDirectories, getNuxtCtx, getNuxtModuleVersion, getNuxtVersion, hasNuxtCompatibility, hasNuxtModule, hasNuxtModuleCompatibility, importModule, installModule, installModules, isIgnored, isNuxt2, isNuxt3, isNuxtMajorVersion, loadNuxt, loadNuxtConfig, loadNuxtModuleInstance, logger, normalizeModuleTranspilePath, normalizePlugin, normalizeSemanticVersion, normalizeTemplate, nuxtCtx, requireModule, resolveAlias, resolveFiles, resolveIgnorePatterns, resolveModule, resolveModuleWithOptions, resolveNuxtModule, resolvePath, runWithNuxtContext, setGlobalHead, tryImportModule, tryRequireModule, tryResolveModule, tryUseNuxt, updateRuntimeConfig, updateTemplates, useLogger, useNitro, useNuxt, useRuntimeConfig, writeTypes };
export type { AddComponentOptions, AddPluginOptions, AddRouteMiddlewareOptions, ExtendConfigOptions, ExtendRouteRulesOptions, ExtendViteConfigOptions, ExtendWebpackConfigOptions, ImportModuleOptions, LayerDirectories, LoadNuxtConfigOptions, LoadNuxtOptions, ResolveModuleOptions, ResolvePathOptions, Resolver };

View file

@ -0,0 +1,552 @@
import * as _nuxt_schema from '@nuxt/schema';
import { ModuleOptions, ModuleDefinition, NuxtModule, NuxtConfig, Nuxt, ModuleMeta, NuxtOptions, SchemaDefinition, NuxtAppConfig, NuxtCompatibility, NuxtCompatibilityIssues, Component, ComponentsDir, NuxtTemplate, NuxtMiddleware, NuxtHooks, NuxtPlugin, NuxtPluginTemplate, ResolvedNuxtTemplate, NuxtServerTemplate, NuxtTypeTemplate } from '@nuxt/schema';
import { LoadConfigOptions } from 'c12';
import { Import, InlinePreset } from 'unimport';
import { WebpackPluginInstance, Configuration } from 'webpack';
import { RspackPluginInstance } from '@rspack/core';
import { Plugin, UserConfig } from 'vite';
import * as unctx from 'unctx';
import { NitroRouteConfig, NitroEventHandler, NitroDevEventHandler, Nitro } from 'nitropack/types';
import { GlobOptions } from 'tinyglobby';
import * as consola from 'consola';
import { ConsolaOptions } from 'consola';
/**
* Define a Nuxt module, automatically merging defaults with user provided options, installing
* any hooks that are provided, and calling an optional setup function for full control.
*/
declare function defineNuxtModule<TOptions extends ModuleOptions>(definition: ModuleDefinition<TOptions, Partial<TOptions>, false> | NuxtModule<TOptions, Partial<TOptions>, false>): NuxtModule<TOptions, TOptions, false>;
declare function defineNuxtModule<TOptions extends ModuleOptions>(): {
with: <TOptionsDefaults extends Partial<TOptions>>(definition: ModuleDefinition<TOptions, TOptionsDefaults, true> | NuxtModule<TOptions, TOptionsDefaults, true>) => NuxtModule<TOptions, TOptionsDefaults, true>;
};
type ModuleToInstall = string | NuxtModule<ModuleOptions, Partial<ModuleOptions>, false>;
/**
* Installs a set of modules on a Nuxt instance.
* @internal
*/
declare function installModules(modulesToInstall: Map<ModuleToInstall, Record<string, any>>, resolvedModulePaths: Set<string>, nuxt?: Nuxt): Promise<void>;
/**
* Installs a module on a Nuxt instance.
* @deprecated Use module dependencies.
*/
declare function installModule<T extends string | NuxtModule, Config extends Extract<NonNullable<NuxtConfig['modules']>[number], [T, any]>>(moduleToInstall: T, inlineOptions?: [Config] extends [never] ? any : Config[1], nuxt?: Nuxt): Promise<void>;
declare function resolveModuleWithOptions(definition: NuxtModule<any> | string | false | undefined | null | [(NuxtModule | string)?, Record<string, any>?], nuxt: Nuxt): {
resolvedPath?: string;
module: string | NuxtModule<any>;
options: Record<string, any>;
} | undefined;
declare function loadNuxtModuleInstance(nuxtModule: string | NuxtModule, nuxt?: Nuxt): Promise<{
nuxtModule: NuxtModule<any>;
buildTimeModuleMeta: ModuleMeta;
resolvedModulePath?: string;
}>;
declare function getDirectory(p: string): string;
declare const normalizeModuleTranspilePath: (p: string) => string;
/**
* Check if a Nuxt module is installed by name.
*
* This will check both the installed modules and the modules to be installed. Note
* that it cannot detect if a module is _going to be_ installed programmatically by another module.
*/
declare function hasNuxtModule(moduleName: string, nuxt?: Nuxt): boolean;
/**
* Checks if a Nuxt Module is compatible with a given semver version.
*/
declare function hasNuxtModuleCompatibility(module: string | NuxtModule, semverVersion: string, nuxt?: Nuxt): Promise<boolean>;
/**
* Get the version of a Nuxt module.
*
* Scans installed modules for the version, if it's not found it will attempt to load the module instance and get the version from there.
*/
declare function getNuxtModuleVersion(module: string | NuxtModule, nuxt?: Nuxt | any): Promise<string | false>;
interface LoadNuxtConfigOptions extends Omit<LoadConfigOptions<NuxtConfig>, 'overrides'> {
overrides?: Exclude<LoadConfigOptions<NuxtConfig>['overrides'], Promise<any> | Function>;
}
declare function loadNuxtConfig(opts: LoadNuxtConfigOptions): Promise<NuxtOptions>;
declare function extendNuxtSchema(def: SchemaDefinition | (() => SchemaDefinition)): void;
interface LoadNuxtOptions extends LoadNuxtConfigOptions {
/** Load nuxt with development mode */
dev?: boolean;
/** Use lazy initialization of nuxt if set to false */
ready?: boolean;
}
declare function loadNuxt(opts: LoadNuxtOptions): Promise<Nuxt>;
declare function buildNuxt(nuxt: Nuxt): Promise<any>;
interface LayerDirectories {
/** Nuxt rootDir (`/` by default) */
readonly root: string;
/** Nitro source directory (`/server` by default) */
readonly server: string;
/** Local modules directory (`/modules` by default) */
readonly modules: string;
/** Shared directory (`/shared` by default) */
readonly shared: string;
/** Public directory (`/public` by default) */
readonly public: string;
/** Nuxt srcDir (`/app/` by default) */
readonly app: string;
/** Layouts directory (`/app/layouts` by default) */
readonly appLayouts: string;
/** Middleware directory (`/app/middleware` by default) */
readonly appMiddleware: string;
/** Pages directory (`/app/pages` by default) */
readonly appPages: string;
/** Plugins directory (`/app/plugins` by default) */
readonly appPlugins: string;
}
/**
* Get the resolved directory paths for all layers in a Nuxt application.
*
* Returns an array of LayerDirectories objects, ordered by layer priority:
* - The first layer is the user/project layer (highest priority)
* - Earlier layers override later layers in the array
* - Base layers appear last in the array (lowest priority)
*
* @param nuxt - The Nuxt instance to get layers from. Defaults to the current Nuxt context.
* @returns Array of LayerDirectories objects, ordered by priority (user layer first)
*/
declare function getLayerDirectories(nuxt?: _nuxt_schema.Nuxt): LayerDirectories[];
declare function setGlobalHead(head: NuxtAppConfig['head']): void;
declare function addImports(imports: Import | Import[]): void;
declare function addImportsDir(dirs: string | string[], opts?: {
prepend?: boolean;
}): void;
declare function addImportsSources(presets: InlinePreset | InlinePreset[]): void;
/**
* Access 'resolved' Nuxt runtime configuration, with values updated from environment.
*
* This mirrors the runtime behavior of Nitro.
*/
declare function useRuntimeConfig(): Record<string, any>;
/**
* Update Nuxt runtime configuration.
*/
declare function updateRuntimeConfig(runtimeConfig: Record<string, unknown>): void | Promise<void>;
interface ExtendConfigOptions {
/**
* Install plugin on dev
* @default true
*/
dev?: boolean;
/**
* Install plugin on build
* @default true
*/
build?: boolean;
/**
* Install plugin on server side
* @default true
*/
server?: boolean;
/**
* Install plugin on client side
* @default true
*/
client?: boolean;
/**
* Prepends the plugin to the array with `unshift()` instead of `push()`.
*/
prepend?: boolean;
}
interface ExtendWebpackConfigOptions extends ExtendConfigOptions {
}
interface ExtendViteConfigOptions extends Omit<ExtendConfigOptions, 'server' | 'client'> {
/**
* Extend server Vite configuration
* @default true
* @deprecated calling \`extendViteConfig\` with only server/client environment is deprecated.
* Nuxt 5+ uses the Vite Environment API which shares a configuration between environments.
* You can likely use a Vite plugin to achieve the same result.
*/
server?: boolean;
/**
* Extend client Vite configuration
* @default true
* @deprecated calling \`extendViteConfig\` with only server/client environment is deprecated.
* Nuxt 5+ uses the Vite Environment API which shares a configuration between environments.
* You can likely use a Vite plugin to achieve the same result.
*/
client?: boolean;
}
/**
* Extend webpack config
*
* The fallback function might be called multiple times
* when applying to both client and server builds.
*/
declare const extendWebpackConfig: (fn: ((config: Configuration) => void), options?: ExtendWebpackConfigOptions) => void;
/**
* Extend rspack config
*
* The fallback function might be called multiple times
* when applying to both client and server builds.
*/
declare const extendRspackConfig: (fn: ((config: Configuration) => void), options?: ExtendWebpackConfigOptions) => void;
/**
* Extend Vite config
*/
declare function extendViteConfig(fn: ((config: UserConfig) => void), options?: ExtendViteConfigOptions): (() => void) | undefined;
/**
* Append webpack plugin to the config.
*/
declare function addWebpackPlugin(pluginOrGetter: WebpackPluginInstance | WebpackPluginInstance[] | (() => WebpackPluginInstance | WebpackPluginInstance[]), options?: ExtendWebpackConfigOptions): void;
/**
* Append rspack plugin to the config.
*/
declare function addRspackPlugin(pluginOrGetter: RspackPluginInstance | RspackPluginInstance[] | (() => RspackPluginInstance | RspackPluginInstance[]), options?: ExtendWebpackConfigOptions): void;
/**
* Append Vite plugin to the config.
*/
declare function addVitePlugin(pluginOrGetter: Plugin | Plugin[] | (() => Plugin | Plugin[]), options?: ExtendConfigOptions): void;
interface AddBuildPluginFactory {
vite?: () => Plugin | Plugin[];
webpack?: () => WebpackPluginInstance | WebpackPluginInstance[];
rspack?: () => RspackPluginInstance | RspackPluginInstance[];
}
declare function addBuildPlugin(pluginFactory: AddBuildPluginFactory, options?: ExtendConfigOptions): void;
declare function normalizeSemanticVersion(version: string): string;
/**
* Check version constraints and return incompatibility issues as an array
*/
declare function checkNuxtCompatibility(constraints: NuxtCompatibility, nuxt?: Nuxt): Promise<NuxtCompatibilityIssues>;
/**
* Check version constraints and throw a detailed error if has any, otherwise returns true
*/
declare function assertNuxtCompatibility(constraints: NuxtCompatibility, nuxt?: Nuxt): Promise<true>;
/**
* Check version constraints and return true if passed, otherwise returns false
*/
declare function hasNuxtCompatibility(constraints: NuxtCompatibility, nuxt?: Nuxt): Promise<boolean>;
/**
* Check if current Nuxt instance is of specified major version
*/
declare function isNuxtMajorVersion(majorVersion: 2 | 3 | 4, nuxt?: Nuxt): boolean;
/**
* @deprecated Use `isNuxtMajorVersion(2, nuxt)` instead. This may be removed in \@nuxt/kit v5 or a future major version.
*/
declare function isNuxt2(nuxt?: Nuxt): boolean;
/**
* @deprecated Use `isNuxtMajorVersion(3, nuxt)` instead. This may be removed in \@nuxt/kit v5 or a future major version.
*/
declare function isNuxt3(nuxt?: Nuxt): boolean;
/**
* Get nuxt version
*/
declare function getNuxtVersion(nuxt?: Nuxt | any): string;
/**
* Register a directory to be scanned for components and imported only when used.
*/
declare function addComponentsDir(dir: ComponentsDir, opts?: {
prepend?: boolean;
}): void;
type AddComponentOptions = {
name: string;
filePath: string;
} & Partial<Exclude<Component, 'shortPath' | 'async' | 'level' | 'import' | 'asyncImport'>>;
/**
* This utility takes a file path or npm package that is scanned for named exports, which are get added automatically
*/
declare function addComponentExports(opts: Omit<AddComponentOptions, 'name'> & {
prefix?: string;
}): void;
/**
* Register a component by its name and filePath.
*/
declare function addComponent(opts: AddComponentOptions): void;
/**
* Direct access to the Nuxt global context - see https://github.com/unjs/unctx.
* @deprecated Use `getNuxtCtx` instead
*/
declare const nuxtCtx: unctx.UseContext<Nuxt>;
/** Direct access to the Nuxt context with asyncLocalStorage - see https://github.com/unjs/unctx. */
declare const getNuxtCtx: () => Nuxt | null;
/**
* Get access to Nuxt instance.
*
* Throws an error if Nuxt instance is unavailable.
* @example
* ```js
* const nuxt = useNuxt()
* ```
*/
declare function useNuxt(): Nuxt;
/**
* Get access to Nuxt instance.
*
* Returns null if Nuxt instance is unavailable.
* @example
* ```js
* const nuxt = tryUseNuxt()
* if (nuxt) {
* // Do something
* }
* ```
*/
declare function tryUseNuxt(): Nuxt | null;
declare function runWithNuxtContext<T extends (...args: any[]) => any>(nuxt: Nuxt, fn: T): ReturnType<T>;
declare function createIsIgnored(nuxt?: _nuxt_schema.Nuxt | null): (pathname: string, stats?: unknown) => boolean;
/**
* Return a filter function to filter an array of paths
*/
declare function isIgnored(pathname: string, _stats?: unknown, nuxt?: _nuxt_schema.Nuxt | null): boolean;
declare function resolveIgnorePatterns(relativePath?: string): string[];
declare function addLayout(template: NuxtTemplate | string, name?: string): void;
declare function extendPages(cb: NuxtHooks['pages:extend']): void;
interface ExtendRouteRulesOptions {
/**
* Override route rule config
* @default false
*/
override?: boolean;
}
declare function extendRouteRules(route: string, rule: NitroRouteConfig, options?: ExtendRouteRulesOptions): void;
interface AddRouteMiddlewareOptions {
/**
* Override existing middleware with the same name, if it exists
* @default false
*/
override?: boolean;
/**
* Prepend middleware to the list
* @default false
*/
prepend?: boolean;
}
declare function addRouteMiddleware(input: NuxtMiddleware | NuxtMiddleware[], options?: AddRouteMiddlewareOptions): void;
declare function normalizePlugin(plugin: NuxtPlugin | string): NuxtPlugin;
/**
* Registers a nuxt plugin and to the plugins array.
*
* Note: You can use mode or .client and .server modifiers with fileName option
* to use plugin only in client or server side.
*
* Note: By default plugin is prepended to the plugins array. You can use second argument to append (push) instead.
* @example
* ```js
* import { createResolver } from '@nuxt/kit'
* const resolver = createResolver(import.meta.url)
*
* addPlugin({
* src: resolver.resolve('templates/foo.js'),
* filename: 'foo.server.js' // [optional] only include in server bundle
* })
* ```
*/
interface AddPluginOptions {
append?: boolean;
}
declare function addPlugin(_plugin: NuxtPlugin | string, opts?: AddPluginOptions): NuxtPlugin;
/**
* Adds a template and registers as a nuxt plugin.
*/
declare function addPluginTemplate(plugin: NuxtPluginTemplate | string, opts?: AddPluginOptions): NuxtPlugin;
interface ResolvePathOptions {
/** Base for resolving paths from. Default is Nuxt rootDir. */
cwd?: string;
/** An object of aliases. Default is Nuxt configured aliases. */
alias?: Record<string, string>;
/**
* The file extensions to try.
* Default is Nuxt configured extensions.
*
* Isn't considered when `type` is set to `'dir'`.
*/
extensions?: string[];
/**
* Whether to resolve files that exist in the Nuxt VFS (for example, as a Nuxt template).
* @default false
*/
virtual?: boolean;
/**
* Whether to fallback to the original path if the resolved path does not exist instead of returning the normalized input path.
* @default false
*/
fallbackToOriginal?: boolean;
/**
* The type of the path to be resolved.
* @default 'file'
*/
type?: PathType;
}
/**
* Resolve the full path to a file or a directory (based on the provided type), respecting Nuxt alias and extensions options.
*
* If a path cannot be resolved, normalized input will be returned unless the `fallbackToOriginal` option is set to `true`,
* in which case the original input path will be returned.
*/
declare function resolvePath(path: string, opts?: ResolvePathOptions): Promise<string>;
/**
* Try to resolve first existing file in paths
*/
declare function findPath(paths: string | string[], opts?: ResolvePathOptions, pathType?: PathType): Promise<string | null>;
/**
* Resolve path aliases respecting Nuxt alias options
*/
declare function resolveAlias(path: string, alias?: Record<string, string>): string;
interface Resolver {
resolve(...path: string[]): string;
resolvePath(path: string, opts?: ResolvePathOptions): Promise<string>;
}
/**
* Create a relative resolver
*/
declare function createResolver(base: string | URL): Resolver;
declare function resolveNuxtModule(base: string, paths: string[]): Promise<string[]>;
type PathType = 'file' | 'dir';
/**
* Resolve absolute file paths in the provided directory with respect to `.nuxtignore` and return them sorted.
* @param path path to the directory to resolve files in
* @param pattern glob pattern or an array of glob patterns to match files
* @param opts options for globbing
* @param opts.followSymbolicLinks whether to follow symbolic links, default is `true`
* @param opts.ignore additional glob patterns to ignore
* @returns sorted array of absolute file paths
*/
declare function resolveFiles(path: string, pattern: string | string[], opts?: {
followSymbolicLinks?: boolean;
ignore?: GlobOptions['ignore'];
}): Promise<string[]>;
/**
* Adds a nitro server handler
*
*/
declare function addServerHandler(handler: NitroEventHandler): void;
/**
* Adds a nitro server handler for development-only
*
*/
declare function addDevServerHandler(handler: NitroDevEventHandler): void;
/**
* Adds a Nitro plugin
*/
declare function addServerPlugin(plugin: string): void;
/**
* Adds routes to be prerendered
*/
declare function addPrerenderRoutes(routes: string | string[]): void;
/**
* Access to the Nitro instance
*
* **Note:** You can call `useNitro()` only after `ready` hook.
*
* **Note:** Changes to the Nitro instance configuration are not applied.
* @example
*
* ```ts
* nuxt.hook('ready', () => {
* console.log(useNitro())
* })
* ```
*/
declare function useNitro(): Nitro;
/**
* Add server imports to be auto-imported by Nitro
*/
declare function addServerImports(imports: Import | Import[]): void;
/**
* Add directories to be scanned for auto-imports by Nitro
*/
declare function addServerImportsDir(dirs: string | string[], opts?: {
prepend?: boolean;
}): void;
/**
* Add directories to be scanned by Nitro. It will check for subdirectories,
* which will be registered just like the `~/server` folder is.
*/
declare function addServerScanDir(dirs: string | string[], opts?: {
prepend?: boolean;
}): void;
/**
* Renders given template during build into the virtual file system (and optionally to disk in the project `buildDir`)
*/
declare function addTemplate<T>(_template: NuxtTemplate<T> | string): ResolvedNuxtTemplate<T>;
/**
* Adds a virtual file that can be used within the Nuxt Nitro server build.
*/
declare function addServerTemplate(template: NuxtServerTemplate): NuxtServerTemplate;
/**
* Renders given types during build to disk in the project `buildDir`
* and register them as types.
*
* You can pass a second context object to specify in which context the type should be added.
*
* If no context object is passed, then it will only be added to the nuxt context.
*/
declare function addTypeTemplate<T>(_template: NuxtTypeTemplate<T>, context?: {
nitro?: boolean;
nuxt?: boolean;
node?: boolean;
shared?: boolean;
}): ResolvedNuxtTemplate<T>;
/**
* Normalize a nuxt template object
*/
declare function normalizeTemplate<T>(template: NuxtTemplate<T> | string, buildDir?: string): ResolvedNuxtTemplate<T>;
/**
* Trigger rebuilding Nuxt templates
*
* You can pass a filter within the options to selectively regenerate a subset of templates.
*/
declare function updateTemplates(options?: {
filter?: (template: ResolvedNuxtTemplate<any>) => boolean;
}): Promise<any>;
declare function writeTypes(nuxt: Nuxt): Promise<void>;
declare const logger: consola.ConsolaInstance;
declare function useLogger(tag?: string, options?: Partial<ConsolaOptions>): consola.ConsolaInstance;
interface ResolveModuleOptions {
/** @deprecated use `url` with URLs pointing at a file - never a directory */
paths?: string | string[];
url?: URL | URL[];
/** @default ['.js', '.mjs', '.cjs', '.ts', '.mts', '.cts'] */
extensions?: string[];
}
declare function directoryToURL(dir: string): URL;
/**
* Resolve a module from a given root path using an algorithm patterned on
* the upcoming `import.meta.resolve`. It returns a file URL
*
* @internal
*/
declare function tryResolveModule(id: string, url: URL | URL[]): Promise<string | undefined>;
/** @deprecated pass URLs pointing at files */
declare function tryResolveModule(id: string, url: string | string[]): Promise<string | undefined>;
declare function resolveModule(id: string, options?: ResolveModuleOptions): string;
interface ImportModuleOptions extends ResolveModuleOptions {
/** Automatically de-default the result of requiring the module. */
interopDefault?: boolean;
}
declare function importModule<T = unknown>(id: string, opts?: ImportModuleOptions): Promise<T>;
declare function tryImportModule<T = unknown>(id: string, opts?: ImportModuleOptions): Promise<T | undefined> | undefined;
/**
* @deprecated Please use `importModule` instead.
*/
declare function requireModule<T = unknown>(id: string, opts?: ImportModuleOptions): T;
/**
* @deprecated Please use `tryImportModule` instead.
*/
declare function tryRequireModule<T = unknown>(id: string, opts?: ImportModuleOptions): T | undefined;
export { addBuildPlugin, addComponent, addComponentExports, addComponentsDir, addDevServerHandler, addImports, addImportsDir, addImportsSources, addLayout, addPlugin, addPluginTemplate, addPrerenderRoutes, addRouteMiddleware, addRspackPlugin, addServerHandler, addServerImports, addServerImportsDir, addServerPlugin, addServerScanDir, addServerTemplate, addTemplate, addTypeTemplate, addVitePlugin, addWebpackPlugin, assertNuxtCompatibility, buildNuxt, checkNuxtCompatibility, createIsIgnored, createResolver, defineNuxtModule, directoryToURL, extendNuxtSchema, extendPages, extendRouteRules, extendRspackConfig, extendViteConfig, extendWebpackConfig, findPath, getDirectory, getLayerDirectories, getNuxtCtx, getNuxtModuleVersion, getNuxtVersion, hasNuxtCompatibility, hasNuxtModule, hasNuxtModuleCompatibility, importModule, installModule, installModules, isIgnored, isNuxt2, isNuxt3, isNuxtMajorVersion, loadNuxt, loadNuxtConfig, loadNuxtModuleInstance, logger, normalizeModuleTranspilePath, normalizePlugin, normalizeSemanticVersion, normalizeTemplate, nuxtCtx, requireModule, resolveAlias, resolveFiles, resolveIgnorePatterns, resolveModule, resolveModuleWithOptions, resolveNuxtModule, resolvePath, runWithNuxtContext, setGlobalHead, tryImportModule, tryRequireModule, tryResolveModule, tryUseNuxt, updateRuntimeConfig, updateTemplates, useLogger, useNitro, useNuxt, useRuntimeConfig, writeTypes };
export type { AddComponentOptions, AddPluginOptions, AddRouteMiddlewareOptions, ExtendConfigOptions, ExtendRouteRulesOptions, ExtendViteConfigOptions, ExtendWebpackConfigOptions, ImportModuleOptions, LayerDirectories, LoadNuxtConfigOptions, LoadNuxtOptions, ResolveModuleOptions, ResolvePathOptions, Resolver };

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,65 @@
{
"name": "@nuxt/kit",
"version": "4.2.2",
"repository": {
"type": "git",
"url": "git+https://github.com/nuxt/nuxt.git",
"directory": "packages/kit"
},
"homepage": "https://nuxt.com/docs/4.x/api/kit",
"description": "Toolkit for authoring modules and interacting with Nuxt",
"license": "MIT",
"type": "module",
"types": "./dist/index.d.ts",
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.mjs"
},
"./package.json": "./package.json"
},
"files": [
"dist"
],
"dependencies": {
"c12": "^3.3.2",
"consola": "^3.4.2",
"defu": "^6.1.4",
"destr": "^2.0.5",
"errx": "^0.1.0",
"exsolve": "^1.0.8",
"ignore": "^7.0.5",
"jiti": "^2.6.1",
"klona": "^2.0.6",
"mlly": "^1.8.0",
"ohash": "^2.0.11",
"pathe": "^2.0.3",
"pkg-types": "^2.3.0",
"rc9": "^2.1.2",
"scule": "^1.3.0",
"semver": "^7.7.3",
"tinyglobby": "^0.2.15",
"ufo": "^1.6.1",
"unctx": "^2.4.1",
"untyped": "^2.0.0"
},
"devDependencies": {
"@rspack/core": "1.6.7",
"@types/semver": "7.7.1",
"hookable": "5.5.3",
"nitropack": "2.12.9",
"unbuild": "3.6.1",
"unimport": "5.5.0",
"vite": "7.2.7",
"vitest": "3.2.4",
"webpack": "5.103.0",
"@nuxt/schema": "4.2.2"
},
"engines": {
"node": ">=18.12.0"
},
"scripts": {
"test:attw": "attw --pack"
}
}

View file

@ -0,0 +1,61 @@
{
"name": "@nuxt/devtools-kit",
"type": "module",
"version": "3.1.1",
"license": "MIT",
"homepage": "https://devtools.nuxt.com/module/utils-kit",
"repository": {
"type": "git",
"url": "git+https://github.com/nuxt/devtools.git",
"directory": "packages/devtools-kit"
},
"exports": {
".": {
"types": "./dist/index.d.ts",
"import": "./dist/index.mjs",
"require": "./dist/index.cjs"
},
"./types": {
"types": "./types.d.ts",
"import": "./dist/types.mjs",
"require": "./dist/types.cjs"
},
"./iframe-client": {
"types": "./iframe-client.d.ts",
"import": "./iframe-client.mjs"
},
"./host-client": {
"types": "./host-client.d.ts",
"import": "./host-client.mjs"
}
},
"main": "./dist/index.cjs",
"types": "./dist/index.d.ts",
"files": [
"*.cjs",
"*.d.ts",
"*.mjs",
"dist"
],
"peerDependencies": {
"vite": ">=6.0"
},
"dependencies": {
"@nuxt/kit": "^4.2.1",
"execa": "^8.0.1"
},
"devDependencies": {
"@nuxt/schema": "^4.2.1",
"birpc": "^2.8.0",
"error-stack-parser-es": "^1.0.5",
"hookable": "^5.5.3",
"unbuild": "^3.6.1",
"unimport": "^5.5.0",
"vue-router": "^4.6.3"
},
"scripts": {
"build": "unbuild",
"stub": "unbuild --stub",
"dev:prepare": "nr stub"
}
}

View file

@ -0,0 +1 @@
export type * from './dist/types.d.mts'

View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022-PRESENT Nuxt Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View file

@ -0,0 +1,2 @@
#!/usr/bin/env node
import('./dist/index.mjs')

View file

@ -0,0 +1,103 @@
import { existsSync } from 'node:fs';
import fsp from 'node:fs/promises';
import { relative } from 'node:path';
import { consola } from 'consola';
import { colors } from 'consola/utils';
import { diffLines } from 'diff';
import { parseModule } from 'magicast';
import { join } from 'pathe';
import prompts from 'prompts';
function findNuxtConfig(cwd) {
const names = [
"nuxt.config.ts",
"nuxt.config.js"
];
for (const name of names) {
const path = join(cwd, name);
if (existsSync(path))
return path;
}
}
function printOutManual(value) {
consola.info(colors.yellow("To manually enable Nuxt DevTools, add the following to your Nuxt config:"));
consola.info(colors.cyan(`
devtools: { enabled: ${value} }
`));
}
async function toggleConfig(cwd, value) {
const nuxtConfig = findNuxtConfig(cwd);
if (!nuxtConfig) {
consola.error(colors.red("Unable to find Nuxt config file in current directory"));
process.exitCode = 1;
printOutManual(true);
return false;
}
try {
const source = await fsp.readFile(nuxtConfig, "utf-8");
const mod = await parseModule(source, { sourceFileName: nuxtConfig });
const config = mod.exports.default.$type === "function-call" ? mod.exports.default.$args[0] : mod.exports.default;
if (config.devtools || value) {
config.devtools ||= {};
if (typeof config.devtools === "object")
config.devtools.enabled = value;
}
const generated = mod.generate().code;
if (source.trim() === generated.trim()) {
consola.info(colors.yellow(`Nuxt DevTools is already ${value ? "enabled" : "disabled"}`));
} else {
consola.log("");
consola.log("We are going to update the Nuxt config with with the following changes:");
consola.log(colors.bold(colors.green(`./${relative(cwd, nuxtConfig)}`)));
consola.log("");
printDiffToCLI(source, generated);
consola.log("");
const { confirm } = await prompts({
type: "confirm",
name: "confirm",
message: "Continue?",
initial: true
});
if (!confirm)
return false;
await fsp.writeFile(nuxtConfig, `${generated.trimEnd()}
`, "utf-8");
}
} catch {
consola.error(colors.red("Unable to update Nuxt config file automatically"));
process.exitCode = 1;
printOutManual(true);
return false;
}
return true;
}
async function enable(cwd) {
await toggleConfig(cwd, true);
}
async function disable(cwd) {
await toggleConfig(cwd, false);
}
function printDiffToCLI(from, to) {
const diffs = diffLines(from.trim(), to.trim());
let output = "";
let no = 0;
for (const diff of diffs) {
const lines = diff.value.trimEnd().split("\n");
for (const line of lines) {
if (!diff.added)
no += 1;
if (diff.added)
output += colors.green(`+ | ${line}
`);
else if (diff.removed)
output += colors.red(`-${no.toString().padStart(3, " ")} | ${line}
`);
else
output += colors.gray(`${colors.dim(`${no.toString().padStart(4, " ")} |`)} ${line}
`);
}
}
consola.log(output.trimEnd());
}
export { disable, enable };

View file

@ -0,0 +1,51 @@
import { consola } from 'consola';
import { colors } from 'consola/utils';
import { readPackageJSON } from 'pkg-types';
const name = "@nuxt/devtools-wizard";
const version = "3.1.1";
async function getNuxtVersion(path) {
try {
const pkg = await readPackageJSON("nuxt", { url: path });
if (!pkg.version)
consola.warn("Cannot find any installed nuxt versions in ", path);
return pkg.version || null;
} catch {
return null;
}
}
async function run() {
const args = process.argv.slice(2);
const command = args[0];
const cwd = process.cwd();
consola.log("");
consola.log(colors.bold(colors.green(" Nuxt ")));
consola.log(`${colors.inverse(colors.bold(colors.green(" DevTools ")))} ${colors.green(`v${version}`)}`);
consola.log(`
${colors.gray("Learn more at https://devtools.nuxt.com\n")}`);
if (name.endsWith("-edge") || name.endsWith("-nightly"))
throw new Error("[Nuxt DevTools] Nightly release of Nuxt DevTools requires to be installed locally. Learn more at https://github.com/nuxt/devtools/#nightly-release-channel");
const nuxtVersion = await getNuxtVersion(cwd);
if (!nuxtVersion) {
consola.error("[Nuxt DevTools] Unable to find any installed nuxt version in the current directory");
process.exit(1);
}
if (command === "enable") {
consola.log(colors.green("Enabling Nuxt DevTools..."));
await import('./chunks/builtin.mjs').then((r) => r.enable(cwd));
} else if (command === "disable") {
consola.log(colors.magenta("Disabling Nuxt DevTools..."));
await import('./chunks/builtin.mjs').then((r) => r.disable(cwd));
} else if (!command) {
consola.log(`npx ${name} enable|disable`);
process.exit(1);
} else {
consola.log(colors.red(`Unknown command "${command}"`));
process.exit(1);
}
}
run().catch((err) => {
consola.error(err);
process.exit(1);
});

View file

@ -0,0 +1,41 @@
{
"name": "@nuxt/devtools-wizard",
"type": "module",
"version": "3.1.1",
"description": "CLI Wizard to toggle Nuxt DevTools",
"license": "MIT",
"homepage": "https://devtools.nuxt.com",
"repository": {
"type": "git",
"url": "git+https://github.com/nuxt/devtools.git",
"directory": "packages/devtools-wizard"
},
"main": "./dist/index.mjs",
"bin": "./cli.mjs",
"files": [
"*.cjs",
"*.d.ts",
"*.mjs",
"dist"
],
"dependencies": {
"consola": "^3.4.2",
"diff": "^8.0.2",
"execa": "^8.0.1",
"magicast": "^0.5.1",
"pathe": "^2.0.3",
"pkg-types": "^2.3.0",
"prompts": "^2.4.2",
"semver": "^7.7.3"
},
"devDependencies": {
"@types/diff": "^8.0.0",
"@types/prompts": "^2.4.9",
"unbuild": "^3.6.1"
},
"scripts": {
"build": "unbuild",
"stub": "unbuild --stub",
"dev:prepare": "nr stub"
}
}

View file

@ -0,0 +1,13 @@
const { join } = require('node:path')
module.exports = {
name: 'Nuxt Server Data',
basedir: join(__dirname, 'discovery'),
embed: true,
// view: {
// assets: [
// './pages/common.css',
// './pages/default.js',
// ],
// },
}

21
Frontend-Learner/node_modules/@nuxt/devtools/LICENSE generated vendored Normal file
View file

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2022-PRESENT Nuxt Team
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

126
Frontend-Learner/node_modules/@nuxt/devtools/README.md generated vendored Normal file
View file

@ -0,0 +1,126 @@
<a href="https://devtools.nuxt.com"><img width="1200" alt="Nuxt DevTools" src="https://github-production-user-asset-6210df.s3.amazonaws.com/904724/261577617-a10567bd-ad33-48cc-9bda-9e37dbe1929f.png"></a>
<br>
<h1>
Nuxt DevTools
</h1>
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![License][license-src]][license-href]
[![Nuxt][nuxt-src]][nuxt-href]
[![Volta][volta-src]][volta-href]
<p>
Unleash Nuxt Developer Experience.
<br>Nuxt DevTools is a set of visual tools that help you to know your app better.
</p>
<p>
<a href="https://nuxt.com/blog/nuxt-devtools-v1-0">👋 Introduction</a> |
<a href="https://github.com/nuxt/devtools/discussions/29">💡 Ideas & Suggestions</a> |
<a href="https://github.com/nuxt/devtools/discussions/31">🗺️ Project Roadmap</a> |
<a href="https://devtools.nuxt.com/">📚 Documentation</a>
</p>
<br>
## Installation
> Nuxt DevTools v2 requires **Nuxt v3.15.0 or higher**.
Nuxt DevTools is **enabled by default** in Nuxt v3.8.0. You can press <kbd>Shift</kbd> + <kbd>Alt</kbd> / <kbd>⇧ Shift</kbd> + <kbd>⌥ Option</kbd> + <kbd>D</kbd> in your app to open it up.
If you want to explicitly enable or disable Nuxt DevTools, you can update your `nuxt.config` with:
```js
export default defineNuxtConfig({
devtools: {
enabled: true // or false to disable
}
})
```
### Nightly Release Channel
Similar to [Nuxt's Nightly Channel](https://nuxt.com/docs/guide/going-further/nightly-release-channel), DevTools also offers a nightly release channel, that automatically releases for every commit to `main` branch.
You can opt-in to the nightly release channel by running:
```diff
{
"devDependencies": {
-- "@nuxt/devtools": "^0.1.0"
++ "@nuxt/devtools": "npm:@nuxt/devtools-nightly@latest"
}
}
```
Remove lockfile (`package-lock.json`, `yarn.lock`, or `pnpm-lock.yaml`) and reinstall dependencies.
### Module Options
To configure Nuxt DevTools, you can pass the `devtools` options.
```ts
// nuxt.config.ts
export default defineNuxtConfig({
devtools: {
// Enable devtools (default: true)
enabled: true,
// VS Code Server options
vscode: {},
// ...other options
}
})
```
For all options available, please refer to TSDocs in your IDE, or the [type definition file](https://github.com/nuxt/devtools/blob/main/packages/devtools-kit/src/_types/options.ts).
## Features
Read the [**Announcement Blog Post 🎊**](https://nuxt.com/blog/nuxt-devtools-v1-0) for why we built Nuxt DevTools and what it can do!
## Module Authors
Please refer to the [Module Authors Guide](https://devtools.nuxt.com/module/guide).
## Contribution Guide
Please refer to the [Contribution Guide](https://devtools.nuxt.com/development/contributing).
## Anonymous Usage Analytics
Nuxt DevTools collects anonymous telemetry data about general usage. This helps us to accurately gauge feature usage and customization across all our users. This data will let us better understand how each features in Nuxt DevTools are used, measuring improvements made (DX and performances) and their relevance. It would also help us to prioritize our efforts and focus on the features that matter the most to our users.
Nuxt DevTools' telemetry data is piped through [Nuxt Telemetry](https://github.com/nuxt/telemetry), meaning that Nuxt DevTools will respect your local and global Nuxt Telemetry settings. You can also opt-out Nuxt DevTools' telemetry in the Nuxt DevTools settings.
The data we collect is completely anonymous, not traceable to the source (using hash+seed), and only meaningful in aggregate form. No data we collect is personally identifiable or trackable.
### Events
On top of the [default Nuxt Telemetry events](https://github.com/nuxt/telemetry#events), Nuxt DevTools also collects the following events:
- Versions of Nuxt DevTools
- Navigations between tabs/feature
- This helps us to understand which features are used the most to prioritize our efforts.
- Browser and OS names and versions
- This helps us improve compatibility across different browsers and operating systems.
- Click event on some action buttons
## License
[MIT](./LICENSE)
<!-- Badges -->
[npm-version-src]: https://img.shields.io/npm/v/@nuxt/devtools/latest.svg?style=flat&colorA=18181B&colorB=28CF8D
[npm-version-href]: https://npmjs.com/package/@nuxt/devtools
[npm-downloads-src]: https://img.shields.io/npm/dm/@nuxt/devtools.svg?style=flat&colorA=18181B&colorB=28CF8D
[npm-downloads-href]: https://npm.chart.dev/@nuxt/devtools
[license-src]: https://img.shields.io/npm/l/@nuxt/devtools.svg?style=flat&colorA=18181B&colorB=28CF8D
[license-href]: https://npmjs.com/package/@nuxt/devtools
[nuxt-src]: https://img.shields.io/badge/Nuxt-18181B?logo=nuxt.js
[nuxt-href]: https://nuxt.com
[volta-src]: https://user-images.githubusercontent.com/904724/209143798-32345f6c-3cf8-4e06-9659-f4ace4a6acde.svg
[volta-href]: https://volta.net/nuxt/devtools?utm_source=nuxt_devtools_readme

2
Frontend-Learner/node_modules/@nuxt/devtools/cli.mjs generated vendored Normal file
View file

@ -0,0 +1,2 @@
#!/usr/bin/env node
import('@nuxt/devtools-wizard')

View file

@ -0,0 +1,58 @@
import { addVitePlugin } from '@nuxt/kit';
import { resolve, join } from 'pathe';
import { readdir, lstat } from 'node:fs/promises';
import { createVitePluginInspect } from './vite-inspect.mjs';
import '@nuxt/devtools-kit';
async function getFolderSize(dir) {
const dirents = await readdir(dir, {
withFileTypes: true
});
if (dirents.length === 0)
return 0;
const files = [];
const directorys = [];
for (const dirent of dirents) {
if (dirent.isFile()) {
files.push(dirent);
continue;
}
if (dirent.isDirectory())
directorys.push(dirent);
}
const sizes = await Promise.all(
[
files.map(async (file) => {
const path = resolve(dir, file.name);
const { size } = await lstat(path);
return size;
}),
directorys.map((directory) => {
const path = resolve(dir, directory.name);
return getFolderSize(path);
})
].flat()
);
return sizes.reduce((total, size) => total += size, 0);
}
async function setup(nuxt, options) {
if (options.viteInspect !== false) {
addVitePlugin(
await createVitePluginInspect({
build: true,
outputDir: join(nuxt.options.analyzeDir, ".vite-inspect")
})
);
}
nuxt.hook("build:analyze:done", async (meta) => {
const _meta = meta;
_meta.size = _meta.size || {};
const dirs = [join(meta.buildDir, "dist/client"), meta.outDir];
const [clientBundleSize, nitroBundleSize] = await Promise.all(dirs.map(getFolderSize));
_meta.size.clientBundle = clientBundleSize;
_meta.size.nitroBundle = nitroBundleSize;
});
}
export { setup };

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,68 @@
function setup({ nuxt }) {
if (!nuxt.options.dev || nuxt.options.test)
return;
nuxt.hook("app:templates", (app) => {
app.templates.filter((i) => i.filename?.startsWith("plugins/")).forEach((i) => {
if (!i.getContents)
return;
const original = i.getContents;
i.getContents = async (...args) => {
let content = await original(...args);
const PAYLOAD_KEY = "__NUXT_DEVTOOLS_PLUGINS_METRIC__";
const WRAPPER_KEY = "__DEVTOOLS_WRAPPER__";
if (content.includes(PAYLOAD_KEY))
return content;
const snippets = `
if (!globalThis.${PAYLOAD_KEY}) {
Object.defineProperty(globalThis, '${PAYLOAD_KEY}', {
value: [],
enumerable: false,
configurable: true,
})
}
function ${WRAPPER_KEY} (plugin, src) {
if (!plugin)
return plugin
return defineNuxtPlugin({
...plugin,
async setup (...args) {
const start = performance.now()
const result = await plugin.apply(this, args)
const end = performance.now()
globalThis.${PAYLOAD_KEY}.push({
src,
start,
end,
duration: end - start,
})
return result
}
})
}
`;
const imports = Array.from(content.matchAll(/(?:\n|^)import (.*) from ['"](.*)['"]/g)).map(([, name, path]) => ({ name, path }));
content = content.replace(/\nexport default\s*\[([\s\S]*)\]/, (_, itemsRaw) => {
const items = itemsRaw.split(",").map((i2) => i2.trim()).map((i2) => {
const importItem = imports.find(({ name }) => name === i2);
if (!importItem)
return i2;
return `${WRAPPER_KEY}(${i2}, ${JSON.stringify(importItem.path)})`;
});
return `
${snippets}
export default [
${items.join(",\n")}
]
`;
});
content = `import { defineNuxtPlugin } from "#imports"
${content}`;
return content;
};
});
});
}
export { setup };

View file

@ -0,0 +1,73 @@
import { resolve } from 'pathe';
import semver from 'semver';
import { runtimeDir } from '../dirs.mjs';
import 'node:path';
import 'node:url';
import 'is-installed-globally';
function setup({ nuxt, options }) {
const helperPath = resolve(runtimeDir, "function-metrics-helpers");
const includeFrom = options.timeline?.functions?.includeFrom || [
"#app",
"@unhead/vue"
];
const include = options.timeline?.functions?.include || [
(i) => includeFrom.includes(i.from),
(i) => i.from.includes("composables")
];
const exclude = options.timeline?.functions?.exclude || [
/^define[A-Z]/
];
function filter(item) {
if (item.type)
return false;
const name = item.as || item.name;
if (!include.some((f) => typeof f === "function" ? f(item) : typeof f === "string" ? name === f : f.test(name)))
return false;
if (exclude.some((f) => typeof f === "function" ? f(item) : typeof f === "string" ? name === f : f.test(name)))
return false;
return true;
}
nuxt.hook("imports:context", (unimport) => {
const ctx = unimport.getInternalContext();
if (!ctx.version || !semver.gte(ctx.version, "3.1.0"))
throw new Error(`[Nuxt DevTools] The timeline feature requires \`unimport\` >= v3.1.0, but got \`${ctx.version || "(unknown)"}\`. Please upgrade using \`nuxi upgrade --force\`.`);
ctx.addons.push(
{
injectImportsResolved(imports, _code, id) {
if (id?.includes("?macro=true"))
return;
return imports.map((i) => {
if (!filter(i))
return i;
const name = i.as || i.name;
return {
...i,
meta: {
wrapperOriginalAs: name
},
as: `_$__${name}`
};
});
},
injectImportsStringified(str, imports, s, id) {
if (id?.includes("?macro=true"))
return;
const code = s.toString();
const injected = imports.filter((i) => i.meta?.wrapperOriginalAs);
if (injected.length) {
const result = [
str,
code.includes("__nuxtTimelineWrap") ? "" : `import { __nuxtTimelineWrap } from ${JSON.stringify(helperPath)}`,
...injected.map((i) => `const ${i.meta.wrapperOriginalAs} = __nuxtTimelineWrap(${JSON.stringify(i.name)}, ${i.as})`),
""
].join(";");
return result;
}
}
}
);
});
}
export { setup };

View file

@ -0,0 +1,61 @@
import { addCustomTab } from '@nuxt/devtools-kit';
import { addVitePlugin } from '@nuxt/kit';
async function createVitePluginInspect(options) {
return await import('vite-plugin-inspect').then((r) => r.default(options));
}
async function setup({ nuxt, rpc }) {
const plugin = await createVitePluginInspect();
addVitePlugin(plugin);
let api;
nuxt.hook("vite:serverCreated", () => {
api = plugin.api;
});
addCustomTab(() => ({
name: "builtin-vite-inspect",
title: "Inspect",
icon: "carbon-ibm-watson-discovery",
category: "advanced",
view: {
type: "iframe",
src: `${nuxt.options.app.baseURL}${nuxt.options.app.buildAssetsDir}/__inspect/`.replace(/\/\//g, "/")
}
}), nuxt);
async function getComponentsRelationships() {
const meta = await api?.rpc.getMetadata();
const modules = (meta && meta.instances[0] ? await api?.rpc.getModulesList({
vite: meta.instances[0].vite,
env: meta.instances[0].environments[0]
}) : null) || [];
const components = await rpc.functions.getComponents() || [];
const vueModules = modules.filter((m) => {
const plainId = m.id.replace(/\?v=\w+$/, "");
if (components.some((c) => c.filePath === plainId))
return true;
return m.id.match(/\.vue($|\?v=)/);
});
const graph = vueModules.map((i) => {
function searchForVueDeps(id, seen = /* @__PURE__ */ new Set()) {
if (seen.has(id))
return [];
seen.add(id);
const module = modules.find((m) => m.id === id);
if (!module)
return [];
return module.deps.flatMap((i2) => {
if (vueModules.find((m) => m.id === i2))
return [i2];
return searchForVueDeps(i2, seen);
});
}
return {
id: i.id,
deps: searchForVueDeps(i.id)
};
});
return graph;
}
rpc.functions.getComponentsRelationships = getComponentsRelationships;
}
export { createVitePluginInspect, setup };

View file

@ -0,0 +1,196 @@
import { existsSync } from 'node:fs';
import fsp from 'node:fs/promises';
import { hostname } from 'node:os';
import { resolve } from 'node:path';
import { startSubprocess } from '@nuxt/devtools-kit';
import { logger } from '@nuxt/kit';
import { execa } from 'execa';
import { checkPort, getPort } from 'get-port-please';
import which from 'which';
import { L as LOG_PREFIX } from './module-main.mjs';
import 'consola/utils';
import 'pathe';
import 'sirv';
import 'vite';
import '../shared/devtools.DuFZOCNN.mjs';
import '../dirs.mjs';
import 'node:url';
import 'is-installed-globally';
import 'ohash';
import 'birpc';
import 'structured-clone-es';
import 'simple-git';
import 'tinyglobby';
import 'image-meta';
import 'perfect-debounce';
import 'destr';
import '../../dist/runtime/shared/hooks.js';
import 'node:process';
import 'node:module';
import 'pkg-types';
import 'node:assert';
import 'node:v8';
import 'node:util';
import 'local-pkg';
import 'magicast';
import 'magicast/helpers';
import 'nypm';
import 'semver';
const codeBinaryOptions = {
"ms-code-cli": {
codeBinary: "code",
launchArg: "serve-web",
licenseTermsArg: "--accept-server-license-terms",
connectionTokenArg: "--without-connection-token"
},
"ms-code-server": {
codeBinary: "code-server",
launchArg: "serve-local",
licenseTermsArg: "--accept-server-license-terms",
connectionTokenArg: "--without-connection-token"
},
"coder-code-server": {
codeBinary: "code-server",
launchArg: "serve-local",
licenseTermsArg: "",
connectionTokenArg: ""
}
};
async function setup({ nuxt, options, openInEditorHooks, rpc }) {
const vsOptions = options?.vscode || {};
const codeServer = vsOptions?.codeServer || "ms-code-server";
const { codeBinary, launchArg, licenseTermsArg, connectionTokenArg } = codeBinaryOptions[codeServer];
const installed = !!await which(codeBinary).catch(() => null);
let port = vsOptions?.port || 3080;
let url = `http://localhost:${port}`;
const host = vsOptions?.host ? `--host=${vsOptions.host}` : "--host=127.0.0.1";
let loaded = false;
let promise = null;
const mode = vsOptions?.mode || "local-serve";
const computerHostName = vsOptions.tunnel?.name || hostname().split(".").join("");
const root = nuxt.options.rootDir;
const vscodeServerControllerFile = resolve(root, ".vscode", ".server-controller-port.log");
openInEditorHooks.push(async (file) => {
if (!existsSync(vscodeServerControllerFile))
return false;
try {
const { port: port2 } = JSON.parse(await fsp.readFile(vscodeServerControllerFile, "utf-8"));
const url2 = `http://localhost:${port2}/open?path=${encodeURIComponent(`${root}/${file}`)}`;
await fetch(url2);
rpc.broadcast.navigateTo("/modules/custom-builtin-vscode");
return true;
} catch (e) {
console.debug(`Failed to open file "${file}" in VS Code Server`);
console.debug(e);
return false;
}
});
async function startCodeServer() {
if (existsSync(vscodeServerControllerFile))
await fsp.rm(vscodeServerControllerFile, { force: true });
if (vsOptions?.reuseExistingServer && !await checkPort(port)) {
loaded = true;
url = `http://localhost:${port}/?folder=${encodeURIComponent(root)}`;
logger.info(LOG_PREFIX, `Existing VS Code Server found at port ${port}...`);
return;
}
port = await getPort({ port });
url = `http://localhost:${port}/?folder=${encodeURIComponent(root)}`;
logger.info(LOG_PREFIX, `Starting VS Code Server at ${url} ...`);
execa(codeBinary, [
"--install-extension",
"antfu.vscode-server-controller"
], { stderr: "inherit", stdout: "ignore", reject: false });
startSubprocess(
{
command: codeBinary,
args: [
launchArg,
licenseTermsArg,
connectionTokenArg,
`--port=${port}`,
host
]
},
{
id: "devtools:vscode",
name: "VS Code Server",
icon: "logos-visual-studio-code"
},
nuxt
);
for (let i = 0; i < 100; i++) {
if (await fetch(url).then((r) => r.ok).catch(() => false))
break;
await new Promise((resolve2) => setTimeout(resolve2, 500));
}
await new Promise((resolve2) => setTimeout(resolve2, 2e3));
loaded = true;
}
async function startCodeTunnel() {
const { stdout: currentDir } = await execa("pwd");
url = `https://vscode.dev/tunnel/${computerHostName}${currentDir}`;
logger.info(LOG_PREFIX, `Starting VS Code tunnel at ${url} ...`);
const command = execa("code", [
"tunnel",
"--accept-server-license-terms",
"--name",
`${computerHostName}`
]);
command.stderr?.pipe(process.stderr);
command.stdout?.pipe(process.stdout);
nuxt.hook("close", () => {
command.kill();
});
for (let i = 0; i < 100; i++) {
if (await fetch(url).then((r) => r.ok).catch(() => false))
break;
await new Promise((resolve2) => setTimeout(resolve2, 500));
}
await new Promise((resolve2) => setTimeout(resolve2, 2e3));
loaded = true;
}
async function start() {
if (mode === "tunnel")
await startCodeTunnel();
else
await startCodeServer();
}
nuxt.hook("devtools:customTabs", (tabs) => {
tabs.push({
name: "builtin-vscode",
title: "VS Code",
icon: "bxl-visual-studio",
category: "modules",
requireAuth: true,
view: !installed && !(vsOptions?.mode === "tunnel") ? {
type: "launch",
title: "Install VS Code Server",
description: `It seems you don't have code-server installed.
Learn more about it with <a href="https://code.visualstudio.com/blogs/2022/07/07/vscode-server" target="_blank">this guide</a>.
Once installed, restart Nuxt and visit this tab again.`,
actions: []
} : !loaded ? {
type: "launch",
description: "Launch VS Code right in the devtools!",
actions: [{
label: promise ? "Starting..." : "Launch",
pending: !!promise,
handle: () => {
promise = promise || start();
return promise;
}
}]
} : {
type: "iframe",
src: url
}
});
});
if (vsOptions?.startOnBoot)
promise = promise || start();
}
export { setup };

View file

@ -0,0 +1,19 @@
import { addPluginTemplate, resolvePath } from '@nuxt/kit';
import { join } from 'pathe';
import { runtimeDir } from '../dirs.mjs';
import 'node:path';
import 'node:url';
import 'is-installed-globally';
async function setup({ nuxt }) {
if (!nuxt.options.dev || nuxt.options.test)
return;
addPluginTemplate({
name: "vue-devtools-client",
mode: "client",
order: -1e3,
src: await resolvePath(join(runtimeDir, "vue-devtools-client"))
});
}
export { setup };

View file

@ -0,0 +1,14 @@
import { addVitePlugin } from '@nuxt/kit';
import { VueTracer } from 'vite-plugin-vue-tracer';
function setup({ nuxt, options }) {
if (!nuxt.options.dev || nuxt.options.test)
return;
if (!options.componentInspector)
return;
const plugin = VueTracer();
if (plugin)
addVitePlugin(plugin);
}
export { setup };

View file

@ -0,0 +1 @@
<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><script type="importmap">{"imports":{"#entry":"/__NUXT_DEVTOOLS_BASE__/_nuxt/b2u55qmz.js"}}</script><link rel="stylesheet" href="/__NUXT_DEVTOOLS_BASE__/_nuxt/entry.css-isd0m9wk.css" crossorigin><link rel="stylesheet" href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/json-editor-vue.css-f8ezrn37.css" crossorigin><link rel="stylesheet" href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/unocss.css-c5u30s53.css" crossorigin><link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/b2u55qmz.js"><link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/json-editor-vue-ho2zu772.js"><link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/shiki-g7cm1eew.js"><link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/unocss-d7th42z7.js"><script type="module" src="/__NUXT_DEVTOOLS_BASE__/_nuxt/b2u55qmz.js" crossorigin></script></head><body><div id="__nuxt"></div><div id="teleports"></div><script type="application/json" data-nuxt-data="nuxt-app" data-ssr="false" id="__NUXT_DATA__">[{"prerenderedAt":1,"serverRendered":2},1764061142449,false]</script><script>window.__NUXT__={};window.__NUXT__.config={public:{},app:{baseURL:"/__NUXT_DEVTOOLS_BASE__/",buildId:"06025e11-48ac-46e3-8f59-eb3ab8bfd4b9",buildAssetsDir:"/_nuxt/",cdnURL:""}}</script></body></html>

View file

@ -0,0 +1 @@
<!DOCTYPE html><html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><script type="importmap">{"imports":{"#entry":"/__NUXT_DEVTOOLS_BASE__/_nuxt/b2u55qmz.js"}}</script><link rel="stylesheet" href="/__NUXT_DEVTOOLS_BASE__/_nuxt/entry.css-isd0m9wk.css" crossorigin><link rel="stylesheet" href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/json-editor-vue.css-f8ezrn37.css" crossorigin><link rel="stylesheet" href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/unocss.css-c5u30s53.css" crossorigin><link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/b2u55qmz.js"><link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/json-editor-vue-ho2zu772.js"><link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/shiki-g7cm1eew.js"><link rel="modulepreload" as="script" crossorigin href="/__NUXT_DEVTOOLS_BASE__/_nuxt/vendor/unocss-d7th42z7.js"><script type="module" src="/__NUXT_DEVTOOLS_BASE__/_nuxt/b2u55qmz.js" crossorigin></script></head><body><div id="__nuxt"></div><div id="teleports"></div><script type="application/json" data-nuxt-data="nuxt-app" data-ssr="false" id="__NUXT_DATA__">[{"prerenderedAt":1,"serverRendered":2},1764061142451,false]</script><script>window.__NUXT__={};window.__NUXT__.config={public:{},app:{baseURL:"/__NUXT_DEVTOOLS_BASE__/",buildId:"06025e11-48ac-46e3-8f59-eb3ab8bfd4b9",buildAssetsDir:"/_nuxt/",cdnURL:""}}</script></body></html>

View file

@ -0,0 +1 @@
import{p as e,J as n,X as t}from"./vendor/json-editor-vue-ho2zu772.js";const c={"h-screen":"","w-screen":"","bg-black":""},r=e({__name:"__blank",setup(o){return(s,_)=>(t(),n("div",c))}});export{r as default};

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

View file

@ -0,0 +1 @@
img{-webkit-user-drag:none;-khtml-user-drag:none;-moz-user-drag:none;-o-user-drag:none;user-drag:none}

Some files were not shown because too many files have changed in this diff Show more