Refactor routing in App component to enhance navigation and improve error handling by integrating dynamic routes and updating the NotFound route.

This commit is contained in:
becarta
2025-05-23 12:43:00 +02:00
parent f40db0f5c9
commit a544759a3b
11127 changed files with 1647032 additions and 0 deletions

14
node_modules/astro/dist/cli/add/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,14 @@
import { type ProxifiedModule } from 'magicast';
import { type Flags } from '../flags.js';
interface AddOptions {
flags: Flags;
}
interface IntegrationInfo {
id: string;
packageName: string;
dependencies: [name: string, version: string][];
type: 'integration' | 'adapter';
}
export declare function add(names: string[], { flags }: AddOptions): Promise<void>;
export declare function setAdapter(mod: ProxifiedModule<any>, adapter: IntegrationInfo, exportName: string): void;
export {};

833
node_modules/astro/dist/cli/add/index.js generated vendored Normal file
View File

@@ -0,0 +1,833 @@
import fsMod, { existsSync, promises as fs } from "node:fs";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import boxen from "boxen";
import { diffWords } from "diff";
import { bold, cyan, dim, green, magenta, red, yellow } from "kleur/colors";
import { builders, generateCode, loadFile } from "magicast";
import { getDefaultExportOptions } from "magicast/helpers";
import ora from "ora";
import preferredPM from "preferred-pm";
import prompts from "prompts";
import maxSatisfying from "semver/ranges/max-satisfying.js";
import {
loadTSConfig,
resolveConfig,
resolveConfigPath,
resolveRoot
} from "../../core/config/index.js";
import {
defaultTSConfig,
presets,
updateTSConfigForFramework
} from "../../core/config/tsconfig.js";
import * as msg from "../../core/messages.js";
import { printHelp } from "../../core/messages.js";
import { appendForwardSlash } from "../../core/path.js";
import { apply as applyPolyfill } from "../../core/polyfill.js";
import { ensureProcessNodeEnv, parseNpmName } from "../../core/util.js";
import { eventCliSession, telemetry } from "../../events/index.js";
import { exec } from "../exec.js";
import { createLoggerFromFlags, flagsToAstroInlineConfig } from "../flags.js";
import { fetchPackageJson, fetchPackageVersions } from "../install-package.js";
const ALIASES = /* @__PURE__ */ new Map([
["solid", "solid-js"],
["tailwindcss", "tailwind"]
]);
const STUBS = {
ASTRO_CONFIG: `import { defineConfig } from 'astro/config';
// https://astro.build/config
export default defineConfig({});`,
TAILWIND_CONFIG: `/** @type {import('tailwindcss').Config} */
export default {
content: ['./src/**/*.{astro,html,js,jsx,md,mdx,svelte,ts,tsx,vue}'],
theme: {
extend: {},
},
plugins: [],
}
`,
SVELTE_CONFIG: `import { vitePreprocess } from '@astrojs/svelte';
export default {
preprocess: vitePreprocess(),
}
`,
LIT_NPMRC: `# Lit libraries are required to be hoisted due to dependency issues.
public-hoist-pattern[]=*lit*
`,
DB_CONFIG: `import { defineDb } from 'astro:db';
// https://astro.build/db/config
export default defineDb({
tables: {}
});
`,
DB_SEED: `import { db } from 'astro:db';
// https://astro.build/db/seed
export default async function seed() {
// TODO
}
`
};
const OFFICIAL_ADAPTER_TO_IMPORT_MAP = {
netlify: "@astrojs/netlify",
vercel: "@astrojs/vercel/serverless",
cloudflare: "@astrojs/cloudflare",
node: "@astrojs/node"
};
async function add(names, { flags }) {
ensureProcessNodeEnv("production");
applyPolyfill();
const inlineConfig = flagsToAstroInlineConfig(flags);
const { userConfig } = await resolveConfig(inlineConfig, "add");
telemetry.record(eventCliSession("add", userConfig));
if (flags.help || names.length === 0) {
printHelp({
commandName: "astro add",
usage: "[...integrations] [...adapters]",
tables: {
Flags: [
["--yes", "Accept all prompts."],
["--help", "Show this help message."]
],
"UI Frameworks": [
["react", "astro add react"],
["preact", "astro add preact"],
["vue", "astro add vue"],
["svelte", "astro add svelte"],
["solid-js", "astro add solid-js"],
["lit", "astro add lit"],
["alpinejs", "astro add alpinejs"]
],
"Documentation Frameworks": [["starlight", "astro add starlight"]],
"SSR Adapters": [
["netlify", "astro add netlify"],
["vercel", "astro add vercel"],
["deno", "astro add deno"],
["cloudflare", "astro add cloudflare"],
["node", "astro add node"]
],
Others: [
["db", "astro add db"],
["tailwind", "astro add tailwind"],
["mdx", "astro add mdx"],
["markdoc", "astro add markdoc"],
["partytown", "astro add partytown"],
["sitemap", "astro add sitemap"]
]
},
description: `For more integrations, check out: ${cyan("https://astro.build/integrations")}`
});
return;
}
const cwd = inlineConfig.root;
const logger = createLoggerFromFlags(flags);
const integrationNames = names.map((name) => ALIASES.has(name) ? ALIASES.get(name) : name);
const integrations = await validateIntegrations(integrationNames);
let installResult = await tryToInstallIntegrations({ integrations, cwd, flags, logger });
const rootPath = resolveRoot(cwd);
const root = pathToFileURL(rootPath);
root.href = appendForwardSlash(root.href);
switch (installResult) {
case 1 /* updated */: {
if (integrations.find((integration) => integration.id === "tailwind")) {
await setupIntegrationConfig({
root,
logger,
flags,
integrationName: "Tailwind",
possibleConfigFiles: [
"./tailwind.config.cjs",
"./tailwind.config.mjs",
"./tailwind.config.ts",
"./tailwind.config.mts",
"./tailwind.config.cts",
"./tailwind.config.js"
],
defaultConfigFile: "./tailwind.config.mjs",
defaultConfigContent: STUBS.TAILWIND_CONFIG
});
}
if (integrations.find((integration) => integration.id === "svelte")) {
await setupIntegrationConfig({
root,
logger,
flags,
integrationName: "Svelte",
possibleConfigFiles: ["./svelte.config.js", "./svelte.config.cjs", "./svelte.config.mjs"],
defaultConfigFile: "./svelte.config.js",
defaultConfigContent: STUBS.SVELTE_CONFIG
});
}
if (integrations.find((integration) => integration.id === "db")) {
if (!existsSync(new URL("./db/", root))) {
logger.info(
"SKIP_FORMAT",
`
${magenta(
`Astro will scaffold ${green("./db/config.ts")}${magenta(" and ")}${green(
"./db/seed.ts"
)}${magenta(" files.")}`
)}
`
);
if (await askToContinue({ flags })) {
await fs.mkdir(new URL("./db", root));
await Promise.all([
fs.writeFile(new URL("./db/config.ts", root), STUBS.DB_CONFIG, { encoding: "utf-8" }),
fs.writeFile(new URL("./db/seed.ts", root), STUBS.DB_SEED, { encoding: "utf-8" })
]);
} else {
logger.info(
"SKIP_FORMAT",
`
Astro DB requires additional configuration. Please refer to https://astro.build/db/config`
);
}
} else {
logger.debug("add", `Using existing db configuration`);
}
}
if (integrations.find((integration) => integration.id === "lit") && (await preferredPM(fileURLToPath(root)))?.name === "pnpm") {
await setupIntegrationConfig({
root,
logger,
flags,
integrationName: "Lit",
possibleConfigFiles: ["./.npmrc"],
defaultConfigFile: "./.npmrc",
defaultConfigContent: STUBS.LIT_NPMRC
});
}
break;
}
case 2 /* cancelled */: {
logger.info(
"SKIP_FORMAT",
msg.cancelled(
`Dependencies ${bold("NOT")} installed.`,
`Be sure to install them manually before continuing!`
)
);
break;
}
case 3 /* failure */: {
throw createPrettyError(new Error(`Unable to install dependencies`));
}
case 0 /* none */:
break;
}
const rawConfigPath = await resolveConfigPath({
root: rootPath,
configFile: inlineConfig.configFile,
fs: fsMod
});
let configURL = rawConfigPath ? pathToFileURL(rawConfigPath) : void 0;
if (configURL) {
logger.debug("add", `Found config at ${configURL}`);
} else {
logger.info("add", `Unable to locate a config file, generating one for you.`);
configURL = new URL("./astro.config.mjs", root);
await fs.writeFile(fileURLToPath(configURL), STUBS.ASTRO_CONFIG, { encoding: "utf-8" });
}
let mod;
try {
mod = await loadFile(fileURLToPath(configURL));
logger.debug("add", "Parsed astro config");
if (mod.exports.default.$type !== "function-call") {
mod.imports.$prepend({ imported: "defineConfig", from: "astro/config" });
mod.exports.default = builders.functionCall("defineConfig", mod.exports.default);
} else if (mod.exports.default.$args[0] == null) {
mod.exports.default.$args[0] = {};
}
logger.debug("add", "Astro config ensured `defineConfig`");
for (const integration of integrations) {
if (isAdapter(integration)) {
const officialExportName = OFFICIAL_ADAPTER_TO_IMPORT_MAP[integration.id];
if (officialExportName) {
setAdapter(mod, integration, officialExportName);
} else {
logger.info(
"SKIP_FORMAT",
`
${magenta(
`Check our deployment docs for ${bold(
integration.packageName
)} to update your "adapter" config.`
)}`
);
}
} else {
addIntegration(mod, integration);
}
logger.debug("add", `Astro config added integration ${integration.id}`);
}
} catch (err) {
logger.debug("add", "Error parsing/modifying astro config: ", err);
throw createPrettyError(err);
}
let configResult;
if (mod) {
try {
configResult = await updateAstroConfig({
configURL,
mod,
flags,
logger,
logAdapterInstructions: integrations.some(isAdapter)
});
} catch (err) {
logger.debug("add", "Error updating astro config", err);
throw createPrettyError(err);
}
}
switch (configResult) {
case 2 /* cancelled */: {
logger.info(
"SKIP_FORMAT",
msg.cancelled(`Your configuration has ${bold("NOT")} been updated.`)
);
break;
}
case 0 /* none */: {
const pkgURL = new URL("./package.json", configURL);
if (existsSync(fileURLToPath(pkgURL))) {
const { dependencies = {}, devDependencies = {} } = await fs.readFile(fileURLToPath(pkgURL)).then((res) => JSON.parse(res.toString()));
const deps = Object.keys(Object.assign(dependencies, devDependencies));
const missingDeps = integrations.filter(
(integration) => !deps.includes(integration.packageName)
);
if (missingDeps.length === 0) {
logger.info("SKIP_FORMAT", msg.success(`Configuration up-to-date.`));
break;
}
}
logger.info("SKIP_FORMAT", msg.success(`Configuration up-to-date.`));
break;
}
case 3 /* failure */:
case 1 /* updated */:
case void 0: {
const list = integrations.map((integration) => ` - ${integration.packageName}`).join("\n");
logger.info(
"SKIP_FORMAT",
msg.success(
`Added the following integration${integrations.length === 1 ? "" : "s"} to your project:
${list}`
)
);
}
}
const updateTSConfigResult = await updateTSConfig(cwd, logger, integrations, flags);
switch (updateTSConfigResult) {
case 0 /* none */: {
break;
}
case 2 /* cancelled */: {
logger.info(
"SKIP_FORMAT",
msg.cancelled(`Your TypeScript configuration has ${bold("NOT")} been updated.`)
);
break;
}
case 3 /* failure */: {
throw new Error(
`Unknown error parsing tsconfig.json or jsconfig.json. Could not update TypeScript settings.`
);
}
case 1 /* updated */:
logger.info("SKIP_FORMAT", msg.success(`Successfully updated TypeScript settings`));
}
}
function isAdapter(integration) {
return integration.type === "adapter";
}
const toIdent = (name) => {
const ident = name.trim().replace(/[-_./]?astro(?:js)?[-_.]?/g, "").replace(/\.js/, "").replace(/[.\-_/]+([a-zA-Z])/g, (_, w) => w.toUpperCase()).replace(/^[^a-zA-Z$_]+/, "").replace(/@.*$/, "");
return `${ident[0].toLowerCase()}${ident.slice(1)}`;
};
function createPrettyError(err) {
err.message = `Astro could not update your astro.config.js file safely.
Reason: ${err.message}
You will need to add these integration(s) manually.
Documentation: https://docs.astro.build/en/guides/integrations-guide/`;
return err;
}
function addIntegration(mod, integration) {
const config = getDefaultExportOptions(mod);
const integrationId = toIdent(integration.id);
if (!mod.imports.$items.some((imp) => imp.local === integrationId)) {
mod.imports.$append({
imported: "default",
local: integrationId,
from: integration.packageName
});
}
config.integrations ??= [];
if (!config.integrations.$ast.elements.some(
(el) => el.type === "CallExpression" && el.callee.type === "Identifier" && el.callee.name === integrationId
)) {
config.integrations.push(builders.functionCall(integrationId));
}
}
function setAdapter(mod, adapter, exportName) {
const config = getDefaultExportOptions(mod);
const adapterId = toIdent(adapter.id);
if (!mod.imports.$items.some((imp) => imp.local === adapterId)) {
mod.imports.$append({
imported: "default",
local: adapterId,
from: exportName
});
}
if (!config.output) {
config.output = "server";
}
switch (adapter.id) {
case "node":
config.adapter = builders.functionCall(adapterId, { mode: "standalone" });
break;
default:
config.adapter = builders.functionCall(adapterId);
break;
}
}
var UpdateResult = /* @__PURE__ */ ((UpdateResult2) => {
UpdateResult2[UpdateResult2["none"] = 0] = "none";
UpdateResult2[UpdateResult2["updated"] = 1] = "updated";
UpdateResult2[UpdateResult2["cancelled"] = 2] = "cancelled";
UpdateResult2[UpdateResult2["failure"] = 3] = "failure";
return UpdateResult2;
})(UpdateResult || {});
async function updateAstroConfig({
configURL,
mod,
flags,
logger,
logAdapterInstructions
}) {
const input = await fs.readFile(fileURLToPath(configURL), { encoding: "utf-8" });
const output = generateCode(mod, {
format: {
objectCurlySpacing: true,
useTabs: false,
tabWidth: 2
}
}).code;
if (input === output) {
return 0 /* none */;
}
const diff = getDiffContent(input, output);
if (!diff) {
return 0 /* none */;
}
const message = `
${boxen(diff, {
margin: 0.5,
padding: 0.5,
borderStyle: "round",
title: configURL.pathname.split("/").pop()
})}
`;
logger.info(
"SKIP_FORMAT",
`
${magenta("Astro will make the following changes to your config file:")}
${message}`
);
if (logAdapterInstructions) {
logger.info(
"SKIP_FORMAT",
magenta(
` For complete deployment options, visit
${bold(
"https://docs.astro.build/en/guides/deploy/"
)}
`
)
);
}
if (await askToContinue({ flags })) {
await fs.writeFile(fileURLToPath(configURL), output, { encoding: "utf-8" });
logger.debug("add", `Updated astro config`);
return 1 /* updated */;
} else {
return 2 /* cancelled */;
}
}
async function getInstallIntegrationsCommand({
integrations,
logger,
cwd = process.cwd()
}) {
const pm = await preferredPM(cwd);
logger.debug("add", `package manager: ${JSON.stringify(pm)}`);
if (!pm) return null;
const dependencies = await convertIntegrationsToInstallSpecifiers(integrations);
switch (pm.name) {
case "npm":
return { pm: "npm", command: "install", flags: [], dependencies };
case "yarn":
return { pm: "yarn", command: "add", flags: [], dependencies };
case "pnpm":
return { pm: "pnpm", command: "add", flags: [], dependencies };
case "bun":
return { pm: "bun", command: "add", flags: [], dependencies };
default:
return null;
}
}
async function convertIntegrationsToInstallSpecifiers(integrations) {
const ranges = {};
for (let { packageName, dependencies } of integrations) {
ranges[packageName] = "*";
for (const [name, range] of dependencies) {
ranges[name] = range;
}
}
return Promise.all(
Object.entries(ranges).map(([name, range]) => resolveRangeToInstallSpecifier(name, range))
);
}
async function resolveRangeToInstallSpecifier(name, range) {
const versions = await fetchPackageVersions(name);
if (versions instanceof Error) return name;
const stableVersions = versions.filter((v) => !v.includes("-"));
const maxStable = maxSatisfying(stableVersions, range) ?? maxSatisfying(versions, range);
if (!maxStable) return name;
return `${name}@^${maxStable}`;
}
const INHERITED_FLAGS = /* @__PURE__ */ new Set([
"P",
"save-prod",
"D",
"save-dev",
"E",
"save-exact",
"no-save"
]);
async function tryToInstallIntegrations({
integrations,
cwd,
flags,
logger
}) {
const installCommand = await getInstallIntegrationsCommand({ integrations, cwd, logger });
const inheritedFlags = Object.entries(flags).map(([flag]) => {
if (flag == "_") return;
if (INHERITED_FLAGS.has(flag)) {
if (flag.length === 1) return `-${flag}`;
return `--${flag}`;
}
}).filter(Boolean).flat();
if (installCommand === null) {
return 0 /* none */;
} else {
const coloredOutput = `${bold(installCommand.pm)} ${installCommand.command}${[
"",
...installCommand.flags,
...inheritedFlags
].join(" ")} ${cyan(installCommand.dependencies.join(" "))}`;
const message = `
${boxen(coloredOutput, {
margin: 0.5,
padding: 0.5,
borderStyle: "round"
})}
`;
logger.info(
"SKIP_FORMAT",
`
${magenta("Astro will run the following command:")}
${dim(
"If you skip this step, you can always run it yourself later"
)}
${message}`
);
if (await askToContinue({ flags })) {
const spinner = ora("Installing dependencies...").start();
try {
await exec(
installCommand.pm,
[
installCommand.command,
...installCommand.flags,
...inheritedFlags,
...installCommand.dependencies
],
{
nodeOptions: {
cwd,
// reset NODE_ENV to ensure install command run in dev mode
env: { NODE_ENV: void 0 }
}
}
);
spinner.succeed();
return 1 /* updated */;
} catch (err) {
spinner.fail();
logger.debug("add", "Error installing dependencies", err);
console.error("\n", err.stdout || err.message, "\n");
return 3 /* failure */;
}
} else {
return 2 /* cancelled */;
}
}
}
async function validateIntegrations(integrations) {
const spinner = ora("Resolving packages...").start();
try {
const integrationEntries = await Promise.all(
integrations.map(async (integration) => {
const parsed = parseIntegrationName(integration);
if (!parsed) {
throw new Error(`${bold(integration)} does not appear to be a valid package name!`);
}
let { scope, name, tag } = parsed;
let pkgJson;
let pkgType;
if (scope && scope !== "@astrojs") {
pkgType = "third-party";
} else {
const firstPartyPkgCheck = await fetchPackageJson("@astrojs", name, tag);
if (firstPartyPkgCheck instanceof Error) {
if (firstPartyPkgCheck.message) {
spinner.warn(yellow(firstPartyPkgCheck.message));
}
spinner.warn(yellow(`${bold(integration)} is not an official Astro package.`));
const response = await prompts({
type: "confirm",
name: "askToContinue",
message: "Continue?",
initial: true
});
if (!response.askToContinue) {
throw new Error(
`No problem! Find our official integrations at ${cyan(
"https://astro.build/integrations"
)}`
);
}
spinner.start("Resolving with third party packages...");
pkgType = "third-party";
} else {
pkgType = "first-party";
pkgJson = firstPartyPkgCheck;
}
}
if (pkgType === "third-party") {
const thirdPartyPkgCheck = await fetchPackageJson(scope, name, tag);
if (thirdPartyPkgCheck instanceof Error) {
if (thirdPartyPkgCheck.message) {
spinner.warn(yellow(thirdPartyPkgCheck.message));
}
throw new Error(`Unable to fetch ${bold(integration)}. Does the package exist?`);
} else {
pkgJson = thirdPartyPkgCheck;
}
}
const resolvedScope = pkgType === "first-party" ? "@astrojs" : scope;
const packageName = `${resolvedScope ? `${resolvedScope}/` : ""}${name}`;
let dependencies = [
[pkgJson["name"], `^${pkgJson["version"]}`]
];
if (pkgJson["peerDependencies"]) {
const meta = pkgJson["peerDependenciesMeta"] || {};
for (const peer in pkgJson["peerDependencies"]) {
const optional = meta[peer]?.optional || false;
const isAstro = peer === "astro";
if (!optional && !isAstro) {
dependencies.push([peer, pkgJson["peerDependencies"][peer]]);
}
}
}
let integrationType;
const keywords = Array.isArray(pkgJson["keywords"]) ? pkgJson["keywords"] : [];
if (keywords.includes("astro-integration")) {
integrationType = "integration";
} else if (keywords.includes("astro-adapter")) {
integrationType = "adapter";
} else {
throw new Error(
`${bold(
packageName
)} doesn't appear to be an integration or an adapter. Find our official integrations at ${cyan(
"https://astro.build/integrations"
)}`
);
}
return { id: integration, packageName, dependencies, type: integrationType };
})
);
spinner.succeed();
return integrationEntries;
} catch (e) {
if (e instanceof Error) {
spinner.fail(e.message);
process.exit(1);
} else {
throw e;
}
}
}
async function updateTSConfig(cwd = process.cwd(), logger, integrationsInfo, flags) {
const integrations = integrationsInfo.map(
(integration) => integration.id
);
const firstIntegrationWithTSSettings = integrations.find(
(integration) => presets.has(integration)
);
if (!firstIntegrationWithTSSettings) {
return 0 /* none */;
}
let inputConfig = await loadTSConfig(cwd);
let inputConfigText = "";
if (inputConfig === "invalid-config" || inputConfig === "unknown-error") {
return 3 /* failure */;
} else if (inputConfig === "missing-config") {
logger.debug("add", "Couldn't find tsconfig.json or jsconfig.json, generating one");
inputConfig = {
tsconfig: defaultTSConfig,
tsconfigFile: path.join(cwd, "tsconfig.json"),
rawConfig: defaultTSConfig
};
} else {
inputConfigText = JSON.stringify(inputConfig.rawConfig, null, 2);
}
const configFileName = path.basename(inputConfig.tsconfigFile);
const outputConfig = updateTSConfigForFramework(
inputConfig.rawConfig,
firstIntegrationWithTSSettings
);
const output = JSON.stringify(outputConfig, null, 2);
const diff = getDiffContent(inputConfigText, output);
if (!diff) {
return 0 /* none */;
}
const message = `
${boxen(diff, {
margin: 0.5,
padding: 0.5,
borderStyle: "round",
title: configFileName
})}
`;
logger.info(
"SKIP_FORMAT",
`
${magenta(`Astro will make the following changes to your ${configFileName}:`)}
${message}`
);
const conflictingIntegrations = [...Object.keys(presets).filter((config) => config !== "vue")];
const hasConflictingIntegrations = integrations.filter((integration) => presets.has(integration)).length > 1 && integrations.filter((integration) => conflictingIntegrations.includes(integration)).length > 0;
if (hasConflictingIntegrations) {
logger.info(
"SKIP_FORMAT",
red(
` ${bold(
"Caution:"
)} Selected UI frameworks require conflicting tsconfig.json settings, as such only settings for ${bold(
firstIntegrationWithTSSettings
)} were used.
More information: https://docs.astro.build/en/guides/typescript/#errors-typing-multiple-jsx-frameworks-at-the-same-time
`
)
);
}
if (await askToContinue({ flags })) {
await fs.writeFile(inputConfig.tsconfigFile, output, {
encoding: "utf-8"
});
logger.debug("add", `Updated ${configFileName} file`);
return 1 /* updated */;
} else {
return 2 /* cancelled */;
}
}
function parseIntegrationName(spec) {
const result = parseNpmName(spec);
if (!result) return;
let { scope, name } = result;
let tag = "latest";
if (scope) {
name = name.replace(scope + "/", "");
}
if (name.includes("@")) {
const tagged = name.split("@");
name = tagged[0];
tag = tagged[1];
}
return { scope, name, tag };
}
async function askToContinue({ flags }) {
if (flags.yes || flags.y) return true;
const response = await prompts({
type: "confirm",
name: "askToContinue",
message: "Continue?",
initial: true
});
return Boolean(response.askToContinue);
}
function getDiffContent(input, output) {
let changes = [];
for (const change of diffWords(input, output)) {
let lines = change.value.trim().split("\n").slice(0, change.count);
if (lines.length === 0) continue;
if (change.added) {
if (!change.value.trim()) continue;
changes.push(change.value);
}
}
if (changes.length === 0) {
return null;
}
let diffed = output;
for (let newContent of changes) {
const coloredOutput = newContent.split("\n").map((ln) => ln ? green(ln) : "").join("\n");
diffed = diffed.replace(newContent, coloredOutput);
}
return diffed;
}
async function setupIntegrationConfig(opts) {
const logger = opts.logger;
const possibleConfigFiles = opts.possibleConfigFiles.map(
(p) => fileURLToPath(new URL(p, opts.root))
);
let alreadyConfigured = false;
for (const possibleConfigPath of possibleConfigFiles) {
if (existsSync(possibleConfigPath)) {
alreadyConfigured = true;
break;
}
}
if (!alreadyConfigured) {
logger.info(
"SKIP_FORMAT",
`
${magenta(`Astro will generate a minimal ${bold(opts.defaultConfigFile)} file.`)}
`
);
if (await askToContinue({ flags: opts.flags })) {
await fs.writeFile(
fileURLToPath(new URL(opts.defaultConfigFile, opts.root)),
opts.defaultConfigContent,
{
encoding: "utf-8"
}
);
logger.debug("add", `Generated default ${opts.defaultConfigFile} file`);
}
} else {
logger.debug("add", `Using existing ${opts.integrationName} configuration`);
}
}
export {
add,
setAdapter
};

6
node_modules/astro/dist/cli/build/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import { type Flags } from '../flags.js';
interface BuildOptions {
flags: Flags;
}
export declare function build({ flags }: BuildOptions): Promise<void>;
export {};

28
node_modules/astro/dist/cli/build/index.js generated vendored Normal file
View File

@@ -0,0 +1,28 @@
import _build from "../../core/build/index.js";
import { printHelp } from "../../core/messages.js";
import { flagsToAstroInlineConfig } from "../flags.js";
async function build({ flags }) {
if (flags?.help || flags?.h) {
printHelp({
commandName: "astro build",
usage: "[...flags]",
tables: {
Flags: [
["--outDir <directory>", `Specify the output directory for the build.`],
[
"--force",
"Clear the content layer and content collection cache, forcing a full rebuild."
],
["--help (-h)", "See all available flags."]
]
},
description: `Builds your site for deployment.`
});
return;
}
const inlineConfig = flagsToAstroInlineConfig(flags);
await _build(inlineConfig);
}
export {
build
};

2
node_modules/astro/dist/cli/check/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import { type Flags } from '../flags.js';
export declare function check(flags: Flags): Promise<boolean | void>;

41
node_modules/astro/dist/cli/check/index.js generated vendored Normal file
View File

@@ -0,0 +1,41 @@
import path from "node:path";
import { ensureProcessNodeEnv } from "../../core/util.js";
import { createLoggerFromFlags, flagsToAstroInlineConfig } from "../flags.js";
import { getPackage } from "../install-package.js";
async function check(flags) {
ensureProcessNodeEnv("production");
const logger = createLoggerFromFlags(flags);
const getPackageOpts = {
skipAsk: !!flags.yes || !!flags.y,
cwd: flags.root
};
const checkPackage = await getPackage(
"@astrojs/check",
logger,
getPackageOpts,
["typescript"]
);
const typescript = await getPackage("typescript", logger, getPackageOpts);
if (!checkPackage || !typescript) {
logger.error(
"check",
"The `@astrojs/check` and `typescript` packages are required for this command to work. Please manually install them into your project and try again."
);
return;
}
if (!flags.noSync && !flags.help) {
const { default: sync } = await import("../../core/sync/index.js");
try {
await sync(flagsToAstroInlineConfig(flags));
} catch (_) {
return process.exit(1);
}
}
const { check: checker, parseArgsAsCheckConfig } = checkPackage;
const config = parseArgsAsCheckConfig(process.argv);
logger.info("check", `Getting diagnostics for Astro files in ${path.resolve(config.root)}...`);
return await checker(config);
}
export {
check
};

6
node_modules/astro/dist/cli/create-key/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import { type Flags } from '../flags.js';
interface CreateKeyOptions {
flags: Flags;
}
export declare function createKey({ flags }: CreateKeyOptions): Promise<0 | 1>;
export {};

27
node_modules/astro/dist/cli/create-key/index.js generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import { createNodeLogger } from "../../core/config/logging.js";
import { createKey as createCryptoKey, encodeKey } from "../../core/encryption.js";
import { flagsToAstroInlineConfig } from "../flags.js";
async function createKey({ flags }) {
try {
const inlineConfig = flagsToAstroInlineConfig(flags);
const logger = createNodeLogger(inlineConfig);
const keyPromise = createCryptoKey();
const key = await keyPromise;
const encoded = await encodeKey(key);
logger.info(
"crypto",
`Generated a key to encrypt props passed to Server islands. To reuse the same key across builds, set this value as ASTRO_KEY in an environment variable on your build server.
ASTRO_KEY=${encoded}`
);
} catch (err) {
if (err != null) {
console.error(err.toString());
}
return 1;
}
return 0;
}
export {
createKey
};

4
node_modules/astro/dist/cli/db/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,4 @@
import type { Arguments } from 'yargs-parser';
export declare function db({ flags }: {
flags: Arguments;
}): Promise<void>;

27
node_modules/astro/dist/cli/db/index.js generated vendored Normal file
View File

@@ -0,0 +1,27 @@
import { resolveConfig } from "../../core/config/config.js";
import { apply as applyPolyfill } from "../../core/polyfill.js";
import { createLoggerFromFlags, flagsToAstroInlineConfig } from "../flags.js";
import { getPackage } from "../install-package.js";
async function db({ flags }) {
applyPolyfill();
const logger = createLoggerFromFlags(flags);
const getPackageOpts = {
skipAsk: !!flags.yes || !!flags.y,
cwd: flags.root
};
const dbPackage = await getPackage("@astrojs/db", logger, getPackageOpts, []);
if (!dbPackage) {
logger.error(
"check",
"The `@astrojs/db` package is required for this command to work. Please manually install it in your project and try again."
);
return;
}
const { cli } = dbPackage;
const inlineConfig = flagsToAstroInlineConfig(flags);
const { astroConfig } = await resolveConfig(inlineConfig, "build");
await cli({ flags, config: astroConfig });
}
export {
db
};

6
node_modules/astro/dist/cli/dev/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import { type Flags } from '../flags.js';
interface DevOptions {
flags: Flags;
}
export declare function dev({ flags }: DevOptions): Promise<import("../../core/dev/dev.js").DevServer | undefined>;
export {};

31
node_modules/astro/dist/cli/dev/index.js generated vendored Normal file
View File

@@ -0,0 +1,31 @@
import { cyan } from "kleur/colors";
import devServer from "../../core/dev/index.js";
import { printHelp } from "../../core/messages.js";
import { flagsToAstroInlineConfig } from "../flags.js";
async function dev({ flags }) {
if (flags.help || flags.h) {
printHelp({
commandName: "astro dev",
usage: "[...flags]",
tables: {
Flags: [
["--port", `Specify which port to run on. Defaults to 4321.`],
["--host", `Listen on all addresses, including LAN and public addresses.`],
["--host <custom-address>", `Expose on a network IP address at <custom-address>`],
["--open", "Automatically open the app in the browser on server start"],
["--force", "Clear the content layer cache, forcing a full rebuild."],
["--help (-h)", "See all available flags."]
]
},
description: `Check ${cyan(
"https://docs.astro.build/en/reference/cli-reference/#astro-dev"
)} for more information.`
});
return;
}
const inlineConfig = flagsToAstroInlineConfig(flags);
return await devServer(inlineConfig);
}
export {
dev
};

6
node_modules/astro/dist/cli/docs/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import type { Flags } from '../flags.js';
interface DocsOptions {
flags: Flags;
}
export declare function docs({ flags }: DocsOptions): Promise<import("tinyexec").Output | undefined>;
export {};

18
node_modules/astro/dist/cli/docs/index.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
import { printHelp } from "../../core/messages.js";
import { openInBrowser } from "./open.js";
async function docs({ flags }) {
if (flags.help || flags.h) {
printHelp({
commandName: "astro docs",
tables: {
Flags: [["--help (-h)", "See all available flags."]]
},
description: `Launches the Astro Docs website directly from the terminal.`
});
return;
}
return await openInBrowser("https://docs.astro.build/");
}
export {
docs
};

2
node_modules/astro/dist/cli/docs/open.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
import type { Result } from 'tinyexec';
export declare function openInBrowser(url: string): Promise<Result>;

28
node_modules/astro/dist/cli/docs/open.js generated vendored Normal file
View File

@@ -0,0 +1,28 @@
import { exec } from "../exec.js";
const getPlatformSpecificCommand = () => {
const isGitPod = Boolean(process.env.GITPOD_REPO_ROOT);
const platform = isGitPod ? "gitpod" : process.platform;
switch (platform) {
case "android":
case "linux":
return ["xdg-open"];
case "darwin":
return ["open"];
case "win32":
return ["cmd", ["/c", "start"]];
case "gitpod":
return ["/ide/bin/remote-cli/gitpod-code", ["--openExternal"]];
default:
throw new Error(
`It looks like your platform ("${platform}") isn't supported!
To view Astro's docs, please visit https://docs.astro.build`
);
}
};
async function openInBrowser(url) {
const [command, args = []] = getPlatformSpecificCommand();
return exec(command, [...args, encodeURI(url)]);
}
export {
openInBrowser
};

5
node_modules/astro/dist/cli/exec.d.ts generated vendored Normal file
View File

@@ -0,0 +1,5 @@
import { type Options } from 'tinyexec';
/**
* Improve tinyexec error logging and set `throwOnError` to `true` by default
*/
export declare function exec(command: string, args?: string[], options?: Partial<Options>): PromiseLike<import("tinyexec").Output>;

23
node_modules/astro/dist/cli/exec.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import { NonZeroExitError, x } from "tinyexec";
function exec(command, args, options) {
return x(command, args, {
throwOnError: true,
...options
}).then(
(o) => o,
(e) => {
if (e instanceof NonZeroExitError) {
const fullCommand = args?.length ? `${command} ${args.map((a) => a.includes(" ") ? `"${a}"` : a).join(" ")}` : command;
const message = `The command \`${fullCommand}\` exited with code ${e.exitCode}`;
const newError = new Error(message, e.cause ? { cause: e.cause } : void 0);
newError.stderr = e.output?.stderr;
newError.stdout = e.output?.stdout;
throw newError;
}
throw e;
}
);
}
export {
exec
};

10
node_modules/astro/dist/cli/flags.d.ts generated vendored Normal file
View File

@@ -0,0 +1,10 @@
import type { Arguments } from 'yargs-parser';
import type { AstroInlineConfig } from '../@types/astro.js';
import { Logger } from '../core/logger/core.js';
export type Flags = Arguments;
export declare function flagsToAstroInlineConfig(flags: Flags): AstroInlineConfig;
/**
* The `logging` is usually created from an `AstroInlineConfig`, but some flows like `add`
* doesn't read the AstroConfig directly, so we create a `logging` object from the CLI flags instead.
*/
export declare function createLoggerFromFlags(flags: Flags): Logger;

37
node_modules/astro/dist/cli/flags.js generated vendored Normal file
View File

@@ -0,0 +1,37 @@
import { Logger } from "../core/logger/core.js";
import { nodeLogDestination } from "../core/logger/node.js";
function flagsToAstroInlineConfig(flags) {
return {
// Inline-only configs
configFile: typeof flags.config === "string" ? flags.config : void 0,
mode: typeof flags.mode === "string" ? flags.mode : void 0,
logLevel: flags.verbose ? "debug" : flags.silent ? "silent" : void 0,
force: flags.force ? true : void 0,
// Astro user configs
root: typeof flags.root === "string" ? flags.root : void 0,
site: typeof flags.site === "string" ? flags.site : void 0,
base: typeof flags.base === "string" ? flags.base : void 0,
outDir: typeof flags.outDir === "string" ? flags.outDir : void 0,
server: {
port: typeof flags.port === "number" ? flags.port : void 0,
host: typeof flags.host === "string" || typeof flags.host === "boolean" ? flags.host : void 0,
open: typeof flags.open === "string" || typeof flags.open === "boolean" ? flags.open : void 0
}
};
}
function createLoggerFromFlags(flags) {
const logging = {
dest: nodeLogDestination,
level: "info"
};
if (flags.verbose) {
logging.level = "debug";
} else if (flags.silent) {
logging.level = "silent";
}
return new Logger(logging);
}
export {
createLoggerFromFlags,
flagsToAstroInlineConfig
};

2
node_modules/astro/dist/cli/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
/** The primary CLI action */
export declare function cli(argv: string[]): Promise<void>;

183
node_modules/astro/dist/cli/index.js generated vendored Normal file
View File

@@ -0,0 +1,183 @@
import * as colors from "kleur/colors";
import yargs from "yargs-parser";
import { ASTRO_VERSION } from "../core/constants.js";
async function printAstroHelp() {
const { printHelp } = await import("../core/messages.js");
printHelp({
commandName: "astro",
usage: "[command] [...flags]",
headline: "Build faster websites.",
tables: {
Commands: [
["add", "Add an integration."],
["build", "Build your project and write it to disk."],
["check", "Check your project for errors."],
["create-key", "Create a cryptography key"],
["db", "Manage your Astro database."],
["dev", "Start the development server."],
["docs", "Open documentation in your web browser."],
["info", "List info about your current Astro setup."],
["preview", "Preview your build locally."],
["sync", "Generate content collection types."],
["preferences", "Configure user preferences."],
["telemetry", "Configure telemetry settings."]
],
"Studio Commands": [
["login", "Authenticate your machine with Astro Studio."],
["logout", "End your authenticated session with Astro Studio."],
["link", "Link this project directory to an Astro Studio project."]
],
"Global Flags": [
["--config <path>", "Specify your config file."],
["--root <path>", "Specify your project root folder."],
["--site <url>", "Specify your project site."],
["--base <pathname>", "Specify your project base."],
["--verbose", "Enable verbose logging."],
["--silent", "Disable all logging."],
["--version", "Show the version number and exit."],
["--help", "Show this help message."]
]
}
});
}
function printVersion() {
console.log();
console.log(` ${colors.bgGreen(colors.black(` astro `))} ${colors.green(`v${ASTRO_VERSION}`)}`);
}
function resolveCommand(flags) {
const cmd = flags._[2];
if (flags.version) return "version";
const supportedCommands = /* @__PURE__ */ new Set([
"add",
"sync",
"telemetry",
"preferences",
"dev",
"build",
"preview",
"check",
"create-key",
"docs",
"db",
"info",
"login",
"logout",
"link",
"init"
]);
if (supportedCommands.has(cmd)) {
return cmd;
}
return "help";
}
async function runCommand(cmd, flags) {
switch (cmd) {
case "help":
await printAstroHelp();
return;
case "version":
printVersion();
return;
case "info": {
const { printInfo } = await import("./info/index.js");
await printInfo({ flags });
return;
}
case "create-key": {
const { createKey } = await import("./create-key/index.js");
const exitCode = await createKey({ flags });
return process.exit(exitCode);
}
case "docs": {
const { docs } = await import("./docs/index.js");
await docs({ flags });
return;
}
case "telemetry": {
const { update } = await import("./telemetry/index.js");
const subcommand = flags._[3]?.toString();
await update(subcommand, { flags });
return;
}
case "sync": {
const { sync } = await import("./sync/index.js");
await sync({ flags });
return;
}
case "preferences": {
const { preferences } = await import("./preferences/index.js");
const [subcommand, key, value] = flags._.slice(3).map((v) => v.toString());
const exitCode = await preferences(subcommand, key, value, { flags });
return process.exit(exitCode);
}
}
if (flags.verbose) {
const { enableVerboseLogging } = await import("../core/logger/node.js");
enableVerboseLogging();
}
const { notify } = await import("./telemetry/index.js");
await notify();
switch (cmd) {
case "add": {
const { add } = await import("./add/index.js");
const packages = flags._.slice(3);
await add(packages, { flags });
return;
}
case "db":
case "login":
case "logout":
case "link":
case "init": {
const { db } = await import("./db/index.js");
await db({ flags });
return;
}
case "dev": {
const { dev } = await import("./dev/index.js");
const server = await dev({ flags });
if (server) {
return await new Promise(() => {
});
}
return;
}
case "build": {
const { build } = await import("./build/index.js");
await build({ flags });
return;
}
case "preview": {
const { preview } = await import("./preview/index.js");
const server = await preview({ flags });
if (server) {
return await server.closed();
}
return;
}
case "check": {
const { check } = await import("./check/index.js");
const checkServer = await check(flags);
if (flags.watch) {
return await new Promise(() => {
});
} else {
return process.exit(checkServer ? 1 : 0);
}
}
}
throw new Error(`Error running ${cmd} -- no command found.`);
}
async function cli(argv) {
const flags = yargs(argv, { boolean: ["global"], alias: { g: "global" } });
const cmd = resolveCommand(flags);
try {
await runCommand(cmd, flags);
} catch (err) {
const { throwAndExit } = await import("./throw-and-exit.js");
await throwAndExit(cmd, err);
}
}
export {
cli
};

11
node_modules/astro/dist/cli/info/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,11 @@
import type { AstroConfig, AstroUserConfig } from '../../@types/astro.js';
import { type Flags } from '../flags.js';
interface InfoOptions {
flags: Flags;
}
export declare function getInfoOutput({ userConfig, print, }: {
userConfig: AstroUserConfig | AstroConfig;
print: boolean;
}): Promise<string>;
export declare function printInfo({ flags }: InfoOptions): Promise<void>;
export {};

125
node_modules/astro/dist/cli/info/index.js generated vendored Normal file
View File

@@ -0,0 +1,125 @@
import { execSync } from "node:child_process";
import { arch, platform } from "node:os";
import * as colors from "kleur/colors";
import prompts from "prompts";
import { resolveConfig } from "../../core/config/index.js";
import { ASTRO_VERSION } from "../../core/constants.js";
import { apply as applyPolyfill } from "../../core/polyfill.js";
import { flagsToAstroInlineConfig } from "../flags.js";
async function getInfoOutput({
userConfig,
print
}) {
const rows = [
["Astro", `v${ASTRO_VERSION}`],
["Node", process.version],
["System", getSystem()],
["Package Manager", getPackageManager()]
];
try {
rows.push(["Output", userConfig.output ?? "static"]);
rows.push(["Adapter", userConfig.adapter?.name ?? "none"]);
const integrations = (userConfig?.integrations ?? []).filter(Boolean).flat().map((i) => i?.name).filter(Boolean);
rows.push(["Integrations", integrations.length > 0 ? integrations : "none"]);
} catch {
}
let output = "";
for (const [label, value] of rows) {
output += printRow(label, value, print);
}
return output.trim();
}
async function printInfo({ flags }) {
applyPolyfill();
const { userConfig } = await resolveConfig(flagsToAstroInlineConfig(flags), "info");
const output = await getInfoOutput({ userConfig, print: true });
await copyToClipboard(output);
}
async function copyToClipboard(text) {
text = text.trim();
const system = platform();
let command = "";
if (system === "darwin") {
command = "pbcopy";
} else if (system === "win32") {
command = "clip";
} else {
const unixCommands = [
["xclip", "-sel clipboard -l 1"],
["wl-copy", '"$0"']
];
for (const [unixCommand, args] of unixCommands) {
try {
const output = execSync(`which ${unixCommand}`, { encoding: "utf8", stdio: "pipe" });
if (output[0] !== "/") {
continue;
}
command = `${unixCommand} ${args}`;
} catch {
continue;
}
}
if (!command) return;
}
console.log();
const { shouldCopy } = await prompts({
type: "confirm",
name: "shouldCopy",
message: "Copy to clipboard?",
initial: true
});
if (!shouldCopy) return;
try {
execSync(command.replaceAll("$0", text), {
stdio: "ignore",
input: text,
encoding: "utf8"
});
} catch {
console.error(
colors.red(`
Sorry, something went wrong!`) + ` Please copy the text above manually.`
);
}
}
const PLATFORM_TO_OS = {
darwin: "macOS",
win32: "Windows",
linux: "Linux"
};
function getSystem() {
const system = PLATFORM_TO_OS[platform()] ?? platform();
return `${system} (${arch()})`;
}
function getPackageManager() {
if (!process.env.npm_config_user_agent) {
return "unknown";
}
const specifier = process.env.npm_config_user_agent.split(" ")[0];
const name = specifier.substring(0, specifier.lastIndexOf("/"));
return name === "npminstall" ? "cnpm" : name;
}
const MAX_PADDING = 25;
function printRow(label, value, print) {
const padding = MAX_PADDING - label.length;
const [first, ...rest] = Array.isArray(value) ? value : [value];
let plaintext = `${label}${" ".repeat(padding)}${first}`;
let richtext = `${colors.bold(label)}${" ".repeat(padding)}${colors.green(first)}`;
if (rest.length > 0) {
for (const entry of rest) {
plaintext += `
${" ".repeat(MAX_PADDING)}${entry}`;
richtext += `
${" ".repeat(MAX_PADDING)}${colors.green(entry)}`;
}
}
plaintext += "\n";
if (print) {
console.log(richtext);
}
return plaintext;
}
export {
getInfoOutput,
printInfo
};

16
node_modules/astro/dist/cli/install-package.d.ts generated vendored Normal file
View File

@@ -0,0 +1,16 @@
import type { Logger } from '../core/logger/core.js';
type GetPackageOptions = {
skipAsk?: boolean;
optional?: boolean;
cwd?: string;
};
export declare function getPackage<T>(packageName: string, logger: Logger, options: GetPackageOptions, otherDeps?: string[]): Promise<T | undefined>;
/**
* Get the command to execute and download a package (e.g. `npx`, `yarn dlx`, `pnpm dlx`, etc.)
* @param packageManager - Optional package manager to use. If not provided, Astro will attempt to detect the preferred package manager.
* @returns The command to execute and download a package
*/
export declare function getExecCommand(packageManager?: string): Promise<string>;
export declare function fetchPackageJson(scope: string | undefined, name: string, tag: string): Promise<Record<string, any> | Error>;
export declare function fetchPackageVersions(packageName: string): Promise<string[] | Error>;
export {};

175
node_modules/astro/dist/cli/install-package.js generated vendored Normal file
View File

@@ -0,0 +1,175 @@
import { createRequire } from "node:module";
import boxen from "boxen";
import ci from "ci-info";
import { bold, cyan, dim, magenta } from "kleur/colors";
import ora from "ora";
import preferredPM from "preferred-pm";
import prompts from "prompts";
import whichPm from "which-pm";
import { exec } from "./exec.js";
const require2 = createRequire(import.meta.url);
async function getPackage(packageName, logger, options, otherDeps = []) {
try {
require2.resolve(packageName, { paths: [options.cwd ?? process.cwd()] });
const packageImport = await import(packageName);
return packageImport;
} catch {
if (options.optional) return void 0;
let message = `To continue, Astro requires the following dependency to be installed: ${bold(
packageName
)}.`;
if (ci.isCI) {
message += ` Packages cannot be installed automatically in CI environments.`;
}
logger.info("SKIP_FORMAT", message);
if (ci.isCI) {
return void 0;
}
const result = await installPackage([packageName, ...otherDeps], options, logger);
if (result) {
const packageImport = await import(packageName);
return packageImport;
} else {
return void 0;
}
}
}
function getInstallCommand(packages, packageManager) {
switch (packageManager) {
case "npm":
return { pm: "npm", command: "install", flags: [], dependencies: packages };
case "yarn":
return { pm: "yarn", command: "add", flags: [], dependencies: packages };
case "pnpm":
return { pm: "pnpm", command: "add", flags: [], dependencies: packages };
case "bun":
return { pm: "bun", command: "add", flags: [], dependencies: packages };
default:
return null;
}
}
async function getExecCommand(packageManager) {
if (!packageManager) {
packageManager = (await preferredPM(process.cwd()))?.name ?? "npm";
}
switch (packageManager) {
case "npm":
return "npx";
case "yarn":
return "yarn dlx";
case "pnpm":
return "pnpm dlx";
case "bun":
return "bunx";
default:
return "npx";
}
}
async function installPackage(packageNames, options, logger) {
const cwd = options.cwd ?? process.cwd();
const packageManager = (await whichPm(cwd))?.name ?? "npm";
const installCommand = getInstallCommand(packageNames, packageManager);
if (!installCommand) {
return false;
}
const coloredOutput = `${bold(installCommand.pm)} ${installCommand.command}${[
"",
...installCommand.flags
].join(" ")} ${cyan(installCommand.dependencies.join(" "))}`;
const message = `
${boxen(coloredOutput, {
margin: 0.5,
padding: 0.5,
borderStyle: "round"
})}
`;
logger.info(
"SKIP_FORMAT",
`
${magenta("Astro will run the following command:")}
${dim(
"If you skip this step, you can always run it yourself later"
)}
${message}`
);
let response;
if (options.skipAsk) {
response = true;
} else {
response = (await prompts({
type: "confirm",
name: "askToContinue",
message: "Continue?",
initial: true
})).askToContinue;
}
if (Boolean(response)) {
const spinner = ora("Installing dependencies...").start();
try {
await exec(
installCommand.pm,
[installCommand.command, ...installCommand.flags, ...installCommand.dependencies],
{
nodeOptions: {
cwd,
// reset NODE_ENV to ensure install command run in dev mode
env: { NODE_ENV: void 0 }
}
}
);
spinner.succeed();
return true;
} catch (err) {
logger.debug("add", "Error installing dependencies", err);
spinner.fail();
return false;
}
} else {
return false;
}
}
async function fetchPackageJson(scope, name, tag) {
const packageName = `${scope ? `${scope}/` : ""}${name}`;
const registry = await getRegistry();
const res = await fetch(`${registry}/${packageName}/${tag}`);
if (res.status >= 200 && res.status < 300) {
return await res.json();
} else if (res.status === 404) {
return new Error();
} else {
return new Error(`Failed to fetch ${registry}/${packageName}/${tag} - GET ${res.status}`);
}
}
async function fetchPackageVersions(packageName) {
const registry = await getRegistry();
const res = await fetch(`${registry}/${packageName}`, {
headers: { accept: "application/vnd.npm.install-v1+json" }
});
if (res.status >= 200 && res.status < 300) {
return await res.json().then((data) => Object.keys(data.versions));
} else if (res.status === 404) {
return new Error();
} else {
return new Error(`Failed to fetch ${registry}/${packageName} - GET ${res.status}`);
}
}
let _registry;
async function getRegistry() {
if (_registry) return _registry;
const fallback = "https://registry.npmjs.org";
const packageManager = (await preferredPM(process.cwd()))?.name || "npm";
try {
const { stdout } = await exec(packageManager, ["config", "get", "registry"]);
_registry = stdout.trim()?.replace(/\/$/, "") || fallback;
if (!new URL(_registry).host) _registry = fallback;
} catch {
_registry = fallback;
}
return _registry;
}
export {
fetchPackageJson,
fetchPackageVersions,
getExecCommand,
getPackage
};

8
node_modules/astro/dist/cli/preferences/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,8 @@
import { type Flags } from '../flags.js';
interface PreferencesOptions {
flags: Flags;
}
declare const PREFERENCES_SUBCOMMANDS: readonly ["get", "set", "enable", "disable", "delete", "reset", "list"];
export type Subcommand = (typeof PREFERENCES_SUBCOMMANDS)[number];
export declare function preferences(subcommand: string, key: string, value: string | undefined, { flags }: PreferencesOptions): Promise<number>;
export {};

298
node_modules/astro/dist/cli/preferences/index.js generated vendored Normal file
View File

@@ -0,0 +1,298 @@
import { fileURLToPath } from "node:url";
import { formatWithOptions } from "node:util";
import dlv from "dlv";
import { flattie } from "flattie";
import { bgGreen, black, bold, dim, yellow } from "kleur/colors";
import { resolveConfig } from "../../core/config/config.js";
import { createSettings } from "../../core/config/settings.js";
import { collectErrorMetadata } from "../../core/errors/dev/utils.js";
import * as msg from "../../core/messages.js";
import { apply as applyPolyfill } from "../../core/polyfill.js";
import { DEFAULT_PREFERENCES } from "../../preferences/defaults.js";
import { coerce, isValidKey } from "../../preferences/index.js";
import { createLoggerFromFlags, flagsToAstroInlineConfig } from "../flags.js";
const PREFERENCES_SUBCOMMANDS = [
"get",
"set",
"enable",
"disable",
"delete",
"reset",
"list"
];
function isValidSubcommand(subcommand) {
return PREFERENCES_SUBCOMMANDS.includes(subcommand);
}
async function preferences(subcommand, key, value, { flags }) {
applyPolyfill();
if (!isValidSubcommand(subcommand) || flags?.help || flags?.h) {
msg.printHelp({
commandName: "astro preferences",
usage: "[command]",
tables: {
Commands: [
["list", "Pretty print all current preferences"],
["list --json", "Log all current preferences as a JSON object"],
["get [key]", "Log current preference value"],
["set [key] [value]", "Update preference value"],
["reset [key]", "Reset preference value to default"],
["enable [key]", "Set a boolean preference to true"],
["disable [key]", "Set a boolean preference to false"]
],
Flags: [
[
"--global",
"Scope command to global preferences (all Astro projects) rather than the current project"
]
]
}
});
return 0;
}
const inlineConfig = flagsToAstroInlineConfig(flags);
const logger = createLoggerFromFlags(flags);
const { astroConfig } = await resolveConfig(inlineConfig ?? {}, "dev");
const settings = await createSettings(astroConfig, fileURLToPath(astroConfig.root));
const opts = {
location: flags.global ? "global" : void 0,
json: !!flags.json
};
if (subcommand === "list") {
return listPreferences(settings, opts);
}
if (subcommand === "enable" || subcommand === "disable") {
key = `${key}.enabled`;
}
if (!isValidKey(key)) {
logger.error("preferences", `Unknown preference "${key}"
`);
return 1;
}
if (subcommand === "set" && value === void 0) {
const type = typeof dlv(DEFAULT_PREFERENCES, key);
console.error(
msg.formatErrorMessage(
collectErrorMetadata(new Error(`Please provide a ${type} value for "${key}"`)),
true
)
);
return 1;
}
switch (subcommand) {
case "get":
return getPreference(settings, key, opts);
case "set":
return setPreference(settings, key, value, opts);
case "reset":
case "delete":
return resetPreference(settings, key, opts);
case "enable":
return enablePreference(settings, key, opts);
case "disable":
return disablePreference(settings, key, opts);
}
}
async function getPreference(settings, key, { location = "project" }) {
try {
let value = await settings.preferences.get(key, { location });
if (value && typeof value === "object" && !Array.isArray(value)) {
if (Object.keys(value).length === 0) {
value = dlv(DEFAULT_PREFERENCES, key);
console.log(msg.preferenceDefaultIntro(key));
}
prettyPrint({ [key]: value });
return 0;
}
if (value === void 0) {
const defaultValue = await settings.preferences.get(key);
console.log(msg.preferenceDefault(key, defaultValue));
return 0;
}
console.log(msg.preferenceGet(key, value));
return 0;
} catch {
}
return 1;
}
async function setPreference(settings, key, value, { location }) {
try {
const defaultType = typeof dlv(DEFAULT_PREFERENCES, key);
if (typeof coerce(key, value) !== defaultType) {
throw new Error(`${key} expects a "${defaultType}" value!`);
}
await settings.preferences.set(key, coerce(key, value), { location });
console.log(msg.preferenceSet(key, value));
return 0;
} catch (e) {
if (e instanceof Error) {
console.error(msg.formatErrorMessage(collectErrorMetadata(e), true));
return 1;
}
throw e;
}
}
async function enablePreference(settings, key, { location }) {
try {
await settings.preferences.set(key, true, { location });
console.log(msg.preferenceEnabled(key.replace(".enabled", "")));
return 0;
} catch {
}
return 1;
}
async function disablePreference(settings, key, { location }) {
try {
await settings.preferences.set(key, false, { location });
console.log(msg.preferenceDisabled(key.replace(".enabled", "")));
return 0;
} catch {
}
return 1;
}
async function resetPreference(settings, key, { location }) {
try {
await settings.preferences.set(key, void 0, { location });
console.log(msg.preferenceReset(key));
return 0;
} catch {
}
return 1;
}
function annotate(flat, annotation) {
return Object.fromEntries(
Object.entries(flat).map(([key, value]) => [key, { annotation, value }])
);
}
function userValues(flatDefault, flatProject, flatGlobal) {
const result = {};
for (const key of Object.keys(flatDefault)) {
if (key in flatProject) {
result[key] = {
value: flatProject[key],
annotation: ""
};
if (key in flatGlobal) {
result[key].annotation += ` (also modified globally)`;
}
} else if (key in flatGlobal) {
result[key] = { value: flatGlobal[key], annotation: "(global)" };
}
}
return result;
}
async function listPreferences(settings, { location, json }) {
if (json) {
const resolved = await settings.preferences.getAll();
console.log(JSON.stringify(resolved, null, 2));
return 0;
}
const { global, project, fromAstroConfig, defaults } = await settings.preferences.list({
location
});
const flatProject = flattie(project);
const flatGlobal = flattie(global);
const flatDefault = flattie(defaults);
const flatUser = userValues(flatDefault, flatProject, flatGlobal);
const userKeys = Object.keys(flatUser);
if (userKeys.length > 0) {
const badge = bgGreen(black(` Your Preferences `));
const table = formatTable(flatUser, ["Preference", "Value"]);
console.log(["", badge, table].join("\n"));
} else {
const badge = bgGreen(black(` Your Preferences `));
const message = dim("No preferences set");
console.log(["", badge, "", message].join("\n"));
}
const flatUnset = annotate(Object.assign({}, flatDefault), "");
for (const key of userKeys) {
delete flatUnset[key];
}
const unsetKeys = Object.keys(flatUnset);
if (unsetKeys.length > 0) {
const badge = bgGreen(black(` Default Preferences `));
const table = formatTable(flatUnset, ["Preference", "Value"]);
console.log(["", badge, table].join("\n"));
} else {
const badge = bgGreen(black(` Default Preferences `));
const message = dim("All preferences have been set");
console.log(["", badge, "", message].join("\n"));
}
if (fromAstroConfig.devToolbar?.enabled === false && flatUser["devToolbar.enabled"]?.value !== false) {
console.log(
yellow(
"The dev toolbar is currently disabled. To enable it, set devToolbar: {enabled: true} in your astroConfig file."
)
);
}
return 0;
}
function prettyPrint(value) {
const flattened = flattie(value);
const table = formatTable(flattened, ["Preference", "Value"]);
console.log(table);
}
const chars = {
h: "\u2500",
hThick: "\u2501",
hThickCross: "\u253F",
v: "\u2502",
vRight: "\u251C",
vRightThick: "\u251D",
vLeft: "\u2524",
vLeftThick: "\u2525",
hTop: "\u2534",
hBottom: "\u252C",
topLeft: "\u256D",
topRight: "\u256E",
bottomLeft: "\u2570",
bottomRight: "\u256F"
};
function annotatedFormat(mv) {
return mv.annotation ? `${mv.value} ${mv.annotation}` : mv.value.toString();
}
function formatAnnotated(mv, style = (v) => v.toString()) {
return mv.annotation ? `${style(mv.value)} ${dim(mv.annotation)}` : style(mv.value);
}
function formatTable(object, columnLabels) {
const [colA, colB] = columnLabels;
const colALength = [colA, ...Object.keys(object)].reduce(longest, 0) + 3;
const colBLength = [colB, ...Object.values(object).map(annotatedFormat)].reduce(longest, 0) + 3;
function formatRow(_i, a, b, style = (v) => v.toString()) {
return `${dim(chars.v)} ${style(a)} ${space(colALength - a.length - 2)} ${dim(
chars.v
)} ${formatAnnotated(b, style)} ${space(colBLength - annotatedFormat(b).length - 3)} ${dim(
chars.v
)}`;
}
const top = dim(
`${chars.topLeft}${chars.h.repeat(colALength + 1)}${chars.hBottom}${chars.h.repeat(
colBLength
)}${chars.topRight}`
);
const bottom = dim(
`${chars.bottomLeft}${chars.h.repeat(colALength + 1)}${chars.hTop}${chars.h.repeat(
colBLength
)}${chars.bottomRight}`
);
const divider = dim(
`${chars.vRightThick}${chars.hThick.repeat(colALength + 1)}${chars.hThickCross}${chars.hThick.repeat(colBLength)}${chars.vLeftThick}`
);
const rows = [top, formatRow(-1, colA, { value: colB, annotation: "" }, bold), divider];
let i = 0;
for (const [key, value] of Object.entries(object)) {
rows.push(formatRow(i, key, value, (v) => formatWithOptions({ colors: true }, v)));
i++;
}
rows.push(bottom);
return rows.join("\n");
}
function space(len) {
return " ".repeat(len);
}
const longest = (a, b) => {
const { length: len } = b.toString();
return a > len ? a : len;
};
export {
preferences
};

6
node_modules/astro/dist/cli/preview/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import { type Flags } from '../flags.js';
interface PreviewOptions {
flags: Flags;
}
export declare function preview({ flags }: PreviewOptions): Promise<import("../../@types/astro.js").PreviewServer | undefined>;
export {};

30
node_modules/astro/dist/cli/preview/index.js generated vendored Normal file
View File

@@ -0,0 +1,30 @@
import { cyan } from "kleur/colors";
import { printHelp } from "../../core/messages.js";
import previewServer from "../../core/preview/index.js";
import { flagsToAstroInlineConfig } from "../flags.js";
async function preview({ flags }) {
if (flags?.help || flags?.h) {
printHelp({
commandName: "astro preview",
usage: "[...flags]",
tables: {
Flags: [
["--port", `Specify which port to run on. Defaults to 4321.`],
["--host", `Listen on all addresses, including LAN and public addresses.`],
["--host <custom-address>", `Expose on a network IP address at <custom-address>`],
["--open", "Automatically open the app in the browser on server start"],
["--help (-h)", "See all available flags."]
]
},
description: `Starts a local server to serve your static dist/ directory. Check ${cyan(
"https://docs.astro.build/en/reference/cli-reference/#astro-preview"
)} for more information.`
});
return;
}
const inlineConfig = flagsToAstroInlineConfig(flags);
return await previewServer(inlineConfig);
}
export {
preview
};

6
node_modules/astro/dist/cli/sync/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,6 @@
import { type Flags } from '../flags.js';
interface SyncOptions {
flags: Flags;
}
export declare function sync({ flags }: SyncOptions): Promise<0 | undefined>;
export {};

23
node_modules/astro/dist/cli/sync/index.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import { printHelp } from "../../core/messages.js";
import _sync from "../../core/sync/index.js";
import { flagsToAstroInlineConfig } from "../flags.js";
async function sync({ flags }) {
if (flags?.help || flags?.h) {
printHelp({
commandName: "astro sync",
usage: "[...flags]",
tables: {
Flags: [
["--force", "Clear the content layer cache, forcing a full rebuild."],
["--help (-h)", "See all available flags."]
]
},
description: `Generates TypeScript types for all Astro modules.`
});
return 0;
}
await _sync(flagsToAstroInlineConfig(flags), { telemetry: true });
}
export {
sync
};

7
node_modules/astro/dist/cli/telemetry/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,7 @@
import { type Flags } from '../flags.js';
interface TelemetryOptions {
flags: Flags;
}
export declare function notify(): Promise<void>;
export declare function update(subcommand: string, { flags }: TelemetryOptions): Promise<void>;
export {};

48
node_modules/astro/dist/cli/telemetry/index.js generated vendored Normal file
View File

@@ -0,0 +1,48 @@
import * as msg from "../../core/messages.js";
import { telemetry } from "../../events/index.js";
import { createLoggerFromFlags } from "../flags.js";
async function notify() {
await telemetry.notify(() => {
console.log(msg.telemetryNotice() + "\n");
return true;
});
}
async function update(subcommand, { flags }) {
const isValid = ["enable", "disable", "reset"].includes(subcommand);
const logger = createLoggerFromFlags(flags);
if (flags.help || flags.h || !isValid) {
msg.printHelp({
commandName: "astro telemetry",
usage: "[command]",
tables: {
Commands: [
["enable", "Enable anonymous data collection."],
["disable", "Disable anonymous data collection."],
["reset", "Reset anonymous data collection settings."]
]
}
});
return;
}
switch (subcommand) {
case "enable": {
telemetry.setEnabled(true);
logger.info("SKIP_FORMAT", msg.telemetryEnabled());
return;
}
case "disable": {
telemetry.setEnabled(false);
logger.info("SKIP_FORMAT", msg.telemetryDisabled());
return;
}
case "reset": {
telemetry.clear();
logger.info("SKIP_FORMAT", msg.telemetryReset());
return;
}
}
}
export {
notify,
update
};

2
node_modules/astro/dist/cli/throw-and-exit.d.ts generated vendored Normal file
View File

@@ -0,0 +1,2 @@
/** Display error and exit */
export declare function throwAndExit(cmd: string, err: unknown): Promise<void>;

23
node_modules/astro/dist/cli/throw-and-exit.js generated vendored Normal file
View File

@@ -0,0 +1,23 @@
import { collectErrorMetadata } from "../core/errors/dev/index.js";
import { isAstroConfigZodError } from "../core/errors/errors.js";
import { createSafeError } from "../core/errors/index.js";
import { debug } from "../core/logger/core.js";
import { formatErrorMessage } from "../core/messages.js";
import { eventError, telemetry } from "../events/index.js";
async function throwAndExit(cmd, err) {
if (isAstroConfigZodError(err)) return;
let telemetryPromise;
let errorMessage;
function exitWithErrorMessage() {
console.error(errorMessage);
process.exit(1);
}
const errorWithMetadata = collectErrorMetadata(createSafeError(err));
telemetryPromise = telemetry.record(eventError({ cmd, err: errorWithMetadata, isFatal: true }));
errorMessage = formatErrorMessage(errorWithMetadata, true);
setTimeout(exitWithErrorMessage, 400);
await telemetryPromise.catch((err2) => debug("telemetry", `record() error: ${err2.message}`)).then(exitWithErrorMessage);
}
export {
throwAndExit
};