feat: init

This commit is contained in:
2026-02-13 22:02:30 +01:00
commit 8f9ff830fb
16711 changed files with 3307340 additions and 0 deletions

31
node_modules/@nuxt/cli/bin/nuxi.mjs generated vendored Executable 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()

42
node_modules/@nuxt/cli/dist/_shared-BCYCnX0T.mjs generated vendored Normal file
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 };

29
node_modules/@nuxt/cli/dist/_utils-B8YNEdpq.mjs generated vendored Normal file
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 };

392
node_modules/@nuxt/cli/dist/add-I_kOiJXU.mjs generated vendored Normal file
View File

@@ -0,0 +1,392 @@
import { t as __exportAll } from "./rolldown-runtime-95iHPtFO.mjs";
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-4LNqcmNp.mjs";
import { t as getNuxtVersion } from "./versions-DD7jbeRR.mjs";
import { n as fetchModules, r as getRegistryFromContent, t as checkNuxtCompatibility } from "./_utils-B8YNEdpq.mjs";
import { t as prepare_default } from "./prepare-CNPL0HH9.mjs";
import { join } from "node:path";
import process from "node:process";
import { defineCommand, runCommand } from "citty";
import { colors } from "consola/utils";
import { hasTTY } from "std-env";
import { autocompleteMultiselect, cancel, confirm, isCancel, select, spinner } from "@clack/prompts";
import { resolve as resolve$1 } from "pathe";
import { fileURLToPath } from "node:url";
import * as fs from "node:fs";
import { existsSync } from "node:fs";
import { joinURL } from "ufo";
import { readPackageJSON } from "pkg-types";
import { satisfies } from "semver";
import { homedir } from "node:os";
import { addDependency, detectPackageManager } from "nypm";
import { $fetch } from "ofetch";
import { Fzf, byLengthAsc } from "fzf";
import { updateConfig } from "c12/update";
//#region ../nuxi/src/commands/_utils.ts
const nuxiCommands = [
"add",
"add-template",
"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/_autocomplete.ts
/**
* Interactive fuzzy search for selecting Nuxt modules
* Returns object with selected module npm package names and cancellation status
*/
async function selectModulesAutocomplete(options) {
const { modules, message = "Search and select modules:" } = options;
if (!hasTTY) {
logger.warn("Interactive module selection requires a TTY. Skipping.");
return {
selected: [],
cancelled: false
};
}
const sortedModules = [...modules].sort((a, b) => {
if (a.type === "official" && b.type !== "official") return -1;
if (a.type !== "official" && b.type === "official") return 1;
return a.npm.localeCompare(b.npm);
});
const fzf = new Fzf(sortedModules, {
selector: (m) => `${m.npm} ${m.name} ${m.category}`,
casing: "case-insensitive",
tiebreakers: [byLengthAsc]
});
const clackOptions = sortedModules.map((m) => ({
value: m.npm,
label: m.npm,
hint: m.description.replace(/\.$/, "")
}));
const filter = (search, option) => {
if (!search) return true;
return fzf.find(search).some((r) => r.item.npm === option.value);
};
const result = await autocompleteMultiselect({
message,
options: clackOptions,
filter,
required: false
});
if (isCancel(result)) return {
selected: [],
cancelled: true
};
return {
selected: result,
cancelled: false
};
}
//#endregion
//#region ../nuxi/src/commands/module/add.ts
var add_exports = /* @__PURE__ */ __exportAll({ default: () => add_default });
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);
let 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);
}
if (modules.length === 0) {
const modulesSpinner = spinner();
modulesSpinner.start("Fetching available modules");
const [allModules, nuxtVersion] = await Promise.all([fetchModules(), getNuxtVersion(cwd)]);
const compatibleModules = allModules.filter((m) => !m.compatibility.nuxt || checkNuxtCompatibility(m, nuxtVersion));
modulesSpinner.stop("Modules loaded");
const result = await selectModulesAutocomplete({
modules: compatibleModules,
message: "Search modules to add (Esc to finish):"
});
if (result.selected.length === 0) {
cancel("No modules selected.");
process.exit(0);
}
modules = result.selected;
}
const resolvedModules = [];
for (const moduleName of modules) {
const resolvedModule = await resolveModule(moduleName, cwd);
if (resolvedModule) resolvedModules.push(resolvedModule);
}
if (resolvedModules.length === 0) {
cancel("No modules to add.");
process.exit(1);
}
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 = false, skipConfig = false, cwd, dev = false }, 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(String(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 }).catch(() => null);
if (!pkgDetails) {
logger.error(`Failed to fetch package details for ${colors.cyan(pkgName)}.`);
return false;
}
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 i, add_exports as n, selectModulesAutocomplete as r, add_default as t };

80
node_modules/@nuxt/cli/dist/add-template-BfsD3GVG.mjs generated vendored Normal file
View File

@@ -0,0 +1,80 @@
import { o as logLevelArgs, t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { n as templates, t as templateNames } from "./templates-CCEGPE6-.mjs";
import { r as relativeToProcess, t as loadKit } from "./kit-4LNqcmNp.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { colors } from "consola/utils";
import { cancel, intro, outro } from "@clack/prompts";
import { dirname, extname, resolve } from "pathe";
import { existsSync, promises } from "node:fs";
//#region ../nuxi/src/commands/add-template.ts
var add_template_default = defineCommand({
meta: {
name: "add-template",
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 = Object.keys(templates).map((name) => colors.cyan(name));
const lastTemplateName = templateNames.pop();
logger.error(`Template ${colors.cyan(templateName)} is not supported.`);
logger.info(`Possible values are ${templateNames.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_template_default as default };

823
node_modules/@nuxt/cli/dist/analyze-GrNVZYjF.mjs generated vendored Normal file
View File

@@ -0,0 +1,823 @@
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-BRiVSJMz.mjs";
import { r as relativeToProcess, t as loadKit } from "./kit-4LNqcmNp.mjs";
import { n as clearDir } from "./fs-BNfOTIDu.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { colors } from "consola/utils";
import { intro, note, outro, taskLog } from "@clack/prompts";
import { join, resolve } from "pathe";
import { defu as defu$1 } from "defu";
import { promises } from "node:fs";
import { FastResponse, FastURL, serve } from "srvx";
//#region ../../node_modules/.pnpm/rou3@0.7.12/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(-(index + 1)).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}`;
path = path.replace(/\\:/g, "%3A");
const segments = splitPath(path);
let node = ctx.root;
let _unnamedParamIndex = 0;
const paramsMap = [];
const paramsRegexp = [];
for (let i = 0; i < segments.length; i++) {
let segment = segments[i];
if (segment.startsWith("**")) {
if (!node.wildcard) node.wildcard = { key: "**" };
node = node.wildcard;
paramsMap.push([
-(i + 1),
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;
}
if (segment === "\\*") segment = segments[i] = "*";
else if (segment === "\\*\\*") segment = segments[i] = "**";
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["/" + segments.join("/")] = 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.14_crossws@0.4.4_srvx@0.11.2_/node_modules/h3/dist/h3-Dol7UbDx.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 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({
...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;
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 } = config;
return onResponse ? Promise.resolve(onResponse(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 } = config;
return onError && !nested ? Promise.resolve(onError(error, event)).catch((error) => error).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 frozen = (name) => (...args) => {
throw new Error(`Headers are frozen (${name} ${args.join(", ")})`);
};
var FrozenHeaders = class extends Headers {
set = frozen("set");
append = frozen("append");
delete = frozen("delete");
};
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 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;
})();
const _textEncoder = new TextEncoder();
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 };

46
node_modules/@nuxt/cli/dist/banner-DNLxDHdP.mjs generated vendored Normal file
View File

@@ -0,0 +1,46 @@
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { n as getPkgJSON, r as getPkgVersion } from "./versions-DD7jbeRR.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")
};
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, dotenv) {
return showVersionsFromConfig(cwd, await kit.loadNuxtConfig({
cwd,
dotenv: dotenv ? {
cwd,
fileName: dotenv
} : void 0
}));
}
//#endregion
export { showVersions as n, showVersionsFromConfig as r, getBuilder as t };

85
node_modules/@nuxt/cli/dist/build-CrY4JY0C.mjs generated vendored Normal file
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-BRiVSJMz.mjs";
import { t as loadKit } from "./kit-4LNqcmNp.mjs";
import "./versions-DD7jbeRR.mjs";
import { n as showVersions } from "./banner-DNLxDHdP.mjs";
import { t as clearBuildDir } from "./fs-BNfOTIDu.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, ctx.args.dotenv);
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 };

32
node_modules/@nuxt/cli/dist/cleanup-viSjdn1J.mjs generated vendored Normal file
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-4LNqcmNp.mjs";
import "./fs-BNfOTIDu.mjs";
import { t as cleanupNuxtDirs } from "./nuxt-4ILhz74C.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 };

715
node_modules/@nuxt/cli/dist/dev-ChFC_-E8.mjs generated vendored Normal file
View File

@@ -0,0 +1,715 @@
import { t as __exportAll } from "./rolldown-runtime-95iHPtFO.mjs";
import { t as overrideEnv } from "./env-BRiVSJMz.mjs";
import { i as withNodePath, t as loadKit } from "./kit-4LNqcmNp.mjs";
import { r as showVersionsFromConfig } from "./banner-DNLxDHdP.mjs";
import { t as clearBuildDir } from "./fs-BNfOTIDu.mjs";
import { a as writeNuxtManifest, i as resolveNuxtManifest, n as loadNuxtManifest } from "./nuxt-4ILhz74C.mjs";
import process from "node:process";
import { provider } from "std-env";
import { join, resolve } from "pathe";
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 { debounce } from "perfect-debounce";
import { toNodeHandler } from "srvx/node";
import { Youch } from "youch";
//#region ../../node_modules/.pnpm/h3@1.15.5/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;
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 = 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, lastComma));
start = pos;
} else pos = lastComma + 1;
} else pos += 1;
}
if (!cookiesSeparatorFound || pos >= cookiesString.length) cookiesStrings.push(cookiesString.slice(start));
}
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, reject) => {
stream.pipe(event.node.res);
if (stream.on) {
stream.on("end", () => {
event.node.res.end();
resolve();
});
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) => {
_initResolve = resolve;
});
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) => r.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) => r.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
var dev_exports = /* @__PURE__ */ __exportAll({ initialize: () => initialize });
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 n, dev_exports as t };

283
node_modules/@nuxt/cli/dist/dev-bt4if7SS.mjs generated vendored Normal file
View File

@@ -0,0 +1,283 @@
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-BRiVSJMz.mjs";
import { n as initialize } from "./dev-ChFC_-E8.mjs";
import "./kit-4LNqcmNp.mjs";
import "./versions-DD7jbeRR.mjs";
import "./banner-DNLxDHdP.mjs";
import "./fs-BNfOTIDu.mjs";
import "./nuxt-4ILhz74C.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { colors } from "consola/utils";
import { isBun, isDeno, isTest } from "std-env";
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 = this.createFork();
fork.ready.then(() => {
if (fork.state === "warming") fork.state = "ready";
}).catch(() => {
this.removeFork(fork);
});
this.pool.push(fork);
}
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, reject) => {
readyResolve = resolve;
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, signal = "SIGTERM") {
fork.state = "dead";
if (fork.process) fork.process.kill(signal === 0 && isDeno ? "SIGTERM" : signal);
this.removeFork(fork);
}
removeFork(fork) {
const index = this.pool.indexOf(fork);
if (index > -1) this.pool.splice(index, 1);
}
killAll(signal) {
for (const fork of this.pool) this.killFork(fork, 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()]);
} };
}
});
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 && 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() {
const httpsArg = this._https;
if (httpsArg === false || httpsArg === "false") return false;
return httpsArg ? options.https : false;
}
};
}
function isBunForkSupported() {
const bunVersion = globalThis.Bun.version;
return satisfies(bunVersion, ">=1.2");
}
//#endregion
export { command as default };

37
node_modules/@nuxt/cli/dist/dev-child-kKJfFeIz.mjs generated vendored Normal file
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-ChFC_-E8.mjs").then((n) => n.t);
await initialize({
cwd,
args: ctx.args
}, ctx);
}
});
//#endregion
export { dev_child_default as default };

68
node_modules/@nuxt/cli/dist/dev/index.d.mts generated vendored Normal file
View File

@@ -0,0 +1,68 @@
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 };

10
node_modules/@nuxt/cli/dist/dev/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import "../logger-B4ge7MhP.mjs";
import "../env-BRiVSJMz.mjs";
import { n as initialize } from "../dev-ChFC_-E8.mjs";
import "../kit-4LNqcmNp.mjs";
import "../versions-DD7jbeRR.mjs";
import "../banner-DNLxDHdP.mjs";
import "../fs-BNfOTIDu.mjs";
import "../nuxt-4ILhz74C.mjs";
export { initialize };

46
node_modules/@nuxt/cli/dist/devtools-BGOrYlGY.mjs generated vendored Normal file
View File

@@ -0,0 +1,46 @@
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);
const command = ctx.args.command;
if (!command || !["enable", "disable"].includes(command)) {
logger.error(`Unknown command ${colors.cyan(command || "")}.`);
process.exit(1);
}
await x("npx", [
"@nuxt/devtools-wizard@latest",
command,
cwd
], {
throwOnError: true,
nodeOptions: {
stdio: "inherit",
cwd
}
});
}
});
//#endregion
export { devtools_default as default };

13
node_modules/@nuxt/cli/dist/env-BRiVSJMz.mjs generated vendored Normal file
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 };

56
node_modules/@nuxt/cli/dist/formatting-PESozNtr.mjs generated vendored Normal file
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 };

40
node_modules/@nuxt/cli/dist/fs-BNfOTIDu.mjs generated vendored Normal file
View File

@@ -0,0 +1,40 @@
import { t as debug } from "./logger-B4ge7MhP.mjs";
import { join } from "pathe";
import { existsSync, promises } from "node:fs";
//#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 };

36
node_modules/@nuxt/cli/dist/generate-DreRkh3n.mjs generated vendored Normal file
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-BRiVSJMz.mjs";
import "./kit-4LNqcmNp.mjs";
import "./versions-DD7jbeRR.mjs";
import "./banner-DNLxDHdP.mjs";
import "./fs-BNfOTIDu.mjs";
import build_default from "./build-CrY4JY0C.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 };

14
node_modules/@nuxt/cli/dist/index.d.mts generated vendored Normal file
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 };

263
node_modules/@nuxt/cli/dist/index.mjs generated vendored Normal file
View File

@@ -0,0 +1,263 @@
import { t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { t as templateNames } from "./templates-CCEGPE6-.mjs";
import { t as templates } from "./templates-BQDUIkuM.mjs";
import { resolve } from "node:path";
import process from "node:process";
import { defineCommand, runCommand as runCommand$1, runMain as runMain$1 } from "citty";
import { colors } from "consola/utils";
import { provider } from "std-env";
import { consola } from "consola";
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-I_kOiJXU.mjs").then((n) => n.n).then(_rDefault),
"add-template": () => import("./add-template-BfsD3GVG.mjs").then(_rDefault),
"analyze": () => import("./analyze-GrNVZYjF.mjs").then(_rDefault),
"build": () => import("./build-CrY4JY0C.mjs").then(_rDefault),
"cleanup": () => import("./cleanup-viSjdn1J.mjs").then(_rDefault),
"_dev": () => import("./dev-child-kKJfFeIz.mjs").then(_rDefault),
"dev": () => import("./dev-bt4if7SS.mjs").then(_rDefault),
"devtools": () => import("./devtools-BGOrYlGY.mjs").then(_rDefault),
"generate": () => import("./generate-DreRkh3n.mjs").then(_rDefault),
"info": () => import("./info-BdhebRiU.mjs").then(_rDefault),
"init": () => import("./init-DNOKWPLa.mjs").then(_rDefault),
"module": () => import("./module-1JKddNR8.mjs").then(_rDefault),
"prepare": () => import("./prepare-CNPL0HH9.mjs").then((n) => n.n).then(_rDefault),
"preview": () => import("./preview-DkA-5PKH.mjs").then(_rDefault),
"start": () => import("./preview-DkA-5PKH.mjs").then(_rDefault),
"test": () => import("./test-pzJ8rBAf.mjs").then(_rDefault),
"typecheck": () => import("./typecheck-C8wVgBzd.mjs").then(_rDefault),
"upgrade": () => import("./upgrade-D81ZftDV.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.33.1";
var description = "Nuxt CLI";
//#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, argv = process.argv.slice(2), data = {}) {
argv.push("--no-clear");
if (!(name in commands)) throw new Error(`Invalid command ${name}`);
return await runCommand$1(await commands[name](), {
rawArgs: argv,
data: { overrides: data.overrides || {} }
});
}
//#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(String(err)));
if (command === "init") await backgroundTasks;
if (command === "add" && ctx.rawArgs[1] && templateNames.includes(ctx.rawArgs[1])) {
logger.warn(`${colors.yellow("Deprecated:")} Using ${colors.cyan("nuxt add <template> <name>")} is deprecated.`);
logger.info(`Please use ${colors.cyan("nuxt add-template <template> <name>")} instead.`);
await runCommand("add-template", [...ctx.rawArgs.slice(1)]).catch((err) => {
console.error(err.message);
process.exit(1);
});
process.exit(0);
}
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
export { main, runCommand, runMain };

139
node_modules/@nuxt/cli/dist/info-BdhebRiU.mjs generated vendored Normal file
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-4LNqcmNp.mjs";
import "./versions-DD7jbeRR.mjs";
import { t as getBuilder } from "./banner-DNLxDHdP.mjs";
import { t as formatInfoBox } from "./formatting-PESozNtr.mjs";
import { t as getPackageManagerVersion } from "./packageManagers-BX7-V04a.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { colors } from "consola/utils";
import { isBun, isDeno, isMinimal } from "std-env";
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.33.1";
//#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) => copy(copyStr, (err) => resolve(!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 };

484
node_modules/@nuxt/cli/dist/init-DNOKWPLa.mjs generated vendored Normal file
View File

@@ -0,0 +1,484 @@
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-4LNqcmNp.mjs";
import { t as getNuxtVersion } from "./versions-DD7jbeRR.mjs";
import "./fs-BNfOTIDu.mjs";
import { i as runCommand$1, r as selectModulesAutocomplete, t as add_default } from "./add-I_kOiJXU.mjs";
import { n as fetchModules, t as checkNuxtCompatibility } from "./_utils-B8YNEdpq.mjs";
import "./prepare-CNPL0HH9.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { colors } from "consola/utils";
import { hasTTY } from "std-env";
import { box, cancel, confirm, intro, isCancel, outro, select, spinner, tasks, text } from "@clack/prompts";
import { basename, join, relative, resolve } from "pathe";
import { existsSync } from "node:fs";
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-BQDUIkuM.mjs").then((n) => n.n).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);
}
let dir = ctx.args.dir;
if (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);
}
dir = result;
}
const cwd = resolve(ctx.args.cwd);
let templateDownloadPath = resolve(cwd, 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;
}
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 (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, 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;
}
let gitInit = ctx.args.gitInit === "false" ? false : ctx.args.gitInit;
if (gitInit === void 0) {
const result = await confirm({ message: "Initialize git repository?" });
if (isCancel(result)) {
cancel("Operation cancelled.");
process.exit(1);
}
gitInit = result;
}
if (ctx.args.install === false || 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
},
silent: true
});
return "Dependencies installed";
}
}];
if (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 browse and install 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 allModules = response.filter((module) => module.npm !== "@nuxt/devtools" && !templateDeps.includes(module.npm) && (!module.compatibility.nuxt || checkNuxtCompatibility(module, nuxtVersion)));
if (allModules.length === 0) logger.info("All modules are already included in this template.");
else {
const result = await selectModulesAutocomplete({ modules: allModules });
if (result.selected.length > 0) {
const modules = result.selected;
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) => `${themeColor + text}\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 };

49
node_modules/@nuxt/cli/dist/kit-4LNqcmNp.mjs generated vendored Normal file
View File

@@ -0,0 +1,49 @@
import process from "node:process";
import { relative } from "pathe";
import { pathToFileURL } from "node:url";
import { resolveModulePath } from "exsolve";
//#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 };

9
node_modules/@nuxt/cli/dist/logger-B4ge7MhP.mjs generated vendored Normal file
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 };

17
node_modules/@nuxt/cli/dist/module-1JKddNR8.mjs generated vendored Normal file
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-I_kOiJXU.mjs").then((n) => n.n).then((r) => r.default || r),
search: () => import("./search--NGnNBGz.mjs").then((r) => r.default || r)
}
});
//#endregion
export { module_default as default };

44
node_modules/@nuxt/cli/dist/nuxt-4ILhz74C.mjs generated vendored Normal file
View File

@@ -0,0 +1,44 @@
import { n as logger } from "./logger-B4ge7MhP.mjs";
import { r as rmRecursive } from "./fs-BNfOTIDu.mjs";
import { dirname, resolve } from "pathe";
import { promises } from "node:fs";
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 };

52
node_modules/@nuxt/cli/dist/prepare-CNPL0HH9.mjs generated vendored Normal file
View File

@@ -0,0 +1,52 @@
import { t as __exportAll } from "./rolldown-runtime-95iHPtFO.mjs";
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-4LNqcmNp.mjs";
import { t as clearBuildDir } from "./fs-BNfOTIDu.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_exports = /* @__PURE__ */ __exportAll({ default: () => prepare_default });
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_exports as n, prepare_default as t };

118
node_modules/@nuxt/cli/dist/preview-DkA-5PKH.mjs generated vendored Normal file
View File

@@ -0,0 +1,118 @@
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-4LNqcmNp.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 { resolve as resolve$1 } from "pathe";
import { existsSync, promises } from "node:fs";
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) => colors.yellow(text)
});
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, ...commandArgs] = nitroJSON.commands.preview.split(" ");
await x(command, commandArgs, {
throwOnError: true,
nodeOptions: {
stdio: "inherit",
cwd: outputPath,
env: {
...process.env,
NUXT_PORT: port,
NITRO_PORT: port
}
}
});
}
});
//#endregion
export { command as default };

View File

@@ -0,0 +1,18 @@
//#region \0rolldown/runtime.js
var __defProp = Object.defineProperty;
var __exportAll = (all, no_symbols) => {
let target = {};
for (var name in all) {
__defProp(target, name, {
get: all[name],
enumerable: true
});
}
if (!no_symbols) {
__defProp(target, Symbol.toStringTag, { value: "Module" });
}
return target;
};
//#endregion
export { __exportAll as t };

120
node_modules/@nuxt/cli/dist/search--NGnNBGz.mjs generated vendored Normal file
View File

@@ -0,0 +1,120 @@
import { t as cwdArgs } from "./_shared-BCYCnX0T.mjs";
import { n as logger } from "./logger-B4ge7MhP.mjs";
import "./kit-4LNqcmNp.mjs";
import { t as getNuxtVersion } from "./versions-DD7jbeRR.mjs";
import { t as formatInfoBox } from "./formatting-PESozNtr.mjs";
import { n as fetchModules, t as checkNuxtCompatibility } from "./_utils-B8YNEdpq.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 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 };

37
node_modules/@nuxt/cli/dist/templates-BQDUIkuM.mjs generated vendored Normal file
View File

@@ -0,0 +1,37 @@
import { t as __exportAll } from "./rolldown-runtime-95iHPtFO.mjs";
//#region ../nuxi/src/data/templates.ts
var templates_exports = /* @__PURE__ */ __exportAll({ templates: () => templates });
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_exports as n, templates as t };

283
node_modules/@nuxt/cli/dist/templates-CCEGPE6-.mjs generated vendored Normal file
View File

@@ -0,0 +1,283 @@
import { 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
};
const _templateNames = {
"api": void 0,
"app": void 0,
"app-config": void 0,
"component": void 0,
"composable": void 0,
"error": void 0,
"layer": void 0,
"layout": void 0,
"middleware": void 0,
"module": void 0,
"page": void 0,
"plugin": void 0,
"server-middleware": void 0,
"server-plugin": void 0,
"server-route": void 0,
"server-util": void 0
};
const templateNames = Object.keys(_templateNames);
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
export { templates as n, templateNames as t };

55
node_modules/@nuxt/cli/dist/test-pzJ8rBAf.mjs generated vendored Normal file
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(String(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 };

102
node_modules/@nuxt/cli/dist/typecheck-C8wVgBzd.mjs generated vendored Normal file
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-4LNqcmNp.mjs";
import process from "node:process";
import { defineCommand } from "citty";
import { isBun } from "std-env";
import { resolve } from "pathe";
import { resolveModulePath } from "exsolve";
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 } = await loadKit(cwd);
const nuxt = await loadNuxt({
cwd,
dotenv: {
cwd,
fileName: dotenv
},
overrides: {
_prepare: true,
logLevel,
...overrides
}
});
await writeTypes(nuxt);
await buildNuxt(nuxt);
await nuxt.close();
}
//#endregion
export { typecheck_default as default };

225
node_modules/@nuxt/cli/dist/upgrade-D81ZftDV.mjs generated vendored Normal file
View File

@@ -0,0 +1,225 @@
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-4LNqcmNp.mjs";
import { t as getNuxtVersion } from "./versions-DD7jbeRR.mjs";
import "./fs-BNfOTIDu.mjs";
import { r as nuxtVersionToGitIdentifier, t as cleanupNuxtDirs } from "./nuxt-4ILhz74C.mjs";
import { t as getPackageManagerVersion } from "./packageManagers-BX7-V04a.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 { resolve } from "pathe";
import { existsSync } from "node:fs";
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"
};
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 };

35
node_modules/@nuxt/cli/dist/versions-DD7jbeRR.mjs generated vendored Normal file
View File

@@ -0,0 +1,35 @@
import { n as tryResolveNuxt } from "./kit-4LNqcmNp.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 };

1
node_modules/@nuxt/cli/node_modules/.bin/giget generated vendored Symbolic link
View File

@@ -0,0 +1 @@
../giget/dist/cli.mjs

21
node_modules/@nuxt/cli/node_modules/citty/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
MIT License
Copyright (c) Pooya Parsa <pooya@pi0.io>
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.

105
node_modules/@nuxt/cli/node_modules/citty/README.md generated vendored Normal file
View File

@@ -0,0 +1,105 @@
# 🌆 citty
<!-- automd:badges color=yellow bundlephobia -->
[![npm version](https://img.shields.io/npm/v/citty?color=yellow)](https://npmjs.com/package/citty)
[![npm downloads](https://img.shields.io/npm/dm/citty?color=yellow)](https://npmjs.com/package/citty)
[![bundle size](https://img.shields.io/bundlephobia/minzip/citty?color=yellow)](https://bundlephobia.com/package/citty)
<!-- /automd -->
Elegant CLI Builder
- Zero dependency
- Fast and lightweight argument parser (based on native [Node.js `util.parseArgs`](https://nodejs.org/api/util.html#utilparseargsconfig))
- Smart value parsing with typecast and boolean shortcuts
- Nested sub-commands
- Lazy and Async commands
- Pluggable and composable API
- Auto generated usage and help
## Usage
Install package:
```sh
npx nypm add -D citty
```
Import:
```js
import { defineCommand, runMain } from "citty";
```
Define main command to run:
```ts
import { defineCommand, runMain } from "citty";
const main = defineCommand({
meta: {
name: "hello",
version: "1.0.0",
description: "My Awesome CLI App",
},
args: {
name: {
type: "positional",
description: "Your name",
required: true,
},
friendly: {
type: "boolean",
description: "Use friendly greeting",
},
},
run({ args }) {
console.log(`${args.friendly ? "Hi" : "Greetings"} ${args.name}!`);
},
});
runMain(main);
```
## Utils
### `defineCommand`
`defineCommand` is a type helper for defining commands.
### `runMain`
Runs a command with usage support and graceful error handling.
### `createMain`
Create a wrapper around command that calls `runMain` when called.
### `runCommand`
Parses input args and runs command and sub-commands (unsupervised). You can access `result` key from returnd/awaited value to access command's result.
### `parseArgs`
Parses input arguments and applies defaults.
### `renderUsage`
Renders command usage to a string value.
### `showUsage`
Renders usage and prints to the console
## Development
- Clone this repository
- Install latest LTS version of [Node.js](https://nodejs.org/en/)
- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable`
- Install dependencies using `pnpm install`
- Run interactive tests using `pnpm dev`
## License
Made with 💛 Published under [MIT License](./LICENSE).

View File

@@ -0,0 +1,33 @@
# Licenses of Bundled Dependencies
The published artifact additionally contains code with the following licenses:
MIT
# Bundled Dependencies
## scule
License: MIT
Repository: https://github.com/unjs/scule
> MIT License
>
> Copyright (c) Pooya Parsa <pooya@pi0.io>
>
> 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,65 @@
const NUMBER_CHAR_RE = /\d/;
const STR_SPLITTERS = [
"-",
"_",
"/",
"."
];
function isUppercase(char = "") {
if (NUMBER_CHAR_RE.test(char)) return;
return char !== char.toLowerCase();
}
function splitByCase(str, separators) {
const splitters = separators ?? STR_SPLITTERS;
const parts = [];
if (!str || typeof str !== "string") return parts;
let buff = "";
let previousUpper;
let previousSplitter;
for (const char of str) {
const isSplitter = splitters.includes(char);
if (isSplitter === true) {
parts.push(buff);
buff = "";
previousUpper = void 0;
continue;
}
const isUpper = isUppercase(char);
if (previousSplitter === false) {
if (previousUpper === false && isUpper === true) {
parts.push(buff);
buff = char;
previousUpper = isUpper;
continue;
}
if (previousUpper === true && isUpper === false && buff.length > 1) {
const lastChar = buff.at(-1);
parts.push(buff.slice(0, Math.max(0, buff.length - 1)));
buff = lastChar + char;
previousUpper = isUpper;
continue;
}
}
buff += char;
previousUpper = isUpper;
previousSplitter = isSplitter;
}
parts.push(buff);
return parts;
}
function upperFirst(str) {
return str ? str[0].toUpperCase() + str.slice(1) : "";
}
function lowerFirst(str) {
return str ? str[0].toLowerCase() + str.slice(1) : "";
}
function pascalCase(str, opts) {
return str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => upperFirst(opts?.normalize ? p.toLowerCase() : p)).join("") : "";
}
function camelCase(str, opts) {
return lowerFirst(pascalCase(str || "", opts));
}
function kebabCase(str, joiner) {
return str ? (Array.isArray(str) ? str : splitByCase(str)).map((p) => p.toLowerCase()).join(joiner ?? "-") : "";
}
export { kebabCase as n, camelCase as t };

View File

@@ -0,0 +1,101 @@
//#region src/types.d.ts
type ArgType = "boolean" | "string" | "enum" | "positional" | undefined;
type _ArgDef<T extends ArgType, VT extends boolean | number | string> = {
type?: T;
description?: string;
valueHint?: string;
alias?: string | string[];
default?: VT;
required?: boolean;
options?: string[];
};
type BooleanArgDef = Omit<_ArgDef<"boolean", boolean>, "options"> & {
negativeDescription?: string;
};
type StringArgDef = Omit<_ArgDef<"string", string>, "options">;
type EnumArgDef = _ArgDef<"enum", string>;
type PositionalArgDef = Omit<_ArgDef<"positional", string>, "alias" | "options">;
type ArgDef = BooleanArgDef | StringArgDef | PositionalArgDef | EnumArgDef;
type ArgsDef = Record<string, ArgDef>;
type Arg = ArgDef & {
name: string;
alias: string[];
};
type ResolveParsedArgType<T extends ArgDef, VT> = T extends {
default?: any;
required?: boolean;
} ? T["default"] extends NonNullable<VT> ? VT : T["required"] extends true ? VT : VT | undefined : VT | undefined;
type ParsedPositionalArg<T extends ArgDef> = T extends {
type: "positional";
} ? ResolveParsedArgType<T, string> : never;
type ParsedStringArg<T extends ArgDef> = T extends {
type: "string";
} ? ResolveParsedArgType<T, string> : never;
type ParsedBooleanArg<T extends ArgDef> = T extends {
type: "boolean";
} ? ResolveParsedArgType<T, boolean> : never;
type ParsedEnumArg<T extends ArgDef> = T extends {
type: "enum";
options: infer U;
} ? U extends Array<any> ? ResolveParsedArgType<T, U[number]> : never : never;
type RawArgs = {
_: string[];
};
type ParsedArg<T extends ArgDef> = T["type"] extends "positional" ? ParsedPositionalArg<T> : T["type"] extends "boolean" ? ParsedBooleanArg<T> : T["type"] extends "string" ? ParsedStringArg<T> : T["type"] extends "enum" ? ParsedEnumArg<T> : never;
type ParsedArgs<T extends ArgsDef = ArgsDef> = RawArgs & { [K in keyof T]: ParsedArg<T[K]> } & { [K in keyof T as T[K] extends {
alias: string;
} ? T[K]["alias"] : never]: ParsedArg<T[K]> } & { [K in keyof T as T[K] extends {
alias: string[];
} ? T[K]["alias"][number] : never]: ParsedArg<T[K]> } & Record<string, string | number | boolean | string[]>;
interface CommandMeta {
name?: string;
version?: string;
description?: string;
hidden?: boolean;
}
type SubCommandsDef = Record<string, Resolvable<CommandDef<any>>>;
type CommandDef<T extends ArgsDef = ArgsDef> = {
meta?: Resolvable<CommandMeta>;
args?: Resolvable<T>;
subCommands?: Resolvable<SubCommandsDef>;
setup?: (context: CommandContext<T>) => any | Promise<any>;
cleanup?: (context: CommandContext<T>) => any | Promise<any>;
run?: (context: CommandContext<T>) => any | Promise<any>;
};
type CommandContext<T extends ArgsDef = ArgsDef> = {
rawArgs: string[];
args: ParsedArgs<T>;
cmd: CommandDef<T>;
subCommand?: CommandDef<T>;
data?: any;
};
type Awaitable<T> = () => T | Promise<T>;
type Resolvable<T> = T | Promise<T> | (() => T) | (() => Promise<T>);
//#endregion
//#region src/command.d.ts
declare function defineCommand<const T extends ArgsDef = ArgsDef>(def: CommandDef<T>): CommandDef<T>;
interface RunCommandOptions {
rawArgs: string[];
data?: any;
showUsage?: boolean;
}
declare function runCommand<T extends ArgsDef = ArgsDef>(cmd: CommandDef<T>, opts: RunCommandOptions): Promise<{
result: unknown;
}>;
//#endregion
//#region src/usage.d.ts
declare function showUsage<T extends ArgsDef = ArgsDef>(cmd: CommandDef<T>, parent?: CommandDef<T>): Promise<void>;
declare function renderUsage<T extends ArgsDef = ArgsDef>(cmd: CommandDef<T>, parent?: CommandDef<T>): Promise<string>;
//#endregion
//#region src/main.d.ts
interface RunMainOptions {
rawArgs?: string[];
showUsage?: typeof showUsage;
}
declare function runMain<T extends ArgsDef = ArgsDef>(cmd: CommandDef<T>, opts?: RunMainOptions): Promise<void>;
declare function createMain<T extends ArgsDef = ArgsDef>(cmd: CommandDef<T>): (opts?: RunMainOptions) => Promise<void>;
//#endregion
//#region src/args.d.ts
declare function parseArgs<T extends ArgsDef = ArgsDef>(rawArgs: string[], argsDef: ArgsDef): ParsedArgs<T>;
//#endregion
export { Arg, ArgDef, ArgType, ArgsDef, Awaitable, BooleanArgDef, CommandContext, CommandDef, CommandMeta, EnumArgDef, ParsedArgs, PositionalArgDef, Resolvable, type RunCommandOptions, type RunMainOptions, StringArgDef, SubCommandsDef, _ArgDef, createMain, defineCommand, parseArgs, renderUsage, runCommand, runMain, showUsage };

View File

@@ -0,0 +1,297 @@
import { n as kebabCase, t as camelCase } from "./_chunks/libs/scule.mjs";
import { parseArgs as parseArgs$1 } from "node:util";
function toArray(val) {
if (Array.isArray(val)) return val;
return val === void 0 ? [] : [val];
}
function formatLineColumns(lines, linePrefix = "") {
const maxLength = [];
for (const line of lines) for (const [i, element] of line.entries()) maxLength[i] = Math.max(maxLength[i] || 0, element.length);
return lines.map((l) => l.map((c, i) => linePrefix + c[i === 0 ? "padStart" : "padEnd"](maxLength[i])).join(" ")).join("\n");
}
function resolveValue(input) {
return typeof input === "function" ? input() : input;
}
var CLIError = class extends Error {
code;
constructor(message, code) {
super(message);
this.name = "CLIError";
this.code = code;
}
};
function parseRawArgs(args = [], opts = {}) {
const booleans = new Set(opts.boolean || []);
const strings = new Set(opts.string || []);
const aliasMap = opts.alias || {};
const defaults = opts.default || {};
const aliasToMain = /* @__PURE__ */ new Map();
const mainToAliases = /* @__PURE__ */ new Map();
for (const [key, value] of Object.entries(aliasMap)) {
const targets = value;
for (const target of targets) {
aliasToMain.set(key, target);
if (!mainToAliases.has(target)) mainToAliases.set(target, []);
mainToAliases.get(target).push(key);
aliasToMain.set(target, key);
if (!mainToAliases.has(key)) mainToAliases.set(key, []);
mainToAliases.get(key).push(target);
}
}
const options = {};
function getType(name) {
if (booleans.has(name)) return "boolean";
const aliases = mainToAliases.get(name) || [];
for (const alias of aliases) if (booleans.has(alias)) return "boolean";
return "string";
}
const allOptions = new Set([
...booleans,
...strings,
...Object.keys(aliasMap),
...Object.values(aliasMap).flat(),
...Object.keys(defaults)
]);
for (const name of allOptions) if (!options[name]) options[name] = {
type: getType(name),
default: defaults[name]
};
for (const [alias, main] of aliasToMain.entries()) if (alias.length === 1 && options[main] && !options[main].short) options[main].short = alias;
const processedArgs = [];
const negatedFlags = {};
for (let i = 0; i < args.length; i++) {
const arg = args[i];
if (arg === "--") {
processedArgs.push(...args.slice(i));
break;
}
if (arg.startsWith("--no-")) {
const flagName = arg.slice(5);
negatedFlags[flagName] = true;
continue;
}
processedArgs.push(arg);
}
let parsed;
try {
parsed = parseArgs$1({
args: processedArgs,
options: Object.keys(options).length > 0 ? options : void 0,
allowPositionals: true,
strict: false
});
} catch {
parsed = {
values: {},
positionals: processedArgs
};
}
const out = { _: [] };
out._ = parsed.positionals;
for (const [key, value] of Object.entries(parsed.values)) out[key] = value;
for (const [name] of Object.entries(negatedFlags)) {
out[name] = false;
const mainName = aliasToMain.get(name);
if (mainName) out[mainName] = false;
const aliases = mainToAliases.get(name);
if (aliases) for (const alias of aliases) out[alias] = false;
}
for (const [alias, main] of aliasToMain.entries()) {
if (out[alias] !== void 0 && out[main] === void 0) out[main] = out[alias];
if (out[main] !== void 0 && out[alias] === void 0) out[alias] = out[main];
}
return out;
}
const noColor = /* @__PURE__ */ (() => {
const env = globalThis.process?.env ?? {};
return env.NO_COLOR === "1" || env.TERM === "dumb" || env.TEST || env.CI;
})();
const _c = (c, r = 39) => (t) => noColor ? t : `\u001B[${c}m${t}\u001B[${r}m`;
const bold = /* @__PURE__ */ _c(1, 22);
const cyan = /* @__PURE__ */ _c(36);
const gray = /* @__PURE__ */ _c(90);
const underline = /* @__PURE__ */ _c(4, 24);
function parseArgs(rawArgs, argsDef) {
const parseOptions = {
boolean: [],
string: [],
alias: {},
default: {}
};
const args = resolveArgs(argsDef);
for (const arg of args) {
if (arg.type === "positional") continue;
if (arg.type === "string" || arg.type === "enum") parseOptions.string.push(arg.name);
else if (arg.type === "boolean") parseOptions.boolean.push(arg.name);
if (arg.default !== void 0) parseOptions.default[arg.name] = arg.default;
if (arg.alias) parseOptions.alias[arg.name] = arg.alias;
const camelName = camelCase(arg.name);
const kebabName = kebabCase(arg.name);
if (camelName !== arg.name || kebabName !== arg.name) {
const existingAliases = toArray(parseOptions.alias[arg.name] || []);
if (camelName !== arg.name && !existingAliases.includes(camelName)) existingAliases.push(camelName);
if (kebabName !== arg.name && !existingAliases.includes(kebabName)) existingAliases.push(kebabName);
if (existingAliases.length > 0) parseOptions.alias[arg.name] = existingAliases;
}
}
const parsed = parseRawArgs(rawArgs, parseOptions);
const [ ...positionalArguments] = parsed._;
const parsedArgsProxy = new Proxy(parsed, { get(target, prop) {
return target[prop] ?? target[camelCase(prop)] ?? target[kebabCase(prop)];
} });
for (const [, arg] of args.entries()) if (arg.type === "positional") {
const nextPositionalArgument = positionalArguments.shift();
if (nextPositionalArgument !== void 0) parsedArgsProxy[arg.name] = nextPositionalArgument;
else if (arg.default === void 0 && arg.required !== false) throw new CLIError(`Missing required positional argument: ${arg.name.toUpperCase()}`, "EARG");
else parsedArgsProxy[arg.name] = arg.default;
} else if (arg.type === "enum") {
const argument = parsedArgsProxy[arg.name];
const options = arg.options || [];
if (argument !== void 0 && options.length > 0 && !options.includes(argument)) throw new CLIError(`Invalid value for argument: ${cyan(`--${arg.name}`)} (${cyan(argument)}). Expected one of: ${options.map((o) => cyan(o)).join(", ")}.`, "EARG");
} else if (arg.required && parsedArgsProxy[arg.name] === void 0) throw new CLIError(`Missing required argument: --${arg.name}`, "EARG");
return parsedArgsProxy;
}
function resolveArgs(argsDef) {
const args = [];
for (const [name, argDef] of Object.entries(argsDef || {})) args.push({
...argDef,
name,
alias: toArray(argDef.alias)
});
return args;
}
function defineCommand(def) {
return def;
}
async function runCommand(cmd, opts) {
const cmdArgs = await resolveValue(cmd.args || {});
const parsedArgs = parseArgs(opts.rawArgs, cmdArgs);
const context = {
rawArgs: opts.rawArgs,
args: parsedArgs,
data: opts.data,
cmd
};
if (typeof cmd.setup === "function") await cmd.setup(context);
let result;
try {
const subCommands = await resolveValue(cmd.subCommands);
if (subCommands && Object.keys(subCommands).length > 0) {
const subCommandArgIndex = opts.rawArgs.findIndex((arg) => !arg.startsWith("-"));
const subCommandName = opts.rawArgs[subCommandArgIndex];
if (subCommandName) {
if (!subCommands[subCommandName]) throw new CLIError(`Unknown command ${cyan(subCommandName)}`, "E_UNKNOWN_COMMAND");
const subCommand = await resolveValue(subCommands[subCommandName]);
if (subCommand) await runCommand(subCommand, { rawArgs: opts.rawArgs.slice(subCommandArgIndex + 1) });
} else if (!cmd.run) throw new CLIError(`No command specified.`, "E_NO_COMMAND");
}
if (typeof cmd.run === "function") result = await cmd.run(context);
} finally {
if (typeof cmd.cleanup === "function") await cmd.cleanup(context);
}
return { result };
}
async function resolveSubCommand(cmd, rawArgs, parent) {
const subCommands = await resolveValue(cmd.subCommands);
if (subCommands && Object.keys(subCommands).length > 0) {
const subCommandArgIndex = rawArgs.findIndex((arg) => !arg.startsWith("-"));
const subCommandName = rawArgs[subCommandArgIndex];
const subCommand = await resolveValue(subCommands[subCommandName]);
if (subCommand) return resolveSubCommand(subCommand, rawArgs.slice(subCommandArgIndex + 1), cmd);
}
return [cmd, parent];
}
async function showUsage(cmd, parent) {
try {
console.log(await renderUsage(cmd, parent) + "\n");
} catch (error) {
console.error(error);
}
}
const negativePrefixRe = /^no[-A-Z]/;
async function renderUsage(cmd, parent) {
const cmdMeta = await resolveValue(cmd.meta || {});
const cmdArgs = resolveArgs(await resolveValue(cmd.args || {}));
const parentMeta = await resolveValue(parent?.meta || {});
const commandName = `${parentMeta.name ? `${parentMeta.name} ` : ""}` + (cmdMeta.name || process.argv[1]);
const argLines = [];
const posLines = [];
const commandsLines = [];
const usageLine = [];
for (const arg of cmdArgs) if (arg.type === "positional") {
const name = arg.name.toUpperCase();
const isRequired = arg.required !== false && arg.default === void 0;
const defaultHint = arg.default ? `="${arg.default}"` : "";
posLines.push([
cyan(name + defaultHint),
arg.description || "",
arg.valueHint ? `<${arg.valueHint}>` : ""
]);
usageLine.push(isRequired ? `<${name}>` : `[${name}]`);
} else {
const isRequired = arg.required === true && arg.default === void 0;
const argStr = [...(arg.alias || []).map((a) => `-${a}`), `--${arg.name}`].join(", ") + (arg.type === "string" && (arg.valueHint || arg.default) ? `=${arg.valueHint ? `<${arg.valueHint}>` : `"${arg.default || ""}"`}` : "") + (arg.type === "enum" && arg.options ? `=<${arg.options.join("|")}>` : "");
argLines.push([cyan(argStr + (isRequired ? " (required)" : "")), arg.description || ""]);
if (arg.type === "boolean" && (arg.default === true || arg.negativeDescription) && !negativePrefixRe.test(arg.name)) {
const negativeArgStr = [...(arg.alias || []).map((a) => `--no-${a}`), `--no-${arg.name}`].join(", ");
argLines.push([cyan(negativeArgStr + (isRequired ? " (required)" : "")), arg.negativeDescription || ""]);
}
if (isRequired) usageLine.push(argStr);
}
if (cmd.subCommands) {
const commandNames = [];
const subCommands = await resolveValue(cmd.subCommands);
for (const [name, sub] of Object.entries(subCommands)) {
const meta = await resolveValue((await resolveValue(sub))?.meta);
if (meta?.hidden) continue;
commandsLines.push([cyan(name), meta?.description || ""]);
commandNames.push(name);
}
usageLine.push(commandNames.join("|"));
}
const usageLines = [];
const version = cmdMeta.version || parentMeta.version;
usageLines.push(gray(`${cmdMeta.description} (${commandName + (version ? ` v${version}` : "")})`), "");
const hasOptions = argLines.length > 0 || posLines.length > 0;
usageLines.push(`${underline(bold("USAGE"))} ${cyan(`${commandName}${hasOptions ? " [OPTIONS]" : ""} ${usageLine.join(" ")}`)}`, "");
if (posLines.length > 0) {
usageLines.push(underline(bold("ARGUMENTS")), "");
usageLines.push(formatLineColumns(posLines, " "));
usageLines.push("");
}
if (argLines.length > 0) {
usageLines.push(underline(bold("OPTIONS")), "");
usageLines.push(formatLineColumns(argLines, " "));
usageLines.push("");
}
if (commandsLines.length > 0) {
usageLines.push(underline(bold("COMMANDS")), "");
usageLines.push(formatLineColumns(commandsLines, " "));
usageLines.push("", `Use ${cyan(`${commandName} <command> --help`)} for more information about a command.`);
}
return usageLines.filter((l) => typeof l === "string").join("\n");
}
async function runMain(cmd, opts = {}) {
const rawArgs = opts.rawArgs || process.argv.slice(2);
const showUsage$1 = opts.showUsage || showUsage;
try {
if (rawArgs.includes("--help") || rawArgs.includes("-h")) {
await showUsage$1(...await resolveSubCommand(cmd, rawArgs));
process.exit(0);
} else if (rawArgs.length === 1 && rawArgs[0] === "--version") {
const meta = typeof cmd.meta === "function" ? await cmd.meta() : await cmd.meta;
if (!meta?.version) throw new CLIError("No version specified", "E_NO_VERSION");
console.log(meta.version);
} else await runCommand(cmd, { rawArgs });
} catch (error) {
if (error instanceof CLIError) {
await showUsage$1(...await resolveSubCommand(cmd, rawArgs));
console.error(error.message);
} else console.error(error, "\n");
process.exit(1);
}
}
function createMain(cmd) {
return (opts = {}) => runMain(cmd, opts);
}
export { createMain, defineCommand, parseArgs, renderUsage, runCommand, runMain, showUsage };

42
node_modules/@nuxt/cli/node_modules/citty/package.json generated vendored Normal file
View File

@@ -0,0 +1,42 @@
{
"name": "citty",
"version": "0.2.1",
"description": "Elegant CLI Builder",
"license": "MIT",
"repository": "unjs/citty",
"files": [
"dist"
],
"type": "module",
"sideEffects": false,
"types": "./dist/index.d.mts",
"exports": {
".": "./dist/index.mjs"
},
"scripts": {
"build": "obuild",
"dev": "vitest dev",
"lint": "oxlint . && oxfmt --check",
"lint:fix": "oxlint . --fix && oxfmt",
"prepack": "pnpm run build",
"play": "node ./playground/cli.ts",
"release": "pnpm test && pnpm build && changelogen --release --push && npm publish",
"test": "pnpm lint && pnpm test:types && vitest run --coverage",
"test:types": "tsgo --noEmit"
},
"devDependencies": {
"@types/node": "^25.2.3",
"@typescript/native-preview": "7.0.0-dev.20260212.1",
"@vitest/coverage-v8": "^4.0.18",
"automd": "^0.4.3",
"changelogen": "^0.6.2",
"eslint-config-unjs": "^0.6.2",
"obuild": "^0.4.27",
"oxfmt": "^0.32.0",
"oxlint": "^1.47.0",
"scule": "^1.3.0",
"typescript": "^5.9.3",
"vitest": "^4.0.18"
},
"packageManager": "pnpm@10.29.3"
}

184
node_modules/@nuxt/cli/node_modules/giget/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,184 @@
MIT License
Copyright (c) Pooya Parsa <pooya@pi0.io>
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.
---
Third party bundled dependencies
- https://github.com/isaacs/node-tar
- https://github.com/isaacs/fs-minipass
"""
The ISC License
Copyright (c) Isaac Z. Schlueter and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
""""
- https://github.com/isaacs/minipass
"""
The ISC License
Copyright (c) 2017-2023 npm, Inc., Isaac Z. Schlueter, and Contributors
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR
IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
"""
- https://github.com/isaacs/minizlib
"""
Minizlib was created by Isaac Z. Schlueter.
It is a derivative work of the Node.js project.
"""
Copyright (c) 2017-2023 Isaac Z. Schlueter and Contributors
Copyright (c) 2017-2023 Node.js contributors. All rights reserved.
Copyright (c) 2017-2023 Joyent, Inc. and other Node contributors. All rights reserved.
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.
"""
- https://github.com/isaacs/node-mkdirp
"""
Copyright (c) 2011-2023 James Halliday (mail@substack.net) and Isaac Z. Schlueter (i@izs.me)
This project is free software released under the MIT license:
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.
"""
- https://github.com/isaacs/yallist/blob/main/LICENSE.md
- https://github.com/isaacs/chownr/blob/main/LICENSE.md
"""
# Blue Oak Model License
Version 1.0.0
## Purpose
This license gives everyone as much permission to work with
this software as possible, while protecting contributors
from liability.
## Acceptance
In order to receive this license, you must agree to its
rules. The rules of this license are both obligations
under that agreement and conditions to your license.
You must not do anything with this software that triggers
a rule that you cannot or will not follow.
## Copyright
Each contributor licenses you to do everything with this
software that would otherwise infringe that contributor's
copyright in it.
## Notices
You must ensure that everyone who gets a copy of
any part of this software from you, with or without
changes, also gets the text of this license or a link to
<https://blueoakcouncil.org/license/1.0.0>.
## Excuse
If anyone notifies you in writing that you have not
complied with [Notices](#notices), you can keep your
license by taking all practical steps to comply within 30
days after the notice. If you do not do so, your license
ends immediately.
## Patent
Each contributor licenses you to do everything with this
software that would otherwise infringe any patent claims
they can license or become able to license.
## Reliability
No contributor can revoke this license.
## No Liability
**_As far as the law allows, this software comes as is,
without any warranty or condition, and no contributor
will be liable to anyone for any damages related to this
software or this license, under any kind of legal claim._**
"""

246
node_modules/@nuxt/cli/node_modules/giget/README.md generated vendored Normal file
View File

@@ -0,0 +1,246 @@
# giget
[![npm version][npm-version-src]][npm-version-href]
[![npm downloads][npm-downloads-src]][npm-downloads-href]
[![Codecov][codecov-src]][codecov-href]
> Download templates and git repositories with pleasure!
## Features
✨ Zero dependency
✨ Support popular git providers (GitHub, GitLab, Bitbucket, Sourcehut) out of the box.
✨ Built-in and custom [template registry](#template-registry).
✨ Fast cloning using tarball gzip without depending on local `git` and `tar`.
✨ Works online and offline with disk cache support.
✨ Custom template provider support with programmatic usage.
✨ Support extracting with a sub dir.
✨ Authorization support to download private templates
✨ Optionally install dependencies after clone using [unjs/nypm](https://github.com/unjs/nypm)
## Usage (CLI)
```bash
npx giget@latest <template> [<dir>] [...options]
```
### Arguments
- **template**: Template name or a URI describing provider, repository, sub dir, and branch/ref. (See [Examples](#examples))
- **dir**: A relative or absolute path where to extract the template.
### Options
- `--force`: Clone to existing directory even if exists.
- `--offline`: Do not attempt to download and use the cached version.
- `--prefer-offline`: Use cache if exists otherwise try to download.
- `--force-clean`: ⚠️ Remove any existing directory or file recursively before cloning.
- `--shell`: ⚠️ Open a new shell with the current working directory in cloned dir. (Experimental).
- `--registry`: URL to a custom registry. (Can be overridden with `GIGET_REGISTRY` environment variable).
- `--no-registry`: Disable registry lookup and functionality.
- `--verbose`: Show verbose debugging info.
- `--cwd`: Set the current working directory to resolve dirs relative to it.
- `--auth`: Custom Authorization token to use for downloading template. (Can be overridden with `GIGET_AUTH` environment variable).
- `--install`: Install dependencies after cloning using [unjs/nypm](https://github.com/unjs/nypm).
### Examples
```sh
# Clone nuxt starter from giget template registry
npx giget@latest nuxt
# Clone the main branch of github.com/unjs/template to unjs-template directory
npx giget@latest gh:unjs/template
# Clone to myProject directory
npx giget@latest gh:unjs/template myProject
# Clone dev branch
npx giget@latest gh:unjs/template#dev
# Clone /test directory from main branch
npx giget@latest gh:unjs/template/test
# Clone from gitlab
npx giget@latest gitlab:unjs/template
# Clone from bitbucket
npx giget@latest bitbucket:unjs/template
# Clone from sourcehut
npx giget@latest sourcehut:pi0/unjs-template
# Clone from https URL (tarball)
npx giget@latest https://api.github.com/repos/unjs/template/tarball/main
# Clone from https URL (JSON)
npx giget@latest https://raw.githubusercontent.com/unjs/giget/main/templates/unjs.json
```
## Template Registry
Giget has a built-in HTTP registry system for resolving templates. This way you can support template name shortcuts and meta-data. The default registry is served from [unjs/giget/templates](./templates/).
If you want to add your template to the built-in registry, just drop a PR to add it to the [./templates](./templates) directory. Slugs are added on a first-come first-served basis but this might change in the future.
### Custom Registry
A custom registry should provide an endpoint with the dynamic path `/:template.json` that returns a JSON response with keys the same as [custom providers](#custom-providers).
- `name`: (required) Name of the template.
- `tar` (required) Link to the tar download link.
- `defaultDir`: (optional) Default cloning directory.
- `url`: (optional) Webpage of the template.
- `subdir`: (optional) Directory inside the tar file.
- `headers`: (optional) Custom headers to send while downloading template.
Because of the simplicity, you can even use a GitHub repository as a template registry but also you can build something more powerful by bringing your own API.
## Usage (Programmatic)
Install package:
```sh
# npm
npm install giget
# yarn
yarn install giget
# pnpm
pnpm install giget
```
Import:
```js
// ESM
import { downloadTemplate } from "giget";
// CommonJS
const { downloadTemplate } = require("giget");
```
### `downloadTemplate(source, options?)`
**Example:**
```js
const { source, dir } = await downloadTemplate("github:unjs/template");
```
**Options:**
- `source`: (string) Input source in format of `[provider]:repo[/subpath][#ref]`.
- `options`: (object) Options are usually inferred from the input string. You can customize them.
- `dir`: (string) Destination directory to clone to. If not provided, `user-name` will be used relative to the current directory.
- `provider`: (string) Either `github`, `gitlab`, `bitbucket` or `sourcehut`. The default is `github`.
- `force`: (boolean) Extract to the existing dir even if already exists.
- `forceClean`: (boolean) ⚠️ Clean up any existing directory or file before cloning.
- `offline`: (boolean) Do not attempt to download and use the cached version.
- `preferOffline`: (boolean) Use cache if exists otherwise try to download.
- `providers`: (object) A map from provider name to custom providers. Can be used to override built-ins too.
- `registry`: (string or false) Set to `false` to disable registry. Set to a URL string (without trailing slash) for custom registry. (Can be overridden with `GIGET_REGISTRY` environment variable).
- `cwd`: (string) Current working directory to resolve dirs relative to it.
- `auth`: (string) Custom Authorization token to use for downloading template. (Can be overridden with `GIGET_AUTH` environment variable).
**Return value:**
The return value is a promise that resolves to the resolved template.
- `dir`: (string) Path to extracted dir.
- `source`: (string) Normalized version of the input source without provider.
- [other provider template keys]
- `url`: (string) URL of the repository that can be opened in the browser. Useful for logging.
## Custom Providers
Using the programmatic method, you can make your custom template providers.
```ts
import type { TemplateProvider } from "giget";
const rainbow: TemplateProvider = async (input, { auth }) => {
return {
name: "rainbow",
version: input,
headers: { authorization: auth },
url: `https://rainbow.template/?variant=${input}`,
tar: `https://rainbow.template/dl/rainbow.${input}.tar.gz`,
};
};
const { source, dir } = await downloadTemplate("rainbow:one", {
providers: { rainbow },
});
```
### Custom Registry Providers
You can define additional [custom registry](#custom-registry) providers using `registryProvider` utility and register to `providers`.
```ts
import { registryProvider } from "giget";
const themes = registryProvider("https://raw.githubusercontent.com/unjs/giget/main/templates");
const { source, dir } = await downloadTemplate("themes:test", {
providers: { themes },
});
```
## Providing token for private repositories
For private repositories and sources, you might need a token. In order to provide it, using CLI, you can use `--auth`, using programmatic API using `auth` option and in both modes also it is possible to use `GIGET_AUTH` environment variable to set it. The value will be set in `Authorization: Bearer ...` header by default.
**Note:** For github private repository access with Fine-grained access tokens, you need to give **Contents** and **Metadata** repository permissions.
### GitHub Actions
If your project depends on a private GitHub repository, you need to add the access token as a secret. Please see GitHub Actions docs on [creating secrets for a repository](https://docs.github.com/en/actions/security-for-github-actions/security-guides/using-secrets-in-github-actions#creating-secrets-for-a-repository). In your workflow, refer to the token as shown in the example below:
```yml
- name: Install packages
run: npm ci
env:
GIGET_AUTH: ${{ secrets.GIGET_AUTH }}
```
## Related projects
Giget wouldn't be possible without inspiration from former projects. In comparison, giget does not depend on any local command which increases stability and performance and supports custom template providers, auth, and many more features out of the box.
- [tiged/tiged](https://github.com/tiged/tiged) (maintained fork of degit)
- [nrjdalal/gitpick](https://github.com/nrjdalal/gitpick) (alternative approach)
- [Rich-Harris/degit](https://github.com/Rich-Harris/degit) (last updated - 2021)
- [samsonjs/gitter](https://github.com/samsonjs/gitter) (archived/updated - 2012)
## 💻 Development
- Clone this repository
- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable` (use `npm i -g corepack` for Node.js < 16.10)
- Install dependencies using `pnpm install`
- Run interactive tests using `pnpm dev`
## License
Made with 💛
Published under [MIT License](./LICENSE).
<!-- Badges -->
[npm-version-src]: https://img.shields.io/npm/v/giget?style=flat&colorA=18181B&colorB=F0DB4F
[npm-version-href]: https://npmjs.com/package/giget
[npm-downloads-src]: https://img.shields.io/npm/dm/giget?style=flat&colorA=18181B&colorB=F0DB4F
[npm-downloads-href]: https://npmjs.com/package/giget
[codecov-src]: https://img.shields.io/codecov/c/gh/unjs/giget/main?style=flat&colorA=18181B&colorB=F0DB4F
[codecov-href]: https://codecov.io/gh/unjs/giget

View File

@@ -0,0 +1,260 @@
import { a as resolve, i as relative, n as basename, r as dirname } from "./libs/nypm.mjs";
import { mkdir, readFile, rm, writeFile } from "node:fs/promises";
import { createWriteStream, existsSync, readdirSync, renameSync } from "node:fs";
import { pipeline } from "node:stream";
import { spawnSync } from "node:child_process";
import { homedir, tmpdir } from "node:os";
import { promisify } from "node:util";
async function download(url, filePath, options = {}) {
const infoPath = filePath + ".json";
const info = JSON.parse(await readFile(infoPath, "utf8").catch(() => "{}"));
const etag = (await sendFetch(url, {
method: "HEAD",
headers: options.headers
}).catch(() => void 0))?.headers.get("etag");
if (info.etag === etag && existsSync(filePath)) return;
if (typeof etag === "string") info.etag = etag;
const response = await sendFetch(url, { headers: options.headers });
if (response.status >= 400) throw new Error(`Failed to download ${url}: ${response.status} ${response.statusText}`);
const stream = createWriteStream(filePath);
await promisify(pipeline)(response.body, stream);
await writeFile(infoPath, JSON.stringify(info), "utf8");
}
const inputRegex = /^(?<repo>[\w.-]+\/[\w.-]+)(?<subdir>[^#]+)?(?<ref>#[\w./@-]+)?/;
function parseGitURI(input) {
const m = input.match(inputRegex)?.groups || {};
return {
repo: m.repo || "",
subdir: m.subdir || "/",
ref: m.ref ? m.ref.slice(1) : "main"
};
}
function debug(...args) {
if (process.env.DEBUG) console.debug("[giget]", ...args);
}
async function sendFetch(url, options = {}) {
if (options.headers?.["sec-fetch-mode"]) options.mode = options.headers["sec-fetch-mode"];
const res = await fetch(url, {
...options,
headers: normalizeHeaders(options.headers)
}).catch((error) => {
throw new Error(`Failed to download ${url}: ${error}`, { cause: error });
});
if (options.validateStatus && res.status >= 400) throw new Error(`Failed to fetch ${url}: ${res.status} ${res.statusText}`);
return res;
}
function cacheDirectory() {
const cacheDir = process.env.XDG_CACHE_HOME ? resolve(process.env.XDG_CACHE_HOME, "giget") : resolve(homedir(), ".cache/giget");
if (process.platform === "win32") {
const windowsCacheDir = resolve(tmpdir(), "giget");
if (!existsSync(windowsCacheDir) && existsSync(cacheDir)) try {
renameSync(cacheDir, windowsCacheDir);
} catch {}
return windowsCacheDir;
}
return cacheDir;
}
function normalizeHeaders(headers = {}) {
const normalized = {};
for (const [key, value] of Object.entries(headers)) {
if (!value) continue;
normalized[key.toLowerCase()] = value;
}
return normalized;
}
function currentShell() {
if (process.env.SHELL) return process.env.SHELL;
if (process.platform === "win32") return "cmd.exe";
return "/bin/bash";
}
function startShell(cwd) {
cwd = resolve(cwd);
const shell = currentShell();
console.info(`(experimental) Opening shell in ${relative(process.cwd(), cwd)}...`);
spawnSync(shell, [], {
cwd,
shell: true,
stdio: "inherit"
});
}
const http = async (input, options) => {
if (input.endsWith(".json")) return await _httpJSON(input, options);
const url = new URL(input);
let name = basename(url.pathname);
try {
const head = await sendFetch(url.href, {
method: "HEAD",
validateStatus: true,
headers: { authorization: options.auth ? `Bearer ${options.auth}` : void 0 }
});
if ((head.headers.get("content-type") || "").includes("application/json")) return await _httpJSON(input, options);
const filename = head.headers.get("content-disposition")?.match(/filename="?(.+)"?/)?.[1];
if (filename) name = filename.split(".")[0];
} catch (error) {
debug(`Failed to fetch HEAD for ${url.href}:`, error);
}
return {
name: `${name}-${url.href.slice(0, 8)}`,
version: "",
subdir: "",
tar: url.href,
defaultDir: name,
headers: { Authorization: options.auth ? `Bearer ${options.auth}` : void 0 }
};
};
const _httpJSON = async (input, options) => {
const info = await (await sendFetch(input, {
validateStatus: true,
headers: { authorization: options.auth ? `Bearer ${options.auth}` : void 0 }
})).json();
if (!info.tar || !info.name) throw new Error(`Invalid template info from ${input}. name or tar fields are missing!`);
return info;
};
const github = (input, options) => {
const parsed = parseGitURI(input);
const githubAPIURL = process.env.GIGET_GITHUB_URL || "https://api.github.com";
return {
name: parsed.repo.replace("/", "-"),
version: parsed.ref,
subdir: parsed.subdir,
headers: {
Authorization: options.auth ? `Bearer ${options.auth}` : void 0,
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28"
},
url: `${githubAPIURL.replace("api.github.com", "github.com")}/${parsed.repo}/tree/${parsed.ref}${parsed.subdir}`,
tar: `${githubAPIURL}/repos/${parsed.repo}/tarball/${parsed.ref}`
};
};
const gitlab = (input, options) => {
const parsed = parseGitURI(input);
const gitlab = process.env.GIGET_GITLAB_URL || "https://gitlab.com";
return {
name: parsed.repo.replace("/", "-"),
version: parsed.ref,
subdir: parsed.subdir,
headers: {
authorization: options.auth ? `Bearer ${options.auth}` : void 0,
"sec-fetch-mode": "same-origin"
},
url: `${gitlab}/${parsed.repo}/tree/${parsed.ref}${parsed.subdir}`,
tar: `${gitlab}/${parsed.repo}/-/archive/${parsed.ref}.tar.gz`
};
};
const bitbucket = (input, options) => {
const parsed = parseGitURI(input);
return {
name: parsed.repo.replace("/", "-"),
version: parsed.ref,
subdir: parsed.subdir,
headers: { authorization: options.auth ? `Bearer ${options.auth}` : void 0 },
url: `https://bitbucket.com/${parsed.repo}/src/${parsed.ref}${parsed.subdir}`,
tar: `https://bitbucket.org/${parsed.repo}/get/${parsed.ref}.tar.gz`
};
};
const sourcehut = (input, options) => {
const parsed = parseGitURI(input);
return {
name: parsed.repo.replace("/", "-"),
version: parsed.ref,
subdir: parsed.subdir,
headers: { authorization: options.auth ? `Bearer ${options.auth}` : void 0 },
url: `https://git.sr.ht/~${parsed.repo}/tree/${parsed.ref}/item${parsed.subdir}`,
tar: `https://git.sr.ht/~${parsed.repo}/archive/${parsed.ref}.tar.gz`
};
};
const providers = {
http,
https: http,
github,
gh: github,
gitlab,
bitbucket,
sourcehut
};
const DEFAULT_REGISTRY = "https://raw.githubusercontent.com/unjs/giget/main/templates";
const registryProvider = (registryEndpoint = DEFAULT_REGISTRY, options = {}) => {
return (async (input) => {
const start = Date.now();
const registryURL = `${registryEndpoint}/${input}.json`;
const result = await sendFetch(registryURL, { headers: { authorization: options.auth ? `Bearer ${options.auth}` : void 0 } });
if (result.status >= 400) throw new Error(`Failed to download ${input} template info from ${registryURL}: ${result.status} ${result.statusText}`);
const info = await result.json();
if (!info.tar || !info.name) throw new Error(`Invalid template info from ${registryURL}. name or tar fields are missing!`);
debug(`Fetched ${input} template info from ${registryURL} in ${Date.now() - start}ms`);
return info;
});
};
const sourceProtoRe = /^([\w-.]+):/;
async function downloadTemplate(input, options = {}) {
options.registry = process.env.GIGET_REGISTRY ?? options.registry;
options.auth = process.env.GIGET_AUTH ?? options.auth;
const registry = options.registry === false ? void 0 : registryProvider(options.registry, { auth: options.auth });
let providerName = options.provider || (registry ? "registry" : "github");
let source = input;
const sourceProviderMatch = input.match(sourceProtoRe);
if (sourceProviderMatch) {
providerName = sourceProviderMatch[1];
source = input.slice(sourceProviderMatch[0].length);
if (providerName === "http" || providerName === "https") source = input;
}
const provider = options.providers?.[providerName] || providers[providerName] || registry;
if (!provider) throw new Error(`Unsupported provider: ${providerName}`);
const template = await Promise.resolve().then(() => provider(source, { auth: options.auth })).catch((error) => {
throw new Error(`Failed to download template from ${providerName}: ${error.message}`);
});
if (!template) throw new Error(`Failed to resolve template from ${providerName}`);
template.name = (template.name || "template").replace(/[^\da-z-]/gi, "-");
template.defaultDir = (template.defaultDir || template.name).replace(/[^\da-z-]/gi, "-");
const tarPath = resolve(resolve(cacheDirectory(), providerName, template.name), (template.version || template.name) + ".tar.gz");
if (options.preferOffline && existsSync(tarPath)) options.offline = true;
if (!options.offline) {
await mkdir(dirname(tarPath), { recursive: true });
const s = Date.now();
await download(template.tar, tarPath, { headers: {
Authorization: options.auth ? `Bearer ${options.auth}` : void 0,
...normalizeHeaders(template.headers)
} }).catch((error) => {
if (!existsSync(tarPath)) throw error;
debug("Download error. Using cached version:", error);
options.offline = true;
});
debug(`Downloaded ${template.tar} to ${tarPath} in ${Date.now() - s}ms`);
}
if (!existsSync(tarPath)) throw new Error(`Tarball not found: ${tarPath} (offline: ${options.offline})`);
const extractPath = resolve(resolve(options.cwd || "."), options.dir || template.defaultDir);
if (options.forceClean) await rm(extractPath, {
recursive: true,
force: true
});
if (!options.force && existsSync(extractPath) && readdirSync(extractPath).length > 0) throw new Error(`Destination ${extractPath} already exists.`);
await mkdir(extractPath, { recursive: true });
const s = Date.now();
const subdir = template.subdir?.replace(/^\//, "") || "";
const { extract } = await import("./libs/tar.mjs").then((n) => n.t);
await extract({
file: tarPath,
cwd: extractPath,
onReadEntry(entry) {
entry.path = entry.path.split("/").splice(1).join("/");
if (subdir) if (entry.path.startsWith(subdir + "/")) entry.path = entry.path.slice(subdir.length);
else entry.path = "";
}
});
debug(`Extracted to ${extractPath} in ${Date.now() - s}ms`);
if (options.install) {
debug("Installing dependencies...");
const { installDependencies } = await import("./libs/nypm.mjs").then((n) => n.t);
await installDependencies({
cwd: extractPath,
silent: options.silent,
...typeof options.install === "object" ? options.install : {}
});
}
return {
...template,
source,
dir: extractPath
};
}
export { registryProvider as n, startShell as r, downloadTemplate as t };

View File

@@ -0,0 +1,527 @@
import Stream from "node:stream";
import EE from "events";
import fs from "fs";
import { EventEmitter as EventEmitter$1 } from "node:events";
import { StringDecoder } from "node:string_decoder";
const proc = typeof process == `object` && process ? process : {
stdout: null,
stderr: null
}, isStream = (t) => !!t && typeof t == `object` && (t instanceof Minipass || t instanceof Stream || isReadable(t) || isWritable(t)), isReadable = (t) => !!t && typeof t == `object` && t instanceof EventEmitter$1 && typeof t.pipe == `function` && t.pipe !== Stream.Writable.prototype.pipe, isWritable = (e) => !!e && typeof e == `object` && e instanceof EventEmitter$1 && typeof e.write == `function` && typeof e.end == `function`, EOF = Symbol(`EOF`), MAYBE_EMIT_END = Symbol(`maybeEmitEnd`), EMITTED_END = Symbol(`emittedEnd`), EMITTING_END = Symbol(`emittingEnd`), EMITTED_ERROR = Symbol(`emittedError`), CLOSED = Symbol(`closed`), READ = Symbol(`read`), FLUSH = Symbol(`flush`), FLUSHCHUNK = Symbol(`flushChunk`), ENCODING = Symbol(`encoding`), DECODER = Symbol(`decoder`), FLOWING = Symbol(`flowing`), PAUSED = Symbol(`paused`), RESUME = Symbol(`resume`), BUFFER = Symbol(`buffer`), PIPES = Symbol(`pipes`), BUFFERLENGTH = Symbol(`bufferLength`), BUFFERPUSH = Symbol(`bufferPush`), BUFFERSHIFT = Symbol(`bufferShift`), OBJECTMODE = Symbol(`objectMode`), DESTROYED = Symbol(`destroyed`), ERROR = Symbol(`error`), EMITDATA = Symbol(`emitData`), EMITEND = Symbol(`emitEnd`), EMITEND2 = Symbol(`emitEnd2`), ASYNC = Symbol(`async`), ABORT = Symbol(`abort`), ABORTED = Symbol(`aborted`), SIGNAL = Symbol(`signal`), DATALISTENERS = Symbol(`dataListeners`), DISCARDED = Symbol(`discarded`), defer = (e) => Promise.resolve().then(e), nodefer = (e) => e(), isEndish = (e) => e === `end` || e === `finish` || e === `prefinish`, isArrayBufferLike = (e) => e instanceof ArrayBuffer || !!e && typeof e == `object` && e.constructor && e.constructor.name === `ArrayBuffer` && e.byteLength >= 0, isArrayBufferView = (e) => !Buffer.isBuffer(e) && ArrayBuffer.isView(e);
var Pipe = class {
src;
dest;
opts;
ondrain;
constructor(e, t, n) {
this.src = e, this.dest = t, this.opts = n, this.ondrain = () => e[RESUME](), this.dest.on(`drain`, this.ondrain);
}
unpipe() {
this.dest.removeListener(`drain`, this.ondrain);
}
proxyErrors(e) {}
end() {
this.unpipe(), this.opts.end && this.dest.end();
}
}, PipeProxyErrors = class extends Pipe {
unpipe() {
this.src.removeListener(`error`, this.proxyErrors), super.unpipe();
}
constructor(e, t, n) {
super(e, t, n), this.proxyErrors = (e) => t.emit(`error`, e), e.on(`error`, this.proxyErrors);
}
};
const isObjectModeOptions = (e) => !!e.objectMode, isEncodingOptions = (e) => !e.objectMode && !!e.encoding && e.encoding !== `buffer`;
var Minipass = class extends EventEmitter$1 {
[FLOWING] = !1;
[PAUSED] = !1;
[PIPES] = [];
[BUFFER] = [];
[OBJECTMODE];
[ENCODING];
[ASYNC];
[DECODER];
[EOF] = !1;
[EMITTED_END] = !1;
[EMITTING_END] = !1;
[CLOSED] = !1;
[EMITTED_ERROR] = null;
[BUFFERLENGTH] = 0;
[DESTROYED] = !1;
[SIGNAL];
[ABORTED] = !1;
[DATALISTENERS] = 0;
[DISCARDED] = !1;
writable = !0;
readable = !0;
constructor(...e) {
let t = e[0] || {};
if (super(), t.objectMode && typeof t.encoding == `string`) throw TypeError(`Encoding and objectMode may not be used together`);
isObjectModeOptions(t) ? (this[OBJECTMODE] = !0, this[ENCODING] = null) : isEncodingOptions(t) ? (this[ENCODING] = t.encoding, this[OBJECTMODE] = !1) : (this[OBJECTMODE] = !1, this[ENCODING] = null), this[ASYNC] = !!t.async, this[DECODER] = this[ENCODING] ? new StringDecoder(this[ENCODING]) : null, t && t.debugExposeBuffer === !0 && Object.defineProperty(this, `buffer`, { get: () => this[BUFFER] }), t && t.debugExposePipes === !0 && Object.defineProperty(this, `pipes`, { get: () => this[PIPES] });
let { signal: n } = t;
n && (this[SIGNAL] = n, n.aborted ? this[ABORT]() : n.addEventListener(`abort`, () => this[ABORT]()));
}
get bufferLength() {
return this[BUFFERLENGTH];
}
get encoding() {
return this[ENCODING];
}
set encoding(e) {
throw Error(`Encoding must be set at instantiation time`);
}
setEncoding(e) {
throw Error(`Encoding must be set at instantiation time`);
}
get objectMode() {
return this[OBJECTMODE];
}
set objectMode(e) {
throw Error(`objectMode must be set at instantiation time`);
}
get async() {
return this[ASYNC];
}
set async(e) {
this[ASYNC] = this[ASYNC] || !!e;
}
[ABORT]() {
this[ABORTED] = !0, this.emit(`abort`, this[SIGNAL]?.reason), this.destroy(this[SIGNAL]?.reason);
}
get aborted() {
return this[ABORTED];
}
set aborted(e) {}
write(e, t, n) {
if (this[ABORTED]) return !1;
if (this[EOF]) throw Error(`write after end`);
if (this[DESTROYED]) return this.emit(`error`, Object.assign(Error(`Cannot call write after a stream was destroyed`), { code: `ERR_STREAM_DESTROYED` })), !0;
typeof t == `function` && (n = t, t = `utf8`), t ||= `utf8`;
let r = this[ASYNC] ? defer : nodefer;
if (!this[OBJECTMODE] && !Buffer.isBuffer(e)) {
if (isArrayBufferView(e)) e = Buffer.from(e.buffer, e.byteOffset, e.byteLength);
else if (isArrayBufferLike(e)) e = Buffer.from(e);
else if (typeof e != `string`) throw Error(`Non-contiguous data written to non-objectMode stream`);
}
return this[OBJECTMODE] ? (this[FLOWING] && this[BUFFERLENGTH] !== 0 && this[FLUSH](!0), this[FLOWING] ? this.emit(`data`, e) : this[BUFFERPUSH](e), this[BUFFERLENGTH] !== 0 && this.emit(`readable`), n && r(n), this[FLOWING]) : e.length ? (typeof e == `string` && !(t === this[ENCODING] && !this[DECODER]?.lastNeed) && (e = Buffer.from(e, t)), Buffer.isBuffer(e) && this[ENCODING] && (e = this[DECODER].write(e)), this[FLOWING] && this[BUFFERLENGTH] !== 0 && this[FLUSH](!0), this[FLOWING] ? this.emit(`data`, e) : this[BUFFERPUSH](e), this[BUFFERLENGTH] !== 0 && this.emit(`readable`), n && r(n), this[FLOWING]) : (this[BUFFERLENGTH] !== 0 && this.emit(`readable`), n && r(n), this[FLOWING]);
}
read(e) {
if (this[DESTROYED]) return null;
if (this[DISCARDED] = !1, this[BUFFERLENGTH] === 0 || e === 0 || e && e > this[BUFFERLENGTH]) return this[MAYBE_EMIT_END](), null;
this[OBJECTMODE] && (e = null), this[BUFFER].length > 1 && !this[OBJECTMODE] && (this[BUFFER] = [this[ENCODING] ? this[BUFFER].join(``) : Buffer.concat(this[BUFFER], this[BUFFERLENGTH])]);
let t = this[READ](e || null, this[BUFFER][0]);
return this[MAYBE_EMIT_END](), t;
}
[READ](e, t) {
if (this[OBJECTMODE]) this[BUFFERSHIFT]();
else {
let n = t;
e === n.length || e === null ? this[BUFFERSHIFT]() : typeof n == `string` ? (this[BUFFER][0] = n.slice(e), t = n.slice(0, e), this[BUFFERLENGTH] -= e) : (this[BUFFER][0] = n.subarray(e), t = n.subarray(0, e), this[BUFFERLENGTH] -= e);
}
return this.emit(`data`, t), !this[BUFFER].length && !this[EOF] && this.emit(`drain`), t;
}
end(e, t, n) {
return typeof e == `function` && (n = e, e = void 0), typeof t == `function` && (n = t, t = `utf8`), e !== void 0 && this.write(e, t), n && this.once(`end`, n), this[EOF] = !0, this.writable = !1, (this[FLOWING] || !this[PAUSED]) && this[MAYBE_EMIT_END](), this;
}
[RESUME]() {
this[DESTROYED] || (!this[DATALISTENERS] && !this[PIPES].length && (this[DISCARDED] = !0), this[PAUSED] = !1, this[FLOWING] = !0, this.emit(`resume`), this[BUFFER].length ? this[FLUSH]() : this[EOF] ? this[MAYBE_EMIT_END]() : this.emit(`drain`));
}
resume() {
return this[RESUME]();
}
pause() {
this[FLOWING] = !1, this[PAUSED] = !0, this[DISCARDED] = !1;
}
get destroyed() {
return this[DESTROYED];
}
get flowing() {
return this[FLOWING];
}
get paused() {
return this[PAUSED];
}
[BUFFERPUSH](e) {
this[OBJECTMODE] ? this[BUFFERLENGTH] += 1 : this[BUFFERLENGTH] += e.length, this[BUFFER].push(e);
}
[BUFFERSHIFT]() {
return this[OBJECTMODE] ? --this[BUFFERLENGTH] : this[BUFFERLENGTH] -= this[BUFFER][0].length, this[BUFFER].shift();
}
[FLUSH](e = !1) {
do ;
while (this[FLUSHCHUNK](this[BUFFERSHIFT]()) && this[BUFFER].length);
!e && !this[BUFFER].length && !this[EOF] && this.emit(`drain`);
}
[FLUSHCHUNK](e) {
return this.emit(`data`, e), this[FLOWING];
}
pipe(e, t) {
if (this[DESTROYED]) return e;
this[DISCARDED] = !1;
let n = this[EMITTED_END];
return t ||= {}, e === proc.stdout || e === proc.stderr ? t.end = !1 : t.end = t.end !== !1, t.proxyErrors = !!t.proxyErrors, n ? t.end && e.end() : (this[PIPES].push(t.proxyErrors ? new PipeProxyErrors(this, e, t) : new Pipe(this, e, t)), this[ASYNC] ? defer(() => this[RESUME]()) : this[RESUME]()), e;
}
unpipe(e) {
let t = this[PIPES].find((t) => t.dest === e);
t && (this[PIPES].length === 1 ? (this[FLOWING] && this[DATALISTENERS] === 0 && (this[FLOWING] = !1), this[PIPES] = []) : this[PIPES].splice(this[PIPES].indexOf(t), 1), t.unpipe());
}
addListener(e, t) {
return this.on(e, t);
}
on(e, t) {
let n = super.on(e, t);
if (e === `data`) this[DISCARDED] = !1, this[DATALISTENERS]++, !this[PIPES].length && !this[FLOWING] && this[RESUME]();
else if (e === `readable` && this[BUFFERLENGTH] !== 0) super.emit(`readable`);
else if (isEndish(e) && this[EMITTED_END]) super.emit(e), this.removeAllListeners(e);
else if (e === `error` && this[EMITTED_ERROR]) {
let e = t;
this[ASYNC] ? defer(() => e.call(this, this[EMITTED_ERROR])) : e.call(this, this[EMITTED_ERROR]);
}
return n;
}
removeListener(e, t) {
return this.off(e, t);
}
off(e, t) {
let n = super.off(e, t);
return e === `data` && (this[DATALISTENERS] = this.listeners(`data`).length, this[DATALISTENERS] === 0 && !this[DISCARDED] && !this[PIPES].length && (this[FLOWING] = !1)), n;
}
removeAllListeners(e) {
let t = super.removeAllListeners(e);
return (e === `data` || e === void 0) && (this[DATALISTENERS] = 0, !this[DISCARDED] && !this[PIPES].length && (this[FLOWING] = !1)), t;
}
get emittedEnd() {
return this[EMITTED_END];
}
[MAYBE_EMIT_END]() {
!this[EMITTING_END] && !this[EMITTED_END] && !this[DESTROYED] && this[BUFFER].length === 0 && this[EOF] && (this[EMITTING_END] = !0, this.emit(`end`), this.emit(`prefinish`), this.emit(`finish`), this[CLOSED] && this.emit(`close`), this[EMITTING_END] = !1);
}
emit(e, ...t) {
let n = t[0];
if (e !== `error` && e !== `close` && e !== DESTROYED && this[DESTROYED]) return !1;
if (e === `data`) return !this[OBJECTMODE] && !n ? !1 : this[ASYNC] ? (defer(() => this[EMITDATA](n)), !0) : this[EMITDATA](n);
if (e === `end`) return this[EMITEND]();
if (e === `close`) {
if (this[CLOSED] = !0, !this[EMITTED_END] && !this[DESTROYED]) return !1;
let e = super.emit(`close`);
return this.removeAllListeners(`close`), e;
} else if (e === `error`) {
this[EMITTED_ERROR] = n, super.emit(ERROR, n);
let e = !this[SIGNAL] || this.listeners(`error`).length ? super.emit(`error`, n) : !1;
return this[MAYBE_EMIT_END](), e;
} else if (e === `resume`) {
let e = super.emit(`resume`);
return this[MAYBE_EMIT_END](), e;
} else if (e === `finish` || e === `prefinish`) {
let t = super.emit(e);
return this.removeAllListeners(e), t;
}
let r = super.emit(e, ...t);
return this[MAYBE_EMIT_END](), r;
}
[EMITDATA](e) {
for (let t of this[PIPES]) t.dest.write(e) === !1 && this.pause();
let t = this[DISCARDED] ? !1 : super.emit(`data`, e);
return this[MAYBE_EMIT_END](), t;
}
[EMITEND]() {
return this[EMITTED_END] ? !1 : (this[EMITTED_END] = !0, this.readable = !1, this[ASYNC] ? (defer(() => this[EMITEND2]()), !0) : this[EMITEND2]());
}
[EMITEND2]() {
if (this[DECODER]) {
let e = this[DECODER].end();
if (e) {
for (let t of this[PIPES]) t.dest.write(e);
this[DISCARDED] || super.emit(`data`, e);
}
}
for (let e of this[PIPES]) e.end();
let e = super.emit(`end`);
return this.removeAllListeners(`end`), e;
}
async collect() {
let e = Object.assign([], { dataLength: 0 });
this[OBJECTMODE] || (e.dataLength = 0);
let t = this.promise();
return this.on(`data`, (t) => {
e.push(t), this[OBJECTMODE] || (e.dataLength += t.length);
}), await t, e;
}
async concat() {
if (this[OBJECTMODE]) throw Error(`cannot concat in objectMode`);
let e = await this.collect();
return this[ENCODING] ? e.join(``) : Buffer.concat(e, e.dataLength);
}
async promise() {
return new Promise((e, t) => {
this.on(DESTROYED, () => t(Error(`stream destroyed`))), this.on(`error`, (e) => t(e)), this.on(`end`, () => e());
});
}
[Symbol.asyncIterator]() {
this[DISCARDED] = !1;
let e = !1, t = async () => (this.pause(), e = !0, {
value: void 0,
done: !0
});
return {
next: () => {
if (e) return t();
let n = this.read();
if (n !== null) return Promise.resolve({
done: !1,
value: n
});
if (this[EOF]) return t();
let r, i, a = (e) => {
this.off(`data`, o), this.off(`end`, s), this.off(DESTROYED, c), t(), i(e);
}, o = (e) => {
this.off(`error`, a), this.off(`end`, s), this.off(DESTROYED, c), this.pause(), r({
value: e,
done: !!this[EOF]
});
}, s = () => {
this.off(`error`, a), this.off(`data`, o), this.off(DESTROYED, c), t(), r({
done: !0,
value: void 0
});
}, c = () => a(Error(`stream destroyed`));
return new Promise((e, t) => {
i = t, r = e, this.once(DESTROYED, c), this.once(`error`, a), this.once(`end`, s), this.once(`data`, o);
});
},
throw: t,
return: t,
[Symbol.asyncIterator]() {
return this;
}
};
}
[Symbol.iterator]() {
this[DISCARDED] = !1;
let e = !1, t = () => (this.pause(), this.off(ERROR, t), this.off(DESTROYED, t), this.off(`end`, t), e = !0, {
done: !0,
value: void 0
});
return this.once(`end`, t), this.once(ERROR, t), this.once(DESTROYED, t), {
next: () => {
if (e) return t();
let n = this.read();
return n === null ? t() : {
done: !1,
value: n
};
},
throw: t,
return: t,
[Symbol.iterator]() {
return this;
}
};
}
destroy(e) {
if (this[DESTROYED]) return e ? this.emit(`error`, e) : this.emit(DESTROYED), this;
this[DESTROYED] = !0, this[DISCARDED] = !0, this[BUFFER].length = 0, this[BUFFERLENGTH] = 0;
let t = this;
return typeof t.close == `function` && !this[CLOSED] && t.close(), e ? this.emit(`error`, e) : this.emit(DESTROYED), this;
}
static get isStream() {
return isStream;
}
};
const writev = fs.writev, _autoClose = Symbol(`_autoClose`), _close = Symbol(`_close`), _ended = Symbol(`_ended`), _fd = Symbol(`_fd`), _finished = Symbol(`_finished`), _flags = Symbol(`_flags`), _flush = Symbol(`_flush`), _handleChunk = Symbol(`_handleChunk`), _makeBuf = Symbol(`_makeBuf`), _mode = Symbol(`_mode`), _needDrain = Symbol(`_needDrain`), _onerror = Symbol(`_onerror`), _onopen = Symbol(`_onopen`), _onread = Symbol(`_onread`), _onwrite = Symbol(`_onwrite`), _open = Symbol(`_open`), _path = Symbol(`_path`), _pos = Symbol(`_pos`), _queue = Symbol(`_queue`), _read = Symbol(`_read`), _readSize = Symbol(`_readSize`), _reading = Symbol(`_reading`), _remain = Symbol(`_remain`), _size = Symbol(`_size`), _write = Symbol(`_write`), _writing = Symbol(`_writing`), _defaultFlag = Symbol(`_defaultFlag`), _errored = Symbol(`_errored`);
var ReadStream = class extends Minipass {
[_errored] = !1;
[_fd];
[_path];
[_readSize];
[_reading] = !1;
[_size];
[_remain];
[_autoClose];
constructor(e, t) {
if (t ||= {}, super(t), this.readable = !0, this.writable = !1, typeof e != `string`) throw TypeError(`path must be a string`);
this[_errored] = !1, this[_fd] = typeof t.fd == `number` ? t.fd : void 0, this[_path] = e, this[_readSize] = t.readSize || 16 * 1024 * 1024, this[_reading] = !1, this[_size] = typeof t.size == `number` ? t.size : Infinity, this[_remain] = this[_size], this[_autoClose] = typeof t.autoClose == `boolean` ? t.autoClose : !0, typeof this[_fd] == `number` ? this[_read]() : this[_open]();
}
get fd() {
return this[_fd];
}
get path() {
return this[_path];
}
write() {
throw TypeError(`this is a readable stream`);
}
end() {
throw TypeError(`this is a readable stream`);
}
[_open]() {
fs.open(this[_path], `r`, (e, t) => this[_onopen](e, t));
}
[_onopen](e, t) {
e ? this[_onerror](e) : (this[_fd] = t, this.emit(`open`, t), this[_read]());
}
[_makeBuf]() {
return Buffer.allocUnsafe(Math.min(this[_readSize], this[_remain]));
}
[_read]() {
if (!this[_reading]) {
this[_reading] = !0;
let e = this[_makeBuf]();
if (e.length === 0) return process.nextTick(() => this[_onread](null, 0, e));
fs.read(this[_fd], e, 0, e.length, null, (e, t, n) => this[_onread](e, t, n));
}
}
[_onread](e, t, n) {
this[_reading] = !1, e ? this[_onerror](e) : this[_handleChunk](t, n) && this[_read]();
}
[_close]() {
if (this[_autoClose] && typeof this[_fd] == `number`) {
let e = this[_fd];
this[_fd] = void 0, fs.close(e, (e) => e ? this.emit(`error`, e) : this.emit(`close`));
}
}
[_onerror](e) {
this[_reading] = !0, this[_close](), this.emit(`error`, e);
}
[_handleChunk](e, t) {
let n = !1;
return this[_remain] -= e, e > 0 && (n = super.write(e < t.length ? t.subarray(0, e) : t)), (e === 0 || this[_remain] <= 0) && (n = !1, this[_close](), super.end()), n;
}
emit(e, ...t) {
switch (e) {
case `prefinish`:
case `finish`: return !1;
case `drain`: return typeof this[_fd] == `number` && this[_read](), !1;
case `error`: return this[_errored] ? !1 : (this[_errored] = !0, super.emit(e, ...t));
default: return super.emit(e, ...t);
}
}
}, ReadStreamSync = class extends ReadStream {
[_open]() {
let e = !0;
try {
this[_onopen](null, fs.openSync(this[_path], `r`)), e = !1;
} finally {
e && this[_close]();
}
}
[_read]() {
let e = !0;
try {
if (!this[_reading]) {
this[_reading] = !0;
do {
let e = this[_makeBuf](), t = e.length === 0 ? 0 : fs.readSync(this[_fd], e, 0, e.length, null);
if (!this[_handleChunk](t, e)) break;
} while (!0);
this[_reading] = !1;
}
e = !1;
} finally {
e && this[_close]();
}
}
[_close]() {
if (this[_autoClose] && typeof this[_fd] == `number`) {
let e = this[_fd];
this[_fd] = void 0, fs.closeSync(e), this.emit(`close`);
}
}
}, WriteStream = class extends EE {
readable = !1;
writable = !0;
[_errored] = !1;
[_writing] = !1;
[_ended] = !1;
[_queue] = [];
[_needDrain] = !1;
[_path];
[_mode];
[_autoClose];
[_fd];
[_defaultFlag];
[_flags];
[_finished] = !1;
[_pos];
constructor(e, t) {
t ||= {}, super(t), this[_path] = e, this[_fd] = typeof t.fd == `number` ? t.fd : void 0, this[_mode] = t.mode === void 0 ? 438 : t.mode, this[_pos] = typeof t.start == `number` ? t.start : void 0, this[_autoClose] = typeof t.autoClose == `boolean` ? t.autoClose : !0;
let n = this[_pos] === void 0 ? `w` : `r+`;
this[_defaultFlag] = t.flags === void 0, this[_flags] = t.flags === void 0 ? n : t.flags, this[_fd] === void 0 && this[_open]();
}
emit(e, ...t) {
if (e === `error`) {
if (this[_errored]) return !1;
this[_errored] = !0;
}
return super.emit(e, ...t);
}
get fd() {
return this[_fd];
}
get path() {
return this[_path];
}
[_onerror](e) {
this[_close](), this[_writing] = !0, this.emit(`error`, e);
}
[_open]() {
fs.open(this[_path], this[_flags], this[_mode], (e, t) => this[_onopen](e, t));
}
[_onopen](e, t) {
this[_defaultFlag] && this[_flags] === `r+` && e && e.code === `ENOENT` ? (this[_flags] = `w`, this[_open]()) : e ? this[_onerror](e) : (this[_fd] = t, this.emit(`open`, t), this[_writing] || this[_flush]());
}
end(e, t) {
return e && this.write(e, t), this[_ended] = !0, !this[_writing] && !this[_queue].length && typeof this[_fd] == `number` && this[_onwrite](null, 0), this;
}
write(e, t) {
return typeof e == `string` && (e = Buffer.from(e, t)), this[_ended] ? (this.emit(`error`, Error(`write() after end()`)), !1) : this[_fd] === void 0 || this[_writing] || this[_queue].length ? (this[_queue].push(e), this[_needDrain] = !0, !1) : (this[_writing] = !0, this[_write](e), !0);
}
[_write](e) {
fs.write(this[_fd], e, 0, e.length, this[_pos], (e, t) => this[_onwrite](e, t));
}
[_onwrite](e, t) {
e ? this[_onerror](e) : (this[_pos] !== void 0 && typeof t == `number` && (this[_pos] += t), this[_queue].length ? this[_flush]() : (this[_writing] = !1, this[_ended] && !this[_finished] ? (this[_finished] = !0, this[_close](), this.emit(`finish`)) : this[_needDrain] && (this[_needDrain] = !1, this.emit(`drain`))));
}
[_flush]() {
if (this[_queue].length === 0) this[_ended] && this[_onwrite](null, 0);
else if (this[_queue].length === 1) this[_write](this[_queue].pop());
else {
let e = this[_queue];
this[_queue] = [], writev(this[_fd], e, this[_pos], (e, t) => this[_onwrite](e, t));
}
}
[_close]() {
if (this[_autoClose] && typeof this[_fd] == `number`) {
let e = this[_fd];
this[_fd] = void 0, fs.close(e, (e) => e ? this.emit(`error`, e) : this.emit(`close`));
}
}
}, WriteStreamSync = class extends WriteStream {
[_open]() {
let e;
if (this[_defaultFlag] && this[_flags] === `r+`) try {
e = fs.openSync(this[_path], this[_flags], this[_mode]);
} catch (e) {
if (e?.code === `ENOENT`) return this[_flags] = `w`, this[_open]();
throw e;
}
else e = fs.openSync(this[_path], this[_flags], this[_mode]);
this[_onopen](null, e);
}
[_close]() {
if (this[_autoClose] && typeof this[_fd] == `number`) {
let e = this[_fd];
this[_fd] = void 0, fs.closeSync(e), this.emit(`close`);
}
}
[_write](e) {
let t = !0;
try {
this[_onwrite](null, fs.writeSync(this[_fd], e, 0, e.length, this[_pos])), t = !1;
} finally {
if (t) try {
this[_close]();
} catch {}
}
}
};
export { Minipass as a, WriteStreamSync as i, ReadStreamSync as n, WriteStream as r, ReadStream as t };

View File

@@ -0,0 +1,48 @@
import fs from "node:fs";
import path from "node:path";
const lchownSync = (t, n, r) => {
try {
return fs.lchownSync(t, n, r);
} catch (e) {
if (e?.code !== `ENOENT`) throw e;
}
}, chown = (t, n, r, i) => {
fs.lchown(t, n, r, (e) => {
i(e && e?.code !== `ENOENT` ? e : null);
});
}, chownrKid = (e, n, i, o, s) => {
n.isDirectory() ? chownr(path.resolve(e, n.name), i, o, (a) => {
if (a) return s(a);
chown(path.resolve(e, n.name), i, o, s);
}) : chown(path.resolve(e, n.name), i, o, s);
}, chownr = (t, n, a, o) => {
fs.readdir(t, { withFileTypes: !0 }, (e, s) => {
if (e) {
if (e.code === `ENOENT`) return o();
if (e.code !== `ENOTDIR` && e.code !== `ENOTSUP`) return o(e);
}
if (e || !s.length) return chown(t, n, a, o);
let c = s.length, l = null, u = (e) => {
if (!l) {
if (e) return o(l = e);
if (--c === 0) return chown(t, n, a, o);
}
};
for (let e of s) chownrKid(t, e, n, a, u);
});
}, chownrKidSync = (e, r, i, a) => {
r.isDirectory() && chownrSync(path.resolve(e, r.name), i, a), lchownSync(path.resolve(e, r.name), i, a);
}, chownrSync = (t, r, i) => {
let a;
try {
a = fs.readdirSync(t, { withFileTypes: !0 });
} catch (e) {
let a = e;
if (a?.code === `ENOENT`) return;
if (a?.code === `ENOTDIR` || a?.code === `ENOTSUP`) return lchownSync(t, r, i);
throw a;
}
for (let e of a) chownrKidSync(t, e, r, i);
return lchownSync(t, r, i);
};
export { chownrSync as n, chownr as t };

View File

@@ -0,0 +1,263 @@
import { parseArgs } from "node:util";
const NUMBER_CHAR_RE = /\d/, STR_SPLITTERS = [
`-`,
`_`,
`/`,
`.`
];
function isUppercase(e = ``) {
if (!NUMBER_CHAR_RE.test(e)) return e !== e.toLowerCase();
}
function splitByCase(e, t) {
let i = t ?? STR_SPLITTERS, a = [];
if (!e || typeof e != `string`) return a;
let o = ``, s, c;
for (let t of e) {
let e = i.includes(t);
if (e === !0) {
a.push(o), o = ``, s = void 0;
continue;
}
let n = isUppercase(t);
if (c === !1) {
if (s === !1 && n === !0) {
a.push(o), o = t, s = n;
continue;
}
if (s === !0 && n === !1 && o.length > 1) {
let e = o.at(-1);
a.push(o.slice(0, Math.max(0, o.length - 1))), o = e + t, s = n;
continue;
}
}
o += t, s = n, c = e;
}
return a.push(o), a;
}
function upperFirst(e) {
return e ? e[0].toUpperCase() + e.slice(1) : ``;
}
function lowerFirst(e) {
return e ? e[0].toLowerCase() + e.slice(1) : ``;
}
function pascalCase(e, t) {
return e ? (Array.isArray(e) ? e : splitByCase(e)).map((e) => upperFirst(t?.normalize ? e.toLowerCase() : e)).join(``) : ``;
}
function camelCase(e, t) {
return lowerFirst(pascalCase(e || ``, t));
}
function kebabCase(e, t) {
return e ? (Array.isArray(e) ? e : splitByCase(e)).map((e) => e.toLowerCase()).join(t ?? `-`) : ``;
}
function toArray(e) {
return Array.isArray(e) ? e : e === void 0 ? [] : [e];
}
function formatLineColumns(e, t = ``) {
let n = [];
for (let t of e) for (let [e, r] of t.entries()) n[e] = Math.max(n[e] || 0, r.length);
return e.map((e) => e.map((e, r) => t + e[r === 0 ? `padStart` : `padEnd`](n[r])).join(` `)).join(`
`);
}
function resolveValue(e) {
return typeof e == `function` ? e() : e;
}
var CLIError = class extends Error {
code;
constructor(e, t) {
super(e), this.name = `CLIError`, this.code = t;
}
};
function parseRawArgs(t = [], n = {}) {
let r = new Set(n.boolean || []), i = new Set(n.string || []), a = n.alias || {}, o = n.default || {}, s = /* @__PURE__ */ new Map(), c = /* @__PURE__ */ new Map();
for (let [e, t] of Object.entries(a)) {
let n = t;
for (let t of n) s.set(e, t), c.has(t) || c.set(t, []), c.get(t).push(e), s.set(t, e), c.has(e) || c.set(e, []), c.get(e).push(t);
}
let l = {};
function u(e) {
if (r.has(e)) return `boolean`;
let t = c.get(e) || [];
for (let e of t) if (r.has(e)) return `boolean`;
return `string`;
}
let d = new Set([
...r,
...i,
...Object.keys(a),
...Object.values(a).flat(),
...Object.keys(o)
]);
for (let e of d) l[e] || (l[e] = {
type: u(e),
default: o[e]
});
for (let [e, t] of s.entries()) e.length === 1 && l[t] && !l[t].short && (l[t].short = e);
let f = [], p = {};
for (let e = 0; e < t.length; e++) {
let n = t[e];
if (n === `--`) {
f.push(...t.slice(e));
break;
}
if (n.startsWith(`--no-`)) {
let e = n.slice(5);
p[e] = !0;
continue;
}
f.push(n);
}
let m;
try {
m = parseArgs({
args: f,
options: Object.keys(l).length > 0 ? l : void 0,
allowPositionals: !0,
strict: !1
});
} catch {
m = {
values: {},
positionals: f
};
}
let h = { _: [] };
h._ = m.positionals;
for (let [e, t] of Object.entries(m.values)) h[e] = t;
for (let [e] of Object.entries(p)) h[e] = !1;
for (let [e, t] of s.entries()) h[e] !== void 0 && h[t] === void 0 && (h[t] = h[e]), h[t] !== void 0 && h[e] === void 0 && (h[e] = h[t]);
return h;
}
const noColor = (() => {
let e = globalThis.process?.env ?? {};
return e.NO_COLOR === `1` || e.TERM === `dumb` || e.TEST || e.CI;
})(), _c = (e, t = 39) => (n) => noColor ? n : `\u001B[${e}m${n}\u001B[${t}m`, bold = _c(1, 22), cyan = _c(36), gray = _c(90), underline = _c(4, 24);
function parseArgs$1(e, t) {
let n = {
boolean: [],
string: [],
alias: {},
default: {}
}, r = resolveArgs(t);
for (let e of r) {
if (e.type === `positional`) continue;
e.type === `string` || e.type === `enum` ? n.string.push(e.name) : e.type === `boolean` && n.boolean.push(e.name), e.default !== void 0 && (n.default[e.name] = e.default), e.alias && (n.alias[e.name] = e.alias);
let t = camelCase(e.name), r = kebabCase(e.name);
if (t !== e.name || r !== e.name) {
let i = toArray(n.alias[e.name] || []);
t !== e.name && !i.includes(t) && i.push(t), r !== e.name && !i.includes(r) && i.push(r), i.length > 0 && (n.alias[e.name] = i);
}
}
let i = parseRawArgs(e, n), [ ...a] = i._, o = new Proxy(i, { get(e, t) {
return e[t] ?? e[camelCase(t)] ?? e[kebabCase(t)];
} });
for (let [, e] of r.entries()) if (e.type === `positional`) {
let t = a.shift();
if (t !== void 0) o[e.name] = t;
else if (e.default === void 0 && e.required !== !1) throw new CLIError(`Missing required positional argument: ${e.name.toUpperCase()}`, `EARG`);
else o[e.name] = e.default;
} else if (e.type === `enum`) {
let t = o[e.name], n = e.options || [];
if (t !== void 0 && n.length > 0 && !n.includes(t)) throw new CLIError(`Invalid value for argument: ${cyan(`--${e.name}`)} (${cyan(t)}). Expected one of: ${n.map((e) => cyan(e)).join(`, `)}.`, `EARG`);
} else if (e.required && o[e.name] === void 0) throw new CLIError(`Missing required argument: --${e.name}`, `EARG`);
return o;
}
function resolveArgs(e) {
let t = [];
for (let [n, r] of Object.entries(e || {})) t.push({
...r,
name: n,
alias: toArray(r.alias)
});
return t;
}
function defineCommand(e) {
return e;
}
async function runCommand(e, t) {
let n = await resolveValue(e.args || {}), r = parseArgs$1(t.rawArgs, n), i = {
rawArgs: t.rawArgs,
args: r,
data: t.data,
cmd: e
};
typeof e.setup == `function` && await e.setup(i);
let a;
try {
let n = await resolveValue(e.subCommands);
if (n && Object.keys(n).length > 0) {
let r = t.rawArgs.findIndex((e) => !e.startsWith(`-`)), i = t.rawArgs[r];
if (i) {
if (!n[i]) throw new CLIError(`Unknown command ${cyan(i)}`, `E_UNKNOWN_COMMAND`);
let e = await resolveValue(n[i]);
e && await runCommand(e, { rawArgs: t.rawArgs.slice(r + 1) });
} else if (!e.run) throw new CLIError(`No command specified.`, `E_NO_COMMAND`);
}
typeof e.run == `function` && (a = await e.run(i));
} finally {
typeof e.cleanup == `function` && await e.cleanup(i);
}
return { result: a };
}
async function resolveSubCommand(e, t, n) {
let r = await resolveValue(e.subCommands);
if (r && Object.keys(r).length > 0) {
let n = t.findIndex((e) => !e.startsWith(`-`)), i = t[n], a = await resolveValue(r[i]);
if (a) return resolveSubCommand(a, t.slice(n + 1), e);
}
return [e, n];
}
async function showUsage(e, t) {
try {
console.log(await renderUsage(e, t) + `
`);
} catch (e) {
console.error(e);
}
}
const negativePrefixRe = /^no[-A-Z]/;
async function renderUsage(e, t) {
let n = await resolveValue(e.meta || {}), r = resolveArgs(await resolveValue(e.args || {})), i = await resolveValue(t?.meta || {}), a = `${i.name ? `${i.name} ` : ``}` + (n.name || process.argv[1]), o = [], s = [], c = [], l = [];
for (let e of r) if (e.type === `positional`) {
let t = e.name.toUpperCase(), n = e.required !== !1 && e.default === void 0, r = e.default ? `="${e.default}"` : ``;
s.push([
cyan(t + r),
e.description || ``,
e.valueHint ? `<${e.valueHint}>` : ``
]), l.push(n ? `<${t}>` : `[${t}]`);
} else {
let t = e.required === !0 && e.default === void 0, n = [...(e.alias || []).map((e) => `-${e}`), `--${e.name}`].join(`, `) + (e.type === `string` && (e.valueHint || e.default) ? `=${e.valueHint ? `<${e.valueHint}>` : `"${e.default || ``}"`}` : ``) + (e.type === `enum` && e.options ? `=<${e.options.join(`|`)}>` : ``);
if (o.push([cyan(n + (t ? ` (required)` : ``)), e.description || ``]), e.type === `boolean` && (e.default === !0 || e.negativeDescription) && !negativePrefixRe.test(e.name)) {
let n = [...(e.alias || []).map((e) => `--no-${e}`), `--no-${e.name}`].join(`, `);
o.push([cyan(n + (t ? ` (required)` : ``)), e.negativeDescription || ``]);
}
t && l.push(n);
}
if (e.subCommands) {
let t = [], n = await resolveValue(e.subCommands);
for (let [e, r] of Object.entries(n)) {
let n = await resolveValue((await resolveValue(r))?.meta);
n?.hidden || (c.push([cyan(e), n?.description || ``]), t.push(e));
}
l.push(t.join(`|`));
}
let u = [], p = n.version || i.version;
u.push(gray(`${n.description} (${a + (p ? ` v${p}` : ``)})`), ``);
let m = o.length > 0 || s.length > 0;
return u.push(`${underline(bold(`USAGE`))} ${cyan(`${a}${m ? ` [OPTIONS]` : ``} ${l.join(` `)}`)}`, ``), s.length > 0 && (u.push(underline(bold(`ARGUMENTS`)), ``), u.push(formatLineColumns(s, ` `)), u.push(``)), o.length > 0 && (u.push(underline(bold(`OPTIONS`)), ``), u.push(formatLineColumns(o, ` `)), u.push(``)), c.length > 0 && (u.push(underline(bold(`COMMANDS`)), ``), u.push(formatLineColumns(c, ` `)), u.push(``, `Use ${cyan(`${a} <command> --help`)} for more information about a command.`)), u.filter((e) => typeof e == `string`).join(`
`);
}
async function runMain(e, t = {}) {
let n = t.rawArgs || process.argv.slice(2), r = t.showUsage || showUsage;
try {
if (n.includes(`--help`) || n.includes(`-h`)) await r(...await resolveSubCommand(e, n)), process.exit(0);
else if (n.length === 1 && n[0] === `--version`) {
let t = typeof e.meta == `function` ? await e.meta() : await e.meta;
if (!t?.version) throw new CLIError(`No version specified`, `E_NO_VERSION`);
console.log(t.version);
} else await runCommand(e, { rawArgs: n });
} catch (t) {
t instanceof CLIError ? (await r(...await resolveSubCommand(e, n)), console.error(t.message)) : console.error(t, `
`), process.exit(1);
}
}
export { runMain as n, defineCommand as t };

View File

@@ -0,0 +1,261 @@
import { a as Minipass } from "./@isaacs/fs-minipass.mjs";
import assert from "assert";
import { Buffer } from "buffer";
import * as realZlib$1 from "zlib";
import realZlib from "zlib";
const realZlibConstants = realZlib.constants || { ZLIB_VERNUM: 4736 }, constants = Object.freeze(Object.assign(Object.create(null), {
Z_NO_FLUSH: 0,
Z_PARTIAL_FLUSH: 1,
Z_SYNC_FLUSH: 2,
Z_FULL_FLUSH: 3,
Z_FINISH: 4,
Z_BLOCK: 5,
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
Z_VERSION_ERROR: -6,
Z_NO_COMPRESSION: 0,
Z_BEST_SPEED: 1,
Z_BEST_COMPRESSION: 9,
Z_DEFAULT_COMPRESSION: -1,
Z_FILTERED: 1,
Z_HUFFMAN_ONLY: 2,
Z_RLE: 3,
Z_FIXED: 4,
Z_DEFAULT_STRATEGY: 0,
DEFLATE: 1,
INFLATE: 2,
GZIP: 3,
GUNZIP: 4,
DEFLATERAW: 5,
INFLATERAW: 6,
UNZIP: 7,
BROTLI_DECODE: 8,
BROTLI_ENCODE: 9,
Z_MIN_WINDOWBITS: 8,
Z_MAX_WINDOWBITS: 15,
Z_DEFAULT_WINDOWBITS: 15,
Z_MIN_CHUNK: 64,
Z_MAX_CHUNK: Infinity,
Z_DEFAULT_CHUNK: 16384,
Z_MIN_MEMLEVEL: 1,
Z_MAX_MEMLEVEL: 9,
Z_DEFAULT_MEMLEVEL: 8,
Z_MIN_LEVEL: -1,
Z_MAX_LEVEL: 9,
Z_DEFAULT_LEVEL: -1,
BROTLI_OPERATION_PROCESS: 0,
BROTLI_OPERATION_FLUSH: 1,
BROTLI_OPERATION_FINISH: 2,
BROTLI_OPERATION_EMIT_METADATA: 3,
BROTLI_MODE_GENERIC: 0,
BROTLI_MODE_TEXT: 1,
BROTLI_MODE_FONT: 2,
BROTLI_DEFAULT_MODE: 0,
BROTLI_MIN_QUALITY: 0,
BROTLI_MAX_QUALITY: 11,
BROTLI_DEFAULT_QUALITY: 11,
BROTLI_MIN_WINDOW_BITS: 10,
BROTLI_MAX_WINDOW_BITS: 24,
BROTLI_LARGE_MAX_WINDOW_BITS: 30,
BROTLI_DEFAULT_WINDOW: 22,
BROTLI_MIN_INPUT_BLOCK_BITS: 16,
BROTLI_MAX_INPUT_BLOCK_BITS: 24,
BROTLI_PARAM_MODE: 0,
BROTLI_PARAM_QUALITY: 1,
BROTLI_PARAM_LGWIN: 2,
BROTLI_PARAM_LGBLOCK: 3,
BROTLI_PARAM_DISABLE_LITERAL_CONTEXT_MODELING: 4,
BROTLI_PARAM_SIZE_HINT: 5,
BROTLI_PARAM_LARGE_WINDOW: 6,
BROTLI_PARAM_NPOSTFIX: 7,
BROTLI_PARAM_NDIRECT: 8,
BROTLI_DECODER_RESULT_ERROR: 0,
BROTLI_DECODER_RESULT_SUCCESS: 1,
BROTLI_DECODER_RESULT_NEEDS_MORE_INPUT: 2,
BROTLI_DECODER_RESULT_NEEDS_MORE_OUTPUT: 3,
BROTLI_DECODER_PARAM_DISABLE_RING_BUFFER_REALLOCATION: 0,
BROTLI_DECODER_PARAM_LARGE_WINDOW: 1,
BROTLI_DECODER_NO_ERROR: 0,
BROTLI_DECODER_SUCCESS: 1,
BROTLI_DECODER_NEEDS_MORE_INPUT: 2,
BROTLI_DECODER_NEEDS_MORE_OUTPUT: 3,
BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_NIBBLE: -1,
BROTLI_DECODER_ERROR_FORMAT_RESERVED: -2,
BROTLI_DECODER_ERROR_FORMAT_EXUBERANT_META_NIBBLE: -3,
BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_ALPHABET: -4,
BROTLI_DECODER_ERROR_FORMAT_SIMPLE_HUFFMAN_SAME: -5,
BROTLI_DECODER_ERROR_FORMAT_CL_SPACE: -6,
BROTLI_DECODER_ERROR_FORMAT_HUFFMAN_SPACE: -7,
BROTLI_DECODER_ERROR_FORMAT_CONTEXT_MAP_REPEAT: -8,
BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_1: -9,
BROTLI_DECODER_ERROR_FORMAT_BLOCK_LENGTH_2: -10,
BROTLI_DECODER_ERROR_FORMAT_TRANSFORM: -11,
BROTLI_DECODER_ERROR_FORMAT_DICTIONARY: -12,
BROTLI_DECODER_ERROR_FORMAT_WINDOW_BITS: -13,
BROTLI_DECODER_ERROR_FORMAT_PADDING_1: -14,
BROTLI_DECODER_ERROR_FORMAT_PADDING_2: -15,
BROTLI_DECODER_ERROR_FORMAT_DISTANCE: -16,
BROTLI_DECODER_ERROR_DICTIONARY_NOT_SET: -19,
BROTLI_DECODER_ERROR_INVALID_ARGUMENTS: -20,
BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MODES: -21,
BROTLI_DECODER_ERROR_ALLOC_TREE_GROUPS: -22,
BROTLI_DECODER_ERROR_ALLOC_CONTEXT_MAP: -25,
BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_1: -26,
BROTLI_DECODER_ERROR_ALLOC_RING_BUFFER_2: -27,
BROTLI_DECODER_ERROR_ALLOC_BLOCK_TYPE_TREES: -30,
BROTLI_DECODER_ERROR_UNREACHABLE: -31
}, realZlibConstants)), OriginalBufferConcat = Buffer.concat, desc = Object.getOwnPropertyDescriptor(Buffer, `concat`), noop = (e) => e, passthroughBufferConcat = desc?.writable === !0 || desc?.set !== void 0 ? (e) => {
Buffer.concat = e ? noop : OriginalBufferConcat;
} : (e) => {}, _superWrite = Symbol(`_superWrite`);
var ZlibError = class extends Error {
code;
errno;
constructor(e, t) {
super(`zlib: ` + e.message, { cause: e }), this.code = e.code, this.errno = e.errno, this.code ||= `ZLIB_ERROR`, this.message = `zlib: ` + e.message, Error.captureStackTrace(this, t ?? this.constructor);
}
get name() {
return `ZlibError`;
}
};
const _flushFlag = Symbol(`flushFlag`);
var ZlibBase = class extends Minipass {
#sawError = !1;
#ended = !1;
#flushFlag;
#finishFlushFlag;
#fullFlushFlag;
#handle;
#onError;
get sawError() {
return this.#sawError;
}
get handle() {
return this.#handle;
}
get flushFlag() {
return this.#flushFlag;
}
constructor(e, t) {
if (!e || typeof e != `object`) throw TypeError(`invalid options for ZlibBase constructor`);
if (super(e), this.#flushFlag = e.flush ?? 0, this.#finishFlushFlag = e.finishFlush ?? 0, this.#fullFlushFlag = e.fullFlushFlag ?? 0, typeof realZlib$1[t] != `function`) throw TypeError(`Compression method not supported: ` + t);
try {
this.#handle = new realZlib$1[t](e);
} catch (e) {
throw new ZlibError(e, this.constructor);
}
this.#onError = (e) => {
this.#sawError || (this.#sawError = !0, this.close(), this.emit(`error`, e));
}, this.#handle?.on(`error`, (e) => this.#onError(new ZlibError(e))), this.once(`end`, () => this.close);
}
close() {
this.#handle && (this.#handle.close(), this.#handle = void 0, this.emit(`close`));
}
reset() {
if (!this.#sawError) return assert(this.#handle, `zlib binding closed`), this.#handle.reset?.();
}
flush(e) {
this.ended || (typeof e != `number` && (e = this.#fullFlushFlag), this.write(Object.assign(Buffer.alloc(0), { [_flushFlag]: e })));
}
end(e, t, n) {
return typeof e == `function` && (n = e, t = void 0, e = void 0), typeof t == `function` && (n = t, t = void 0), e && (t ? this.write(e, t) : this.write(e)), this.flush(this.#finishFlushFlag), this.#ended = !0, super.end(n);
}
get ended() {
return this.#ended;
}
[_superWrite](e) {
return super.write(e);
}
write(e, r, i) {
if (typeof r == `function` && (i = r, r = `utf8`), typeof e == `string` && (e = Buffer.from(e, r)), this.#sawError) return;
assert(this.#handle, `zlib binding closed`);
let a = this.#handle._handle, o = a.close;
a.close = () => {};
let s = this.#handle.close;
this.#handle.close = () => {}, passthroughBufferConcat(!0);
let c;
try {
let t = typeof e[_flushFlag] == `number` ? e[_flushFlag] : this.#flushFlag;
c = this.#handle._processChunk(e, t), passthroughBufferConcat(!1);
} catch (e) {
passthroughBufferConcat(!1), this.#onError(new ZlibError(e, this.write));
} finally {
this.#handle && (this.#handle._handle = a, a.close = o, this.#handle.close = s, this.#handle.removeAllListeners(`error`));
}
this.#handle && this.#handle.on(`error`, (e) => this.#onError(new ZlibError(e, this.write)));
let l;
if (c) if (Array.isArray(c) && c.length > 0) {
let e = c[0];
l = this[_superWrite](Buffer.from(e));
for (let e = 1; e < c.length; e++) l = this[_superWrite](c[e]);
} else l = this[_superWrite](Buffer.from(c));
return i && i(), l;
}
}, Zlib = class extends ZlibBase {
#level;
#strategy;
constructor(e, t) {
e ||= {}, e.flush = e.flush || constants.Z_NO_FLUSH, e.finishFlush = e.finishFlush || constants.Z_FINISH, e.fullFlushFlag = constants.Z_FULL_FLUSH, super(e, t), this.#level = e.level, this.#strategy = e.strategy;
}
params(e, n) {
if (!this.sawError) {
if (!this.handle) throw Error(`cannot switch params when binding is closed`);
if (!this.handle.params) throw Error(`not supported in this implementation`);
if (this.#level !== e || this.#strategy !== n) {
this.flush(constants.Z_SYNC_FLUSH), assert(this.handle, `zlib binding closed`);
let r = this.handle.flush;
this.handle.flush = (e, t) => {
typeof e == `function` && (t = e, e = this.flushFlag), this.flush(e), t?.();
};
try {
this.handle.params(e, n);
} finally {
this.handle.flush = r;
}
this.handle && (this.#level = e, this.#strategy = n);
}
}
}
}, Gzip = class extends Zlib {
#portable;
constructor(e) {
super(e, `Gzip`), this.#portable = e && !!e.portable;
}
[_superWrite](e) {
return this.#portable ? (this.#portable = !1, e[9] = 255, super[_superWrite](e)) : super[_superWrite](e);
}
}, Unzip = class extends Zlib {
constructor(e) {
super(e, `Unzip`);
}
}, Brotli = class extends ZlibBase {
constructor(e, t) {
e ||= {}, e.flush = e.flush || constants.BROTLI_OPERATION_PROCESS, e.finishFlush = e.finishFlush || constants.BROTLI_OPERATION_FINISH, e.fullFlushFlag = constants.BROTLI_OPERATION_FLUSH, super(e, t);
}
}, BrotliCompress = class extends Brotli {
constructor(e) {
super(e, `BrotliCompress`);
}
}, BrotliDecompress = class extends Brotli {
constructor(e) {
super(e, `BrotliDecompress`);
}
}, Zstd = class extends ZlibBase {
constructor(e, t) {
e ||= {}, e.flush = e.flush || constants.ZSTD_e_continue, e.finishFlush = e.finishFlush || constants.ZSTD_e_end, e.fullFlushFlag = constants.ZSTD_e_flush, super(e, t);
}
}, ZstdCompress = class extends Zstd {
constructor(e) {
super(e, `ZstdCompress`);
}
}, ZstdDecompress = class extends Zstd {
constructor(e) {
super(e, `ZstdDecompress`);
}
};
export { ZstdCompress as a, Unzip as i, BrotliDecompress as n, ZstdDecompress as o, Gzip as r, BrotliCompress as t };

View File

@@ -0,0 +1 @@
type PackageManagerName=`npm`|`yarn`|`pnpm`|`bun`|`deno`;type PackageManager={name:PackageManagerName;command:string;version?:string;buildMeta?:string;majorVersion?:string;lockFile?:string|string[];files?:string[];};type OperationOptions={cwd?:string;env?:Record<string,string>;silent?:boolean;packageManager?:PackageManager|PackageManagerName;installPeerDependencies?:boolean;dev?:boolean;workspace?:boolean|string;global?:boolean;corepack?:boolean;dry?:boolean;};type OperationResult={exec?:{command:string;args:string[];};};declare function installDependencies(e?:Pick<OperationOptions,`cwd`|`silent`|`packageManager`|`dry`|`corepack`>&{frozenLockFile?:boolean;ignoreWorkspace?:boolean;}): Promise<OperationResult>;export{installDependencies as t};

View File

@@ -0,0 +1,677 @@
import { t as __exportAll } from "../rolldown-runtime.mjs";
import "node:module";
import { readFile } from "node:fs/promises";
import { existsSync } from "node:fs";
import { PassThrough } from "node:stream";
import { spawn } from "node:child_process";
import { createRequire } from "module";
import { delimiter, dirname, join, normalize, resolve } from "node:path";
import { cwd } from "node:process";
import c from "node:readline";
const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//;
function normalizeWindowsPath(e = ``) {
return e && e.replace(/\\/g, `/`).replace(_DRIVE_LETTER_START_RE, (e) => e.toUpperCase());
}
const _UNC_REGEX = /^[/\\]{2}/, _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/, _DRIVE_LETTER_RE = /^[A-Za-z]:$/, _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/, normalize$1 = function(e) {
if (e.length === 0) return `.`;
e = normalizeWindowsPath(e);
let t = e.match(_UNC_REGEX), n = isAbsolute(e), r = e[e.length - 1] === `/`;
return e = normalizeString(e, !n), e.length === 0 ? n ? `/` : r ? `./` : `.` : (r && (e += `/`), _DRIVE_LETTER_RE.test(e) && (e += `/`), t ? n ? `//${e}` : `//./${e}` : n && !isAbsolute(e) ? `/${e}` : e);
}, join$1 = function(...e) {
let t = ``;
for (let n of e) if (n) if (t.length > 0) {
let e = t[t.length - 1] === `/`, r = n[0] === `/`;
e && r ? t += n.slice(1) : t += e || r ? n : `/${n}`;
} else t += n;
return normalize$1(t);
};
function cwd$1() {
return typeof process < `u` && typeof process.cwd == `function` ? process.cwd().replace(/\\/g, `/`) : `/`;
}
const resolve$1 = function(...e) {
e = e.map((e) => normalizeWindowsPath(e));
let t = ``, n = !1;
for (let r = e.length - 1; r >= -1 && !n; r--) {
let i = r >= 0 ? e[r] : cwd$1();
!i || i.length === 0 || (t = `${i}/${t}`, n = isAbsolute(i));
}
return t = normalizeString(t, !n), n && !isAbsolute(t) ? `/${t}` : t.length > 0 ? t : `.`;
};
function normalizeString(e, t) {
let n = ``, r = 0, i = -1, a = 0, o = null;
for (let s = 0; s <= e.length; ++s) {
if (s < e.length) o = e[s];
else if (o === `/`) break;
else o = `/`;
if (o === `/`) {
if (!(i === s - 1 || a === 1)) if (a === 2) {
if (n.length < 2 || r !== 2 || n[n.length - 1] !== `.` || n[n.length - 2] !== `.`) {
if (n.length > 2) {
let e = n.lastIndexOf(`/`);
e === -1 ? (n = ``, r = 0) : (n = n.slice(0, e), r = n.length - 1 - n.lastIndexOf(`/`)), i = s, a = 0;
continue;
} else if (n.length > 0) {
n = ``, r = 0, i = s, a = 0;
continue;
}
}
t && (n += n.length > 0 ? `/..` : `..`, r = 2);
} else n.length > 0 ? n += `/${e.slice(i + 1, s)}` : n = e.slice(i + 1, s), r = s - i - 1;
i = s, a = 0;
} else o === `.` && a !== -1 ? ++a : a = -1;
}
return n;
}
const isAbsolute = function(e) {
return _IS_ABSOLUTE_RE.test(e);
}, relative = function(e, t) {
let n = resolve$1(e).replace(_ROOT_FOLDER_RE, `$1`).split(`/`), r = resolve$1(t).replace(_ROOT_FOLDER_RE, `$1`).split(`/`);
if (r[0][1] === `:` && n[0][1] === `:` && n[0] !== r[0]) return r.join(`/`);
let i = [...n];
for (let e of i) {
if (r[0] !== e) break;
n.shift(), r.shift();
}
return [...n.map(() => `..`), ...r].join(`/`);
}, dirname$1 = function(e) {
let t = normalizeWindowsPath(e).replace(/\/$/, ``).split(`/`).slice(0, -1);
return t.length === 1 && _DRIVE_LETTER_RE.test(t[0]) && (t[0] += `/`), t.join(`/`) || (isAbsolute(e) ? `/` : `.`);
}, basename$1 = function(e, t) {
let n = normalizeWindowsPath(e).split(`/`), r = ``;
for (let e = n.length - 1; e >= 0; e--) {
let t = n[e];
if (t) {
r = t;
break;
}
}
return t && r.endsWith(t) ? r.slice(0, -t.length) : r;
};
var l = Object.create, u = Object.defineProperty, d = Object.getOwnPropertyDescriptor, f = Object.getOwnPropertyNames, p = Object.getPrototypeOf, m = Object.prototype.hasOwnProperty, h = (e, t) => () => (t || e((t = { exports: {} }).exports, t), t.exports), g = (e, t, n, r) => {
if (t && typeof t == `object` || typeof t == `function`) for (var i = f(t), a = 0, o = i.length, s; a < o; a++) s = i[a], !m.call(e, s) && s !== n && u(e, s, {
get: ((e) => t[e]).bind(null, s),
enumerable: !(r = d(t, s)) || r.enumerable
});
return e;
}, _ = (e, t, n) => (n = e == null ? {} : l(p(e)), g(t || !e || !e.__esModule ? u(n, `default`, {
value: e,
enumerable: !0
}) : n, e)), v = createRequire(import.meta.url);
const y = /^path$/i, b = {
key: `PATH`,
value: ``
};
function x(e) {
for (let t in e) {
if (!Object.prototype.hasOwnProperty.call(e, t) || !y.test(t)) continue;
let n = e[t];
return n ? {
key: t,
value: n
} : b;
}
return b;
}
function S(e, t) {
let n = t.value.split(delimiter), r = e, i;
do
n.push(resolve(r, `node_modules`, `.bin`)), i = r, r = dirname(r);
while (r !== i);
return {
key: t.key,
value: n.join(delimiter)
};
}
function C(e, t) {
let n = {
...process.env,
...t
}, r = S(e, x(n));
return n[r.key] = r.value, n;
}
const w = (e) => {
let t = e.length, n = new PassThrough(), i = () => {
--t === 0 && n.emit(`end`);
};
for (let t of e) t.pipe(n, { end: !1 }), t.on(`end`, i);
return n;
};
var T = h((e, t) => {
t.exports = a, a.sync = o;
var n = v(`fs`);
function r(e, t) {
var n = t.pathExt === void 0 ? process.env.PATHEXT : t.pathExt;
if (!n || (n = n.split(`;`), n.indexOf(``) !== -1)) return !0;
for (var r = 0; r < n.length; r++) {
var i = n[r].toLowerCase();
if (i && e.substr(-i.length).toLowerCase() === i) return !0;
}
return !1;
}
function i(e, t, n) {
return !e.isSymbolicLink() && !e.isFile() ? !1 : r(t, n);
}
function a(e, t, r) {
n.stat(e, function(n, a) {
r(n, n ? !1 : i(a, e, t));
});
}
function o(e, t) {
return i(n.statSync(e), e, t);
}
}), E = h((e, t) => {
t.exports = r, r.sync = i;
var n = v(`fs`);
function r(e, t, r) {
n.stat(e, function(e, n) {
r(e, e ? !1 : a(n, t));
});
}
function i(e, t) {
return a(n.statSync(e), t);
}
function a(e, t) {
return e.isFile() && o(e, t);
}
function o(e, t) {
var n = e.mode, r = e.uid, i = e.gid, a = t.uid === void 0 ? process.getuid && process.getuid() : t.uid, o = t.gid === void 0 ? process.getgid && process.getgid() : t.gid, s = 64, L = 8, J = 1, Y = s | L;
return n & J || n & L && i === o || n & s && r === a || n & Y && a === 0;
}
}), D = h((e, t) => {
v(`fs`);
var n = process.platform === `win32` || global.TESTING_WINDOWS ? T() : E();
t.exports = r, r.sync = i;
function r(e, t, i) {
if (typeof t == `function` && (i = t, t = {}), !i) {
if (typeof Promise != `function`) throw TypeError(`callback not provided`);
return new Promise(function(n, i) {
r(e, t || {}, function(e, t) {
e ? i(e) : n(t);
});
});
}
n(e, t || {}, function(e, n) {
e && (e.code === `EACCES` || t && t.ignoreErrors) && (e = null, n = !1), i(e, n);
});
}
function i(e, t) {
try {
return n.sync(e, t || {});
} catch (e) {
if (t && t.ignoreErrors || e.code === `EACCES`) return !1;
throw e;
}
}
}), O = h((e, t) => {
let n = process.platform === `win32` || process.env.OSTYPE === `cygwin` || process.env.OSTYPE === `msys`, r = v(`path`), i = n ? `;` : `:`, a = D(), o = (e) => Object.assign(Error(`not found: ${e}`), { code: `ENOENT` }), s = (e, t) => {
let r = t.colon || i, a = e.match(/\//) || n && e.match(/\\/) ? [``] : [...n ? [process.cwd()] : [], ...(t.path || process.env.PATH || ``).split(r)], o = n ? t.pathExt || process.env.PATHEXT || `.EXE;.CMD;.BAT;.COM` : ``, s = n ? o.split(r) : [``];
return n && e.indexOf(`.`) !== -1 && s[0] !== `` && s.unshift(``), {
pathEnv: a,
pathExt: s,
pathExtExe: o
};
}, L = (e, t, n) => {
typeof t == `function` && (n = t, t = {}), t ||= {};
let { pathEnv: i, pathExt: L, pathExtExe: J } = s(e, t), Y = [], X = (n) => new Promise((a, s) => {
if (n === i.length) return t.all && Y.length ? a(Y) : s(o(e));
let L = i[n], J = /^".*"$/.test(L) ? L.slice(1, -1) : L, X = r.join(J, e);
a(Z(!J && /^\.[\\\/]/.test(e) ? e.slice(0, 2) + X : X, n, 0));
}), Z = (e, n, r) => new Promise((i, o) => {
if (r === L.length) return i(X(n + 1));
let s = L[r];
a(e + s, { pathExt: J }, (a, o) => {
if (!a && o) if (t.all) Y.push(e + s);
else return i(e + s);
return i(Z(e, n, r + 1));
});
});
return n ? X(0).then((e) => n(null, e), n) : X(0);
};
t.exports = L, L.sync = (e, t) => {
t ||= {};
let { pathEnv: n, pathExt: i, pathExtExe: L } = s(e, t), J = [];
for (let o = 0; o < n.length; o++) {
let s = n[o], Y = /^".*"$/.test(s) ? s.slice(1, -1) : s, X = r.join(Y, e), Z = !Y && /^\.[\\\/]/.test(e) ? e.slice(0, 2) + X : X;
for (let e = 0; e < i.length; e++) {
let n = Z + i[e];
try {
if (a.sync(n, { pathExt: L })) if (t.all) J.push(n);
else return n;
} catch {}
}
}
if (t.all && J.length) return J;
if (t.nothrow) return null;
throw o(e);
};
}), k = h((e, t) => {
let n = (e = {}) => {
let t = e.env || process.env;
return (e.platform || process.platform) === `win32` ? Object.keys(t).reverse().find((e) => e.toUpperCase() === `PATH`) || `Path` : `PATH`;
};
t.exports = n, t.exports.default = n;
}), A = h((e, t) => {
let n = v(`path`), r = O(), i = k();
function a(e, t) {
let a = e.options.env || process.env, o = process.cwd(), s = e.options.cwd != null, L = s && process.chdir !== void 0 && !process.chdir.disabled;
if (L) try {
process.chdir(e.options.cwd);
} catch {}
let J;
try {
J = r.sync(e.command, {
path: a[i({ env: a })],
pathExt: t ? n.delimiter : void 0
});
} catch {} finally {
L && process.chdir(o);
}
return J &&= n.resolve(s ? e.options.cwd : ``, J), J;
}
function o(e) {
return a(e) || a(e, !0);
}
t.exports = o;
}), j = h((e, t) => {
let n = /([()\][%!^"`<>&|;, *?])/g;
function r(e) {
return e = e.replace(n, `^$1`), e;
}
function i(e, t) {
return e = `${e}`, e = e.replace(/(\\*)"/g, `$1$1\\"`), e = e.replace(/(\\*)$/, `$1$1`), e = `"${e}"`, e = e.replace(n, `^$1`), t && (e = e.replace(n, `^$1`)), e;
}
t.exports.command = r, t.exports.argument = i;
}), M = h((e, t) => {
t.exports = /^#!(.*)/;
}), N = h((e, t) => {
let n = M();
t.exports = (e = ``) => {
let t = e.match(n);
if (!t) return null;
let [r, i] = t[0].replace(/#! ?/, ``).split(` `), a = r.split(`/`).pop();
return a === `env` ? i : i ? `${a} ${i}` : a;
};
}), P = h((e, t) => {
let n = v(`fs`), r = N();
function i(e) {
let t = Buffer.alloc(150), i;
try {
i = n.openSync(e, `r`), n.readSync(i, t, 0, 150, 0), n.closeSync(i);
} catch {}
return r(t.toString());
}
t.exports = i;
}), F = h((e, t) => {
let n = v(`path`), r = A(), i = j(), a = P(), o = process.platform === `win32`, s = /\.(?:com|exe)$/i, L = /node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;
function J(e) {
e.file = r(e);
let t = e.file && a(e.file);
return t ? (e.args.unshift(e.file), e.command = t, r(e)) : e.file;
}
function Y(e) {
if (!o) return e;
let t = J(e), r = !s.test(t);
if (e.options.forceShell || r) {
let r = L.test(t);
e.command = n.normalize(e.command), e.command = i.command(e.command), e.args = e.args.map((e) => i.argument(e, r)), e.args = [
`/d`,
`/s`,
`/c`,
`"${[e.command].concat(e.args).join(` `)}"`
], e.command = process.env.comspec || `cmd.exe`, e.options.windowsVerbatimArguments = !0;
}
return e;
}
function X(e, t, n) {
t && !Array.isArray(t) && (n = t, t = null), t = t ? t.slice(0) : [], n = Object.assign({}, n);
let r = {
command: e,
args: t,
options: n,
file: void 0,
original: {
command: e,
args: t
}
};
return n.shell ? r : Y(r);
}
t.exports = X;
}), I = h((e, t) => {
let n = process.platform === `win32`;
function r(e, t) {
return Object.assign(Error(`${t} ${e.command} ENOENT`), {
code: `ENOENT`,
errno: `ENOENT`,
syscall: `${t} ${e.command}`,
path: e.command,
spawnargs: e.args
});
}
function i(e, t) {
if (!n) return;
let r = e.emit;
e.emit = function(n, i) {
if (n === `exit`) {
let n = a(i, t, `spawn`);
if (n) return r.call(e, `error`, n);
}
return r.apply(e, arguments);
};
}
function a(e, t) {
return n && e === 1 && !t.file ? r(t.original, `spawn`) : null;
}
function o(e, t) {
return n && e === 1 && !t.file ? r(t.original, `spawnSync`) : null;
}
t.exports = {
hookChildProcess: i,
verifyENOENT: a,
verifyENOENTSync: o,
notFoundError: r
};
}), R = _(h((e, t) => {
let n = v(`child_process`), r = F(), i = I();
function a(e, t, a) {
let o = r(e, t, a), s = n.spawn(o.command, o.args, o.options);
return i.hookChildProcess(s, o), s;
}
function o(e, t, a) {
let o = r(e, t, a), s = n.spawnSync(o.command, o.args, o.options);
return s.error = s.error || i.verifyENOENTSync(s.status, o), s;
}
t.exports = a, t.exports.spawn = a, t.exports.sync = o, t.exports._parse = r, t.exports._enoent = i;
})(), 1), z = class extends Error {
result;
output;
get exitCode() {
if (this.result.exitCode !== null) return this.result.exitCode;
}
constructor(e, t) {
super(`Process exited with non-zero status (${e.exitCode})`), this.result = e, this.output = t;
}
};
const B = {
timeout: void 0,
persist: !1
}, V = { windowsHide: !0 };
function H(e, t) {
return {
command: normalize(e),
args: t ?? []
};
}
function U(e) {
let t = new AbortController();
for (let n of e) {
if (n.aborted) return t.abort(), n;
n.addEventListener(`abort`, () => {
t.abort(n.reason);
}, { signal: t.signal });
}
return t.signal;
}
async function W(e) {
let t = ``;
for await (let n of e) t += n.toString();
return t;
}
var G = class {
_process;
_aborted = !1;
_options;
_command;
_args;
_resolveClose;
_processClosed;
_thrownError;
get process() {
return this._process;
}
get pid() {
return this._process?.pid;
}
get exitCode() {
if (this._process && this._process.exitCode !== null) return this._process.exitCode;
}
constructor(e, t, n) {
this._options = {
...B,
...n
}, this._command = e, this._args = t ?? [], this._processClosed = new Promise((e) => {
this._resolveClose = e;
});
}
kill(e) {
return this._process?.kill(e) === !0;
}
get aborted() {
return this._aborted;
}
get killed() {
return this._process?.killed === !0;
}
pipe(e, t, n) {
return q(e, t, {
...n,
stdin: this
});
}
async *[Symbol.asyncIterator]() {
let e = this._process;
if (!e) return;
let t = [];
this._streamErr && t.push(this._streamErr), this._streamOut && t.push(this._streamOut);
let n = w(t), r = c.createInterface({ input: n });
for await (let e of r) yield e.toString();
if (await this._processClosed, e.removeAllListeners(), this._thrownError) throw this._thrownError;
if (this._options?.throwOnError && this.exitCode !== 0 && this.exitCode !== void 0) throw new z(this);
}
async _waitForOutput() {
let e = this._process;
if (!e) throw Error(`No process was started`);
let [t, n] = await Promise.all([this._streamOut ? W(this._streamOut) : ``, this._streamErr ? W(this._streamErr) : ``]);
if (await this._processClosed, this._options?.stdin && await this._options.stdin, e.removeAllListeners(), this._thrownError) throw this._thrownError;
let r = {
stderr: n,
stdout: t,
exitCode: this.exitCode
};
if (this._options.throwOnError && this.exitCode !== 0 && this.exitCode !== void 0) throw new z(this, r);
return r;
}
then(e, t) {
return this._waitForOutput().then(e, t);
}
_streamOut;
_streamErr;
spawn() {
let e = cwd(), t = this._options, n = {
...V,
...t.nodeOptions
}, r = [];
this._resetState(), t.timeout !== void 0 && r.push(AbortSignal.timeout(t.timeout)), t.signal !== void 0 && r.push(t.signal), t.persist === !0 && (n.detached = !0), r.length > 0 && (n.signal = U(r)), n.env = C(e, n.env);
let { command: a, args: o } = H(this._command, this._args), s = (0, R._parse)(a, o, n), L = spawn(s.command, s.args, s.options);
if (L.stderr && (this._streamErr = L.stderr), L.stdout && (this._streamOut = L.stdout), this._process = L, L.once(`error`, this._onError), L.once(`close`, this._onClose), t.stdin !== void 0 && L.stdin && t.stdin.process) {
let { stdout: e } = t.stdin.process;
e && e.pipe(L.stdin);
}
}
_resetState() {
this._aborted = !1, this._processClosed = new Promise((e) => {
this._resolveClose = e;
}), this._thrownError = void 0;
}
_onError = (e) => {
if (e.name === `AbortError` && (!(e.cause instanceof Error) || e.cause.name !== `TimeoutError`)) {
this._aborted = !0;
return;
}
this._thrownError = e;
};
_onClose = () => {
this._resolveClose && this._resolveClose();
};
};
const K = (e, t, n) => {
let r = new G(e, t, n);
return r.spawn(), r;
}, q = K;
var dist_exports = __exportAll({
detectPackageManager: () => detectPackageManager,
installDependencies: () => installDependencies,
packageManagers: () => packageManagers
});
async function findup(e, t, n = {}) {
let r = normalize$1(e).split(`/`);
for (; r.length > 0;) {
let e = await t(r.join(`/`) || `/`);
if (e || !n.includeParentDirs) return e;
r.pop();
}
}
function cached(e) {
let t;
return () => (t === void 0 && (t = e().then((e) => (t = e, t))), t);
}
const hasCorepack = cached(async () => {
if (globalThis.process?.versions?.webcontainer) return !1;
try {
let { exitCode: e } = await K(`corepack`, [`--version`]);
return e === 0;
} catch {
return !1;
}
});
async function executeCommand(e, t, n = {}) {
let r = e !== `npm` && e !== `bun` && e !== `deno` && n.corepack !== !1 && await hasCorepack() ? [`corepack`, [e, ...t]] : [e, t], { exitCode: i, stdout: a, stderr: o } = await K(r[0], r[1], { nodeOptions: {
cwd: resolve$1(n.cwd || process.cwd()),
env: n.env,
stdio: n.silent ? `pipe` : `inherit`
} });
if (i !== 0) throw Error(`\`${r.flat().join(` `)}\` failed.${n.silent ? [
``,
a,
o
].join(`
`) : ``}`);
}
async function resolveOperationOptions(e = {}) {
let t = e.cwd || process.cwd(), n = {
...process.env,
...e.env
}, r = (typeof e.packageManager == `string` ? packageManagers.find((t) => t.name === e.packageManager) : e.packageManager) || await detectPackageManager(e.cwd || process.cwd());
if (!r) throw Error(`No package manager auto-detected.`);
return {
cwd: t,
env: n,
silent: e.silent ?? !1,
packageManager: r,
dev: e.dev ?? !1,
workspace: e.workspace,
global: e.global ?? !1,
dry: e.dry ?? !1,
corepack: e.corepack ?? !0
};
}
function parsePackageManagerField(e) {
let [t, n] = (e || ``).split(`@`), [r, i] = n?.split(`+`) || [];
if (t && t !== `-` && /^(@[a-z0-9-~][a-z0-9-._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/.test(t)) return {
name: t,
version: r,
buildMeta: i
};
let a = (t || ``).replace(/\W+/g, ``);
return {
name: a,
version: r,
buildMeta: i,
warnings: [`Abnormal characters found in \`packageManager\` field, sanitizing from \`${t}\` to \`${a}\``]
};
}
const packageManagers = [
{
name: `npm`,
command: `npm`,
lockFile: `package-lock.json`
},
{
name: `pnpm`,
command: `pnpm`,
lockFile: `pnpm-lock.yaml`,
files: [`pnpm-workspace.yaml`]
},
{
name: `bun`,
command: `bun`,
lockFile: [`bun.lockb`, `bun.lock`]
},
{
name: `yarn`,
command: `yarn`,
lockFile: `yarn.lock`,
files: [`.yarnrc.yml`]
},
{
name: `deno`,
command: `deno`,
lockFile: `deno.lock`,
files: [`deno.json`]
}
];
async function detectPackageManager(e, r = {}) {
let i = await findup(resolve$1(e || `.`), async (e) => {
if (!r.ignorePackageJSON) {
let r = join$1(e, `package.json`);
if (existsSync(r)) {
let e = JSON.parse(await readFile(r, `utf8`));
if (e?.packageManager) {
let { name: t, version: n = `0.0.0`, buildMeta: r, warnings: i } = parsePackageManagerField(e.packageManager);
if (t) {
let e = n.split(`.`)[0], a = packageManagers.find((n) => n.name === t && n.majorVersion === e) || packageManagers.find((e) => e.name === t);
return {
name: t,
command: t,
version: n,
majorVersion: e,
buildMeta: r,
warnings: i,
files: a?.files,
lockFile: a?.lockFile
};
}
}
}
if (existsSync(join$1(e, `deno.json`))) return packageManagers.find((e) => e.name === `deno`);
}
if (!r.ignoreLockFile) {
for (let t of packageManagers) if ([t.lockFile, t.files].flat().filter(Boolean).some((t) => existsSync(resolve$1(e, t)))) return { ...t };
}
}, { includeParentDirs: r.includeParentDirs ?? !0 });
if (!i && !r.ignoreArgv) {
let e = process.argv[1];
if (e) {
for (let t of packageManagers) if (RegExp(`[/\\\\]\\.?${t.command}`).test(e)) return t;
}
}
return i;
}
async function installDependencies(e = {}) {
let t = await resolveOperationOptions(e), n = e.frozenLockFile ? {
npm: [`ci`],
yarn: [`install`, `--immutable`],
bun: [`install`, `--frozen-lockfile`],
pnpm: [`install`, `--frozen-lockfile`],
deno: [`install`, `--frozen`]
}[t.packageManager.name] : [`install`];
return e.ignoreWorkspace && t.packageManager.name === `pnpm` && n.push(`--ignore-workspace`), t.dry || await executeCommand(t.packageManager.command, n, {
cwd: t.cwd,
silent: t.silent,
corepack: t.corepack
}), { exec: {
command: t.packageManager.command,
args: n
} };
}
export { resolve$1 as a, relative as i, basename$1 as n, dirname$1 as r, dist_exports as t };

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,12 @@
import "node:module";
var __defProp = Object.defineProperty;
var __exportAll = (all, symbols) => {
let target = {};
for (var name in all) __defProp(target, name, {
get: all[name],
enumerable: true
});
if (symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
return target;
};
export { __exportAll as t };

View File

@@ -0,0 +1 @@
export { };

76
node_modules/@nuxt/cli/node_modules/giget/dist/cli.mjs generated vendored Executable file
View File

@@ -0,0 +1,76 @@
#!/usr/bin/env node
import { i as relative } from "./_chunks/libs/nypm.mjs";
import { r as startShell, t as downloadTemplate } from "./_chunks/giget.mjs";
import { n as runMain, t as defineCommand } from "./_chunks/libs/citty.mjs";
runMain(defineCommand({
meta: {
name: "giget",
version: "3.1.1",
description: "Download templates and git repositories with pleasure!"
},
args: {
template: {
type: "positional",
required: true,
description: "Template name or a URI describing provider, repository, subdir, and branch/ref"
},
dir: {
type: "positional",
description: "A relative or absolute path where to extract the template",
required: false
},
auth: {
type: "string",
description: "Custom Authorization token to use for downloading template. (Can be overridden with `GIGET_AUTH` environment variable)"
},
cwd: {
type: "string",
description: "Set current working directory to resolve dirs relative to it"
},
force: {
type: "boolean",
description: "Clone to existing directory even if exists"
},
forceClean: {
type: "boolean",
description: "Remove any existing directory or file recursively before cloning"
},
offline: {
type: "boolean",
description: "Do not attempt to download and use cached version"
},
preferOffline: {
type: "boolean",
description: "Use cache if exists otherwise try to download"
},
shell: {
type: "boolean",
description: "Open a new shell with the current working directory set to the cloned directory (experimental)"
},
install: {
type: "boolean",
description: "Install dependencies after cloning"
},
verbose: {
type: "boolean",
description: "Show verbose debugging info"
}
},
run: async ({ args }) => {
if (args.verbose) process.env.DEBUG = process.env.DEBUG || "true";
const r = await downloadTemplate(args.template, {
dir: args.dir,
force: args.force,
forceClean: args.forceClean,
offline: args.offline,
preferOffline: args.preferOffline,
auth: args.auth,
install: args.install
});
const _from = r.name || r.url;
const _to = relative(process.cwd(), r.dir) || "./";
console.log(`✨ Successfully cloned \`${_from}\` to \`${_to}\`\n`);
if (args.shell) startShell(r.dir);
}
}));
export {};

View File

@@ -0,0 +1,57 @@
import { t as installDependencies } from "./_chunks/libs/nypm.mjs";
import "node:http";
//#region src/types.d.ts
interface GitInfo {
provider: "github" | "gitlab" | "bitbucket" | "sourcehut";
repo: string;
subdir: string;
ref: string;
}
interface TemplateInfo {
name: string;
tar: string;
version?: string;
subdir?: string;
url?: string;
defaultDir?: string;
headers?: Record<string, string | undefined>;
source?: never;
dir?: never;
[key: string]: any;
}
type TemplateProvider = (input: string, options: {
auth?: string;
}) => TemplateInfo | Promise<TemplateInfo> | null;
//#endregion
//#region src/giget.d.ts
type InstallOptions = Parameters<typeof installDependencies>[0];
interface DownloadTemplateOptions {
provider?: string;
force?: boolean;
forceClean?: boolean;
offline?: boolean;
preferOffline?: boolean;
providers?: Record<string, TemplateProvider>;
dir?: string;
registry?: false | string;
cwd?: string;
auth?: string;
install?: boolean | InstallOptions;
silent?: boolean;
}
type DownloadTemplateResult = Omit<TemplateInfo, "dir" | "source"> & {
dir: string;
source: string;
};
declare function downloadTemplate(input: string, options?: DownloadTemplateOptions): Promise<DownloadTemplateResult>;
//#endregion
//#region src/registry.d.ts
declare const registryProvider: (registryEndpoint?: string, options?: {
auth?: string;
}) => TemplateProvider;
//#endregion
//#region src/_utils.d.ts
declare function startShell(cwd: string): void;
//#endregion
export { DownloadTemplateOptions, DownloadTemplateResult, GitInfo, TemplateInfo, TemplateProvider, downloadTemplate, registryProvider, startShell };

View File

@@ -0,0 +1,3 @@
import "./_chunks/libs/nypm.mjs";
import { n as registryProvider, r as startShell, t as downloadTemplate } from "./_chunks/giget.mjs";
export { downloadTemplate, registryProvider, startShell };

50
node_modules/@nuxt/cli/node_modules/giget/package.json generated vendored Normal file
View File

@@ -0,0 +1,50 @@
{
"name": "giget",
"version": "3.1.2",
"description": "Download templates and git repositories with pleasure!",
"license": "MIT",
"repository": "unjs/giget",
"bin": {
"giget": "./dist/cli.mjs"
},
"files": [
"dist"
],
"type": "module",
"sideEffects": false,
"types": "./dist/index.d.mts",
"exports": {
".": "./dist/index.mjs"
},
"scripts": {
"build": "obuild",
"dev": "vitest dev",
"giget": "node ./src/cli.ts",
"lint": "oxlint . && oxfmt --check src test",
"lint:fix": "oxlint . --fix && oxfmt src test",
"play": "pnpm giget --force-clean --verbose unjs .tmp/clone",
"release": "pnpm test && pnpm build && changelogen --release && npm publish && git push --follow-tags",
"test": "pnpm lint && pnpm test:types && vitest run --coverage",
"test:types": "tsgo --noEmit"
},
"devDependencies": {
"@types/node": "^25.2.1",
"@types/tar": "^6.1.13",
"@typescript/native-preview": "^7.0.0-dev.20260205.1",
"@vitest/coverage-v8": "^4.0.18",
"changelogen": "^0.6.2",
"citty": "^0.2.0",
"eslint-config-unjs": "^0.6.2",
"nypm": "^0.6.5",
"obuild": "^0.4.22",
"oxfmt": "^0.28.0",
"oxlint": "^1.43.0",
"pathe": "^2.0.3",
"rolldown": "^1.0.0-rc.3",
"tar": "^7.5.7",
"typescript": "^5.9.3",
"unbuild": "^3.6.1",
"vitest": "^4.0.18"
},
"packageManager": "pnpm@10.28.2"
}

70
node_modules/@nuxt/cli/node_modules/pathe/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,70 @@
MIT License
Copyright (c) Pooya Parsa <pooya@pi0.io> - Daniel Roe <daniel@roe.dev>
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.
---
Copyright Joyent, Inc. and other Node 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.
---
Bundled zeptomatch (https://github.com/fabiospampinato/zeptomatch)
The MIT License (MIT)
Copyright (c) 2023-present Fabio Spampinato
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.

73
node_modules/@nuxt/cli/node_modules/pathe/README.md generated vendored Normal file
View File

@@ -0,0 +1,73 @@
# 🛣️ pathe
> Universal filesystem path utils
[![version][npm-v-src]][npm-v-href]
[![downloads][npm-d-src]][npm-d-href]
[![size][size-src]][size-href]
## ❓ Why
For [historical reasons](https://docs.microsoft.com/en-us/archive/blogs/larryosterman/why-is-the-dos-path-character), windows followed MS-DOS and used backslash for separating paths rather than slash used for macOS, Linux, and other Posix operating systems. Nowadays, [Windows](https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file?redirectedfrom=MSDN) supports both Slash and Backslash for paths. [Node.js's built-in `path` module](https://nodejs.org/api/path.html) in the default operation of the path module varies based on the operating system on which a Node.js application is running. Specifically, when running on a Windows operating system, the path module will assume that Windows-style paths are being used. **This makes inconsistent code behavior between Windows and POSIX.**
Compared to popular [upath](https://github.com/anodynos/upath), pathe provides **identical exports** of Node.js with normalization on **all operations** and is written in modern **ESM/TypeScript** and has **no dependency on Node.js**!
This package is a drop-in replacement of the Node.js's [path module](https://nodejs.org/api/path.html) module and ensures paths are normalized with slash `/` and work in environments including Node.js.
## 💿 Usage
Install using npm or yarn:
```bash
# npm
npm i pathe
# yarn
yarn add pathe
# pnpm
pnpm i pathe
```
Import:
```js
// ESM / Typescript
import { resolve, matchesGlob } from "pathe";
// CommonJS
const { resolve, matchesGlob } = require("pathe");
```
Read more about path utils from [Node.js documentation](https://nodejs.org/api/path.html) and rest assured behavior is consistently like POSIX regardless of your input paths format and running platform (the only exception is `delimiter` constant export, it will be set to `;` on windows platform).
### Extra utilities
Pathe exports some extra utilities that do not exist in standard Node.js [path module](https://nodejs.org/api/path.html).
In order to use them, you can import from `pathe/utils` subpath:
```js
import {
filename,
normalizeAliases,
resolveAlias,
reverseResolveAlias,
} from "pathe/utils";
```
## License
Made with 💛 Published under the [MIT](./LICENSE) license.
Some code was used from the Node.js project. Glob supported is powered by [zeptomatch](https://github.com/fabiospampinato/zeptomatch).
<!-- Refs -->
[npm-v-src]: https://img.shields.io/npm/v/pathe?style=flat-square
[npm-v-href]: https://npmjs.com/package/pathe
[npm-d-src]: https://img.shields.io/npm/dm/pathe?style=flat-square
[npm-d-href]: https://npmjs.com/package/pathe
[github-actions-src]: https://img.shields.io/github/workflow/status/unjs/pathe/ci/main?style=flat-square
[github-actions-href]: https://github.com/unjs/pathe/actions?query=workflow%3Aci
[size-src]: https://packagephobia.now.sh/badge?p=pathe
[size-href]: https://packagephobia.now.sh/result?p=pathe

View File

@@ -0,0 +1,39 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const _path = require('./shared/pathe.BSlhyZSM.cjs');
const delimiter = /* @__PURE__ */ (() => globalThis.process?.platform === "win32" ? ";" : ":")();
const _platforms = { posix: void 0, win32: void 0 };
const mix = (del = delimiter) => {
return new Proxy(_path._path, {
get(_, prop) {
if (prop === "delimiter") return del;
if (prop === "posix") return posix;
if (prop === "win32") return win32;
return _platforms[prop] || _path._path[prop];
}
});
};
const posix = /* @__PURE__ */ mix(":");
const win32 = /* @__PURE__ */ mix(";");
exports.basename = _path.basename;
exports.dirname = _path.dirname;
exports.extname = _path.extname;
exports.format = _path.format;
exports.isAbsolute = _path.isAbsolute;
exports.join = _path.join;
exports.matchesGlob = _path.matchesGlob;
exports.normalize = _path.normalize;
exports.normalizeString = _path.normalizeString;
exports.parse = _path.parse;
exports.relative = _path.relative;
exports.resolve = _path.resolve;
exports.sep = _path.sep;
exports.toNamespacedPath = _path.toNamespacedPath;
exports.default = posix;
exports.delimiter = delimiter;
exports.posix = posix;
exports.win32 = win32;

View File

@@ -0,0 +1,47 @@
import * as path from 'node:path';
import path__default from 'node:path';
/**
* Constant for path separator.
*
* Always equals to `"/"`.
*/
declare const sep = "/";
declare const normalize: typeof path__default.normalize;
declare const join: typeof path__default.join;
declare const resolve: typeof path__default.resolve;
/**
* Resolves a string path, resolving '.' and '.' segments and allowing paths above the root.
*
* @param path - The path to normalise.
* @param allowAboveRoot - Whether to allow the resulting path to be above the root directory.
* @returns the normalised path string.
*/
declare function normalizeString(path: string, allowAboveRoot: boolean): string;
declare const isAbsolute: typeof path__default.isAbsolute;
declare const toNamespacedPath: typeof path__default.toNamespacedPath;
declare const extname: typeof path__default.extname;
declare const relative: typeof path__default.relative;
declare const dirname: typeof path__default.dirname;
declare const format: typeof path__default.format;
declare const basename: typeof path__default.basename;
declare const parse: typeof path__default.parse;
/**
* The `path.matchesGlob()` method determines if `path` matches the `pattern`.
* @param path The path to glob-match against.
* @param pattern The glob to check the path against.
*/
declare const matchesGlob: (path: string, pattern: string | string[]) => boolean;
type NodePath = typeof path;
/**
* The platform-specific file delimiter.
*
* Equals to `";"` in windows and `":"` in all other platforms.
*/
declare const delimiter: ";" | ":";
declare const posix: NodePath["posix"];
declare const win32: NodePath["win32"];
declare const _default: NodePath;
export { basename, _default as default, delimiter, dirname, extname, format, isAbsolute, join, matchesGlob, normalize, normalizeString, parse, posix, relative, resolve, sep, toNamespacedPath, win32 };

View File

@@ -0,0 +1,47 @@
import * as path from 'node:path';
import path__default from 'node:path';
/**
* Constant for path separator.
*
* Always equals to `"/"`.
*/
declare const sep = "/";
declare const normalize: typeof path__default.normalize;
declare const join: typeof path__default.join;
declare const resolve: typeof path__default.resolve;
/**
* Resolves a string path, resolving '.' and '.' segments and allowing paths above the root.
*
* @param path - The path to normalise.
* @param allowAboveRoot - Whether to allow the resulting path to be above the root directory.
* @returns the normalised path string.
*/
declare function normalizeString(path: string, allowAboveRoot: boolean): string;
declare const isAbsolute: typeof path__default.isAbsolute;
declare const toNamespacedPath: typeof path__default.toNamespacedPath;
declare const extname: typeof path__default.extname;
declare const relative: typeof path__default.relative;
declare const dirname: typeof path__default.dirname;
declare const format: typeof path__default.format;
declare const basename: typeof path__default.basename;
declare const parse: typeof path__default.parse;
/**
* The `path.matchesGlob()` method determines if `path` matches the `pattern`.
* @param path The path to glob-match against.
* @param pattern The glob to check the path against.
*/
declare const matchesGlob: (path: string, pattern: string | string[]) => boolean;
type NodePath = typeof path;
/**
* The platform-specific file delimiter.
*
* Equals to `";"` in windows and `":"` in all other platforms.
*/
declare const delimiter: ";" | ":";
declare const posix: NodePath["posix"];
declare const win32: NodePath["win32"];
declare const _default: NodePath;
export { basename, _default as default, delimiter, dirname, extname, format, isAbsolute, join, matchesGlob, normalize, normalizeString, parse, posix, relative, resolve, sep, toNamespacedPath, win32 };

View File

@@ -0,0 +1,47 @@
import * as path from 'node:path';
import path__default from 'node:path';
/**
* Constant for path separator.
*
* Always equals to `"/"`.
*/
declare const sep = "/";
declare const normalize: typeof path__default.normalize;
declare const join: typeof path__default.join;
declare const resolve: typeof path__default.resolve;
/**
* Resolves a string path, resolving '.' and '.' segments and allowing paths above the root.
*
* @param path - The path to normalise.
* @param allowAboveRoot - Whether to allow the resulting path to be above the root directory.
* @returns the normalised path string.
*/
declare function normalizeString(path: string, allowAboveRoot: boolean): string;
declare const isAbsolute: typeof path__default.isAbsolute;
declare const toNamespacedPath: typeof path__default.toNamespacedPath;
declare const extname: typeof path__default.extname;
declare const relative: typeof path__default.relative;
declare const dirname: typeof path__default.dirname;
declare const format: typeof path__default.format;
declare const basename: typeof path__default.basename;
declare const parse: typeof path__default.parse;
/**
* The `path.matchesGlob()` method determines if `path` matches the `pattern`.
* @param path The path to glob-match against.
* @param pattern The glob to check the path against.
*/
declare const matchesGlob: (path: string, pattern: string | string[]) => boolean;
type NodePath = typeof path;
/**
* The platform-specific file delimiter.
*
* Equals to `";"` in windows and `":"` in all other platforms.
*/
declare const delimiter: ";" | ":";
declare const posix: NodePath["posix"];
declare const win32: NodePath["win32"];
declare const _default: NodePath;
export { basename, _default as default, delimiter, dirname, extname, format, isAbsolute, join, matchesGlob, normalize, normalizeString, parse, posix, relative, resolve, sep, toNamespacedPath, win32 };

View File

@@ -0,0 +1,19 @@
import { _ as _path } from './shared/pathe.M-eThtNZ.mjs';
export { c as basename, d as dirname, e as extname, f as format, i as isAbsolute, j as join, m as matchesGlob, n as normalize, a as normalizeString, p as parse, b as relative, r as resolve, s as sep, t as toNamespacedPath } from './shared/pathe.M-eThtNZ.mjs';
const delimiter = /* @__PURE__ */ (() => globalThis.process?.platform === "win32" ? ";" : ":")();
const _platforms = { posix: void 0, win32: void 0 };
const mix = (del = delimiter) => {
return new Proxy(_path, {
get(_, prop) {
if (prop === "delimiter") return del;
if (prop === "posix") return posix;
if (prop === "win32") return win32;
return _platforms[prop] || _path[prop];
}
});
};
const posix = /* @__PURE__ */ mix(":");
const win32 = /* @__PURE__ */ mix(";");
export { posix as default, delimiter, posix, win32 };

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,82 @@
'use strict';
const _path = require('./shared/pathe.BSlhyZSM.cjs');
const pathSeparators = /* @__PURE__ */ new Set(["/", "\\", void 0]);
const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias");
const SLASH_RE = /[/\\]/;
function normalizeAliases(_aliases) {
if (_aliases[normalizedAliasSymbol]) {
return _aliases;
}
const aliases = Object.fromEntries(
Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b))
);
for (const key in aliases) {
for (const alias in aliases) {
if (alias === key || key.startsWith(alias)) {
continue;
}
if (aliases[key]?.startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) {
aliases[key] = aliases[alias] + aliases[key].slice(alias.length);
}
}
}
Object.defineProperty(aliases, normalizedAliasSymbol, {
value: true,
enumerable: false
});
return aliases;
}
function resolveAlias(path, aliases) {
const _path$1 = _path.normalizeWindowsPath(path);
aliases = normalizeAliases(aliases);
for (const [alias, to] of Object.entries(aliases)) {
if (!_path$1.startsWith(alias)) {
continue;
}
const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias;
if (hasTrailingSlash(_path$1[_alias.length])) {
return _path.join(to, _path$1.slice(alias.length));
}
}
return _path$1;
}
function reverseResolveAlias(path, aliases) {
const _path$1 = _path.normalizeWindowsPath(path);
aliases = normalizeAliases(aliases);
const matches = [];
for (const [to, alias] of Object.entries(aliases)) {
if (!_path$1.startsWith(alias)) {
continue;
}
const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias;
if (hasTrailingSlash(_path$1[_alias.length])) {
matches.push(_path.join(to, _path$1.slice(alias.length)));
}
}
return matches.sort((a, b) => b.length - a.length);
}
function filename(path) {
const base = path.split(SLASH_RE).pop();
if (!base) {
return void 0;
}
const separatorIndex = base.lastIndexOf(".");
if (separatorIndex <= 0) {
return base;
}
return base.slice(0, separatorIndex);
}
function _compareAliases(a, b) {
return b.split("/").length - a.split("/").length;
}
function hasTrailingSlash(path = "/") {
const lastChar = path[path.length - 1];
return lastChar === "/" || lastChar === "\\";
}
exports.filename = filename;
exports.normalizeAliases = normalizeAliases;
exports.resolveAlias = resolveAlias;
exports.reverseResolveAlias = reverseResolveAlias;

View File

@@ -0,0 +1,32 @@
/**
* Normalises alias mappings, ensuring that more specific aliases are resolved before less specific ones.
* This function also ensures that aliases do not resolve to themselves cyclically.
*
* @param _aliases - A set of alias mappings where each key is an alias and its value is the actual path it points to.
* @returns a set of normalised alias mappings.
*/
declare function normalizeAliases(_aliases: Record<string, string>): Record<string, string>;
/**
* Resolves a path string to its alias if applicable, otherwise returns the original path.
* This function normalises the path, resolves the alias and then joins it to the alias target if necessary.
*
* @param path - The path string to resolve.
* @param aliases - A set of alias mappings to use for resolution.
* @returns the resolved path as a string.
*/
declare function resolveAlias(path: string, aliases: Record<string, string>): string;
/**
* Resolves a path string to its possible alias.
*
* Returns an array of possible alias resolutions (could be empty), sorted by specificity (longest first).
*/
declare function reverseResolveAlias(path: string, aliases: Record<string, string>): string[];
/**
* Extracts the filename from a given path, excluding any directory paths and the file extension.
*
* @param path - The full path of the file from which to extract the filename.
* @returns the filename without the extension, or `undefined` if the filename cannot be extracted.
*/
declare function filename(path: string): string | undefined;
export { filename, normalizeAliases, resolveAlias, reverseResolveAlias };

View File

@@ -0,0 +1,32 @@
/**
* Normalises alias mappings, ensuring that more specific aliases are resolved before less specific ones.
* This function also ensures that aliases do not resolve to themselves cyclically.
*
* @param _aliases - A set of alias mappings where each key is an alias and its value is the actual path it points to.
* @returns a set of normalised alias mappings.
*/
declare function normalizeAliases(_aliases: Record<string, string>): Record<string, string>;
/**
* Resolves a path string to its alias if applicable, otherwise returns the original path.
* This function normalises the path, resolves the alias and then joins it to the alias target if necessary.
*
* @param path - The path string to resolve.
* @param aliases - A set of alias mappings to use for resolution.
* @returns the resolved path as a string.
*/
declare function resolveAlias(path: string, aliases: Record<string, string>): string;
/**
* Resolves a path string to its possible alias.
*
* Returns an array of possible alias resolutions (could be empty), sorted by specificity (longest first).
*/
declare function reverseResolveAlias(path: string, aliases: Record<string, string>): string[];
/**
* Extracts the filename from a given path, excluding any directory paths and the file extension.
*
* @param path - The full path of the file from which to extract the filename.
* @returns the filename without the extension, or `undefined` if the filename cannot be extracted.
*/
declare function filename(path: string): string | undefined;
export { filename, normalizeAliases, resolveAlias, reverseResolveAlias };

View File

@@ -0,0 +1,32 @@
/**
* Normalises alias mappings, ensuring that more specific aliases are resolved before less specific ones.
* This function also ensures that aliases do not resolve to themselves cyclically.
*
* @param _aliases - A set of alias mappings where each key is an alias and its value is the actual path it points to.
* @returns a set of normalised alias mappings.
*/
declare function normalizeAliases(_aliases: Record<string, string>): Record<string, string>;
/**
* Resolves a path string to its alias if applicable, otherwise returns the original path.
* This function normalises the path, resolves the alias and then joins it to the alias target if necessary.
*
* @param path - The path string to resolve.
* @param aliases - A set of alias mappings to use for resolution.
* @returns the resolved path as a string.
*/
declare function resolveAlias(path: string, aliases: Record<string, string>): string;
/**
* Resolves a path string to its possible alias.
*
* Returns an array of possible alias resolutions (could be empty), sorted by specificity (longest first).
*/
declare function reverseResolveAlias(path: string, aliases: Record<string, string>): string[];
/**
* Extracts the filename from a given path, excluding any directory paths and the file extension.
*
* @param path - The full path of the file from which to extract the filename.
* @returns the filename without the extension, or `undefined` if the filename cannot be extracted.
*/
declare function filename(path: string): string | undefined;
export { filename, normalizeAliases, resolveAlias, reverseResolveAlias };

View File

@@ -0,0 +1,77 @@
import { g as normalizeWindowsPath, j as join } from './shared/pathe.M-eThtNZ.mjs';
const pathSeparators = /* @__PURE__ */ new Set(["/", "\\", void 0]);
const normalizedAliasSymbol = Symbol.for("pathe:normalizedAlias");
const SLASH_RE = /[/\\]/;
function normalizeAliases(_aliases) {
if (_aliases[normalizedAliasSymbol]) {
return _aliases;
}
const aliases = Object.fromEntries(
Object.entries(_aliases).sort(([a], [b]) => _compareAliases(a, b))
);
for (const key in aliases) {
for (const alias in aliases) {
if (alias === key || key.startsWith(alias)) {
continue;
}
if (aliases[key]?.startsWith(alias) && pathSeparators.has(aliases[key][alias.length])) {
aliases[key] = aliases[alias] + aliases[key].slice(alias.length);
}
}
}
Object.defineProperty(aliases, normalizedAliasSymbol, {
value: true,
enumerable: false
});
return aliases;
}
function resolveAlias(path, aliases) {
const _path = normalizeWindowsPath(path);
aliases = normalizeAliases(aliases);
for (const [alias, to] of Object.entries(aliases)) {
if (!_path.startsWith(alias)) {
continue;
}
const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias;
if (hasTrailingSlash(_path[_alias.length])) {
return join(to, _path.slice(alias.length));
}
}
return _path;
}
function reverseResolveAlias(path, aliases) {
const _path = normalizeWindowsPath(path);
aliases = normalizeAliases(aliases);
const matches = [];
for (const [to, alias] of Object.entries(aliases)) {
if (!_path.startsWith(alias)) {
continue;
}
const _alias = hasTrailingSlash(alias) ? alias.slice(0, -1) : alias;
if (hasTrailingSlash(_path[_alias.length])) {
matches.push(join(to, _path.slice(alias.length)));
}
}
return matches.sort((a, b) => b.length - a.length);
}
function filename(path) {
const base = path.split(SLASH_RE).pop();
if (!base) {
return void 0;
}
const separatorIndex = base.lastIndexOf(".");
if (separatorIndex <= 0) {
return base;
}
return base.slice(0, separatorIndex);
}
function _compareAliases(a, b) {
return b.split("/").length - a.split("/").length;
}
function hasTrailingSlash(path = "/") {
const lastChar = path[path.length - 1];
return lastChar === "/" || lastChar === "\\";
}
export { filename, normalizeAliases, resolveAlias, reverseResolveAlias };

61
node_modules/@nuxt/cli/node_modules/pathe/package.json generated vendored Normal file
View File

@@ -0,0 +1,61 @@
{
"name": "pathe",
"version": "2.0.3",
"description": "Universal filesystem path utils",
"repository": "unjs/pathe",
"license": "MIT",
"sideEffects": false,
"type": "module",
"exports": {
".": {
"import": {
"types": "./dist/index.d.mts",
"default": "./dist/index.mjs"
},
"require": {
"types": "./dist/index.d.cts",
"default": "./dist/index.cjs"
}
},
"./utils": {
"import": {
"types": "./dist/utils.d.mts",
"default": "./dist/utils.mjs"
},
"require": {
"types": "./dist/utils.d.cts",
"default": "./dist/utils.cjs"
}
}
},
"main": "./dist/index.cjs",
"module": "./dist/index.mjs",
"types": "./dist/index.d.ts",
"files": [
"dist",
"utils.d.ts"
],
"devDependencies": {
"@types/node": "^22.13.1",
"@vitest/coverage-v8": "^3.0.5",
"changelogen": "^0.5.7",
"esbuild": "^0.25.0",
"eslint": "^9.20.1",
"eslint-config-unjs": "^0.4.2",
"jiti": "^2.4.2",
"prettier": "^3.5.0",
"typescript": "^5.7.3",
"unbuild": "^3.3.1",
"vitest": "^3.0.5",
"zeptomatch": "^2.0.0"
},
"scripts": {
"build": "unbuild",
"dev": "vitest",
"lint": "eslint . && prettier -c src test",
"lint:fix": "eslint . --fix && prettier -w src test",
"release": "pnpm test && pnpm build && changelogen --release && pnpm publish && git push --follow-tags",
"test": "pnpm lint && vitest run --coverage",
"test:types": "tsc --noEmit"
}
}

1
node_modules/@nuxt/cli/node_modules/pathe/utils.d.ts generated vendored Normal file
View File

@@ -0,0 +1 @@
export * from "./dist/utils";

92
node_modules/@nuxt/cli/package.json generated vendored Normal file
View File

@@ -0,0 +1,92 @@
{
"name": "@nuxt/cli",
"type": "module",
"version": "3.33.1",
"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"
},
"peerDependencies": {
"@nuxt/schema": "^4.3.0"
},
"peerDependenciesMeta": {
"@nuxt/schema": {
"optional": true
}
},
"dependencies": {
"@bomb.sh/tab": "^0.0.12",
"@clack/prompts": "^1.0.0",
"c12": "^3.3.3",
"citty": "^0.2.0",
"confbox": "^0.2.4",
"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",
"fzf": "^0.5.2",
"giget": "^3.1.2",
"jiti": "^2.6.1",
"listhen": "^1.9.0",
"nypm": "^0.6.5",
"ofetch": "^1.5.1",
"ohash": "^2.0.11",
"pathe": "^2.0.3",
"perfect-debounce": "^2.1.0",
"pkg-types": "^2.3.0",
"scule": "^1.3.0",
"semver": "^7.7.4",
"srvx": "^0.11.2",
"std-env": "^3.10.0",
"tinyexec": "^1.0.2",
"ufo": "^1.6.3",
"youch": "^4.1.0-beta.13"
},
"devDependencies": {
"@nuxt/kit": "^4.3.1",
"@nuxt/schema": "^4.3.1",
"@types/debug": "^4.1.12",
"@types/node": "^24.10.12",
"get-port-please": "^3.2.0",
"h3": "^1.15.5",
"h3-next": "npm:h3@^2.0.1-rc.14",
"nitro": "^3.0.1-alpha.2",
"nitropack": "^2.13.1",
"rollup": "^4.57.1",
"rollup-plugin-visualizer": "^6.0.5",
"tsdown": "^0.20.3",
"typescript": "^5.9.3",
"undici": "^7.21.0",
"unplugin-purge-polyfills": "^0.1.0",
"vitest": "^4.0.18",
"youch": "^4.1.0-beta.13"
}
}

7
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
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

236
node_modules/@nuxt/devalue/dist/devalue.js generated vendored Normal file
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;

234
node_modules/@nuxt/devalue/dist/devalue.mjs generated vendored Normal file
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 };

3
node_modules/@nuxt/devalue/dist/index.d.ts generated vendored Normal file
View File

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

39
node_modules/@nuxt/devalue/package.json generated vendored Normal file
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"
}
}

21
node_modules/@nuxt/devtools-kit/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.

110
node_modules/@nuxt/devtools-kit/dist/index.cjs generated vendored Normal file
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;

35
node_modules/@nuxt/devtools-kit/dist/index.d.cts generated vendored Normal file
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, N as NuxtDevtoolsInfo, S as SubprocessOptions, T as TerminalState } from './shared/devtools-kit.BE8MVpwl.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): void | 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 extends object = Record<string, unknown>, ServerFunctions extends object = Record<string, unknown>>(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 };

35
node_modules/@nuxt/devtools-kit/dist/index.d.mts generated vendored Normal file
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, N as NuxtDevtoolsInfo, S as SubprocessOptions, T as TerminalState } from './shared/devtools-kit.BE8MVpwl.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): void | 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 extends object = Record<string, unknown>, ServerFunctions extends object = Record<string, unknown>>(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 };

35
node_modules/@nuxt/devtools-kit/dist/index.d.ts generated vendored Normal file
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, N as NuxtDevtoolsInfo, S as SubprocessOptions, T as TerminalState } from './shared/devtools-kit.BE8MVpwl.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): void | 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 extends object = Record<string, unknown>, ServerFunctions extends object = Record<string, unknown>>(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 };

104
node_modules/@nuxt/devtools-kit/dist/index.mjs generated vendored Normal file
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 extends object = Record<string, unknown>, ServerFunctions extends object = Record<string, unknown>>(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 { RouteInfo as $, AnalyzeBuildMeta as A, BasicModuleInfo as B, ClientFunctions as C, ModuleStaticInfo as D, ModuleStats as E, ModuleTabInfo as F, GetWizardArgs as G, HookInfo as H, ImageMeta as I, ModuleType as J, ModuleVNodeView as K, LoadingTimeMetric as L, ModuleCustomTab as M, NuxtDevtoolsInfo as N, ModuleView as O, PluginMetric as P, NpmCommandOptions as Q, NpmCommandType as R, SubprocessOptions as S, TerminalState as T, NuxtDevToolsOptions as U, NuxtDevtoolsServerContext as V, NuxtServerData as W, PackageManagerName as X, PackageUpdateInfo as Y, Payload as Z, PluginInfoWithMetic as _, ServerFunctions as a, ScannedNitroTasks as a0, ServerDebugContext as a1, ServerDebugModuleMutationRecord as a2, ServerRouteInfo as a3, ServerRouteInput as a4, ServerRouteInputType as a5, ServerTaskInfo as a6, TabCategory as a7, TerminalAction as a8, TerminalBase as a9, TerminalInfo as aa, VSCodeIntegrationOptions as ab, VSCodeTunnelOptions as ac, VueInspectorClient as ad, VueInspectorData as ae, WizardActions as af, WizardFunctions as ag, AnalyzeBuildsInfo as b, AssetEntry as c, AssetInfo as d, AssetType as e, AutoImportsWithMetadata as f, CategorizedTabs as g, ClientUpdateEvent as h, CodeServerOptions as i, CodeServerType as j, CodeSnippet as k, CompatibilityStatus as l, ComponentRelationship as m, ComponentWithRelationships as n, GitHubContributor as o, InstallModuleReturn as p, InstalledModuleInfo as q, MaintainerInfo as r, ModuleBuiltinTab as s, ModuleCompatibility as t, ModuleGlobalOptions as u, ModuleIframeTabLazyOptions as v, ModuleIframeView as w, ModuleLaunchAction as x, ModuleLaunchView as y, ModuleOptions 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 extends object = Record<string, unknown>, ServerFunctions extends object = Record<string, unknown>>(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 { RouteInfo as $, AnalyzeBuildMeta as A, BasicModuleInfo as B, ClientFunctions as C, ModuleStaticInfo as D, ModuleStats as E, ModuleTabInfo as F, GetWizardArgs as G, HookInfo as H, ImageMeta as I, ModuleType as J, ModuleVNodeView as K, LoadingTimeMetric as L, ModuleCustomTab as M, NuxtDevtoolsInfo as N, ModuleView as O, PluginMetric as P, NpmCommandOptions as Q, NpmCommandType as R, SubprocessOptions as S, TerminalState as T, NuxtDevToolsOptions as U, NuxtDevtoolsServerContext as V, NuxtServerData as W, PackageManagerName as X, PackageUpdateInfo as Y, Payload as Z, PluginInfoWithMetic as _, ServerFunctions as a, ScannedNitroTasks as a0, ServerDebugContext as a1, ServerDebugModuleMutationRecord as a2, ServerRouteInfo as a3, ServerRouteInput as a4, ServerRouteInputType as a5, ServerTaskInfo as a6, TabCategory as a7, TerminalAction as a8, TerminalBase as a9, TerminalInfo as aa, VSCodeIntegrationOptions as ab, VSCodeTunnelOptions as ac, VueInspectorClient as ad, VueInspectorData as ae, WizardActions as af, WizardFunctions as ag, AnalyzeBuildsInfo as b, AssetEntry as c, AssetInfo as d, AssetType as e, AutoImportsWithMetadata as f, CategorizedTabs as g, ClientUpdateEvent as h, CodeServerOptions as i, CodeServerType as j, CodeSnippet as k, CompatibilityStatus as l, ComponentRelationship as m, ComponentWithRelationships as n, GitHubContributor as o, InstallModuleReturn as p, InstalledModuleInfo as q, MaintainerInfo as r, ModuleBuiltinTab as s, ModuleCompatibility as t, ModuleGlobalOptions as u, ModuleIframeTabLazyOptions as v, ModuleIframeView as w, ModuleLaunchAction as x, ModuleLaunchView as y, ModuleOptions 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 extends object = Record<string, unknown>, ServerFunctions extends object = Record<string, unknown>>(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 { RouteInfo as $, AnalyzeBuildMeta as A, BasicModuleInfo as B, ClientFunctions as C, ModuleStaticInfo as D, ModuleStats as E, ModuleTabInfo as F, GetWizardArgs as G, HookInfo as H, ImageMeta as I, ModuleType as J, ModuleVNodeView as K, LoadingTimeMetric as L, ModuleCustomTab as M, NuxtDevtoolsInfo as N, ModuleView as O, PluginMetric as P, NpmCommandOptions as Q, NpmCommandType as R, SubprocessOptions as S, TerminalState as T, NuxtDevToolsOptions as U, NuxtDevtoolsServerContext as V, NuxtServerData as W, PackageManagerName as X, PackageUpdateInfo as Y, Payload as Z, PluginInfoWithMetic as _, ServerFunctions as a, ScannedNitroTasks as a0, ServerDebugContext as a1, ServerDebugModuleMutationRecord as a2, ServerRouteInfo as a3, ServerRouteInput as a4, ServerRouteInputType as a5, ServerTaskInfo as a6, TabCategory as a7, TerminalAction as a8, TerminalBase as a9, TerminalInfo as aa, VSCodeIntegrationOptions as ab, VSCodeTunnelOptions as ac, VueInspectorClient as ad, VueInspectorData as ae, WizardActions as af, WizardFunctions as ag, AnalyzeBuildsInfo as b, AssetEntry as c, AssetInfo as d, AssetType as e, AutoImportsWithMetadata as f, CategorizedTabs as g, ClientUpdateEvent as h, CodeServerOptions as i, CodeServerType as j, CodeSnippet as k, CompatibilityStatus as l, ComponentRelationship as m, ComponentWithRelationships as n, GitHubContributor as o, InstallModuleReturn as p, InstalledModuleInfo as q, MaintainerInfo as r, ModuleBuiltinTab as s, ModuleCompatibility as t, ModuleGlobalOptions as u, ModuleIframeTabLazyOptions as v, ModuleIframeView as w, ModuleLaunchAction as x, ModuleLaunchView as y, ModuleOptions as z };

2
node_modules/@nuxt/devtools-kit/dist/types.cjs generated vendored Normal file
View File

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

181
node_modules/@nuxt/devtools-kit/dist/types.d.cts generated vendored Normal file
View File

@@ -0,0 +1,181 @@
import { a as ServerFunctions, C as ClientFunctions, H as HookInfo, P as PluginMetric, L as LoadingTimeMetric } from './shared/devtools-kit.BE8MVpwl.cjs';
export { A as AnalyzeBuildMeta, b as AnalyzeBuildsInfo, c as AssetEntry, d as AssetInfo, e as AssetType, f as AutoImportsWithMetadata, B as BasicModuleInfo, g as CategorizedTabs, h as ClientUpdateEvent, i as CodeServerOptions, j as CodeServerType, k as CodeSnippet, l as CompatibilityStatus, m as ComponentRelationship, n as ComponentWithRelationships, G as GetWizardArgs, o as GitHubContributor, I as ImageMeta, p as InstallModuleReturn, q as InstalledModuleInfo, r as MaintainerInfo, s as ModuleBuiltinTab, t as ModuleCompatibility, M as ModuleCustomTab, u as ModuleGlobalOptions, v as ModuleIframeTabLazyOptions, w as ModuleIframeView, x as ModuleLaunchAction, y as ModuleLaunchView, z as ModuleOptions, D as ModuleStaticInfo, E as ModuleStats, F as ModuleTabInfo, J as ModuleType, K as ModuleVNodeView, O as ModuleView, Q as NpmCommandOptions, R as NpmCommandType, U as NuxtDevToolsOptions, N as NuxtDevtoolsInfo, V as NuxtDevtoolsServerContext, W as NuxtServerData, X as PackageManagerName, Y as PackageUpdateInfo, Z as Payload, _ as PluginInfoWithMetic, $ as RouteInfo, a0 as ScannedNitroTasks, a1 as ServerDebugContext, a2 as ServerDebugModuleMutationRecord, a3 as ServerRouteInfo, a4 as ServerRouteInput, a5 as ServerRouteInputType, a6 as ServerTaskInfo, S as SubprocessOptions, a7 as TabCategory, a8 as TerminalAction, a9 as TerminalBase, aa as TerminalInfo, T as TerminalState, ab as VSCodeIntegrationOptions, ac as VSCodeTunnelOptions, ad as VueInspectorClient, ae as VueInspectorData, af as WizardActions, ag as WizardFunctions } from './shared/devtools-kit.BE8MVpwl.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 extends object = Record<string, unknown>, ClientFunctions extends object = Record<string, unknown>>(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 };

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