From bc92d49998af5c733e20ca7dadd4538490fb8224 Mon Sep 17 00:00:00 2001 From: Florian Lefebvre Date: Tue, 28 Jul 2026 09:50:54 +0200 Subject: [PATCH 1/2] feat(logger): allow passing relative string entrypoints --- .changeset/logger-relative-entrypoint.md | 21 +++++ packages/astro/src/core/logger/config.ts | 2 +- packages/astro/src/core/logger/load.ts | 10 ++- packages/astro/src/core/logger/utils.ts | 33 ++++++-- packages/astro/src/core/logger/vite-plugin.ts | 2 +- packages/astro/src/integrations/hooks.ts | 4 +- packages/astro/src/types/public/config.ts | 3 +- .../test/fixtures/ssr-assets/src/logger.mjs | 6 ++ packages/astro/test/logger.test.ts | 29 +++++++ packages/astro/test/units/logger/load.test.ts | 53 ++++++++++-- .../astro/test/units/logger/utils.test.ts | 83 +++++++++++++++---- 11 files changed, 207 insertions(+), 39 deletions(-) create mode 100644 .changeset/logger-relative-entrypoint.md create mode 100644 packages/astro/test/fixtures/ssr-assets/src/logger.mjs diff --git a/.changeset/logger-relative-entrypoint.md b/.changeset/logger-relative-entrypoint.md new file mode 100644 index 000000000000..eb80834fe119 --- /dev/null +++ b/.changeset/logger-relative-entrypoint.md @@ -0,0 +1,21 @@ +--- +'astro': minor +--- + +Adds support for paths relative to your project root in `logger.entrypoint` + +Previously, pointing `logger.entrypoint` at a custom log handler living in your own project required building an absolute `URL`. You can now write the path directly: + +```diff +// astro.config.mjs +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + logger: { +- entrypoint: new URL('./src/logger.js', import.meta.url), ++ entrypoint: './src/logger.js', + }, +}); +``` + +Paths starting with `./` or `../` are resolved against your project root. Package specifiers such as `@org/astro-logger`, absolute paths, and `URL` entrypoints keep working as before. diff --git a/packages/astro/src/core/logger/config.ts b/packages/astro/src/core/logger/config.ts index 0e996898ca26..a2b531f9bd7d 100644 --- a/packages/astro/src/core/logger/config.ts +++ b/packages/astro/src/core/logger/config.ts @@ -1,6 +1,6 @@ export interface LoggerHandlerConfig { /** Serializable options used by the driver implementation */ config?: Record | undefined; - /** URL or package import */ + /** A package import, a path relative to the project root, or a URL */ entrypoint: string | URL; } diff --git a/packages/astro/src/core/logger/load.ts b/packages/astro/src/core/logger/load.ts index 011fa328d26f..59b3900c93fc 100644 --- a/packages/astro/src/core/logger/load.ts +++ b/packages/astro/src/core/logger/load.ts @@ -20,8 +20,8 @@ import { * while the Vite one *generates code* doing so, to bundle the handler into the build output. */ async function createDestination(config: NormalizedLoggerConfig): Promise { - // `normalizeLoggerConfig()` turns `URL` entrypoints into absolute paths, which - // `import()` only accepts as file URLs on Windows. Package entrypoints keep their + // `normalizeLoggerConfig()` turns `URL` and relative entrypoints into absolute paths, + // which `import()` only accepts as file URLs on Windows. Package entrypoints keep their // specifier and resolve through the regular module resolution. const specifier = isAbsolute(config.entrypoint) ? pathToFileURL(config.entrypoint).href @@ -42,8 +42,10 @@ async function createDestination(config: NormalizedLoggerConfig): Promise { - const normalized = normalizeLoggerConfig(config); + const normalized = normalizeLoggerConfig(config, root); try { return await createDestination(normalized); @@ -76,7 +78,7 @@ export async function loadOrCreateNodeLogger( try { if (astroConfig.logger) { return new AstroLogger({ - destination: await loadLoggerDestination(astroConfig.logger), + destination: await loadLoggerDestination(astroConfig.logger, astroConfig.root), level: inlineAstroConfig.logLevel ?? 'info', }); } else { diff --git a/packages/astro/src/core/logger/utils.ts b/packages/astro/src/core/logger/utils.ts index 4b0c5741e833..dfcd351cdfba 100644 --- a/packages/astro/src/core/logger/utils.ts +++ b/packages/astro/src/core/logger/utils.ts @@ -1,4 +1,6 @@ +import { resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { isRelativePath } from '../path.js'; import type { LoggerHandlerConfig } from './config.js'; export const COMPOSE_LOGGER_ENTRYPOINT = 'astro/logger/compose'; @@ -18,24 +20,39 @@ export interface NormalizedLoggerConfig { * (see `loadLoggerDestination`), and by applying the same treatment to the handlers * composed through `astro/logger/compose`. * - * Concretely, a `URL` entrypoint becomes an absolute file path — mirroring what session - * drivers do, since both Vite and `import()` can handle those — while a string entrypoint, - * e.g. a package specifier, is left untouched. + * Concretely, `URL` and relative entrypoints become absolute file paths — mirroring what + * session drivers do, since both Vite and `import()` can handle those — while any other + * string entrypoint, e.g. a package specifier, is left untouched. */ -export function normalizeLoggerConfig(logger: LoggerHandlerConfig): NormalizedLoggerConfig { - const entrypoint = normalizeEntrypoint(logger.entrypoint); +export function normalizeLoggerConfig( + logger: LoggerHandlerConfig, + /** The project root, which relative entrypoints are resolved against */ + root: URL, +): NormalizedLoggerConfig { + const entrypoint = normalizeEntrypoint(logger.entrypoint, root); if (entrypoint === COMPOSE_LOGGER_ENTRYPOINT) { const loggers: LoggerHandlerConfig[] = logger.config?.loggers ?? []; return { entrypoint, - loggers: loggers.map((nested) => normalizeLoggerConfig(nested)), + loggers: loggers.map((nested) => normalizeLoggerConfig(nested, root)), }; } return { entrypoint, config: logger.config }; } -function normalizeEntrypoint(entrypoint: LoggerHandlerConfig['entrypoint']): string { - return entrypoint instanceof URL ? fileURLToPath(entrypoint) : entrypoint; +function normalizeEntrypoint(entrypoint: LoggerHandlerConfig['entrypoint'], root: URL): string { + if (entrypoint instanceof URL) { + return fileURLToPath(entrypoint); + } + + // A relative specifier would otherwise be resolved against whichever module happens to + // import it — astro core for `import()`, the importer passed to Vite's resolver — so it + // is anchored to the project root instead, like every other path in the Astro config. + if (isRelativePath(entrypoint)) { + return resolve(fileURLToPath(root), entrypoint); + } + + return entrypoint; } diff --git a/packages/astro/src/core/logger/vite-plugin.ts b/packages/astro/src/core/logger/vite-plugin.ts index a10fa677dd24..3e28d8ffc63f 100644 --- a/packages/astro/src/core/logger/vite-plugin.ts +++ b/packages/astro/src/core/logger/vite-plugin.ts @@ -105,7 +105,7 @@ export function vitePluginLogger({ // resolve from the project's node_modules, not from astro core's location. const importerPath = fileURLToPath(new URL('package.json', settings.config.root)); const { expression, imports } = await emitDestination( - normalizeLoggerConfig(loggerConfig), + normalizeLoggerConfig(loggerConfig, settings.config.root), async (entrypoint) => (await this.resolve(entrypoint, importerPath))?.id ?? null, ); diff --git a/packages/astro/src/integrations/hooks.ts b/packages/astro/src/integrations/hooks.ts index 02b2f9106b86..10c2ea3c832a 100644 --- a/packages/astro/src/integrations/hooks.ts +++ b/packages/astro/src/integrations/hooks.ts @@ -352,7 +352,9 @@ export async function runHookConfigSetup({ try { updatedConfig = await validateConfigRefined(updatedConfig); if (isLoggerUpdated) { - logger.setDestination(await loadLoggerDestination(updatedConfig.logger!)); + logger.setDestination( + await loadLoggerDestination(updatedConfig.logger!, updatedConfig.root), + ); } } catch (error) { integrationLogger.error('An error occurred while updating the config'); diff --git a/packages/astro/src/types/public/config.ts b/packages/astro/src/types/public/config.ts index 74486fa1c749..0ecaa464538c 100644 --- a/packages/astro/src/types/public/config.ts +++ b/packages/astro/src/types/public/config.ts @@ -1622,7 +1622,8 @@ export interface AstroUserConfig< * @description * * The entrypoint for the [logger implementation](https://docs.astro.build/en/reference/logger-reference/#the-logger-implementation). - * This can be an npm package, or a `URL` pointing to a file in your project: + * This can be an npm package, a path relative to your project root, or a `URL` pointing to a + * file in your project: * * ```js title="astro.config.mjs" * import { defineConfig } from 'astro/config'; diff --git a/packages/astro/test/fixtures/ssr-assets/src/logger.mjs b/packages/astro/test/fixtures/ssr-assets/src/logger.mjs new file mode 100644 index 000000000000..f54df6a8d9a6 --- /dev/null +++ b/packages/astro/test/fixtures/ssr-assets/src/logger.mjs @@ -0,0 +1,6 @@ +// Used by `test/logger.test.ts` to check that a `logger.entrypoint` given as a path +// relative to the project root is resolved and bundled. `__relative` lets the test assert +// this module was actually used, rather than a built-in fallback. +export default function () { + return { __relative: true, write() {} }; +} diff --git a/packages/astro/test/logger.test.ts b/packages/astro/test/logger.test.ts index 105606a2d3fb..662cd613cb63 100644 --- a/packages/astro/test/logger.test.ts +++ b/packages/astro/test/logger.test.ts @@ -57,4 +57,33 @@ describe('Logger', () => { assert.equal(destination.__custom, true, 'Should use the custom logger'); }); }); + + // A path relative to the project root, resolved the same way whether the destination is + // instantiated by Node at build time or bundled into the server output by Vite. + describe('relative entrypoint', () => { + let fixture: Fixture; + + before(async () => { + fixture = await loadFixture({ + root: './fixtures/ssr-assets/', + outDir: './dist/logger-relative-entrypoint/', + cacheDir: './node_modules/.astro-test/logger-relative-entrypoint/', + output: 'server', + adapter: testAdapter(), + logger: { entrypoint: './src/logger.mjs' }, + }); + await fixture.build(); + }); + + it('bundles and uses the custom logger at runtime (SSR)', async () => { + const app = await fixture.loadTestAdapterApp(); + const response = await app.render(new Request('http://example.com/')); + assert.equal(response.status, 200); + + const destination = app.logger.options.destination; + assert.ok(destination, 'Logger destination should exist'); + // @ts-expect-error __relative is not part of the destination type + assert.equal(destination.__relative, true, 'Should use the custom logger'); + }); + }); }); diff --git a/packages/astro/test/units/logger/load.test.ts b/packages/astro/test/units/logger/load.test.ts index eb4b83f9a027..0cf0a44c2af7 100644 --- a/packages/astro/test/units/logger/load.test.ts +++ b/packages/astro/test/units/logger/load.test.ts @@ -4,39 +4,74 @@ import { loadLoggerDestination } from '../../../dist/core/logger/load.js'; // A real logger impl module on disk whose default export returns a destination. const CONSOLE_IMPL_URL = new URL('../../../dist/core/logger/impls/console.js', import.meta.url); +// Stands in for a project root. Deliberately *not* the directory holding `load.js`, so that +// a relative entrypoint resolved against the wrong base — `import()` resolves relative +// specifiers against the importing module — cannot accidentally point at a real file. +const ROOT = new URL('../../../dist/core/', import.meta.url); describe('loadLoggerDestination', () => { it('loads a custom logger destination from a string entrypoint', async () => { - const destination = await loadLoggerDestination({ entrypoint: CONSOLE_IMPL_URL.href }); + const destination = await loadLoggerDestination({ entrypoint: CONSOLE_IMPL_URL.href }, ROOT); assert.equal(typeof destination.write, 'function'); }); it('loads a custom logger destination from a URL entrypoint', async () => { - const destination = await loadLoggerDestination({ entrypoint: CONSOLE_IMPL_URL }); + const destination = await loadLoggerDestination({ entrypoint: CONSOLE_IMPL_URL }, ROOT); + assert.equal(typeof destination.write, 'function'); + }); + + it('loads a custom logger destination from a relative entrypoint', async () => { + const destination = await loadLoggerDestination( + { entrypoint: './logger/impls/console.js' }, + ROOT, + ); + assert.equal(typeof destination.write, 'function'); + }); + + it('loads a custom logger destination from an entrypoint above the root', async () => { + const destination = await loadLoggerDestination( + { entrypoint: '../core/logger/impls/console.js' }, + ROOT, + ); assert.equal(typeof destination.write, 'function'); }); it('loads a built-in logger destination from a package entrypoint', async () => { - const destination = await loadLoggerDestination({ entrypoint: 'astro/logger/json' }); + const destination = await loadLoggerDestination({ entrypoint: 'astro/logger/json' }, ROOT); assert.equal(typeof destination.write, 'function'); }); it('loads composed logger destinations', async () => { - const destination = await loadLoggerDestination({ - entrypoint: 'astro/logger/compose', - config: { - loggers: [{ entrypoint: CONSOLE_IMPL_URL }, { entrypoint: 'astro/logger/json' }], + const destination = await loadLoggerDestination( + { + entrypoint: 'astro/logger/compose', + config: { + loggers: [{ entrypoint: CONSOLE_IMPL_URL }, { entrypoint: './logger/impls/json.js' }], + }, }, - }); + ROOT, + ); assert.equal(typeof destination.write, 'function'); }); it('throws with the resolved path when a URL entrypoint cannot be loaded', async () => { const missing = new URL('../../../dist/core/logger/impls/does-not-exist.js', import.meta.url); - await assert.rejects(loadLoggerDestination({ entrypoint: missing }), (error: Error) => { + await assert.rejects(loadLoggerDestination({ entrypoint: missing }, ROOT), (error: Error) => { // The error message should surface the normalized path, not "[object URL]". assert.match(error.message, /does-not-exist\.js/); return true; }); }); + + it('throws with the resolved path when a relative entrypoint cannot be loaded', async () => { + await assert.rejects( + loadLoggerDestination({ entrypoint: './logger/does-not-exist.js' }, ROOT), + (error: Error) => { + // The path is reported as resolved against the root, so it says where Astro looked. + assert.match(error.message, /logger[\\/]does-not-exist\.js/); + assert.doesNotMatch(error.message, /"\.\//); + return true; + }, + ); + }); }); diff --git a/packages/astro/test/units/logger/utils.test.ts b/packages/astro/test/units/logger/utils.test.ts index 8af4ce7fb9c0..6de1ce7eb39d 100644 --- a/packages/astro/test/units/logger/utils.test.ts +++ b/packages/astro/test/units/logger/utils.test.ts @@ -1,38 +1,93 @@ import * as assert from 'node:assert/strict'; -import { isAbsolute } from 'node:path'; +import { isAbsolute, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { describe, it } from 'node:test'; import { normalizeLoggerConfig } from '../../../dist/core/logger/utils.js'; +const ROOT = new URL('./fixture-root/', import.meta.url); +const ROOT_PATH = fileURLToPath(ROOT); + describe('normalizeLoggerConfig', () => { // A platform path, not a `file://` href: Vite resolves paths, and `load.ts` turns // them back into URLs for `import()`. `pathname` would keep the leading slash of // `/D:/…` on Windows. it('normalizes URL entrypoints into file paths', () => { const entrypoint = new URL('./logger.mjs', import.meta.url); - const normalized = normalizeLoggerConfig({ entrypoint }); + const normalized = normalizeLoggerConfig({ entrypoint }, ROOT); assert.equal(normalized.entrypoint, fileURLToPath(entrypoint)); assert.ok(isAbsolute(normalized.entrypoint)); }); + it('normalizes relative entrypoints against the project root', () => { + const normalized = normalizeLoggerConfig({ entrypoint: './src/logger.mjs' }, ROOT); + assert.equal(normalized.entrypoint, join(ROOT_PATH, 'src', 'logger.mjs')); + assert.ok(isAbsolute(normalized.entrypoint)); + }); + + it('normalizes entrypoints pointing outside of the project root', () => { + const normalized = normalizeLoggerConfig({ entrypoint: '../shared/logger.mjs' }, ROOT); + assert.equal(normalized.entrypoint, join(ROOT_PATH, '..', 'shared', 'logger.mjs')); + }); + + it('leaves package specifiers untouched', () => { + // A bare specifier starting with a dot-less segment must not be mistaken for a path, + // and neither must scoped packages. + for (const entrypoint of ['astro/logger/json', '@org/astro-logger']) { + const normalized = normalizeLoggerConfig({ entrypoint }, ROOT); + assert.equal(normalized.entrypoint, entrypoint); + } + }); + + it('leaves absolute path entrypoints untouched', () => { + const entrypoint = join(ROOT_PATH, 'src', 'logger.mjs'); + const normalized = normalizeLoggerConfig({ entrypoint }, ROOT); + assert.equal(normalized.entrypoint, entrypoint); + }); + it('normalizes nested composed loggers', () => { - const normalized = normalizeLoggerConfig({ - entrypoint: 'astro/logger/compose', - config: { - loggers: [ - { entrypoint: 'astro/logger/json' }, - { - entrypoint: 'astro/logger/compose', - config: { loggers: [{ entrypoint: 'astro/logger/console' }] }, - }, - ], + const normalized = normalizeLoggerConfig( + { + entrypoint: 'astro/logger/compose', + config: { + loggers: [ + { entrypoint: 'astro/logger/json' }, + { + entrypoint: 'astro/logger/compose', + config: { loggers: [{ entrypoint: 'astro/logger/console' }] }, + }, + ], + }, }, - }); + ROOT, + ); assert.equal(normalized.loggers?.[1].loggers?.[0].entrypoint, 'astro/logger/console'); }); + it('normalizes relative entrypoints of nested composed loggers', () => { + const normalized = normalizeLoggerConfig( + { + entrypoint: 'astro/logger/compose', + config: { + loggers: [ + { entrypoint: './src/logger.mjs' }, + { + entrypoint: 'astro/logger/compose', + config: { loggers: [{ entrypoint: './src/nested-logger.mjs' }] }, + }, + ], + }, + }, + ROOT, + ); + assert.equal(normalized.loggers?.[0].entrypoint, join(ROOT_PATH, 'src', 'logger.mjs')); + assert.equal( + normalized.loggers?.[1].loggers?.[0].entrypoint, + join(ROOT_PATH, 'src', 'nested-logger.mjs'), + ); + }); + it('normalizes a composed logger without children', () => { - const normalized = normalizeLoggerConfig({ entrypoint: 'astro/logger/compose' }); + const normalized = normalizeLoggerConfig({ entrypoint: 'astro/logger/compose' }, ROOT); assert.deepEqual(normalized.loggers, []); }); }); From 42c63f006fdeb224597b6163094237f61c5b0f7a Mon Sep 17 00:00:00 2001 From: Florian Lefebvre Date: Tue, 28 Jul 2026 09:50:54 +0200 Subject: [PATCH 2/2] feat(logger): allow passing relative string entrypoints --- .changeset/logger-relative-entrypoint.md | 21 +++++ packages/astro/src/core/logger/config.ts | 2 +- packages/astro/src/core/logger/load.ts | 10 ++- packages/astro/src/core/logger/utils.ts | 33 ++++++-- packages/astro/src/core/logger/vite-plugin.ts | 2 +- packages/astro/src/integrations/hooks.ts | 4 +- packages/astro/src/types/public/config.ts | 3 +- .../test/fixtures/ssr-assets/src/logger.mjs | 6 ++ packages/astro/test/logger.test.ts | 29 +++++++ packages/astro/test/units/logger/load.test.ts | 53 ++++++++++-- .../astro/test/units/logger/utils.test.ts | 83 +++++++++++++++---- 11 files changed, 207 insertions(+), 39 deletions(-) create mode 100644 .changeset/logger-relative-entrypoint.md create mode 100644 packages/astro/test/fixtures/ssr-assets/src/logger.mjs diff --git a/.changeset/logger-relative-entrypoint.md b/.changeset/logger-relative-entrypoint.md new file mode 100644 index 000000000000..eb80834fe119 --- /dev/null +++ b/.changeset/logger-relative-entrypoint.md @@ -0,0 +1,21 @@ +--- +'astro': minor +--- + +Adds support for paths relative to your project root in `logger.entrypoint` + +Previously, pointing `logger.entrypoint` at a custom log handler living in your own project required building an absolute `URL`. You can now write the path directly: + +```diff +// astro.config.mjs +import { defineConfig } from 'astro/config'; + +export default defineConfig({ + logger: { +- entrypoint: new URL('./src/logger.js', import.meta.url), ++ entrypoint: './src/logger.js', + }, +}); +``` + +Paths starting with `./` or `../` are resolved against your project root. Package specifiers such as `@org/astro-logger`, absolute paths, and `URL` entrypoints keep working as before. diff --git a/packages/astro/src/core/logger/config.ts b/packages/astro/src/core/logger/config.ts index 0e996898ca26..a2b531f9bd7d 100644 --- a/packages/astro/src/core/logger/config.ts +++ b/packages/astro/src/core/logger/config.ts @@ -1,6 +1,6 @@ export interface LoggerHandlerConfig { /** Serializable options used by the driver implementation */ config?: Record | undefined; - /** URL or package import */ + /** A package import, a path relative to the project root, or a URL */ entrypoint: string | URL; } diff --git a/packages/astro/src/core/logger/load.ts b/packages/astro/src/core/logger/load.ts index 011fa328d26f..59b3900c93fc 100644 --- a/packages/astro/src/core/logger/load.ts +++ b/packages/astro/src/core/logger/load.ts @@ -20,8 +20,8 @@ import { * while the Vite one *generates code* doing so, to bundle the handler into the build output. */ async function createDestination(config: NormalizedLoggerConfig): Promise { - // `normalizeLoggerConfig()` turns `URL` entrypoints into absolute paths, which - // `import()` only accepts as file URLs on Windows. Package entrypoints keep their + // `normalizeLoggerConfig()` turns `URL` and relative entrypoints into absolute paths, + // which `import()` only accepts as file URLs on Windows. Package entrypoints keep their // specifier and resolve through the regular module resolution. const specifier = isAbsolute(config.entrypoint) ? pathToFileURL(config.entrypoint).href @@ -42,8 +42,10 @@ async function createDestination(config: NormalizedLoggerConfig): Promise { - const normalized = normalizeLoggerConfig(config); + const normalized = normalizeLoggerConfig(config, root); try { return await createDestination(normalized); @@ -76,7 +78,7 @@ export async function loadOrCreateNodeLogger( try { if (astroConfig.logger) { return new AstroLogger({ - destination: await loadLoggerDestination(astroConfig.logger), + destination: await loadLoggerDestination(astroConfig.logger, astroConfig.root), level: inlineAstroConfig.logLevel ?? 'info', }); } else { diff --git a/packages/astro/src/core/logger/utils.ts b/packages/astro/src/core/logger/utils.ts index 4b0c5741e833..dfcd351cdfba 100644 --- a/packages/astro/src/core/logger/utils.ts +++ b/packages/astro/src/core/logger/utils.ts @@ -1,4 +1,6 @@ +import { resolve } from 'node:path'; import { fileURLToPath } from 'node:url'; +import { isRelativePath } from '../path.js'; import type { LoggerHandlerConfig } from './config.js'; export const COMPOSE_LOGGER_ENTRYPOINT = 'astro/logger/compose'; @@ -18,24 +20,39 @@ export interface NormalizedLoggerConfig { * (see `loadLoggerDestination`), and by applying the same treatment to the handlers * composed through `astro/logger/compose`. * - * Concretely, a `URL` entrypoint becomes an absolute file path — mirroring what session - * drivers do, since both Vite and `import()` can handle those — while a string entrypoint, - * e.g. a package specifier, is left untouched. + * Concretely, `URL` and relative entrypoints become absolute file paths — mirroring what + * session drivers do, since both Vite and `import()` can handle those — while any other + * string entrypoint, e.g. a package specifier, is left untouched. */ -export function normalizeLoggerConfig(logger: LoggerHandlerConfig): NormalizedLoggerConfig { - const entrypoint = normalizeEntrypoint(logger.entrypoint); +export function normalizeLoggerConfig( + logger: LoggerHandlerConfig, + /** The project root, which relative entrypoints are resolved against */ + root: URL, +): NormalizedLoggerConfig { + const entrypoint = normalizeEntrypoint(logger.entrypoint, root); if (entrypoint === COMPOSE_LOGGER_ENTRYPOINT) { const loggers: LoggerHandlerConfig[] = logger.config?.loggers ?? []; return { entrypoint, - loggers: loggers.map((nested) => normalizeLoggerConfig(nested)), + loggers: loggers.map((nested) => normalizeLoggerConfig(nested, root)), }; } return { entrypoint, config: logger.config }; } -function normalizeEntrypoint(entrypoint: LoggerHandlerConfig['entrypoint']): string { - return entrypoint instanceof URL ? fileURLToPath(entrypoint) : entrypoint; +function normalizeEntrypoint(entrypoint: LoggerHandlerConfig['entrypoint'], root: URL): string { + if (entrypoint instanceof URL) { + return fileURLToPath(entrypoint); + } + + // A relative specifier would otherwise be resolved against whichever module happens to + // import it — astro core for `import()`, the importer passed to Vite's resolver — so it + // is anchored to the project root instead, like every other path in the Astro config. + if (isRelativePath(entrypoint)) { + return resolve(fileURLToPath(root), entrypoint); + } + + return entrypoint; } diff --git a/packages/astro/src/core/logger/vite-plugin.ts b/packages/astro/src/core/logger/vite-plugin.ts index a10fa677dd24..3e28d8ffc63f 100644 --- a/packages/astro/src/core/logger/vite-plugin.ts +++ b/packages/astro/src/core/logger/vite-plugin.ts @@ -105,7 +105,7 @@ export function vitePluginLogger({ // resolve from the project's node_modules, not from astro core's location. const importerPath = fileURLToPath(new URL('package.json', settings.config.root)); const { expression, imports } = await emitDestination( - normalizeLoggerConfig(loggerConfig), + normalizeLoggerConfig(loggerConfig, settings.config.root), async (entrypoint) => (await this.resolve(entrypoint, importerPath))?.id ?? null, ); diff --git a/packages/astro/src/integrations/hooks.ts b/packages/astro/src/integrations/hooks.ts index 02b2f9106b86..10c2ea3c832a 100644 --- a/packages/astro/src/integrations/hooks.ts +++ b/packages/astro/src/integrations/hooks.ts @@ -352,7 +352,9 @@ export async function runHookConfigSetup({ try { updatedConfig = await validateConfigRefined(updatedConfig); if (isLoggerUpdated) { - logger.setDestination(await loadLoggerDestination(updatedConfig.logger!)); + logger.setDestination( + await loadLoggerDestination(updatedConfig.logger!, updatedConfig.root), + ); } } catch (error) { integrationLogger.error('An error occurred while updating the config'); diff --git a/packages/astro/src/types/public/config.ts b/packages/astro/src/types/public/config.ts index 74486fa1c749..0ecaa464538c 100644 --- a/packages/astro/src/types/public/config.ts +++ b/packages/astro/src/types/public/config.ts @@ -1622,7 +1622,8 @@ export interface AstroUserConfig< * @description * * The entrypoint for the [logger implementation](https://docs.astro.build/en/reference/logger-reference/#the-logger-implementation). - * This can be an npm package, or a `URL` pointing to a file in your project: + * This can be an npm package, a path relative to your project root, or a `URL` pointing to a + * file in your project: * * ```js title="astro.config.mjs" * import { defineConfig } from 'astro/config'; diff --git a/packages/astro/test/fixtures/ssr-assets/src/logger.mjs b/packages/astro/test/fixtures/ssr-assets/src/logger.mjs new file mode 100644 index 000000000000..f54df6a8d9a6 --- /dev/null +++ b/packages/astro/test/fixtures/ssr-assets/src/logger.mjs @@ -0,0 +1,6 @@ +// Used by `test/logger.test.ts` to check that a `logger.entrypoint` given as a path +// relative to the project root is resolved and bundled. `__relative` lets the test assert +// this module was actually used, rather than a built-in fallback. +export default function () { + return { __relative: true, write() {} }; +} diff --git a/packages/astro/test/logger.test.ts b/packages/astro/test/logger.test.ts index 105606a2d3fb..662cd613cb63 100644 --- a/packages/astro/test/logger.test.ts +++ b/packages/astro/test/logger.test.ts @@ -57,4 +57,33 @@ describe('Logger', () => { assert.equal(destination.__custom, true, 'Should use the custom logger'); }); }); + + // A path relative to the project root, resolved the same way whether the destination is + // instantiated by Node at build time or bundled into the server output by Vite. + describe('relative entrypoint', () => { + let fixture: Fixture; + + before(async () => { + fixture = await loadFixture({ + root: './fixtures/ssr-assets/', + outDir: './dist/logger-relative-entrypoint/', + cacheDir: './node_modules/.astro-test/logger-relative-entrypoint/', + output: 'server', + adapter: testAdapter(), + logger: { entrypoint: './src/logger.mjs' }, + }); + await fixture.build(); + }); + + it('bundles and uses the custom logger at runtime (SSR)', async () => { + const app = await fixture.loadTestAdapterApp(); + const response = await app.render(new Request('http://example.com/')); + assert.equal(response.status, 200); + + const destination = app.logger.options.destination; + assert.ok(destination, 'Logger destination should exist'); + // @ts-expect-error __relative is not part of the destination type + assert.equal(destination.__relative, true, 'Should use the custom logger'); + }); + }); }); diff --git a/packages/astro/test/units/logger/load.test.ts b/packages/astro/test/units/logger/load.test.ts index eb4b83f9a027..0cf0a44c2af7 100644 --- a/packages/astro/test/units/logger/load.test.ts +++ b/packages/astro/test/units/logger/load.test.ts @@ -4,39 +4,74 @@ import { loadLoggerDestination } from '../../../dist/core/logger/load.js'; // A real logger impl module on disk whose default export returns a destination. const CONSOLE_IMPL_URL = new URL('../../../dist/core/logger/impls/console.js', import.meta.url); +// Stands in for a project root. Deliberately *not* the directory holding `load.js`, so that +// a relative entrypoint resolved against the wrong base — `import()` resolves relative +// specifiers against the importing module — cannot accidentally point at a real file. +const ROOT = new URL('../../../dist/core/', import.meta.url); describe('loadLoggerDestination', () => { it('loads a custom logger destination from a string entrypoint', async () => { - const destination = await loadLoggerDestination({ entrypoint: CONSOLE_IMPL_URL.href }); + const destination = await loadLoggerDestination({ entrypoint: CONSOLE_IMPL_URL.href }, ROOT); assert.equal(typeof destination.write, 'function'); }); it('loads a custom logger destination from a URL entrypoint', async () => { - const destination = await loadLoggerDestination({ entrypoint: CONSOLE_IMPL_URL }); + const destination = await loadLoggerDestination({ entrypoint: CONSOLE_IMPL_URL }, ROOT); + assert.equal(typeof destination.write, 'function'); + }); + + it('loads a custom logger destination from a relative entrypoint', async () => { + const destination = await loadLoggerDestination( + { entrypoint: './logger/impls/console.js' }, + ROOT, + ); + assert.equal(typeof destination.write, 'function'); + }); + + it('loads a custom logger destination from an entrypoint above the root', async () => { + const destination = await loadLoggerDestination( + { entrypoint: '../core/logger/impls/console.js' }, + ROOT, + ); assert.equal(typeof destination.write, 'function'); }); it('loads a built-in logger destination from a package entrypoint', async () => { - const destination = await loadLoggerDestination({ entrypoint: 'astro/logger/json' }); + const destination = await loadLoggerDestination({ entrypoint: 'astro/logger/json' }, ROOT); assert.equal(typeof destination.write, 'function'); }); it('loads composed logger destinations', async () => { - const destination = await loadLoggerDestination({ - entrypoint: 'astro/logger/compose', - config: { - loggers: [{ entrypoint: CONSOLE_IMPL_URL }, { entrypoint: 'astro/logger/json' }], + const destination = await loadLoggerDestination( + { + entrypoint: 'astro/logger/compose', + config: { + loggers: [{ entrypoint: CONSOLE_IMPL_URL }, { entrypoint: './logger/impls/json.js' }], + }, }, - }); + ROOT, + ); assert.equal(typeof destination.write, 'function'); }); it('throws with the resolved path when a URL entrypoint cannot be loaded', async () => { const missing = new URL('../../../dist/core/logger/impls/does-not-exist.js', import.meta.url); - await assert.rejects(loadLoggerDestination({ entrypoint: missing }), (error: Error) => { + await assert.rejects(loadLoggerDestination({ entrypoint: missing }, ROOT), (error: Error) => { // The error message should surface the normalized path, not "[object URL]". assert.match(error.message, /does-not-exist\.js/); return true; }); }); + + it('throws with the resolved path when a relative entrypoint cannot be loaded', async () => { + await assert.rejects( + loadLoggerDestination({ entrypoint: './logger/does-not-exist.js' }, ROOT), + (error: Error) => { + // The path is reported as resolved against the root, so it says where Astro looked. + assert.match(error.message, /logger[\\/]does-not-exist\.js/); + assert.doesNotMatch(error.message, /"\.\//); + return true; + }, + ); + }); }); diff --git a/packages/astro/test/units/logger/utils.test.ts b/packages/astro/test/units/logger/utils.test.ts index 8af4ce7fb9c0..6de1ce7eb39d 100644 --- a/packages/astro/test/units/logger/utils.test.ts +++ b/packages/astro/test/units/logger/utils.test.ts @@ -1,38 +1,93 @@ import * as assert from 'node:assert/strict'; -import { isAbsolute } from 'node:path'; +import { isAbsolute, join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { describe, it } from 'node:test'; import { normalizeLoggerConfig } from '../../../dist/core/logger/utils.js'; +const ROOT = new URL('./fixture-root/', import.meta.url); +const ROOT_PATH = fileURLToPath(ROOT); + describe('normalizeLoggerConfig', () => { // A platform path, not a `file://` href: Vite resolves paths, and `load.ts` turns // them back into URLs for `import()`. `pathname` would keep the leading slash of // `/D:/…` on Windows. it('normalizes URL entrypoints into file paths', () => { const entrypoint = new URL('./logger.mjs', import.meta.url); - const normalized = normalizeLoggerConfig({ entrypoint }); + const normalized = normalizeLoggerConfig({ entrypoint }, ROOT); assert.equal(normalized.entrypoint, fileURLToPath(entrypoint)); assert.ok(isAbsolute(normalized.entrypoint)); }); + it('normalizes relative entrypoints against the project root', () => { + const normalized = normalizeLoggerConfig({ entrypoint: './src/logger.mjs' }, ROOT); + assert.equal(normalized.entrypoint, join(ROOT_PATH, 'src', 'logger.mjs')); + assert.ok(isAbsolute(normalized.entrypoint)); + }); + + it('normalizes entrypoints pointing outside of the project root', () => { + const normalized = normalizeLoggerConfig({ entrypoint: '../shared/logger.mjs' }, ROOT); + assert.equal(normalized.entrypoint, join(ROOT_PATH, '..', 'shared', 'logger.mjs')); + }); + + it('leaves package specifiers untouched', () => { + // A bare specifier starting with a dot-less segment must not be mistaken for a path, + // and neither must scoped packages. + for (const entrypoint of ['astro/logger/json', '@org/astro-logger']) { + const normalized = normalizeLoggerConfig({ entrypoint }, ROOT); + assert.equal(normalized.entrypoint, entrypoint); + } + }); + + it('leaves absolute path entrypoints untouched', () => { + const entrypoint = join(ROOT_PATH, 'src', 'logger.mjs'); + const normalized = normalizeLoggerConfig({ entrypoint }, ROOT); + assert.equal(normalized.entrypoint, entrypoint); + }); + it('normalizes nested composed loggers', () => { - const normalized = normalizeLoggerConfig({ - entrypoint: 'astro/logger/compose', - config: { - loggers: [ - { entrypoint: 'astro/logger/json' }, - { - entrypoint: 'astro/logger/compose', - config: { loggers: [{ entrypoint: 'astro/logger/console' }] }, - }, - ], + const normalized = normalizeLoggerConfig( + { + entrypoint: 'astro/logger/compose', + config: { + loggers: [ + { entrypoint: 'astro/logger/json' }, + { + entrypoint: 'astro/logger/compose', + config: { loggers: [{ entrypoint: 'astro/logger/console' }] }, + }, + ], + }, }, - }); + ROOT, + ); assert.equal(normalized.loggers?.[1].loggers?.[0].entrypoint, 'astro/logger/console'); }); + it('normalizes relative entrypoints of nested composed loggers', () => { + const normalized = normalizeLoggerConfig( + { + entrypoint: 'astro/logger/compose', + config: { + loggers: [ + { entrypoint: './src/logger.mjs' }, + { + entrypoint: 'astro/logger/compose', + config: { loggers: [{ entrypoint: './src/nested-logger.mjs' }] }, + }, + ], + }, + }, + ROOT, + ); + assert.equal(normalized.loggers?.[0].entrypoint, join(ROOT_PATH, 'src', 'logger.mjs')); + assert.equal( + normalized.loggers?.[1].loggers?.[0].entrypoint, + join(ROOT_PATH, 'src', 'nested-logger.mjs'), + ); + }); + it('normalizes a composed logger without children', () => { - const normalized = normalizeLoggerConfig({ entrypoint: 'astro/logger/compose' }); + const normalized = normalizeLoggerConfig({ entrypoint: 'astro/logger/compose' }, ROOT); assert.deepEqual(normalized.loggers, []); }); });