Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
21 changes: 21 additions & 0 deletions .changeset/logger-relative-entrypoint.md
Original file line number Diff line number Diff line change
@@ -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.
2 changes: 1 addition & 1 deletion packages/astro/src/core/logger/config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export interface LoggerHandlerConfig {
/** Serializable options used by the driver implementation */
config?: Record<string, any> | undefined;
/** URL or package import */
/** A package import, a path relative to the project root, or a URL */
entrypoint: string | URL;
}
10 changes: 6 additions & 4 deletions packages/astro/src/core/logger/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<AstroLoggerDestination> {
// `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
Expand All @@ -42,8 +42,10 @@ async function createDestination(config: NormalizedLoggerConfig): Promise<AstroL
*/
export async function loadLoggerDestination(
config: LoggerHandlerConfig,
/** The project root, which relative entrypoints are resolved against */
root: URL,
): Promise<AstroLoggerDestination> {
const normalized = normalizeLoggerConfig(config);
const normalized = normalizeLoggerConfig(config, root);

try {
return await createDestination(normalized);
Expand Down Expand Up @@ -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 {
Expand Down
33 changes: 25 additions & 8 deletions packages/astro/src/core/logger/utils.ts
Original file line number Diff line number Diff line change
@@ -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';
Expand All @@ -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;
}
2 changes: 1 addition & 1 deletion packages/astro/src/core/logger/vite-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
);

Expand Down
4 changes: 3 additions & 1 deletion packages/astro/src/integrations/hooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down
3 changes: 2 additions & 1 deletion packages/astro/src/types/public/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand Down
6 changes: 6 additions & 0 deletions packages/astro/test/fixtures/ssr-assets/src/logger.mjs
Original file line number Diff line number Diff line change
@@ -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() {} };
}
29 changes: 29 additions & 0 deletions packages/astro/test/logger.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});
});
53 changes: 44 additions & 9 deletions packages/astro/test/units/logger/load.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
},
);
});
});
83 changes: 69 additions & 14 deletions packages/astro/test/units/logger/utils.test.ts
Original file line number Diff line number Diff line change
@@ -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, []);
});
});
Loading