diff options
Diffstat (limited to 'packages/astro')
83 files changed, 131 insertions, 252 deletions
diff --git a/packages/astro/astro.js b/packages/astro/astro.js index 1fcf633a9..37ea869bc 100755 --- a/packages/astro/astro.js +++ b/packages/astro/astro.js @@ -1,5 +1,4 @@ #!/usr/bin/env node -/* eslint-disable no-console */ 'use strict'; // ISOMORPHIC FILE: NO TOP-LEVEL IMPORT/REQUIRE() ALLOWED diff --git a/packages/astro/e2e/css-sourcemaps.test.js b/packages/astro/e2e/css-sourcemaps.test.js index 919d3c864..50b18834f 100644 --- a/packages/astro/e2e/css-sourcemaps.test.js +++ b/packages/astro/e2e/css-sourcemaps.test.js @@ -1,5 +1,5 @@ import { expect } from '@playwright/test'; -import { getColor, isWindows, testFactory } from './test-utils.js'; +import { isWindows, testFactory } from './test-utils.js'; const test = testFactory({ root: './fixtures/css/', diff --git a/packages/astro/e2e/hydration-race.test.js b/packages/astro/e2e/hydration-race.test.js index ffa78125f..0ee578243 100644 --- a/packages/astro/e2e/hydration-race.test.js +++ b/packages/astro/e2e/hydration-race.test.js @@ -19,8 +19,6 @@ test.describe('Hydration race', () => { test('Islands inside of slots hydrate', async ({ page, astro }) => { await page.goto(astro.resolveUrl('/slot')); - const html = await page.content(); - const one = page.locator('#one'); await expect(one, 'updated text').toHaveText('Hello One in the client'); diff --git a/packages/astro/e2e/test-utils.js b/packages/astro/e2e/test-utils.js index 72c6e8d56..0d0f18eb9 100644 --- a/packages/astro/e2e/test-utils.js +++ b/packages/astro/e2e/test-utils.js @@ -18,8 +18,7 @@ for (let i = 0; i < testFiles.length; i++) { } export function loadFixture(inlineConfig) { - if (!inlineConfig || !inlineConfig.root) - throw new Error("Must provide { root: './fixtures/...' }"); + if (!inlineConfig?.root) throw new Error("Must provide { root: './fixtures/...' }"); // resolve the relative root (i.e. "./fixtures/tailwindcss") to a full filepath // without this, the main `loadFixture` helper will resolve relative to `packages/astro/test` diff --git a/packages/astro/src/assets/image-endpoint.ts b/packages/astro/src/assets/image-endpoint.ts index e3553edbc..49fce8f05 100644 --- a/packages/astro/src/assets/image-endpoint.ts +++ b/packages/astro/src/assets/image-endpoint.ts @@ -35,7 +35,7 @@ export const get: APIRoute = async ({ request }) => { const url = new URL(request.url); const transform = await imageService.parseURL(url, imageServiceConfig); - if (!transform || !transform.src) { + if (!transform?.src) { throw new Error('Incorrect transform returned by `parseURL`'); } diff --git a/packages/astro/src/assets/services/squoosh.ts b/packages/astro/src/assets/services/squoosh.ts index 089fcbc81..45933d600 100644 --- a/packages/astro/src/assets/services/squoosh.ts +++ b/packages/astro/src/assets/services/squoosh.ts @@ -36,7 +36,7 @@ const service: LocalImageService = { async transform(inputBuffer, transformOptions) { const transform: BaseServiceTransform = transformOptions as BaseServiceTransform; - let format = transform.format!; + let format = transform.format; const operations: Operation[] = []; diff --git a/packages/astro/src/assets/services/vendor/squoosh/codecs.ts b/packages/astro/src/assets/services/vendor/squoosh/codecs.ts index d4065cee4..55b56d596 100644 --- a/packages/astro/src/assets/services/vendor/squoosh/codecs.ts +++ b/packages/astro/src/assets/services/vendor/squoosh/codecs.ts @@ -291,7 +291,6 @@ export const codecs = { avif: { name: 'AVIF', extension: 'avif', - // eslint-disable-next-line no-control-regex detectors: [/^\x00\x00\x00 ftypavif\x00\x00\x00\x00/], dec: () => instantiateEmscriptenWasm(avifDec as DecodeModuleFactory, avifDecWasm), @@ -322,7 +321,6 @@ export const codecs = { oxipng: { name: 'OxiPNG', extension: 'png', - // eslint-disable-next-line no-control-regex detectors: [/^\x89PNG\x0D\x0A\x1A\x0A/], dec: async () => { await pngEncDecInit() diff --git a/packages/astro/src/assets/services/vendor/squoosh/image.ts b/packages/astro/src/assets/services/vendor/squoosh/image.ts index 4a05d212c..694f994d2 100644 --- a/packages/astro/src/assets/services/vendor/squoosh/image.ts +++ b/packages/astro/src/assets/services/vendor/squoosh/image.ts @@ -29,14 +29,14 @@ export async function processBuffer( switch (encoding) { case 'avif': - return await impl.encodeAvif(imageData, { quality }) as Uint8Array; + return await impl.encodeAvif(imageData, { quality }); case 'jpeg': case 'jpg': - return await impl.encodeJpeg(imageData, { quality }) as Uint8Array; + return await impl.encodeJpeg(imageData, { quality }); case 'png': - return await impl.encodePng(imageData) as Uint8Array; + return await impl.encodePng(imageData); case 'webp': - return await impl.encodeWebp(imageData, { quality }) as Uint8Array; + return await impl.encodeWebp(imageData, { quality }); default: throw Error(`Unsupported encoding format`) } diff --git a/packages/astro/src/assets/vendor/image-size/types/jp2.ts b/packages/astro/src/assets/vendor/image-size/types/jp2.ts index e23e1aced..127a96d60 100644 --- a/packages/astro/src/assets/vendor/image-size/types/jp2.ts +++ b/packages/astro/src/assets/vendor/image-size/types/jp2.ts @@ -49,7 +49,6 @@ export const JP2: IImage = { switch (nextBoxType) { case BoxTypes.rreq: // WHAT ARE THESE 4 BYTES????? - // eslint-disable-next-line no-case-declarations const MAGIC = 4 offset = offset + 4 + MAGIC + calculateRREQLength(buffer.slice(offset + 4)) return parseIHDR(buffer.slice(offset + 8, offset + 24)) diff --git a/packages/astro/src/assets/vendor/image-size/types/pnm.ts b/packages/astro/src/assets/vendor/image-size/types/pnm.ts index 687c6265e..fa30a53d5 100644 --- a/packages/astro/src/assets/vendor/image-size/types/pnm.ts +++ b/packages/astro/src/assets/vendor/image-size/types/pnm.ts @@ -19,7 +19,7 @@ const handlers: { [type: string]: Handler} = { let dimensions: string[] = [] while (lines.length > 0) { - const line = lines.shift() as string + const line = lines.shift()! if (line[0] === '#') { continue } @@ -39,7 +39,7 @@ const handlers: { [type: string]: Handler} = { pam: (lines) => { const size: { [key: string]: number } = {} while (lines.length > 0) { - const line = lines.shift() as string + const line = lines.shift()! if (line.length > 16 || line.charCodeAt(0) > 128) { continue } diff --git a/packages/astro/src/assets/vendor/image-size/types/svg.ts b/packages/astro/src/assets/vendor/image-size/types/svg.ts index 7cb164679..945be962d 100644 --- a/packages/astro/src/assets/vendor/image-size/types/svg.ts +++ b/packages/astro/src/assets/vendor/image-size/types/svg.ts @@ -41,8 +41,8 @@ function parseLength(len: string) { function parseViewbox(viewbox: string): IAttributes { const bounds = viewbox.split(' ') return { - height: parseLength(bounds[3]) as number, - width: parseLength(bounds[2]) as number + height: parseLength(bounds[3])!, + width: parseLength(bounds[2])! } } @@ -51,21 +51,21 @@ function parseAttributes(root: string): IAttributes { const height = root.match(extractorRegExps.height) const viewbox = root.match(extractorRegExps.viewbox) return { - height: height && parseLength(height[2]) as number, - viewbox: viewbox && parseViewbox(viewbox[2]) as IAttributes, - width: width && parseLength(width[2]) as number, + height: height && parseLength(height[2])!, + viewbox: viewbox && parseViewbox(viewbox[2])!, + width: width && parseLength(width[2])!, } } function calculateByDimensions(attrs: IAttributes): ISize { return { - height: attrs.height as number, - width: attrs.width as number, + height: attrs.height!, + width: attrs.width!, } } function calculateByViewbox(attrs: IAttributes, viewbox: IAttributes): ISize { - const ratio = (viewbox.width as number) / (viewbox.height as number) + const ratio = (viewbox.width!) / (viewbox.height!) if (attrs.width) { return { height: Math.floor(attrs.width / ratio), @@ -79,8 +79,8 @@ function calculateByViewbox(attrs: IAttributes, viewbox: IAttributes): ISize { } } return { - height: viewbox.height as number, - width: viewbox.width as number, + height: viewbox.height!, + width: viewbox.width!, } } diff --git a/packages/astro/src/assets/vendor/image-size/types/tiff.ts b/packages/astro/src/assets/vendor/image-size/types/tiff.ts index 1be697d29..dcbc9cf55 100644 --- a/packages/astro/src/assets/vendor/image-size/types/tiff.ts +++ b/packages/astro/src/assets/vendor/image-size/types/tiff.ts @@ -44,7 +44,7 @@ function extractTags(buffer: Buffer, isBigEndian: boolean) { const tags: {[key: number]: number} = {} let temp: Buffer | undefined = buffer - while (temp && temp.length) { + while (temp?.length) { const code = readUInt(temp, 16, 0, isBigEndian) const type = readUInt(temp, 16, 2, isBigEndian) const length = readUInt(temp, 32, 4, isBigEndian) diff --git a/packages/astro/src/cli/check/index.ts b/packages/astro/src/cli/check/index.ts index 07648aabe..cf0105461 100644 --- a/packages/astro/src/cli/check/index.ts +++ b/packages/astro/src/cli/check/index.ts @@ -1,4 +1,3 @@ -/* eslint-disable no-console */ import { AstroCheck, DiagnosticSeverity, diff --git a/packages/astro/src/content/error-map.ts b/packages/astro/src/content/error-map.ts index 9fbfaf343..706de3882 100644 --- a/packages/astro/src/content/error-map.ts +++ b/packages/astro/src/content/error-map.ts @@ -14,7 +14,7 @@ export const errorMap: ZodErrorMap = (baseError, ctx) => { // raise a single error when `key` does not match: // > Did not match union. // > key: Expected `'tutorial' | 'blog'`, received 'foo' - let typeOrLiteralErrByPath: Map<string, TypeOrLiteralErrByPathEntry> = new Map(); + let typeOrLiteralErrByPath = new Map<string, TypeOrLiteralErrByPathEntry>(); for (const unionError of baseError.unionErrors.map((e) => e.errors).flat()) { if (unionError.code === 'invalid_type' || unionError.code === 'invalid_literal') { const flattenedErrorPath = flattenErrorPath(unionError.path); diff --git a/packages/astro/src/content/utils.ts b/packages/astro/src/content/utils.ts index 631f30e1f..d273dc105 100644 --- a/packages/astro/src/content/utils.ts +++ b/packages/astro/src/content/utils.ts @@ -177,7 +177,7 @@ export function getDataEntryExts(settings: Pick<AstroSettings, 'dataEntryTypes'> export function getEntryConfigByExtMap<TEntryType extends ContentEntryType | DataEntryType>( entryTypes: TEntryType[] ): Map<string, TEntryType> { - const map: Map<string, TEntryType> = new Map(); + const map = new Map<string, TEntryType>(); for (const entryType of entryTypes) { for (const ext of entryType.extensions) { map.set(ext, entryType); @@ -310,7 +310,7 @@ function getYAMLErrorLine(rawData: string | undefined, objectKey: string) { return numNewlinesBeforeKey; } -export function parseFrontmatter(fileContents: string, filePath: string) { +export function parseFrontmatter(fileContents: string) { try { // `matter` is empty string on cache results // clear cache to prevent this diff --git a/packages/astro/src/core/app/index.ts b/packages/astro/src/core/app/index.ts index 69f8f73c4..c69267b92 100644 --- a/packages/astro/src/core/app/index.ts +++ b/packages/astro/src/core/app/index.ts @@ -203,7 +203,7 @@ export class App { ): Promise<Response> { const url = new URL(request.url); const pathname = prependForwardSlash(this.removeBase(url.pathname)); - const info = this.#routeDataToRouteInfo.get(routeData!)!; + const info = this.#routeDataToRouteInfo.get(routeData)!; const isCompressHTML = this.#manifest.compressHTML ?? false; // may be used in the future for handling rel=modulepreload, rel=icon, rel=manifest etc. const links = new Set<never>(); diff --git a/packages/astro/src/core/app/node.ts b/packages/astro/src/core/app/node.ts index 40b7b4e7c..3e6207309 100644 --- a/packages/astro/src/core/app/node.ts +++ b/packages/astro/src/core/app/node.ts @@ -34,7 +34,7 @@ class NodeIncomingMessage extends IncomingMessage { /** * The read-only body property of the Request interface contains a ReadableStream with the body contents that have been added to the request. */ - body?: any | undefined; + body?: unknown; } export class NodeApp extends App { diff --git a/packages/astro/src/core/build/generate.ts b/packages/astro/src/core/build/generate.ts index 1ab28ecc0..72339a680 100644 --- a/packages/astro/src/core/build/generate.ts +++ b/packages/astro/src/core/build/generate.ts @@ -121,7 +121,7 @@ export function chunkIsPage( if (output.type !== 'chunk') { return false; } - const chunk = output as OutputChunk; + const chunk = output; if (chunk.facadeModuleId) { const facadeToEntryId = prependForwardSlash( rootRelativeFacadeId(chunk.facadeModuleId, settings) @@ -470,15 +470,7 @@ async function generatePath( onRequest?: MiddlewareHandler<unknown> ) { const { settings, logging, origin, routeCache } = opts; - const { - mod, - internals, - linkIds, - scripts: hoistedScripts, - styles: _styles, - pageData, - renderers, - } = gopts; + const { mod, internals, scripts: hoistedScripts, styles: _styles, pageData, renderers } = gopts; // This adds the page name to the array so it can be shown as part of stats. if (pageData.route.type === 'page') { diff --git a/packages/astro/src/core/build/plugins/index.ts b/packages/astro/src/core/build/plugins/index.ts index 4563bb696..160e18fdd 100644 --- a/packages/astro/src/core/build/plugins/index.ts +++ b/packages/astro/src/core/build/plugins/index.ts @@ -18,11 +18,11 @@ export function registerAllPlugins({ internals, options, register }: AstroBuildP register(pluginAliasResolve(internals)); register(pluginAnalyzer(internals)); register(pluginInternals(internals)); - register(pluginRenderers(options, internals)); - register(pluginMiddleware(options, internals)); + register(pluginRenderers(options)); + register(pluginMiddleware(options)); register(pluginPages(options, internals)); register(pluginCSS(options, internals)); - register(astroHeadBuildPlugin(options, internals)); + register(astroHeadBuildPlugin(internals)); register(pluginPrerender(options, internals)); register(astroConfigBuildPlugin(options, internals)); register(pluginHoistedScripts(options, internals)); diff --git a/packages/astro/src/core/build/plugins/plugin-analyzer.ts b/packages/astro/src/core/build/plugins/plugin-analyzer.ts index e90063f28..b650e04f1 100644 --- a/packages/astro/src/core/build/plugins/plugin-analyzer.ts +++ b/packages/astro/src/core/build/plugins/plugin-analyzer.ts @@ -126,7 +126,7 @@ export function vitePluginAnalyzer(internals: BuildInternals): VitePlugin { for (const id of ids) { const info = this.getModuleInfo(id); - if (!info || !info.meta?.astro) continue; + if (!info?.meta?.astro) continue; const astro = info.meta.astro as AstroPluginMetadata['astro']; diff --git a/packages/astro/src/core/build/plugins/plugin-component-entry.ts b/packages/astro/src/core/build/plugins/plugin-component-entry.ts index 444aa6a19..01e480e2f 100644 --- a/packages/astro/src/core/build/plugins/plugin-component-entry.ts +++ b/packages/astro/src/core/build/plugins/plugin-component-entry.ts @@ -10,7 +10,7 @@ export const astroEntryPrefix = '\0astro-entry:'; * entries to re-export only the names the user is using. */ export function vitePluginComponentEntry(internals: BuildInternals): VitePlugin { - const componentToExportNames: Map<string, string[]> = new Map(); + const componentToExportNames = new Map<string, string[]>(); mergeComponentExportNames(internals.discoveredHydratedComponents); mergeComponentExportNames(internals.discoveredClientOnlyComponents); diff --git a/packages/astro/src/core/build/plugins/plugin-css.ts b/packages/astro/src/core/build/plugins/plugin-css.ts index 1d2aa58ea..8971cf553 100644 --- a/packages/astro/src/core/build/plugins/plugin-css.ts +++ b/packages/astro/src/core/build/plugins/plugin-css.ts @@ -107,7 +107,7 @@ function rollupPluginAstroBuildCSS(options: PluginOptions): VitePlugin[] { }, async generateBundle(_outputOptions, bundle) { - for (const [_, chunk] of Object.entries(bundle)) { + for (const [, chunk] of Object.entries(bundle)) { if (chunk.type !== 'chunk') continue; if ('viteMetadata' in chunk === false) continue; const meta = chunk.viteMetadata as ViteMetadata; diff --git a/packages/astro/src/core/build/plugins/plugin-middleware.ts b/packages/astro/src/core/build/plugins/plugin-middleware.ts index 7e3ea8cb9..dee73d2f8 100644 --- a/packages/astro/src/core/build/plugins/plugin-middleware.ts +++ b/packages/astro/src/core/build/plugins/plugin-middleware.ts @@ -1,7 +1,6 @@ import type { Plugin as VitePlugin } from 'vite'; import { MIDDLEWARE_PATH_SEGMENT_NAME } from '../../constants.js'; import { addRollupInput } from '../add-rollup-input.js'; -import type { BuildInternals } from '../internal.js'; import type { AstroBuildPlugin } from '../plugin'; import type { StaticBuildOptions } from '../types'; @@ -9,10 +8,7 @@ export const MIDDLEWARE_MODULE_ID = '@astro-middleware'; const EMPTY_MIDDLEWARE = '\0empty-middleware'; -export function vitePluginMiddleware( - opts: StaticBuildOptions, - _internals: BuildInternals -): VitePlugin { +export function vitePluginMiddleware(opts: StaticBuildOptions): VitePlugin { return { name: '@astro/plugin-middleware', @@ -44,16 +40,13 @@ export function vitePluginMiddleware( }; } -export function pluginMiddleware( - opts: StaticBuildOptions, - internals: BuildInternals -): AstroBuildPlugin { +export function pluginMiddleware(opts: StaticBuildOptions): AstroBuildPlugin { return { build: 'ssr', hooks: { 'build:before': () => { return { - vitePlugin: vitePluginMiddleware(opts, internals), + vitePlugin: vitePluginMiddleware(opts), }; }, }, diff --git a/packages/astro/src/core/build/plugins/plugin-pages.ts b/packages/astro/src/core/build/plugins/plugin-pages.ts index c40449a39..cf078f0b5 100644 --- a/packages/astro/src/core/build/plugins/plugin-pages.ts +++ b/packages/astro/src/core/build/plugins/plugin-pages.ts @@ -39,7 +39,7 @@ function vitePluginPages(opts: StaticBuildOptions, internals: BuildInternals): V options(options) { if (opts.settings.config.output === 'static') { - const inputs: Set<string> = new Set(); + const inputs = new Set<string>(); for (const [path, pageData] of Object.entries(opts.allPages)) { if (routeIsRedirect(pageData.route)) { diff --git a/packages/astro/src/core/build/plugins/plugin-renderers.ts b/packages/astro/src/core/build/plugins/plugin-renderers.ts index d18eb5a02..912df4241 100644 --- a/packages/astro/src/core/build/plugins/plugin-renderers.ts +++ b/packages/astro/src/core/build/plugins/plugin-renderers.ts @@ -1,17 +1,12 @@ import type { Plugin as VitePlugin } from 'vite'; import { addRollupInput } from '../add-rollup-input.js'; -import type { BuildInternals } from '../internal.js'; import type { AstroBuildPlugin } from '../plugin'; import type { StaticBuildOptions } from '../types'; export const RENDERERS_MODULE_ID = '@astro-renderers'; export const RESOLVED_RENDERERS_MODULE_ID = `\0${RENDERERS_MODULE_ID}`; -let inputs: Set<string> = new Set(); -export function vitePluginRenderers( - opts: StaticBuildOptions, - _internals: BuildInternals -): VitePlugin { +export function vitePluginRenderers(opts: StaticBuildOptions): VitePlugin { return { name: '@astro/plugin-renderers', @@ -49,16 +44,13 @@ export function vitePluginRenderers( }; } -export function pluginRenderers( - opts: StaticBuildOptions, - internals: BuildInternals -): AstroBuildPlugin { +export function pluginRenderers(opts: StaticBuildOptions): AstroBuildPlugin { return { build: 'ssr', hooks: { 'build:before': () => { return { - vitePlugin: vitePluginRenderers(opts, internals), + vitePlugin: vitePluginRenderers(opts), }; }, }, diff --git a/packages/astro/src/core/build/plugins/plugin-ssr.ts b/packages/astro/src/core/build/plugins/plugin-ssr.ts index 254037e59..41f38a8b2 100644 --- a/packages/astro/src/core/build/plugins/plugin-ssr.ts +++ b/packages/astro/src/core/build/plugins/plugin-ssr.ts @@ -42,10 +42,7 @@ function vitePluginSSR( }, async load(id) { if (id === RESOLVED_SSR_VIRTUAL_MODULE_ID) { - const { - settings: { config }, - allPages, - } = options; + const { allPages } = options; const imports: string[] = []; const contents: string[] = []; const exports: string[] = []; @@ -82,7 +79,7 @@ function vitePluginSSR( }, async generateBundle(_opts, bundle) { // Add assets from this SSR chunk as well. - for (const [_chunkName, chunk] of Object.entries(bundle)) { + for (const [, chunk] of Object.entries(bundle)) { if (chunk.type === 'asset') { internals.staticFiles.add(chunk.fileName); } @@ -162,7 +159,7 @@ function vitePluginSSRSplit( enforce: 'post', options(opts) { if (options.settings.config.build.split) { - const inputs: Set<string> = new Set(); + const inputs = new Set<string>(); for (const path of Object.keys(options.allPages)) { inputs.add(getVirtualModulePageNameFromPath(SPLIT_MODULE_ID, path)); @@ -178,10 +175,6 @@ function vitePluginSSRSplit( }, async load(id) { if (id.startsWith(RESOLVED_SPLIT_MODULE_ID)) { - const { - settings: { config }, - allPages, - } = options; const imports: string[] = []; const contents: string[] = []; const exports: string[] = []; @@ -204,7 +197,7 @@ function vitePluginSSRSplit( }, async generateBundle(_opts, bundle) { // Add assets from this SSR chunk as well. - for (const [_chunkName, chunk] of Object.entries(bundle)) { + for (const [, chunk] of Object.entries(bundle)) { if (chunk.type === 'asset') { internals.staticFiles.add(chunk.fileName); } @@ -268,7 +261,7 @@ export function pluginSSRSplit( logging: options.logging, entryPoints: internals.entryPoints, }); - for (const [moduleName, chunk] of internals.ssrSplitEntryChunks) { + for (const [, chunk] of internals.ssrSplitEntryChunks) { const code = injectManifest(manifest, chunk); mutate(chunk, 'server', code); } @@ -413,8 +406,8 @@ function buildManifest( if (!route.prerender) continue; if (!route.pathname) continue; - const outFolder = getOutFolder(opts.settings.config, route.pathname!, route.type); - const outFile = getOutFile(opts.settings.config, outFolder, route.pathname!, route.type); + const outFolder = getOutFolder(opts.settings.config, route.pathname, route.type); + const outFile = getOutFile(opts.settings.config, outFolder, route.pathname, route.type); const file = outFile.toString().replace(opts.settings.config.build.client.toString(), ''); routes.push({ file, diff --git a/packages/astro/src/core/compile/compile.ts b/packages/astro/src/core/compile/compile.ts index e78a761a4..425677123 100644 --- a/packages/astro/src/core/compile/compile.ts +++ b/packages/astro/src/core/compile/compile.ts @@ -78,6 +78,8 @@ export async function compile({ } function handleCompileResultErrors(result: TransformResult, cssTransformErrors: AstroError[]) { + // TODO: Export the DiagnosticSeverity enum from @astrojs/compiler? + // eslint-disable-next-line @typescript-eslint/no-unsafe-enum-comparison const compilerError = result.diagnostics.find((diag) => diag.severity === 1); if (compilerError) { @@ -96,7 +98,6 @@ function handleCompileResultErrors(result: TransformResult, cssTransformErrors: case 0: break; case 1: { - const error = cssTransformErrors[0]; throw cssTransformErrors[0]; } default: { diff --git a/packages/astro/src/core/config/schema.ts b/packages/astro/src/core/config/schema.ts index 99ef653d0..7410df470 100644 --- a/packages/astro/src/core/config/schema.ts +++ b/packages/astro/src/core/config/schema.ts @@ -8,7 +8,7 @@ import { BUNDLED_THEMES } from 'shiki'; import { z } from 'zod'; import { appendForwardSlash, prependForwardSlash, trimSlashes } from '../path.js'; -const ASTRO_CONFIG_DEFAULTS: AstroUserConfig & any = { +const ASTRO_CONFIG_DEFAULTS = { root: '.', srcDir: './src', publicDir: './public', @@ -30,7 +30,6 @@ const ASTRO_CONFIG_DEFAULTS: AstroUserConfig & any = { server: { host: false, port: 3000, - streaming: true, open: false, }, integrations: [], @@ -45,7 +44,7 @@ const ASTRO_CONFIG_DEFAULTS: AstroUserConfig & any = { assets: false, redirects: false, }, -}; +} satisfies AstroUserConfig & { server: { open: boolean } }; export const AstroConfigSchema = z.object({ root: z @@ -172,8 +171,8 @@ export const AstroConfigSchema = z.object({ theme: z .enum(BUNDLED_THEMES as [Theme, ...Theme[]]) .or(z.custom<IThemeRegistration>()) - .default(ASTRO_CONFIG_DEFAULTS.markdown.shikiConfig.theme), - wrap: z.boolean().or(z.null()).default(ASTRO_CONFIG_DEFAULTS.markdown.shikiConfig.wrap), + .default(ASTRO_CONFIG_DEFAULTS.markdown.shikiConfig.theme!), + wrap: z.boolean().or(z.null()).default(ASTRO_CONFIG_DEFAULTS.markdown.shikiConfig.wrap!), }) .default({}), remarkPlugins: z diff --git a/packages/astro/src/core/config/timer.ts b/packages/astro/src/core/config/timer.ts index 7360b5510..82860e0a7 100644 --- a/packages/astro/src/core/config/timer.ts +++ b/packages/astro/src/core/config/timer.ts @@ -18,7 +18,7 @@ interface OngoingStat { */ export class AstroTimer { private enabled: boolean; - private ongoingTimers: Map<string, OngoingStat> = new Map(); + private ongoingTimers = new Map<string, OngoingStat>(); private stats: Record<string, Stat> = {}; constructor() { diff --git a/packages/astro/src/core/cookies/cookies.ts b/packages/astro/src/core/cookies/cookies.ts index e997c772e..013357f32 100644 --- a/packages/astro/src/core/cookies/cookies.ts +++ b/packages/astro/src/core/cookies/cookies.ts @@ -99,7 +99,7 @@ class AstroCookies implements AstroCookiesInterface { */ get(key: string): AstroCookie { // Check for outgoing Set-Cookie values first - if (this.#outgoing !== null && this.#outgoing.has(key)) { + if (this.#outgoing?.has(key)) { let [serializedValue, , isSetValue] = this.#outgoing.get(key)!; if (isSetValue) { return new AstroCookie(serializedValue); @@ -120,7 +120,7 @@ class AstroCookies implements AstroCookiesInterface { * @returns */ has(key: string): boolean { - if (this.#outgoing !== null && this.#outgoing.has(key)) { + if (this.#outgoing?.has(key)) { let [, , isSetValue] = this.#outgoing.get(key)!; return isSetValue; } diff --git a/packages/astro/src/core/create-vite.ts b/packages/astro/src/core/create-vite.ts index 89dec9d4b..60c847045 100644 --- a/packages/astro/src/core/create-vite.ts +++ b/packages/astro/src/core/create-vite.ts @@ -121,10 +121,10 @@ export async function createVite( markdownVitePlugin({ settings, logging }), htmlVitePlugin(), jsxVitePlugin({ settings, logging }), - astroPostprocessVitePlugin({ settings }), + astroPostprocessVitePlugin(), mode === 'dev' && astroIntegrationsContainerPlugin({ settings, logging }), astroScriptsPageSSRPlugin({ settings }), - astroHeadPlugin({ settings }), + astroHeadPlugin(), astroScannerPlugin({ settings }), astroInjectEnvTsPlugin({ settings, logging, fs }), astroContentVirtualModPlugin({ settings }), @@ -315,12 +315,3 @@ function isCommonNotAstro(dep: string): boolean { ) ); } - -interface PkgJSON { - name: string; - dependencies?: Record<string, string>; - devDependencies?: Record<string, string>; - peerDependencies?: Record<string, string>; - keywords?: string[]; - [key: string]: any; -} diff --git a/packages/astro/src/core/dev/restart.ts b/packages/astro/src/core/dev/restart.ts index 9c71b7aa3..6e4c0b16f 100644 --- a/packages/astro/src/core/dev/restart.ts +++ b/packages/astro/src/core/dev/restart.ts @@ -125,7 +125,7 @@ interface Restart { export async function createContainerWithAutomaticRestart({ flags, - handleConfigError = (_e: Error) => {}, + handleConfigError = () => {}, beforeRestart, params, }: CreateContainerWithAutomaticRestart): Promise<Restart> { @@ -143,7 +143,6 @@ export async function createContainerWithAutomaticRestart({ }; async function handleServerRestart(logMsg: string) { - // eslint-disable-next-line @typescript-eslint/no-shadow const container = restart.container; const { container: newContainer, error } = await restartContainer({ beforeRestart, diff --git a/packages/astro/src/core/errors/dev/utils.ts b/packages/astro/src/core/errors/dev/utils.ts index 29468c7fd..69026b6cd 100644 --- a/packages/astro/src/core/errors/dev/utils.ts +++ b/packages/astro/src/core/errors/dev/utils.ts @@ -20,11 +20,9 @@ type EsbuildMessage = ESBuildTransformResult['warnings'][number]; */ export function collectErrorMetadata(e: any, rootFolder?: URL | undefined): ErrorWithMetadata { const err = - AggregateError.is(e) || Array.isArray((e as any).errors) - ? (e.errors as SSRError[]) - : [e as SSRError]; + AggregateError.is(e) || Array.isArray(e.errors) ? (e.errors as SSRError[]) : [e as SSRError]; - err.forEach((error, idx) => { + err.forEach((error) => { if (e.stack) { const stackInfo = collectInfoFromStacktrace(e); error.stack = stackInfo.stack; @@ -73,7 +71,7 @@ export function collectErrorMetadata(e: any, rootFolder?: URL | undefined): Erro // If we received an array of errors and it's not from us, it's most likely from ESBuild, try to extract info for Vite to display // NOTE: We still need to be defensive here, because it might not necessarily be from ESBuild, it's just fairly likely. - if (!AggregateError.is(e) && Array.isArray((e as any).errors)) { + if (!AggregateError.is(e) && Array.isArray(e.errors)) { (e.errors as EsbuildMessage[]).forEach((buildError, i) => { const { location, pluginName, text } = buildError; @@ -226,7 +224,7 @@ export function renderErrorMarkdown(markdown: string, target: 'html' | 'cli') { } else { return markdown .replace(linkRegex, (fullMatch, m1, m2) => `${bold(m1)} ${underline(m2)}`) - .replace(urlRegex, (fullMatch, m1) => ` ${underline(fullMatch.trim())} `) + .replace(urlRegex, (fullMatch) => ` ${underline(fullMatch.trim())} `) .replace(boldRegex, (fullMatch, m1) => `${bold(m1)}`); } } diff --git a/packages/astro/src/core/errors/errors.ts b/packages/astro/src/core/errors/errors.ts index cda4f328a..a73728124 100644 --- a/packages/astro/src/core/errors/errors.ts +++ b/packages/astro/src/core/errors/errors.ts @@ -81,7 +81,7 @@ export class AstroError extends Error { this.frame = codeFrame(source, location); } - static is(err: Error | unknown): err is AstroError { + static is(err: unknown): err is AstroError { return (err as AstroError).type === 'AstroError'; } } @@ -95,7 +95,7 @@ export class CompilerError extends AstroError { this.name = 'CompilerError'; } - static is(err: Error | unknown): err is CompilerError { + static is(err: unknown): err is CompilerError { return (err as CompilerError).type === 'CompilerError'; } } @@ -103,7 +103,7 @@ export class CompilerError extends AstroError { export class CSSError extends AstroError { type: ErrorTypes = 'CSSError'; - static is(err: Error | unknown): err is CSSError { + static is(err: unknown): err is CSSError { return (err as CSSError).type === 'CSSError'; } } @@ -111,7 +111,7 @@ export class CSSError extends AstroError { export class MarkdownError extends AstroError { type: ErrorTypes = 'MarkdownError'; - static is(err: Error | unknown): err is MarkdownError { + static is(err: unknown): err is MarkdownError { return (err as MarkdownError).type === 'MarkdownError'; } } @@ -119,7 +119,7 @@ export class MarkdownError extends AstroError { export class InternalError extends AstroError { type: ErrorTypes = 'InternalError'; - static is(err: Error | unknown): err is InternalError { + static is(err: unknown): err is InternalError { return (err as InternalError).type === 'InternalError'; } } @@ -136,7 +136,7 @@ export class AggregateError extends AstroError { this.errors = props.errors; } - static is(err: Error | unknown): err is AggregateError { + static is(err: unknown): err is AggregateError { return (err as AggregateError).type === 'AggregateError'; } } diff --git a/packages/astro/src/core/errors/overlay.ts b/packages/astro/src/core/errors/overlay.ts index 8f7e464f8..5a24f898a 100644 --- a/packages/astro/src/core/errors/overlay.ts +++ b/packages/astro/src/core/errors/overlay.ts @@ -1,4 +1,3 @@ -import type { AstroConfig } from '../../@types/astro'; import type { AstroErrorPayload } from './dev/vite'; const style = /* css */ ` @@ -665,7 +664,7 @@ class ErrorOverlay extends HTMLElement { const errorLine = this.root.querySelector<HTMLSpanElement>('.error-line'); if (errorLine) { - if (errorLine.parentElement && errorLine.parentElement.parentElement) { + if (errorLine.parentElement?.parentElement) { errorLine.parentElement.parentElement.scrollTop = errorLine.offsetTop - errorLine.parentElement.parentElement.offsetTop - 8; } @@ -745,6 +744,6 @@ function getOverlayCode() { `; } -export function patchOverlay(code: string, config: AstroConfig) { +export function patchOverlay(code: string) { return code.replace('class ErrorOverlay', getOverlayCode() + '\nclass ViteErrorOverlay'); } diff --git a/packages/astro/src/core/errors/utils.ts b/packages/astro/src/core/errors/utils.ts index 99cdde028..ea238d441 100644 --- a/packages/astro/src/core/errors/utils.ts +++ b/packages/astro/src/core/errors/utils.ts @@ -89,7 +89,7 @@ export function formatYAMLException(e: YAMLException): ViteErrorPayload['err'] { /** Coalesce any throw variable to an Error instance. */ export function createSafeError(err: any): Error { - if (err instanceof Error || (err && err.name && err.message)) { + if (err instanceof Error || (err?.name && err.message)) { return err; } else { const error = new Error(JSON.stringify(err)); diff --git a/packages/astro/src/core/middleware/callMiddleware.ts b/packages/astro/src/core/middleware/callMiddleware.ts index f202a401a..afa0156c9 100644 --- a/packages/astro/src/core/middleware/callMiddleware.ts +++ b/packages/astro/src/core/middleware/callMiddleware.ts @@ -49,11 +49,6 @@ export async function callMiddleware<R>( apiContext: APIContext, responseFunction: () => Promise<R> ): Promise<Response | R> { - let resolveResolve: any; - new Promise((resolve) => { - resolveResolve = resolve; - }); - let nextCalled = false; let responseFunctionPromise: Promise<R> | undefined = undefined; const next: MiddlewareNext<R> = async () => { diff --git a/packages/astro/src/core/render/dev/index.ts b/packages/astro/src/core/render/dev/index.ts index 43c0d450f..3fd0203fc 100644 --- a/packages/astro/src/core/render/dev/index.ts +++ b/packages/astro/src/core/render/dev/index.ts @@ -174,7 +174,7 @@ export async function renderPage(options: SSROptions): Promise<Response> { adapterName: options.env.adapterName, }); if (options.middleware) { - if (options.middleware && options.middleware.onRequest) { + if (options.middleware?.onRequest) { const onRequest = options.middleware.onRequest as MiddlewareResponseHandler; const response = await callMiddleware<Response>(env.logging, onRequest, apiContext, () => { return coreRenderPage({ diff --git a/packages/astro/src/core/routing/manifest/create.ts b/packages/astro/src/core/routing/manifest/create.ts index b5a683164..7695ccaec 100644 --- a/packages/astro/src/core/routing/manifest/create.ts +++ b/packages/astro/src/core/routing/manifest/create.ts @@ -33,8 +33,8 @@ interface Item { function countOccurrences(needle: string, haystack: string) { let count = 0; - for (let i = 0; i < haystack.length; i += 1) { - if (haystack[i] === needle) count += 1; + for (const hay of haystack) { + if (hay === needle) count += 1; } return count; } @@ -61,10 +61,6 @@ function getParts(part: string, file: string) { return result; } -function areSamePart(a: RoutePart, b: RoutePart) { - return a.content === b.content && a.dynamic === b.dynamic && a.spread === b.spread; -} - function getPattern( segments: RoutePart[][], base: string, @@ -208,25 +204,6 @@ function injectedRouteToItem( }; } -// Seeings if the two routes are siblings of each other, with `b` being the route -// in focus. If it is in the same parent folder as `a`, they are siblings. -function areSiblings(a: RouteData, b: RouteData) { - if (a.segments.length < b.segments.length) return false; - for (let i = 0; i < b.segments.length - 1; i++) { - let segment = b.segments[i]; - if (segment.length === a.segments[i].length) { - for (let j = 0; j < segment.length; j++) { - if (!areSamePart(segment[j], a.segments[i][j])) { - return false; - } - } - } else { - return false; - } - } - return true; -} - export interface CreateRouteManifestParams { /** Astro Settings object */ settings: AstroSettings; @@ -243,16 +220,16 @@ export function createRouteManifest( ): ManifestData { const components: string[] = []; const routes: RouteData[] = []; - const validPageExtensions: Set<string> = new Set([ + const validPageExtensions = new Set<string>([ '.astro', ...SUPPORTED_MARKDOWN_FILE_EXTENSIONS, ...settings.pageExtensions, ]); - const validEndpointExtensions: Set<string> = new Set(['.js', '.ts']); + const validEndpointExtensions = new Set<string>(['.js', '.ts']); const localFs = fsMod ?? nodeFs; const prerender = getPrerenderDefault(settings.config); - const foundInvalidFileExtensions: Set<string> = new Set(); + const foundInvalidFileExtensions = new Set<string>(); function walk( fs: typeof nodeFs, diff --git a/packages/astro/src/events/error.ts b/packages/astro/src/events/error.ts index 73ac2b5e4..cc7279f3d 100644 --- a/packages/astro/src/events/error.ts +++ b/packages/astro/src/events/error.ts @@ -29,7 +29,7 @@ interface ConfigErrorEventPayload extends ErrorEventPayload { const ANONYMIZE_MESSAGE_REGEX = /^(\w| )+/; function anonymizeErrorMessage(msg: string): string | undefined { const matchedMessage = msg.match(ANONYMIZE_MESSAGE_REGEX); - if (!matchedMessage || !matchedMessage[0]) { + if (!matchedMessage?.[0]) { return undefined; } return matchedMessage[0].trim().substring(0, 20); @@ -72,6 +72,8 @@ export function eventError({ cliCommand: cmd, isFatal: isFatal, anonymousMessageHint: + // https://github.com/typescript-eslint/typescript-eslint/issues/4820 + // eslint-disable-next-line @typescript-eslint/prefer-optional-chain -- errorData may be false errorData && errorData.message ? getSafeErrorMessage(errorData.message) : anonymizeErrorMessage(err.message), diff --git a/packages/astro/src/runtime/client/visible.ts b/packages/astro/src/runtime/client/visible.ts index e42b04339..cc4f77771 100644 --- a/packages/astro/src/runtime/client/visible.ts +++ b/packages/astro/src/runtime/client/visible.ts @@ -21,8 +21,7 @@ const visibleDirective: ClientDirective = (load, _options, el) => { } }); - for (let i = 0; i < el.children.length; i++) { - const child = el.children[i]; + for (const child of el.children) { io.observe(child); } }; diff --git a/packages/astro/src/runtime/server/astro-global.ts b/packages/astro/src/runtime/server/astro-global.ts index da1f0e784..82855c669 100644 --- a/packages/astro/src/runtime/server/astro-global.ts +++ b/packages/astro/src/runtime/server/astro-global.ts @@ -4,7 +4,7 @@ import { AstroError, AstroErrorData } from '../../core/errors/index.js'; /** Create the Astro.glob() runtime function. */ function createAstroGlobFn() { - const globHandler = (importMetaGlobResult: Record<string, any>, globValue: () => any) => { + const globHandler = (importMetaGlobResult: Record<string, any>) => { if (typeof importMetaGlobResult === 'string') { throw new AstroError({ ...AstroErrorData.AstroGlobUsedOutside, diff --git a/packages/astro/src/runtime/server/astro-island.ts b/packages/astro/src/runtime/server/astro-island.ts index 3f93cd817..5887f3149 100644 --- a/packages/astro/src/runtime/server/astro-island.ts +++ b/packages/astro/src/runtime/server/astro-island.ts @@ -118,13 +118,13 @@ declare const Astro: { const templates = this.querySelectorAll('template[data-astro-template]'); for (const template of templates) { const closest = template.closest(this.tagName); - if (!closest || !closest.isSameNode(this)) continue; + if (!closest?.isSameNode(this)) continue; slots[template.getAttribute('data-astro-template') || 'default'] = template.innerHTML; template.remove(); } for (const slot of slotted) { const closest = slot.closest(this.tagName); - if (!closest || !closest.isSameNode(this)) continue; + if (!closest?.isSameNode(this)) continue; slots[slot.getAttribute('name') || 'default'] = slot.innerHTML; } const props = this.hasAttribute('props') diff --git a/packages/astro/src/runtime/server/endpoint.ts b/packages/astro/src/runtime/server/endpoint.ts index 8adc10c72..c56ab7646 100644 --- a/packages/astro/src/runtime/server/endpoint.ts +++ b/packages/astro/src/runtime/server/endpoint.ts @@ -19,7 +19,7 @@ function getHandlerFromModule(mod: EndpointHandler, method: string) { /** Renders an endpoint request to completion, returning the body. */ export async function renderEndpoint(mod: EndpointHandler, context: APIContext, ssr: boolean) { - const { request, params, locals } = context; + const { request, params } = context; const chosenMethod = request.method?.toLowerCase(); const handler = getHandlerFromModule(mod, chosenMethod); if (!ssr && ssr === false && chosenMethod && chosenMethod !== 'get') { diff --git a/packages/astro/src/runtime/server/jsx.ts b/packages/astro/src/runtime/server/jsx.ts index c8da19eaf..6bea1bc71 100644 --- a/packages/astro/src/runtime/server/jsx.ts +++ b/packages/astro/src/runtime/server/jsx.ts @@ -85,10 +85,7 @@ Did you forget to import the component or is it possible there is a typo?`); let props: Record<string, any> = {}; let slots: Record<string, any> = {}; for (const [key, value] of Object.entries(vnode.props ?? {})) { - if ( - key === 'children' || - (value && typeof value === 'object' && (value as any)['$$slot']) - ) { + if (key === 'children' || (value && typeof value === 'object' && value['$$slot'])) { slots[key === 'children' ? 'default' : key] = () => renderJSX(result, value); } else { props[key] = value; @@ -117,7 +114,7 @@ Did you forget to import the component or is it possible there is a typo?`); try { const output = await vnode.type(vnode.props ?? {}); let renderResult: any; - if (output && output[AstroJSX]) { + if (output?.[AstroJSX]) { renderResult = await renderJSXVNode(result, output, skip); return renderResult; } else if (!output) { @@ -251,11 +248,9 @@ function useConsoleFilter() { consoleFilterRefs++; if (!originalConsoleError) { - // eslint-disable-next-line no-console originalConsoleError = console.error; try { - // eslint-disable-next-line no-console console.error = filteredConsoleError; } catch (error) { // If we're unable to hook `console.error`, just accept it diff --git a/packages/astro/src/runtime/server/render/head.ts b/packages/astro/src/runtime/server/render/head.ts index 52923c790..8ac9df0e0 100644 --- a/packages/astro/src/runtime/server/render/head.ts +++ b/packages/astro/src/runtime/server/render/head.ts @@ -25,7 +25,7 @@ export function renderAllHeadContent(result: SSRResult) { result.styles.clear(); const scripts = Array.from(result.scripts) .filter(uniqueElements) - .map((script, i) => { + .map((script) => { return renderElement('script', script, false); }); const links = Array.from(result.links) diff --git a/packages/astro/src/runtime/server/render/slot.ts b/packages/astro/src/runtime/server/render/slot.ts index 09a8ff39c..152230ba9 100644 --- a/packages/astro/src/runtime/server/render/slot.ts +++ b/packages/astro/src/runtime/server/render/slot.ts @@ -51,7 +51,7 @@ export async function renderSlotToString( let instructions: null | RenderInstruction[] = null; let iterator = renderSlot(result, slotted, fallback); for await (const chunk of iterator) { - if (typeof (chunk as any).type === 'string') { + if (typeof chunk.type === 'string') { if (instructions === null) { instructions = []; } diff --git a/packages/astro/src/vite-plugin-astro-postprocess/index.ts b/packages/astro/src/vite-plugin-astro-postprocess/index.ts index 96735f2cb..be8ddb7b0 100644 --- a/packages/astro/src/vite-plugin-astro-postprocess/index.ts +++ b/packages/astro/src/vite-plugin-astro-postprocess/index.ts @@ -2,17 +2,12 @@ import { parse } from 'acorn'; import { walk } from 'estree-walker'; import MagicString from 'magic-string'; import type { Plugin } from 'vite'; -import type { AstroSettings } from '../@types/astro'; import { isMarkdownFile } from '../core/util.js'; // Check for `Astro.glob()`. Be very forgiving of whitespace. False positives are okay. const ASTRO_GLOB_REGEX = /Astro2?\s*\.\s*glob\s*\(/; -interface AstroPluginOptions { - settings: AstroSettings; -} - -export default function astro(_opts: AstroPluginOptions): Plugin { +export default function astro(): Plugin { return { name: 'astro:postprocess', async transform(code, id) { diff --git a/packages/astro/src/vite-plugin-astro-server/plugin.ts b/packages/astro/src/vite-plugin-astro-server/plugin.ts index 29f83c85c..72d6deb95 100644 --- a/packages/astro/src/vite-plugin-astro-server/plugin.ts +++ b/packages/astro/src/vite-plugin-astro-server/plugin.ts @@ -31,7 +31,7 @@ export default function createVitePluginAstroServer({ const serverController = createController({ loader }); /** rebuild the route cache + manifest, as needed. */ - function rebuildManifest(needsManifestRebuild: boolean, _file: string) { + function rebuildManifest(needsManifestRebuild: boolean) { env.routeCache.clearAll(); if (needsManifestRebuild) { manifest = createRouteManifest({ settings }, logging); @@ -66,7 +66,7 @@ export default function createVitePluginAstroServer({ if (!id.includes('vite/dist/client/client.mjs')) return; // Replace the Vite overlay with ours - return patchOverlay(code, settings.config); + return patchOverlay(code); }, }; } diff --git a/packages/astro/src/vite-plugin-astro-server/request.ts b/packages/astro/src/vite-plugin-astro-server/request.ts index 197033b04..21599064c 100644 --- a/packages/astro/src/vite-plugin-astro-server/request.ts +++ b/packages/astro/src/vite-plugin-astro-server/request.ts @@ -84,7 +84,7 @@ export async function handleRequest( // This could be a runtime error from Vite's SSR module, so try to fix it here try { - env.loader.fixStacktrace(err as Error); + env.loader.fixStacktrace(err); } catch {} // This is our last line of defense regarding errors where we still might have some information about the request diff --git a/packages/astro/src/vite-plugin-astro-server/route.ts b/packages/astro/src/vite-plugin-astro-server/route.ts index ffa6e1da6..aa3342a6c 100644 --- a/packages/astro/src/vite-plugin-astro-server/route.ts +++ b/packages/astro/src/vite-plugin-astro-server/route.ts @@ -137,7 +137,7 @@ export async function handleRoute( const { config } = settings; const filePath: URL | undefined = matchedRoute.filePath; - const { route, preloadedComponent, mod } = matchedRoute; + const { route, preloadedComponent } = matchedRoute; const buildingToSSR = isServerLikeOutput(config); // Headers are only available when using SSR. diff --git a/packages/astro/src/vite-plugin-astro/compile.ts b/packages/astro/src/vite-plugin-astro/compile.ts index 6bee4f672..001367615 100644 --- a/packages/astro/src/vite-plugin-astro/compile.ts +++ b/packages/astro/src/vite-plugin-astro/compile.ts @@ -93,8 +93,6 @@ async function enhanceCompileError({ err, id, source, - config, - logging, }: EnhanceCompilerErrorOptions): Promise<void> { const lineText = (err as any).loc?.lineText; // Verify frontmatter: a common reason that this plugin fails is that @@ -122,7 +120,7 @@ async function enhanceCompileError({ } catch (frontmatterErr: any) { // Improve the error by replacing the phrase "unexpected end of file" // with "unexpected end of frontmatter" in the esbuild error message. - if (frontmatterErr && frontmatterErr.message) { + if (frontmatterErr?.message) { frontmatterErr.message = frontmatterErr.message.replace( 'end of file', 'end of frontmatter' diff --git a/packages/astro/src/vite-plugin-astro/hmr.ts b/packages/astro/src/vite-plugin-astro/hmr.ts index 8c94cb646..f123dba3a 100644 --- a/packages/astro/src/vite-plugin-astro/hmr.ts +++ b/packages/astro/src/vite-plugin-astro/hmr.ts @@ -15,7 +15,7 @@ import { isAstroScript } from './query.js'; const PKG_PREFIX = fileURLToPath(new URL('../../', import.meta.url)); const E2E_PREFIX = fileURLToPath(new URL('../../e2e', import.meta.url)); const isPkgFile = (id: string | null) => { - return id && id.startsWith(PKG_PREFIX) && !id.startsWith(E2E_PREFIX); + return id?.startsWith(PKG_PREFIX) && !id.startsWith(E2E_PREFIX); }; export interface HandleHotUpdateOptions { diff --git a/packages/astro/src/vite-plugin-astro/index.ts b/packages/astro/src/vite-plugin-astro/index.ts index 70c4da611..c5523d712 100644 --- a/packages/astro/src/vite-plugin-astro/index.ts +++ b/packages/astro/src/vite-plugin-astro/index.ts @@ -88,7 +88,7 @@ export default function astro({ settings, logging }: AstroPluginOptions): vite.P } if (hoistedScript.type === 'external') { - const src = hoistedScript.src!; + const src = hoistedScript.src; if (src.startsWith('/') && !isBrowserPath(src)) { const publicDir = config.publicDir.pathname.replace(/\/$/, '').split('/').pop() + '/'; throw new Error( diff --git a/packages/astro/src/vite-plugin-head/index.ts b/packages/astro/src/vite-plugin-head/index.ts index 4f44aaf6e..9cfdc739f 100644 --- a/packages/astro/src/vite-plugin-head/index.ts +++ b/packages/astro/src/vite-plugin-head/index.ts @@ -1,8 +1,7 @@ import type { ModuleInfo } from 'rollup'; import type * as vite from 'vite'; -import type { AstroSettings, SSRComponentMetadata, SSRResult } from '../@types/astro'; +import type { SSRComponentMetadata, SSRResult } from '../@types/astro'; import type { AstroBuildPlugin } from '../core/build/plugin.js'; -import type { StaticBuildOptions } from '../core/build/types'; import type { PluginMetadata } from '../vite-plugin-astro/types'; import { getTopLevelPages, walkParentInfos } from '../core/build/graph.js'; @@ -12,11 +11,7 @@ import { getAstroMetadata } from '../vite-plugin-astro/index.js'; // Detect this in comments, both in .astro components and in js/ts files. const injectExp = /(^\/\/|\/\/!)\s*astro-head-inject/; -export default function configHeadVitePlugin({ - settings, -}: { - settings: AstroSettings; -}): vite.Plugin { +export default function configHeadVitePlugin(): vite.Plugin { let server: vite.ViteDevServer; function propagateMetadata< @@ -70,10 +65,7 @@ export default function configHeadVitePlugin({ }; } -export function astroHeadBuildPlugin( - options: StaticBuildOptions, - internals: BuildInternals -): AstroBuildPlugin { +export function astroHeadBuildPlugin(internals: BuildInternals): AstroBuildPlugin { return { build: 'ssr', hooks: { diff --git a/packages/astro/src/vite-plugin-html/transform/escape.ts b/packages/astro/src/vite-plugin-html/transform/escape.ts index 5f2ecf6d6..1c250d43d 100644 --- a/packages/astro/src/vite-plugin-html/transform/escape.ts +++ b/packages/astro/src/vite-plugin-html/transform/escape.ts @@ -6,8 +6,8 @@ import { visit } from 'unist-util-visit'; import { escape, needsEscape, replaceAttribute } from './utils.js'; const rehypeEscape: Plugin<[{ s: MagicString }], Root> = ({ s }) => { - return (tree, file) => { - visit(tree, (node: Root | RootContent, index, parent) => { + return (tree) => { + visit(tree, (node: Root | RootContent) => { if (node.type === 'text' || node.type === 'comment') { if (needsEscape(node.value)) { s.overwrite(node.position!.start.offset!, node.position!.end.offset!, escape(node.value)); diff --git a/packages/astro/src/vite-plugin-html/transform/slots.ts b/packages/astro/src/vite-plugin-html/transform/slots.ts index e89cad42c..a549a48c9 100644 --- a/packages/astro/src/vite-plugin-html/transform/slots.ts +++ b/packages/astro/src/vite-plugin-html/transform/slots.ts @@ -7,7 +7,7 @@ import { escape } from './utils.js'; const rehypeSlots: Plugin<[{ s: MagicString }], Root> = ({ s }) => { return (tree, file) => { - visit(tree, (node: Root | RootContent, index, parent) => { + visit(tree, (node: Root | RootContent) => { if (node.type === 'element' && node.tagName === 'slot') { if (typeof node.properties?.['is:inline'] !== 'undefined') return; const name = node.properties?.['name'] ?? 'default'; diff --git a/packages/astro/src/vite-plugin-jsx/import-source.ts b/packages/astro/src/vite-plugin-jsx/import-source.ts index 35efcaeda..c1f9ea6dc 100644 --- a/packages/astro/src/vite-plugin-jsx/import-source.ts +++ b/packages/astro/src/vite-plugin-jsx/import-source.ts @@ -51,7 +51,7 @@ function detectImportSourceFromComments(code: string): string | undefined { // if no imports were found, look for @jsxImportSource comment const multiline = code.match(/\/\*\*?[\S\s]*\*\//gm) || []; for (const comment of multiline) { - const [_, lib] = comment.slice(0, -2).match(/@jsxImportSource\s*(\S+)/) || []; + const [, lib] = comment.slice(0, -2).match(/@jsxImportSource\s*(\S+)/) || []; if (lib) { return lib.trim(); } diff --git a/packages/astro/src/vite-plugin-jsx/tag.ts b/packages/astro/src/vite-plugin-jsx/tag.ts index eab920f63..5efc4c41f 100644 --- a/packages/astro/src/vite-plugin-jsx/tag.ts +++ b/packages/astro/src/vite-plugin-jsx/tag.ts @@ -11,7 +11,6 @@ import * as t from '@babel/types'; */ export default async function tagExportsWithRenderer({ rendererName, - root, }: { rendererName: string; root: URL; diff --git a/packages/astro/src/vite-plugin-markdown/content-entry-type.ts b/packages/astro/src/vite-plugin-markdown/content-entry-type.ts index 92bb118d4..dc3296974 100644 --- a/packages/astro/src/vite-plugin-markdown/content-entry-type.ts +++ b/packages/astro/src/vite-plugin-markdown/content-entry-type.ts @@ -1,11 +1,10 @@ -import { fileURLToPath } from 'node:url'; import type { ContentEntryType } from '../@types/astro.js'; import { parseFrontmatter } from '../content/utils.js'; export const markdownContentEntryType: ContentEntryType = { extensions: ['.md'], - async getEntryInfo({ fileUrl, contents }: { fileUrl: URL; contents: string }) { - const parsed = parseFrontmatter(contents, fileURLToPath(fileUrl)); + async getEntryInfo({ contents }: { contents: string }) { + const parsed = parseFrontmatter(contents); return { data: parsed.data, body: parsed.content, diff --git a/packages/astro/src/vite-plugin-scanner/scan.ts b/packages/astro/src/vite-plugin-scanner/scan.ts index 7723c3fd6..83ca3c5c5 100644 --- a/packages/astro/src/vite-plugin-scanner/scan.ts +++ b/packages/astro/src/vite-plugin-scanner/scan.ts @@ -41,7 +41,7 @@ export async function scan(code: string, id: string, isHybridOutput = false): Pr didInit = true; } - const [_, exports] = eslexer.parse(code, id); + const [, exports] = eslexer.parse(code, id); let pageOptions: PageOptions = {}; for (const _export of exports) { const { n: name, le: endOfLocalName } = _export; diff --git a/packages/astro/src/vite-plugin-scripts/index.ts b/packages/astro/src/vite-plugin-scripts/index.ts index 18f90b057..d49d0e22f 100644 --- a/packages/astro/src/vite-plugin-scripts/index.ts +++ b/packages/astro/src/vite-plugin-scripts/index.ts @@ -48,7 +48,7 @@ export default function astroScriptsPlugin({ settings }: { settings: AstroSettin } return null; }, - buildStart(options) { + buildStart() { const hasHydrationScripts = settings.scripts.some((s) => s.stage === 'before-hydration'); if (hasHydrationScripts && env?.command === 'build' && !env?.ssrBuild) { this.emitFile({ diff --git a/packages/astro/src/vite-plugin-ssr-manifest/index.ts b/packages/astro/src/vite-plugin-ssr-manifest/index.ts index 4ced3d032..05e1f54be 100644 --- a/packages/astro/src/vite-plugin-ssr-manifest/index.ts +++ b/packages/astro/src/vite-plugin-ssr-manifest/index.ts @@ -7,7 +7,7 @@ export function vitePluginSSRManifest(): VitePlugin { return { name: '@astrojs/vite-plugin-astro-ssr-manifest', enforce: 'post', - resolveId(id, parent) { + resolveId(id) { if (id === manifestVirtualModuleId) { return resolvedManifestVirtualModuleId; } diff --git a/packages/astro/test/astro-dynamic.test.js b/packages/astro/test/astro-dynamic.test.js index 5ed34b8ba..5d91815ba 100644 --- a/packages/astro/test/astro-dynamic.test.js +++ b/packages/astro/test/astro-dynamic.test.js @@ -20,7 +20,6 @@ describe('Dynamic components', () => { }); it('Loads pages using client:media hydrator', async () => { - const root = new URL('http://example.com/media/index.html'); const html = await fixture.readFile('/media/index.html'); const $ = cheerio.load(html); diff --git a/packages/astro/test/astro-pagination.test.js b/packages/astro/test/astro-pagination.test.js index 994f8e0ac..5fb3a8dbd 100644 --- a/packages/astro/test/astro-pagination.test.js +++ b/packages/astro/test/astro-pagination.test.js @@ -41,7 +41,7 @@ describe('Pagination', () => { { color: 'blue', p: '2' }, ]; await Promise.all( - params.map(async ({ color, p }, idx) => { + params.map(async ({ color, p }) => { const html = await fixture.readFile(`/posts/${color}/${p}/index.html`); const $ = cheerio.load(html); expect($('#page-param').text()).to.equal(p); diff --git a/packages/astro/test/astro-response.test.js b/packages/astro/test/astro-response.test.js index 050feaabb..c77e7bad3 100644 --- a/packages/astro/test/astro-response.test.js +++ b/packages/astro/test/astro-response.test.js @@ -1,5 +1,4 @@ import { expect } from 'chai'; -import { load as cheerioLoad } from 'cheerio'; import { loadFixture } from './test-utils.js'; // Asset bundling diff --git a/packages/astro/test/component-library.test.js b/packages/astro/test/component-library.test.js index bab16230b..58c7fb6b8 100644 --- a/packages/astro/test/component-library.test.js +++ b/packages/astro/test/component-library.test.js @@ -21,7 +21,7 @@ describe('Component Libraries', () => { await fixture.build(); }); - function createFindEvidence(expected, prefix) { + function createFindEvidence(expected) { return async function findEvidence(pathname) { const html = await fixture.readFile(pathname); const $ = cheerioLoad(html); @@ -102,7 +102,7 @@ describe('Component Libraries', () => { await devServer.stop(); }); - function createFindEvidence(expected, prefix) { + function createFindEvidence(expected) { return async function findEvidence(pathname) { const html = await fixture.fetch(pathname).then((res) => res.text()); const $ = cheerioLoad(html); diff --git a/packages/astro/test/config-mode.test.js b/packages/astro/test/config-mode.test.js index 76c45ba48..84dafb81f 100644 --- a/packages/astro/test/config-mode.test.js +++ b/packages/astro/test/config-mode.test.js @@ -1,5 +1,4 @@ import { expect } from 'chai'; -import { load as cheerioLoad } from 'cheerio'; import { loadFixture } from './test-utils.js'; import testAdapter from './test-adapter.js'; diff --git a/packages/astro/test/error-bad-js.test.js b/packages/astro/test/error-bad-js.test.js index 9149d8ad5..ba02c62ff 100644 --- a/packages/astro/test/error-bad-js.test.js +++ b/packages/astro/test/error-bad-js.test.js @@ -1,5 +1,4 @@ import { expect } from 'chai'; -import * as cheerio from 'cheerio'; import { loadFixture, silentLogging } from './test-utils.js'; describe('Errors in JavaScript', () => { diff --git a/packages/astro/test/postcss.test.js b/packages/astro/test/postcss.test.js index b2d663533..126fca95c 100644 --- a/packages/astro/test/postcss.test.js +++ b/packages/astro/test/postcss.test.js @@ -4,8 +4,6 @@ import eol from 'eol'; import { loadFixture } from './test-utils.js'; describe('PostCSS', function () { - const PREFIXED_CSS = `{-webkit-appearance:none;appearance:none`; - let fixture; let bundledCSS; before(async () => { diff --git a/packages/astro/test/public-base-404.test.js b/packages/astro/test/public-base-404.test.js index bf98967cb..c8d58471d 100644 --- a/packages/astro/test/public-base-404.test.js +++ b/packages/astro/test/public-base-404.test.js @@ -5,8 +5,6 @@ import { loadFixture } from './test-utils.js'; describe('Public dev with base', () => { /** @type {import('./test-utils').Fixture} */ let fixture; - /** @type {import('./test-utils').DevServer} */ - let devServer; let $; before(async () => { @@ -15,7 +13,7 @@ describe('Public dev with base', () => { site: 'http://example.com/', base: '/blog', }); - devServer = await fixture.startDevServer(); + await fixture.startDevServer(); }); it('200 when loading /@vite/client', async () => { diff --git a/packages/astro/test/static-build-page-url-format.test.js b/packages/astro/test/static-build-page-url-format.test.js index 6d08e85e6..2f8660b63 100644 --- a/packages/astro/test/static-build-page-url-format.test.js +++ b/packages/astro/test/static-build-page-url-format.test.js @@ -1,11 +1,6 @@ import { expect } from 'chai'; -import * as cheerio from 'cheerio'; import { loadFixture } from './test-utils.js'; -function addLeadingSlash(path) { - return path.startsWith('/') ? path : '/' + path; -} - describe("Static build - format: 'file'", () => { let fixture; diff --git a/packages/astro/test/static-build.test.js b/packages/astro/test/static-build.test.js index db35ef991..d4a687a5d 100644 --- a/packages/astro/test/static-build.test.js +++ b/packages/astro/test/static-build.test.js @@ -88,7 +88,7 @@ describe('Static build', () => { } }); - function createFindEvidence(expected, prefix) { + function createFindEvidence(expected) { return async function findEvidence(pathname) { const html = await fixture.readFile(pathname); const $ = cheerioLoad(html); diff --git a/packages/astro/test/test-utils.js b/packages/astro/test/test-utils.js index 953ebf6da..1fa04d47a 100644 --- a/packages/astro/test/test-utils.js +++ b/packages/astro/test/test-utils.js @@ -101,8 +101,7 @@ export const silentLogging = { * .clean() - Async. Removes the project’s dist folder. */ export async function loadFixture(inlineConfig) { - if (!inlineConfig || !inlineConfig.root) - throw new Error("Must provide { root: './fixtures/...' }"); + if (!inlineConfig?.root) throw new Error("Must provide { root: './fixtures/...' }"); // load config let cwd = inlineConfig.root; @@ -235,7 +234,7 @@ export async function loadFixture(inlineConfig) { }, loadTestAdapterApp: async (streaming) => { const url = new URL(`./server/entry.mjs?id=${fixtureId}`, config.outDir); - const { createApp, manifest, middleware } = await import(url); + const { createApp, manifest } = await import(url); const app = createApp(streaming); app.manifest = manifest; return app; diff --git a/packages/astro/test/units/compile/invalid-css.test.js b/packages/astro/test/units/compile/invalid-css.test.js index 6be17620a..52da94816 100644 --- a/packages/astro/test/units/compile/invalid-css.test.js +++ b/packages/astro/test/units/compile/invalid-css.test.js @@ -9,7 +9,7 @@ describe('astro/src/core/compile', () => { it('throws an aggregate error with the errors', async () => { let error; try { - let r = await cachedCompilation({ + await cachedCompilation({ astroConfig: { root: pathToFileURL('/'), }, diff --git a/packages/astro/test/units/config/format.test.js b/packages/astro/test/units/config/format.test.js index 175ea9f04..602c19cc3 100644 --- a/packages/astro/test/units/config/format.test.js +++ b/packages/astro/test/units/config/format.test.js @@ -1,6 +1,4 @@ import { expect } from 'chai'; -import * as cheerio from 'cheerio'; -import { fileURLToPath } from 'url'; import { runInContainer } from '../../../dist/core/dev/index.js'; import { openConfig, createSettings } from '../../../dist/core/config/index.js'; diff --git a/packages/astro/test/units/dev/hydration.test.js b/packages/astro/test/units/dev/hydration.test.js index 0fb10ffda..0a176b4db 100644 --- a/packages/astro/test/units/dev/hydration.test.js +++ b/packages/astro/test/units/dev/hydration.test.js @@ -48,7 +48,7 @@ describe('dev container', () => { url: '/', }); container.handle(req, res); - const html = await done; + await done; expect(res.statusCode).to.equal( 200, "We get a 200 because the error occurs in the template, but we didn't crash!" diff --git a/packages/astro/test/units/dev/styles.test.js b/packages/astro/test/units/dev/styles.test.js index 76af929be..45bb6e172 100644 --- a/packages/astro/test/units/dev/styles.test.js +++ b/packages/astro/test/units/dev/styles.test.js @@ -1,5 +1,4 @@ import { expect } from 'chai'; -import { fileURLToPath } from 'url'; import { getStylesForURL } from '../../../dist/core/render/dev/css.js'; import { viteID } from '../../../dist/core/util.js'; diff --git a/packages/astro/test/units/render/head.test.js b/packages/astro/test/units/render/head.test.js index 83fbc8b11..480651fd1 100644 --- a/packages/astro/test/units/render/head.test.js +++ b/packages/astro/test/units/render/head.test.js @@ -72,7 +72,7 @@ describe('core/render', () => { `; }); - const Page = createComponent((result, _props) => { + const Page = createComponent((result) => { return render`${renderComponent( result, 'PageLayout', @@ -158,7 +158,7 @@ describe('core/render', () => { `; }); - const Page = createComponent((result, _props) => { + const Page = createComponent((result) => { return render`${renderComponent( result, 'PageLayout', @@ -221,7 +221,7 @@ describe('core/render', () => { `; }); - const Page = createComponent((result, _props) => { + const Page = createComponent((result) => { return render`${renderComponent( result, 'PageLayout', diff --git a/packages/astro/test/units/render/jsx.test.js b/packages/astro/test/units/render/jsx.test.js index 09cf79239..e972213f1 100644 --- a/packages/astro/test/units/render/jsx.test.js +++ b/packages/astro/test/units/render/jsx.test.js @@ -119,7 +119,7 @@ describe('core/render', () => { throw new Error('uh oh'); }); - const Page = createComponent((result, _props) => { + const Page = createComponent((result) => { return render`<div>${renderComponent(result, 'Component', Component, {})}</div>`; }); diff --git a/packages/astro/test/units/test-utils.js b/packages/astro/test/units/test-utils.js index 68a86d475..78c7daca0 100644 --- a/packages/astro/test/units/test-utils.js +++ b/packages/astro/test/units/test-utils.js @@ -3,7 +3,7 @@ import { Volume } from 'memfs'; import httpMocks from 'node-mocks-http'; import realFS from 'node:fs'; import npath from 'path'; -import { fileURLToPath, pathToFileURL } from 'url'; +import { fileURLToPath } from 'url'; import { unixify } from './correct-path.js'; class VirtualVolume extends Volume { diff --git a/packages/astro/test/units/vite-plugin-scanner/scan.test.js b/packages/astro/test/units/vite-plugin-scanner/scan.test.js index 7b9c598be..3d812a893 100644 --- a/packages/astro/test/units/vite-plugin-scanner/scan.test.js +++ b/packages/astro/test/units/vite-plugin-scanner/scan.test.js @@ -49,7 +49,7 @@ describe('astro scan', () => { it('throws on let boolean literal', async () => { try { - const result = await scan(`export let prerender = true;`, '/src/components/index.astro'); + await scan(`export let prerender = true;`, '/src/components/index.astro'); expect(false).to.be.true; } catch (e) { expect(e.message).to.contain( @@ -60,7 +60,7 @@ describe('astro scan', () => { it('throws on var boolean literal', async () => { try { - const result = await scan(`export var prerender = true;`, '/src/components/index.astro'); + await scan(`export var prerender = true;`, '/src/components/index.astro'); expect(false).to.be.true; } catch (e) { expect(e.message).to.contain( @@ -71,7 +71,7 @@ describe('astro scan', () => { it('throws on unknown values I', async () => { try { - const result = await scan(`export const prerender = !!value;`, '/src/components/index.astro'); + await scan(`export const prerender = !!value;`, '/src/components/index.astro'); expect(false).to.be.true; } catch (e) { expect(e.message).to.contain( @@ -82,7 +82,7 @@ describe('astro scan', () => { it('throws on unknown values II', async () => { try { - const result = await scan(`export const prerender = value;`, '/src/components/index.astro'); + await scan(`export const prerender = value;`, '/src/components/index.astro'); expect(false).to.be.true; } catch (e) { expect(e.message).to.contain( @@ -93,7 +93,7 @@ describe('astro scan', () => { it('throws on unknown values III', async () => { try { - const result = await scan( + await scan( `export let prerender = undefined; prerender = true;`, '/src/components/index.astro' ); @@ -107,10 +107,7 @@ describe('astro scan', () => { it('throws on unknown values IV', async () => { try { - const result = await scan( - `let prerender = true; export { prerender }`, - '/src/components/index.astro' - ); + await scan(`let prerender = true; export { prerender }`, '/src/components/index.astro'); expect(false).to.be.true; } catch (e) { expect(e.message).to.contain( diff --git a/packages/astro/test/vue-with-multi-renderer.test.js b/packages/astro/test/vue-with-multi-renderer.test.js index 62ad96491..78b243d78 100644 --- a/packages/astro/test/vue-with-multi-renderer.test.js +++ b/packages/astro/test/vue-with-multi-renderer.test.js @@ -1,5 +1,4 @@ import { expect } from 'chai'; -import * as cheerio from 'cheerio'; import { loadFixture } from './test-utils.js'; describe('Vue with multi-renderer', () => { |