Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: pass config instead of settings to content layer loaders #11862

Merged
merged 3 commits into from
Aug 28, 2024
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
26 changes: 26 additions & 0 deletions .changeset/chilled-timers-shave.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
---
'astro': patch
---

**BREAKING CHANGE to experimental content layer loaders only!**

Passes `AstroConfig` instead of `AstroSettings` object to content layer loaders.

This will not affect you unless you have created a loader that uses the `settings` object. If you have, you will need to update your loader to use the `config` object instead.

```diff
export default function myLoader() {
return {
name: 'my-loader'
- async load({ settings }) {
- const base = settings.config.base;
+ async load({ config }) {
+ const base = config.base;
// ...
}
}
}

```

Other properties of the settings object are private internals, and should not be accessed directly. If you think you need access to other properties, please open an issue to discuss your use case.
3 changes: 2 additions & 1 deletion packages/astro/src/@types/astro.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2505,6 +2505,7 @@ export interface RouteOptions {

/**
* Resolved Astro Config
*
* Config with user settings along with all defaults filled in.
*/
export interface AstroConfig extends AstroConfigType {
Expand Down Expand Up @@ -2593,7 +2594,7 @@ export interface ContentEntryType {
},
): rollup.LoadResult | Promise<rollup.LoadResult>;
contentModuleTypes?: string;
getRenderFunction?(settings: AstroSettings): Promise<ContentEntryRenderFuction>;
getRenderFunction?(config: AstroConfig): Promise<ContentEntryRenderFuction>;

/**
* Handle asset propagation for rendered content to avoid bleed.
Expand Down
15 changes: 12 additions & 3 deletions packages/astro/src/content/content-layer.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { isAbsolute } from 'node:path';
import { fileURLToPath } from 'node:url';
import type { FSWatcher } from 'vite';
import xxhash from 'xxhash-wasm';
import type { AstroSettings } from '../@types/astro.js';
import type { AstroSettings, ContentEntryType } from '../@types/astro.js';
import { AstroUserError } from '../core/errors/errors.js';
import type { Logger } from '../core/logger/core.js';
import {
Expand All @@ -14,7 +14,12 @@ import {
} from './consts.js';
import type { LoaderContext } from './loaders/types.js';
import type { MutableDataStore } from './mutable-data-store.js';
import { getEntryDataAndImages, globalContentConfigObserver, posixRelative } from './utils.js';
import {
getEntryConfigByExtMap,
getEntryDataAndImages,
globalContentConfigObserver,
posixRelative,
} from './utils.js';

export interface ContentLayerOptions {
store: MutableDataStore;
Expand Down Expand Up @@ -118,10 +123,14 @@ export class ContentLayer {
store: this.#store.scopedStore(collectionName),
meta: this.#store.metaStore(collectionName),
logger: this.#logger.forkIntegrationLogger(loaderName),
settings: this.#settings,
config: this.#settings.config,
parseData,
generateDigest: await this.#getGenerateDigest(),
watcher: this.#watcher,
entryTypes: getEntryConfigByExtMap([
...this.#settings.contentEntryTypes,
...this.#settings.dataEntryTypes,
] as Array<ContentEntryType>),
};
}

Expand Down
14 changes: 7 additions & 7 deletions packages/astro/src/content/loaders/file.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export function file(fileName: string): Loader {
throw new Error('Glob patterns are not supported in `file` loader. Use `glob` loader instead.');
}

async function syncData(filePath: string, { logger, parseData, store, settings }: LoaderContext) {
async function syncData(filePath: string, { logger, parseData, store, config }: LoaderContext) {
let json: Array<Record<string, unknown>>;

try {
Expand All @@ -26,7 +26,7 @@ export function file(fileName: string): Loader {
return;
}

const normalizedFilePath = posixRelative(fileURLToPath(settings.config.root), filePath);
const normalizedFilePath = posixRelative(fileURLToPath(config.root), filePath);

if (Array.isArray(json)) {
if (json.length === 0) {
Expand Down Expand Up @@ -58,22 +58,22 @@ export function file(fileName: string): Loader {

return {
name: 'file-loader',
load: async (options) => {
const { settings, logger, watcher } = options;
load: async (context) => {
const { config, logger, watcher } = context;
logger.debug(`Loading data from ${fileName}`);
const url = new URL(fileName, settings.config.root);
const url = new URL(fileName, config.root);
if (!existsSync(url)) {
logger.error(`File not found: ${fileName}`);
return;
}
const filePath = fileURLToPath(url);

await syncData(filePath, options);
await syncData(filePath, context);

watcher?.on('change', async (changedPath) => {
if (changedPath === filePath) {
logger.info(`Reloading data from ${fileName}`);
await syncData(filePath, options);
await syncData(filePath, context);
}
});
},
Expand Down
21 changes: 7 additions & 14 deletions packages/astro/src/content/loaders/glob.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import micromatch from 'micromatch';
import pLimit from 'p-limit';
import type { ContentEntryRenderFuction, ContentEntryType } from '../../@types/astro.js';
import type { RenderedContent } from '../data-store.js';
import { getContentEntryIdAndSlug, getEntryConfigByExtMap, posixRelative } from '../utils.js';
import { getContentEntryIdAndSlug, posixRelative } from '../utils.js';
import type { Loader } from './types.js';

export interface GenerateIdOptions {
Expand Down Expand Up @@ -66,7 +66,7 @@ export function glob(globOptions: GlobOptions): Loader {

return {
name: 'glob-loader',
load: async ({ settings, logger, watcher, parseData, store, generateDigest }) => {
load: async ({ config, logger, watcher, parseData, store, generateDigest, entryTypes }) => {
const renderFunctionByContentType = new WeakMap<
ContentEntryType,
ContentEntryRenderFuction
Expand Down Expand Up @@ -121,7 +121,7 @@ export function glob(globOptions: GlobOptions): Loader {

const filePath = fileURLToPath(fileUrl);

const relativePath = posixRelative(fileURLToPath(settings.config.root), filePath);
const relativePath = posixRelative(fileURLToPath(config.root), filePath);

const parsedData = await parseData({
id,
Expand All @@ -131,7 +131,7 @@ export function glob(globOptions: GlobOptions): Loader {
if (entryType.getRenderFunction) {
let render = renderFunctionByContentType.get(entryType);
if (!render) {
render = await entryType.getRenderFunction(settings);
render = await entryType.getRenderFunction(config);
// Cache the render function for this content type, so it can re-use parsers and other expensive setup
renderFunctionByContentType.set(entryType, render);
}
Expand Down Expand Up @@ -177,14 +177,7 @@ export function glob(globOptions: GlobOptions): Loader {
fileToIdMap.set(filePath, id);
}

const entryConfigByExt = getEntryConfigByExtMap([
...settings.contentEntryTypes,
...settings.dataEntryTypes,
] as Array<ContentEntryType>);

const baseDir = globOptions.base
? new URL(globOptions.base, settings.config.root)
: settings.config.root;
const baseDir = globOptions.base ? new URL(globOptions.base, config.root) : config.root;

if (!baseDir.pathname.endsWith('/')) {
baseDir.pathname = `${baseDir.pathname}/`;
Expand All @@ -200,13 +193,13 @@ export function glob(globOptions: GlobOptions): Loader {
logger.warn(`No extension found for ${file}`);
return;
}
return entryConfigByExt.get(`.${ext}`);
return entryTypes.get(`.${ext}`);
}

const limit = pLimit(10);
const skippedFiles: Array<string> = [];

const contentDir = new URL('content/', settings.config.srcDir);
const contentDir = new URL('content/', config.srcDir);

function isInContentDir(file: string) {
const fileUrl = new URL(file, baseDir);
Expand Down
9 changes: 5 additions & 4 deletions packages/astro/src/content/loaders/types.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import type { FSWatcher } from 'vite';
import type { ZodSchema } from 'zod';
import type { AstroIntegrationLogger, AstroSettings } from '../../@types/astro.js';
import type { AstroConfig, AstroIntegrationLogger, ContentEntryType } from '../../@types/astro.js';
import type { MetaStore, ScopedDataStore } from '../mutable-data-store.js';

export interface ParseDataOptions<TData extends Record<string, unknown>> {
Expand All @@ -20,9 +20,8 @@ export interface LoaderContext {
/** A simple KV store, designed for things like sync tokens */
meta: MetaStore;
logger: AstroIntegrationLogger;

settings: AstroSettings;

/** Astro config, with user config and merged defaults */
config: AstroConfig;
/** Validates and parses the data according to the collection schema */
parseData<TData extends Record<string, unknown>>(props: ParseDataOptions<TData>): Promise<TData>;

Expand All @@ -31,6 +30,8 @@ export interface LoaderContext {

/** When running in dev, this is a filesystem watcher that can be used to trigger updates */
watcher?: FSWatcher;

entryTypes: Map<string, ContentEntryType>;
}

export interface Loader {
Expand Down
3 changes: 2 additions & 1 deletion packages/astro/src/content/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ const collectionConfigParser = z.union([
store: z.any(),
meta: z.any(),
logger: z.any(),
settings: z.any(),
config: z.any(),
entryTypes: z.any(),
parseData: z.any(),
generateDigest: z.function(z.tuple([z.any()], z.string())),
watcher: z.any().optional(),
Expand Down
4 changes: 2 additions & 2 deletions packages/astro/src/vite-plugin-markdown/content-entry-type.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ export const markdownContentEntryType: ContentEntryType = {
// We need to handle propagation for Markdown because they support layouts which will bring in styles.
handlePropagation: true,

async getRenderFunction(settings) {
const processor = await createMarkdownProcessor(settings.config.markdown);
async getRenderFunction(config) {
const processor = await createMarkdownProcessor(config.markdown);
return async function renderToString(entry) {
if (!entry.body) {
return {
Expand Down
Loading