Skip to content
Open
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
7 changes: 7 additions & 0 deletions packages/docusaurus-mdx-loader/src/options.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,13 @@ export type Options = Partial<MDXOptions> & {
frontMatter: {[key: string]: unknown};
}) => {[key: string]: unknown};
resolveMarkdownLink?: ResolveMarkdownLink;
/**
* Fallback used when `resolveMarkdownLink` can't resolve a Markdown link.
* It looks at the Markdown files of the whole site, not just those of the
* plugin owning the source file, and enables cross-plugin Markdown links.
* See https://github.com/facebook/docusaurus/issues/9117
*/
resolveSiteMarkdownLink?: ResolveMarkdownLink;
// Options passed to remark-mdx (only for the 'mdx' format)
// Replaces our default {acornOptions: {ecmaVersion: 2025, sourceType: 'module'}}
remarkMdxOptions?: RemarkMdxOptions;
Expand Down
3 changes: 2 additions & 1 deletion packages/docusaurus-mdx-loader/src/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,11 +148,12 @@ function createProcessorUncached({
} satisfies TransformImageOptions,
],
// TODO merge this with transformLinks?
options.resolveMarkdownLink
options.resolveMarkdownLink || options.resolveSiteMarkdownLink
? [
resolveMarkdownLinks,
{
resolveMarkdownLink: options.resolveMarkdownLink,
resolveSiteMarkdownLink: options.resolveSiteMarkdownLink,
onBrokenMarkdownLinks:
options.markdownConfig.hooks.onBrokenMarkdownLinks,
} satisfies ResolveMarkdownLinksOptions,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,70 @@ this is a code block
`);
});

describe('resolveSiteMarkdownLink', () => {
const resolveSiteMarkdownLink: PluginOptions['resolveSiteMarkdownLink'] = ({
linkPathname,
}) => `/SITE-RESOLVED---${linkPathname}`;

it('is used as a fallback when the plugin can not resolve the link', async () => {
/* language=markdown */
const content = `[link1](link1.mdx)`;

const result = await process(content, {
resolveMarkdownLink: () => null,
resolveSiteMarkdownLink,
});

expect(result).toMatchInlineSnapshot(`
"[link1](/SITE-RESOLVED---link1.mdx)
"
`);
});

it('is not used when the plugin resolves the link', async () => {
/* language=markdown */
const content = `[link1](link1.mdx)`;

const result = await process(content, {resolveSiteMarkdownLink});

expect(result).toMatchInlineSnapshot(`
"[link1](/RESOLVED---link1.mdx)
"
`);
});

it('is used when the plugin does not provide any resolver', async () => {
/* language=markdown */
const content = `[link1](link1.mdx)`;

const result = await process(content, {
resolveMarkdownLink: undefined,
resolveSiteMarkdownLink,
});

expect(result).toMatchInlineSnapshot(`
"[link1](/SITE-RESOLVED---link1.mdx)
"
`);
});

it('reports a broken link when no resolver can resolve the link', async () => {
/* language=markdown */
const content = `[link1](link1.mdx)`;

await expect(() =>
process(content, {
resolveMarkdownLink: () => null,
resolveSiteMarkdownLink: () => null,
}),
).rejects.toThrowErrorMatchingInlineSnapshot(`
[Error: Markdown link with URL \`link1.mdx\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" (1:1) couldn't be resolved.
Make sure it references a local Markdown file that exists within the site.
To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs.]
`);
});
});

describe('onBrokenMarkdownLinks', () => {
async function processResolutionErrors(
content: string,
Expand All @@ -201,7 +265,7 @@ this is a code block
await expect(() => processResolutionErrors(content)).rejects
.toThrowErrorMatchingInlineSnapshot(`
[Error: Markdown link with URL \`link1.mdx\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" (1:1) couldn't be resolved.
Make sure it references a local Markdown file that exists within the current plugin.
Make sure it references a local Markdown file that exists within the site.
To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs.]
`);
});
Expand All @@ -213,7 +277,7 @@ this is a code block
await expect(() => processResolutionErrors(content)).rejects
.toThrowErrorMatchingInlineSnapshot(`
[Error: Markdown link with URL \`link1.md\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" (1:1) couldn't be resolved.
Make sure it references a local Markdown file that exists within the current plugin.
Make sure it references a local Markdown file that exists within the site.
To ignore this error, use the \`siteConfig.markdown.hooks.onBrokenMarkdownLinks\` option, or apply the \`pathname://\` protocol to the broken link URLs.]
`);
});
Expand Down Expand Up @@ -252,11 +316,11 @@ this is a code block
[
[
"[WARNING] Markdown link with URL \`link1.mdx\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" (2:1) couldn't be resolved.
Make sure it references a local Markdown file that exists within the current plugin.",
Make sure it references a local Markdown file that exists within the site.",
],
[
"[WARNING] Markdown link with URL \`dir/link3.md\` in source file "packages/docusaurus-mdx-loader/src/remark/resolveMarkdownLinks/__tests__/docs/myFile.mdx" (6:1) couldn't be resolved.
Make sure it references a local Markdown file that exists within the current plugin.",
Make sure it references a local Markdown file that exists within the site.",
],
]
`);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,17 @@ export type ResolveMarkdownLink = (
) => string | null;

export interface PluginOptions {
resolveMarkdownLink: ResolveMarkdownLink;
/**
* Resolves the link against the Markdown files of the plugin owning the
* source file. It has priority over `resolveSiteMarkdownLink`.
*/
resolveMarkdownLink?: ResolveMarkdownLink;
/**
* Resolves the link against the Markdown files of the whole site, whatever
* plugin owns them. Used as a fallback, to support cross-plugin links.
* See https://github.com/facebook/docusaurus/issues/9117
*/
resolveSiteMarkdownLink?: ResolveMarkdownLink;
onBrokenMarkdownLinks: MarkdownConfig['hooks']['onBrokenMarkdownLinks'];
}

Expand All @@ -58,7 +68,7 @@ function asFunction(
)`Markdown link with URL code=${linkUrl} in source file path=${relativePath}${formatNodePositionExtraMessage(
node,
)} couldn't be resolved.
Make sure it references a local Markdown file that exists within the current plugin.${extraHelp}`;
Make sure it references a local Markdown file that exists within the site.${extraHelp}`;
};
} else {
return (params) =>
Expand Down Expand Up @@ -97,7 +107,7 @@ function parseMarkdownLinkURLPath(link: string): URLPath | null {
const plugin: Plugin<PluginOptions[], Root> = function plugin(
options,
): Transformer<Root> {
const {resolveMarkdownLink} = options;
const {resolveMarkdownLink, resolveSiteMarkdownLink} = options;

const onBrokenMarkdownLinks = asFunction(options.onBrokenMarkdownLinks);

Expand All @@ -111,10 +121,17 @@ const plugin: Plugin<PluginOptions[], Root> = function plugin(

const sourceFilePath = file.path;

const permalink = resolveMarkdownLink({
const resolveParams = {
sourceFilePath,
linkPathname: linkURLPath.pathname,
});
};

// The plugin owning the source file resolves its own links in priority
// We only fall back to the site-wide registry for cross-plugin links
const permalink =
resolveMarkdownLink?.(resolveParams) ??
resolveSiteMarkdownLink?.(resolveParams) ??
null;

if (permalink) {
// This reapplies the link ?qs#hash part to the resolved pathname
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -124,6 +124,10 @@ const getPlugin = async (
generatedFilesDir,
i18n,
localizationDir,
siteMarkdownLinks: {
sourceToPermalink: new Map(),
resolveMarkdownLink: () => null,
},
} as LoadContext,
validateOptions({
validate: normalizePluginOptions as Validate<
Expand Down
2 changes: 2 additions & 0 deletions packages/docusaurus-plugin-content-blog/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@ export default async function pluginContentBlog(
siteConfig,
generatedFilesDir,
localizationDir,
siteMarkdownLinks,
i18n: {currentLocale},
} = context;

Expand Down Expand Up @@ -166,6 +167,7 @@ export default async function pluginContentBlog(
contentPaths,
});
},
resolveSiteMarkdownLink: siteMarkdownLinks.resolveMarkdownLink,
});

function createBlogMarkdownLoader(): RuleSetUseItem {
Expand Down
4 changes: 3 additions & 1 deletion packages/docusaurus-plugin-content-docs/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,8 @@ export default async function pluginContentDocs(
context: LoadContext,
options: PluginOptions,
): Promise<Plugin<LoadedContent>> {
const {siteDir, generatedFilesDir, baseUrl, siteConfig} = context;
const {siteDir, generatedFilesDir, baseUrl, siteConfig, siteMarkdownLinks} =
context;
// Mutate options to resolve sidebar path according to siteDir
options.sidebarPath = resolveSidebarPathOption(siteDir, options.sidebarPath);

Expand Down Expand Up @@ -171,6 +172,7 @@ export default async function pluginContentDocs(
contentPaths: version,
});
},
resolveSiteMarkdownLink: siteMarkdownLinks.resolveMarkdownLink,
},
});
}
Expand Down
3 changes: 2 additions & 1 deletion packages/docusaurus-plugin-content-pages/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export default function pluginContentPages(
context: LoadContext,
options: PluginOptions,
): Plugin<LoadedContent | null> {
const {siteConfig, siteDir, generatedFilesDir} = context;
const {siteConfig, siteDir, generatedFilesDir, siteMarkdownLinks} = context;

const contentPaths = createPagesContentPaths({context, options});
const contentHelpers = createContentHelpers();
Expand Down Expand Up @@ -92,6 +92,7 @@ export default function pluginContentPages(
contentPaths,
});
},
resolveSiteMarkdownLink: siteMarkdownLinks.resolveMarkdownLink,
},
});
}
Expand Down
41 changes: 41 additions & 0 deletions packages/docusaurus-types/src/context.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,41 @@ export type SiteStorage = {

export type GlobalData = {[pluginName: string]: {[pluginId: string]: unknown}};

/**
* A site-wide registry of the Markdown files of all the content plugins.
*
* Content plugins own a registry of their own Markdown files, and use it to
* resolve the Markdown links found in their own content. This site-wide
* registry is the fallback used when a Markdown link can't be resolved within
* the plugin owning the source file, and permits cross-plugin Markdown links.
*
* See https://github.com/facebook/docusaurus/issues/9117
*/
export type SiteMarkdownLinks = {
/**
* Aliased source file path (`@site/docs/intro.mdx`) to permalink (`/docs/
* intro`) of all the Markdown files of the site, whatever plugin owns them.
*
* /!\ This map is mutable: it is emptied and refilled on each site reload.
* The identity of the `SiteMarkdownLinks` object holding it remains stable
* for the whole dev server lifetime, because the MDX loader receives it
* through `configureWebpack()`, which only runs once.
*/
sourceToPermalink: Map<string, string>;

/**
* Resolves a Markdown link pathname against `sourceToPermalink`, looking at
* the Markdown files of the whole site. Returns `null` when the link can't
* be resolved to any Markdown file of the site.
*/
resolveMarkdownLink: (params: {
/** Absolute path of the source file containing the Markdown link. */
sourceFilePath: string;
/** The link pathname to resolve, such as `./intro.mdx`. */
linkPathname: string;
}) => string | null;
};

export type LoadContext = {
siteDir: string;
siteVersion: string | undefined;
Expand Down Expand Up @@ -80,6 +115,12 @@ export type LoadContext = {
* The bundler used to build the site (Webpack or Rspack)
*/
currentBundler: CurrentBundler;

/**
* Site-wide Markdown files registry, used by content plugins as a fallback
* to resolve Markdown links pointing to files owned by other plugins.
*/
siteMarkdownLinks: SiteMarkdownLinks;
};

export type Props = LoadContext & {
Expand Down
1 change: 1 addition & 0 deletions packages/docusaurus-types/src/index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ export {
GlobalData,
LoadContext,
SiteStorage,
SiteMarkdownLinks,
Props,
} from './context';

Expand Down
Loading