An open source design system that's fully customizable and agent ready
TypeScript
feat(Markdown): read what a plugin declares, and render one plugin node as Markdown does (#7036)
Cindy Zhangb421f01f1f5b
diff --git a/.changeset/markdown-plugin-node-renderer.md b/.changeset/markdown-plugin-node-renderer.mdnew file mode 100644index 0000000000..e951f82de8--- /dev/null+++ b/.changeset/markdown-plugin-node-renderer.md@@ -0,0 +1,8 @@+---+'@astryxdesign/core': patch+---++[feat] Markdown plugins: read what a plugin declares, and render one plugin node as Markdown does+@cixzhang++`getMarkdownPluginCapabilities(plugin)`, from `@astryxdesign/core/Markdown/plugins`, reports whether a plugin declares syntax and whether it declares a transform, and nothing else; plugin entries stay opaque. `MarkdownPluginNodeRenderer`, from the new client-only `@astryxdesign/core/Markdown/plugin-renderer` subpath, renders one parsed extension node with the given plugins exactly as `Markdown` presents it — the plugin's renderer inside the same error boundary and suspense fallback, the same readable fallback text, and the same failure report — with no element of its own. `Markdown`'s own output is unchanged.diff --git a/internal/eslint-plugin-astryx/shared.js b/internal/eslint-plugin-astryx/shared.jsindex 46ac1f3879..a16c1aadb5 100644--- a/internal/eslint-plugin-astryx/shared.js+++ b/internal/eslint-plugin-astryx/shared.js@@ -33,6 +33,8 @@ export const COMPONENT_RULE_ALLOWED = new Set(['LinkProviderProps','MediaThemeProps','InternationalizationProviderProps',+ // Renders one Markdown plugin node with no element of its own (spec:AST-064)+ 'MarkdownPluginNodeRendererProps',// Hook return-value / editor-config prop bags — not DOM-component props'OverlayContainerProps','PowerSearchEditorProps',diff --git a/packages/core/package.json b/packages/core/package.jsonindex 22c7849b0f..da63735166 100644--- a/packages/core/package.json+++ b/packages/core/package.json@@ -634,6 +634,11 @@"types": "./dist/Markdown/plugins/index.d.ts","default": "./dist/Markdown/plugins/index.js"},+ "./Markdown/plugin-renderer": {+ "source": "./src/Markdown/plugin-renderer/index.ts",+ "types": "./dist/Markdown/plugin-renderer/index.d.ts",+ "default": "./dist/Markdown/plugin-renderer/index.js"+ },"./Markdown/parser": {"source": "./src/Markdown/parser/index.ts","types": "./dist/Markdown/parser/index.d.ts",diff --git a/packages/core/src/Markdown/Markdown.doc.mjs b/packages/core/src/Markdown/Markdown.doc.mjsindex b3b41adad6..a0bdf568af 100644--- a/packages/core/src/Markdown/Markdown.doc.mjs+++ b/packages/core/src/Markdown/Markdown.doc.mjs@@ -252,6 +252,11 @@ export const docs = {description:'Use plugins created by createMarkdownPlugin for reusable syntax, immutable AST transforms, and typed extension rendering. Keep the ordered list stable while its syntax configuration is unchanged.',},+ {+ guidance: true,+ description:+ 'To render a plugin node outside Markdown, as another surface showing the same document does, read what the plugin declares with getMarkdownPluginCapabilities (syntax and transform, nothing else), and render each parsed extension node with MarkdownPluginNodeRenderer from the client-only @astryxdesign/core/Markdown/plugin-renderer subpath. It presents the node exactly as Markdown does, fallbacks and failure reports included, with no element of its own.',+ },{guidance: true,description:@@ -762,6 +767,11 @@ export const docsZh = {description:'Use plugins created by createMarkdownPlugin for reusable syntax, immutable AST transforms, and typed extension rendering. Keep the ordered list stable while its syntax configuration is unchanged.',},+ {+ guidance: true,+ description:+ 'To render a plugin node outside Markdown, as another surface showing the same document does, read what the plugin declares with getMarkdownPluginCapabilities (syntax and transform, nothing else), and render each parsed extension node with MarkdownPluginNodeRenderer from the client-only @astryxdesign/core/Markdown/plugin-renderer subpath. It presents the node exactly as Markdown does, fallbacks and failure reports included, with no element of its own.',+ },{guidance: true,description:@@ -854,6 +864,11 @@ export const docsDense = {description:'Use plugins created by createMarkdownPlugin for reusable syntax, immutable AST transforms, and typed extension rendering. Keep the ordered list stable while its syntax configuration is unchanged.',},+ {+ guidance: true,+ description:+ 'To render a plugin node outside Markdown, as another surface showing the same document does, read what the plugin declares with getMarkdownPluginCapabilities (syntax and transform, nothing else), and render each parsed extension node with MarkdownPluginNodeRenderer from the client-only @astryxdesign/core/Markdown/plugin-renderer subpath. It presents the node exactly as Markdown does, fallbacks and failure reports included, with no element of its own.',+ },{guidance: true,description:diff --git a/packages/core/src/Markdown/Markdown.tsx b/packages/core/src/Markdown/Markdown.tsxindex de9df45214..e88f46b640 100644--- a/packages/core/src/Markdown/Markdown.tsx+++ b/packages/core/src/Markdown/Markdown.tsx@@ -9,7 +9,7 @@* @position Core implementation; renders markdown as Astryx components*/-import {Component, Suspense, useMemo, useRef} from 'react';+import {Suspense, useMemo, useRef} from 'react';import type React from 'react';import {Fragment} from 'react';import * as stylex from '@stylexjs/stylex';@@ -70,6 +70,10 @@ import {reportMarkdownPluginFailure,} from './plugins/protocol';import {getMarkdownFenceProposal} from './plugins/semanticFence';+import {+ MarkdownPluginBoundary,+ renderMarkdownPluginNode,+} from './plugin-renderer/MarkdownPluginNodeRenderer';import type {MarkdownExtensionNode,MarkdownPluginEntry,@@ -787,57 +791,6 @@ function applyInlinePlugins(return segments;}-interface MarkdownPluginBoundaryProps {- children: React.ReactNode;- fallback: React.ReactNode;- pluginName: string;- resetKey: unknown;- resetRenderer: unknown;-}--interface MarkdownPluginBoundaryState {- failed: boolean;- resetKey: unknown;- resetRenderer: unknown;-}--class MarkdownPluginBoundary extends Component<- MarkdownPluginBoundaryProps,- MarkdownPluginBoundaryState-> {- state: MarkdownPluginBoundaryState = {- failed: false,- resetKey: this.props.resetKey,- resetRenderer: this.props.resetRenderer,- };-- static getDerivedStateFromError(): Partial<MarkdownPluginBoundaryState> {- return {failed: true};- }-- static getDerivedStateFromProps(- props: MarkdownPluginBoundaryProps,- state: MarkdownPluginBoundaryState,- ): Partial<MarkdownPluginBoundaryState> | null {- return props.resetKey === state.resetKey &&- props.resetRenderer === state.resetRenderer- ? null- : {- failed: false,- resetKey: props.resetKey,- resetRenderer: props.resetRenderer,- };- }-- componentDidCatch(error: unknown): void {- reportMarkdownPluginFailure(this.props.pluginName, 'render', error);- }-- render(): React.ReactNode {- return this.state.failed ? this.props.fallback : this.props.children;- }-}-function useStableMarkdownSyntaxEntries(plugins: PreparedMarkdownPlugins | undefined,): ReadonlyArray<MarkdownPluginEntry> | undefined {@@ -1139,34 +1092,17 @@ function renderInline(/>);}- case 'extension': {- const renderer = getMarkdownExtensionRenderer(preparedPlugins, node);- const fallback = wrapTextWithFade(- node.source ?? markdownExtensionText(preparedPlugins, node),- cursor,+ case 'extension':+ return renderMarkdownPluginNode(+ preparedPlugins,+ node,+ wrapTextWithFade(+ node.source ?? markdownExtensionText(preparedPlugins, node),+ cursor,+ index,+ ),index,);- if (renderer == null) {- return fallback;- }- let rendered: React.ReactNode;- try {- rendered = renderer.render({node});- } catch (error) {- reportMarkdownPluginFailure(node.plugin, 'render', error);- return fallback;- }- return (- <MarkdownPluginBoundary- key={index}- pluginName={node.plugin}- resetKey={node}- resetRenderer={renderer.render}- fallback={fallback}>- <Suspense fallback={fallback}>{rendered}</Suspense>- </MarkdownPluginBoundary>- );- }case 'break':cursor.offset += 1;return <br key={index} />;@@ -1896,27 +1832,15 @@ function renderBlock();}case 'extension': {- const renderer = getMarkdownExtensionRenderer(preparedPlugins, node);- const fallbackText =- node.source ?? markdownExtensionText(preparedPlugins, node);- const fallback = wrapTextWithFade(fallbackText, cursor, index);- let content: React.ReactNode = fallback;- if (renderer != null) {- try {- const rendered = renderer.render({node});- content = (- <MarkdownPluginBoundary- pluginName={node.plugin}- resetKey={node}- resetRenderer={renderer.render}- fallback={fallback}>- <Suspense fallback={fallback}>{rendered}</Suspense>- </MarkdownPluginBoundary>- );- } catch (error) {- reportMarkdownPluginFailure(node.plugin, 'render', error);- }- }+ const content = renderMarkdownPluginNode(+ preparedPlugins,+ node,+ wrapTextWithFade(+ node.source ?? markdownExtensionText(preparedPlugins, node),+ cursor,+ index,+ ),+ );return (<divkey={index}diff --git a/packages/core/src/Markdown/parser.public.test.ts b/packages/core/src/Markdown/parser.public.test.tsindex c6ed04dd08..396b7d1c1e 100644--- a/packages/core/src/Markdown/parser.public.test.ts+++ b/packages/core/src/Markdown/parser.public.test.ts@@ -13,6 +13,7 @@ import {describe, expect, expectTypeOf, it} from 'vitest';import {createMarkdownFrontmatter,createMarkdownPlugin,+ getMarkdownPluginCapabilities,} from '@astryxdesign/core/Markdown/plugins';import {createIncrementalState,@@ -64,6 +65,36 @@ describe('@astryxdesign/core/Markdown/parser', () => {}});+ it('reports plugin capabilities from the server-safe plugin entry, and renders one node only from the client-only renderer entry (spec:AST-064 DEC-6)', () => {+ const packageJson = JSON.parse(+ readFileSync(join(process.cwd(), 'packages/core/package.json'), 'utf8'),+ ) as {+ exports: Record<string, unknown>;+ };+ expect(packageJson.exports['./Markdown/plugin-renderer']).toEqual({+ source: './src/Markdown/plugin-renderer/index.ts',+ types: './dist/Markdown/plugin-renderer/index.d.ts',+ default: './dist/Markdown/plugin-renderer/index.js',+ });+ for (const path of [+ 'packages/core/src/Markdown/plugin-renderer/index.ts',+ 'packages/core/src/Markdown/plugin-renderer/MarkdownPluginNodeRenderer.tsx',+ ]) {+ expect(readFileSync(join(process.cwd(), path), 'utf8')).toMatch(+ /^(?:\/\/[^\n]*\n|\s)*['"]use client['"]/,+ );+ }+ const transformOnly = createMarkdownPlugin({+ name: 'server-capabilities',+ apiVersion: 1,+ transform: root => root,+ });+ expect(getMarkdownPluginCapabilities(transformOnly)).toEqual({+ syntax: false,+ transform: true,+ });+ });+it('exposes legacy and canonical parser results from a server-only entry point', () => {const source = '# Heading\n\nParagraph';const blockAst = parseMarkdownAst(source);diff --git a/packages/core/src/Markdown/plugin-renderer/MarkdownPluginNodeRenderer.test.tsx b/packages/core/src/Markdown/plugin-renderer/MarkdownPluginNodeRenderer.test.tsxnew file mode 100644index 0000000000..4449c7a69f--- /dev/null+++ b/packages/core/src/Markdown/plugin-renderer/MarkdownPluginNodeRenderer.test.tsx@@ -0,0 +1,300 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file MarkdownPluginNodeRenderer.test.tsx+ * @input Renders extension nodes through Markdown and MarkdownPluginNodeRenderer+ * @output Proves the single-node renderer renders a node exactly as Markdown+ * does — output, nothing, fallbacks, and failure reports — with no element+ * of its own (spec:AST-064 FR8, DEC-6)+ */++import {render} from '@testing-library/react';+import {describe, expect, it, vi} from 'vitest';+import {Markdown} from '../Markdown';+import {parseInlineAst, parseMarkdownAst} from '../parser';+import {createMarkdownPlugin} from '../plugins/protocol';+import type {+ MarkdownExtensionNode,+ MarkdownPluginEntry,+} from '../plugins/protocol';+import {MarkdownPluginNodeRenderer} from './index';++type ProbeNode = MarkdownExtensionNode<+ string,+ 'probe',+ {readonly label: string},+ 'inline'+>;+type BlockProbeNode = MarkdownExtensionNode<+ string,+ 'probe',+ {readonly label: string},+ 'block'+>;++function ThrowingChild(): never {+ throw new Error('broken probe child');+}++const neverSettles = new Promise<never>(() => {});+function Suspending(): never {+ // Suspense's protocol: a component suspends by throwing a promise.+ // eslint-disable-next-line @typescript-eslint/only-throw-error+ throw neverSettles;+}++/** A plugin whose renderer does what each node's label says. */+function probePlugin(name: string): MarkdownPluginEntry<ProbeNode> {+ return createMarkdownPlugin<string, ProbeNode>({+ name,+ apiVersion: 1,+ parseKey: 'v1',+ syntax: {+ inline: [+ {+ startsWith: ['@{'],+ maxSpan: 40,+ tokenize({source, offset, end}) {+ const close = source.indexOf('}', offset + 2);+ if (close < 0 || close >= end) {+ return {status: 'no-match'};+ }+ return {+ status: 'match',+ end: close + 1,+ node: {+ type: 'extension',+ plugin: name,+ name: 'probe',+ display: 'inline',+ data: {label: source.slice(offset + 2, close)},+ },+ };+ },+ },+ ],+ },+ renderers: {+ probe: {+ render: ({node}) => {+ switch (node.data.label) {+ case 'nothing':+ return null;+ case 'throw':+ throw new Error('broken probe');+ case 'child':+ return <ThrowingChild />;+ case 'suspend':+ return <Suspending />;+ default:+ return <mark data-probe="">{node.data.label}</mark>;+ }+ },+ toText: node => `probe ${node.data.label}`,+ },+ },+ });+}++/** A block plugin whose renderer does what each node's label says. */+function blockProbePlugin(name: string): MarkdownPluginEntry<BlockProbeNode> {+ return createMarkdownPlugin<string, BlockProbeNode>({+ name,+ apiVersion: 1,+ parseKey: 'v1',+ syntax: {+ block: [+ {+ startsWith: [':::'],+ maxSpan: 40,+ tokenize({source, offset, end}) {+ const lineEnd = source.indexOf('\n', offset);+ const stop = lineEnd < 0 || lineEnd > end ? end : lineEnd;+ return {+ status: 'match',+ end: stop,+ node: {+ type: 'extension',+ plugin: name,+ name: 'probe',+ display: 'block',+ data: {label: source.slice(offset + 3, stop)},+ },+ };+ },+ },+ ],+ },+ renderers: {+ probe: {+ render: ({node}) => {+ switch (node.data.label) {+ case 'nothing':+ return null;+ case 'throw':+ throw new Error('broken block probe');+ case 'child':+ return <ThrowingChild />;+ case 'suspend':+ return <Suspending />;+ default:+ return <aside data-probe="">{node.data.label}</aside>;+ }+ },+ toText: node => `block probe ${node.data.label}`,+ },+ },+ });+}++/** What Markdown renders for a block `source` inside its block wrapper. */+function markdownBlockOutput(+ source: string,+ plugin: MarkdownPluginEntry,+): string {+ const {container, unmount} = render(+ <Markdown plugins={[plugin]}>{source}</Markdown>,+ );+ const wrapper = container.firstElementChild?.firstElementChild;+ const html = wrapper?.innerHTML ?? '';+ unmount();+ return html;+}++/** The one block extension node `source` parses to with `plugin`. */+function blockNodeOf(+ source: string,+ plugin: MarkdownPluginEntry,+): BlockProbeNode {+ const [node] = parseMarkdownAst(source, {plugins: [plugin]}).children;+ if (node?.type !== 'extension') {+ throw new Error(`${source} did not parse to a block extension node`);+ }+ return node as BlockProbeNode;+}++/** The one extension node `source` parses to with `plugin`. */+function nodeOf(source: string, plugin: MarkdownPluginEntry): ProbeNode {+ const [node] = parseInlineAst(source, {plugins: [plugin]});+ if (node?.type !== 'extension') {+ throw new Error(`${source} did not parse to an extension node`);+ }+ return node as ProbeNode;+}++/** What Markdown renders for `source` inside its inline root. */+function markdownOutput(source: string, plugin: MarkdownPluginEntry): string {+ const {container, unmount} = render(+ <Markdown display="inline" plugins={[plugin]}>+ {source}+ </Markdown>,+ );+ const html = container.firstElementChild?.innerHTML ?? '';+ unmount();+ return html;+}++function nodeRendererOutput(+ node: ProbeNode | BlockProbeNode,+ plugins: ReadonlyArray<MarkdownPluginEntry>,+): string {+ const {container, unmount} = render(+ <MarkdownPluginNodeRenderer plugins={plugins} node={node} />,+ );+ const html = container.innerHTML;+ unmount();+ return html;+}++describe('MarkdownPluginNodeRenderer', () => {+ it.each([+ ['content', '@{content}', '<mark data-probe="">content</mark>'],+ ['nothing', '@{nothing}', ''],+ ['a renderer that throws when called', '@{throw}', '@{throw}'],+ ['a renderer whose component throws', '@{child}', '@{child}'],+ ['a renderer that suspends', '@{suspend}', '@{suspend}'],+ ])(+ 'renders %s exactly as Markdown does, with no element of its own',+ (_, source, expected) => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ const plugin = probePlugin(`probe-${source}`);+ const node = nodeOf(source, plugin);+ expect(markdownOutput(source, plugin)).toBe(expected);+ expect(nodeRendererOutput(node, [plugin])).toBe(expected);+ } finally {+ warn.mockRestore();+ error.mockRestore();+ }+ },+ );++ it.each([+ ['content', ':::content', '<aside data-probe="">content</aside>'],+ ['nothing', ':::nothing', ''],+ ['a renderer that throws when called', ':::throw', ':::throw'],+ ['a renderer whose component throws', ':::child', ':::child'],+ ['a renderer that suspends', ':::suspend', ':::suspend'],+ ])(+ 'renders a block node with %s exactly as Markdown does below its block wrapper',+ (_, source, expected) => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ const plugin = blockProbePlugin(`block-probe-${source}`);+ const node = blockNodeOf(source, plugin);+ expect(markdownBlockOutput(source, plugin)).toBe(expected);+ expect(nodeRendererOutput(node, [plugin])).toBe(expected);+ } finally {+ warn.mockRestore();+ error.mockRestore();+ }+ },+ );++ it("shows a sourceless block node's text as Markdown would", () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const plugin = blockProbePlugin('block-probe-fallbacks');+ const {source: _source, ...withoutSource} = blockNodeOf(+ ':::throw',+ plugin,+ );+ expect(nodeRendererOutput(withoutSource, [plugin])).toBe(+ 'block probe throw',+ );+ } finally {+ warn.mockRestore();+ }+ });++ it('reports a failure as Markdown does', () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ const error = vi.spyOn(console, 'error').mockImplementation(() => {});+ try {+ const plugin = probePlugin('probe-report');+ nodeRendererOutput(nodeOf('@{throw}', plugin), [plugin]);+ expect(JSON.stringify(warn.mock.calls)).toContain(+ 'plugin \\"probe-report\\" failed in render; rendered readable fallback.',+ );+ } finally {+ warn.mockRestore();+ error.mockRestore();+ }+ });++ it("shows the plugin's text for a node with no source, and the source without the plugin", () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});+ try {+ const plugin = probePlugin('probe-fallbacks');+ const {source: _source, ...withoutSource} = nodeOf('@{throw}', plugin);+ expect(nodeRendererOutput(withoutSource, [plugin])).toBe('probe throw');+ expect(nodeRendererOutput(nodeOf('@{content}', plugin), [])).toBe(+ '@{content}',+ );+ } finally {+ warn.mockRestore();+ }+ });+});diff --git a/packages/core/src/Markdown/plugin-renderer/MarkdownPluginNodeRenderer.tsx b/packages/core/src/Markdown/plugin-renderer/MarkdownPluginNodeRenderer.tsxnew file mode 100644index 0000000000..5ae9a33d56--- /dev/null+++ b/packages/core/src/Markdown/plugin-renderer/MarkdownPluginNodeRenderer.tsx@@ -0,0 +1,155 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file MarkdownPluginNodeRenderer.tsx+ * @input Uses React (Component, Suspense, useMemo) and the plugin protocol's+ * preparation, renderer lookup, text projection, and failure reporting.+ * @output Exports MarkdownPluginNodeRenderer, which renders one parsed+ * extension node with the given plugins; renderMarkdownPluginNode, the one+ * rendering path Markdown and MarkdownPluginNodeRenderer share; and+ * MarkdownPluginBoundary, the error boundary both, and Markdown's semantic+ * fences, render plugin output inside.+ * @position Client-only entry `@astryxdesign/core/Markdown/plugin-renderer`.+ * `Markdown` renders every extension node through renderMarkdownPluginNode,+ * so a surface that renders a node with MarkdownPluginNodeRenderer — the+ * RichText surfaces do — renders it exactly as `Markdown` does: the plugin's+ * renderer inside an error boundary and a suspense fallback, the node's+ * readable text when it fails, and the same failure report. It adds no+ * element or theme target of its own (spec:AST-064 FR8, DEC-6).+ */++import {Component, Suspense, useMemo, type JSX, type ReactNode} from 'react';+import {+ getMarkdownExtensionRenderer,+ markdownExtensionText,+ prepareMarkdownPlugins,+ reportMarkdownPluginFailure,+ type MarkdownExtensionNode,+ type MarkdownPluginEntry,+ type PreparedMarkdownPlugins,+} from '../plugins/protocol';++interface MarkdownPluginBoundaryProps {+ children: ReactNode;+ fallback: ReactNode;+ pluginName: string;+ resetKey: unknown;+ resetRenderer: unknown;+}++interface MarkdownPluginBoundaryState {+ failed: boolean;+ resetKey: unknown;+ resetRenderer: unknown;+}++/**+ * @internal The error boundary around a plugin's rendered output: shows+ * `fallback` and reports a render failure when the output throws, and tries+ * again when the node or its renderer changes. Markdown's semantic fences use+ * it too.+ */+export class MarkdownPluginBoundary extends Component<+ MarkdownPluginBoundaryProps,+ MarkdownPluginBoundaryState+> {+ state: MarkdownPluginBoundaryState = {+ failed: false,+ resetKey: this.props.resetKey,+ resetRenderer: this.props.resetRenderer,+ };++ static getDerivedStateFromError(): Partial<MarkdownPluginBoundaryState> {+ return {failed: true};+ }++ static getDerivedStateFromProps(+ props: MarkdownPluginBoundaryProps,+ state: MarkdownPluginBoundaryState,+ ): Partial<MarkdownPluginBoundaryState> | null {+ return props.resetKey === state.resetKey &&+ props.resetRenderer === state.resetRenderer+ ? null+ : {+ failed: false,+ resetKey: props.resetKey,+ resetRenderer: props.resetRenderer,+ };+ }++ componentDidCatch(error: unknown): void {+ reportMarkdownPluginFailure(this.props.pluginName, 'render', error);+ }++ render(): ReactNode {+ return this.state.failed ? this.props.fallback : this.props.children;+ }+}++/**+ * @internal Renders one extension node the way `Markdown` does: `fallback`+ * when no renderer owns the node or the renderer throws when called, and+ * otherwise the renderer's output inside an error boundary and a suspense+ * fallback that both show `fallback`.+ */+export function renderMarkdownPluginNode<Fallback extends ReactNode>(+ plugins: PreparedMarkdownPlugins | undefined,+ node: MarkdownExtensionNode,+ fallback: Fallback,+ key?: string | number,+): Fallback | JSX.Element {+ const renderer = getMarkdownExtensionRenderer(plugins, node);+ if (renderer == null) {+ return fallback;+ }+ let rendered: ReactNode;+ try {+ rendered = renderer.render({node});+ } catch (error) {+ reportMarkdownPluginFailure(node.plugin, 'render', error);+ return fallback;+ }+ return (+ <MarkdownPluginBoundary+ key={key}+ pluginName={node.plugin}+ resetKey={node}+ resetRenderer={renderer.render}+ fallback={fallback}>+ <Suspense fallback={fallback}>{rendered}</Suspense>+ </MarkdownPluginBoundary>+ );+}++export interface MarkdownPluginNodeRendererProps {+ /** The plugins the node was parsed with, as passed to `Markdown`. */+ readonly plugins: ReadonlyArray<MarkdownPluginEntry>;+ /** One extension node from a parse with those plugins. */+ readonly node: MarkdownExtensionNode;+}++/**+ * Renders one parsed extension node exactly as `Markdown` renders it, with no+ * element of its own. When no plugin renders the node, it shows the node's+ * source, or its plugin's text projection for a node with no source.+ */+export function MarkdownPluginNodeRenderer({+ plugins,+ node,+}: MarkdownPluginNodeRendererProps): ReactNode {+ const prepared = useMemo(() => {+ try {+ return prepareMarkdownPlugins(plugins);+ } catch (error) {+ reportMarkdownPluginFailure('configuration', 'transform', error);+ return undefined;+ }+ }, [plugins]);+ return renderMarkdownPluginNode(+ prepared,+ node,+ node.source ?? markdownExtensionText(prepared, node),+ );+}diff --git a/packages/core/src/Markdown/plugin-renderer/index.ts b/packages/core/src/Markdown/plugin-renderer/index.tsnew file mode 100644index 0000000000..5e647cb85b--- /dev/null+++ b/packages/core/src/Markdown/plugin-renderer/index.ts@@ -0,0 +1,13 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++'use client';++/**+ * @file index.ts+ * @output Public single-node renderer for Markdown plugin extension nodes+ * @position Client-only subpath entry point:+ * `@astryxdesign/core/Markdown/plugin-renderer`+ */++export {MarkdownPluginNodeRenderer} from './MarkdownPluginNodeRenderer';+export type {MarkdownPluginNodeRendererProps} from './MarkdownPluginNodeRenderer';diff --git a/packages/core/src/Markdown/plugins/index.ts b/packages/core/src/Markdown/plugins/index.tsindex 234db27951..de5aad7dc7 100644--- a/packages/core/src/Markdown/plugins/index.ts+++ b/packages/core/src/Markdown/plugins/index.ts@@ -6,7 +6,11 @@* @position Subpath entry point: `@astryxdesign/core/Markdown/plugins`*/-export {createMarkdownPlugin, isMarkdownExtensionNode} from './protocol';+export {+ createMarkdownPlugin,+ getMarkdownPluginCapabilities,+ isMarkdownExtensionNode,+} from './protocol';export {createMarkdownTextTransform} from './textTransform';export type {MarkdownTextTransformContext,@@ -37,6 +41,7 @@ export type {MarkdownFrontmatterParseResult,} from './frontmatter';export type {+ MarkdownPluginCapabilities,MarkdownPluginData,MarkdownExtensionNode,MarkdownTokenizerInput,diff --git a/packages/core/src/Markdown/plugins/protocol.test.tsx b/packages/core/src/Markdown/plugins/protocol.test.tsxindex dbf72a53dd..5d589aaec4 100644--- a/packages/core/src/Markdown/plugins/protocol.test.tsx+++ b/packages/core/src/Markdown/plugins/protocol.test.tsx@@ -19,7 +19,11 @@ import {parseMarkdownIncremental,} from '../parser';import type {InlineNode} from '../parser';-import {createMarkdownPlugin, isMarkdownExtensionNode} from './protocol';+import {+ createMarkdownPlugin,+ getMarkdownPluginCapabilities,+ isMarkdownExtensionNode,+} from './protocol';import {visitMarkdownNodes} from '../ast';import type {MarkdownExtensionNode,@@ -46,6 +50,13 @@ function ThrowingRendererChild(): never {throw new Error('broken renderer child');}+type CapabilityNode = MarkdownExtensionNode<+ 'capability-both',+ 'mark',+ {readonly label: string},+ 'inline'+>;+type InvalidSyntaxNode = MarkdownExtensionNode<'invalid-syntax','mention',@@ -211,6 +222,56 @@ function replaceText(value: string, replacement: string) {});}+describe('getMarkdownPluginCapabilities (spec:AST-064 FR4)', () => {+ it('reports only whether a plugin declares syntax and a transform', () => {+ const transformOnly = createMarkdownPlugin({+ name: 'capability-transform',+ apiVersion: 1,+ transform: root => root,+ });+ const both = createMarkdownPlugin<'capability-both', CapabilityNode>({+ name: 'capability-both',+ apiVersion: 1,+ parseKey: 'v1',+ syntax: {+ inline: [+ {+ startsWith: ['%%'],+ maxSpan: 8,+ tokenize: () => ({status: 'no-match'}),+ },+ ],+ },+ transform: root => root,+ renderers: {mark: {render: () => null, toText: () => ''}},+ });+ expect(getMarkdownPluginCapabilities(mentionPlugin)).toEqual({+ syntax: true,+ transform: false,+ });+ expect(getMarkdownPluginCapabilities(transformOnly)).toEqual({+ syntax: false,+ transform: true,+ });+ expect(getMarkdownPluginCapabilities(both)).toEqual({+ syntax: true,+ transform: true,+ });+ const report = getMarkdownPluginCapabilities(mentionPlugin);+ expect(Object.keys(report)).toEqual(['syntax', 'transform']);+ expect(Object.isFrozen(report)).toBe(true);+ });++ it('refuses an entry that did not come from createMarkdownPlugin', () => {+ expect(() =>+ getMarkdownPluginCapabilities({+ name: 'forged',+ apiVersion: 1,+ } as unknown as typeof mentionPlugin),+ ).toThrow('entries must come from a compatible createMarkdownPlugin()');+ });+});+describe('Markdown plugin protocol', () => {it('keeps omitted and explicit empty pipelines identical', () => {const source = '# Heading\n\nPlain **text**.';diff --git a/packages/core/src/Markdown/plugins/protocol.ts b/packages/core/src/Markdown/plugins/protocol.tsindex 538dfe8b1d..f9a003b2f5 100644--- a/packages/core/src/Markdown/plugins/protocol.ts+++ b/packages/core/src/Markdown/plugins/protocol.ts@@ -332,6 +332,31 @@ export function getMarkdownPluginDefinition(return definition;}+/** What a plugin declares, without the definition itself. */+export interface MarkdownPluginCapabilities {+ /** The plugin declares inline or block syntax. */+ readonly syntax: boolean;+ /** The plugin declares an immutable document transform. */+ readonly transform: boolean;+}++/**+ * Whether `plugin` declares syntax and whether it declares a transform, and+ * nothing else about it: the entry stays opaque. Throws, as every consumer of+ * an entry does, when `plugin` did not come from a compatible+ * `createMarkdownPlugin()`. Surfaces that adopt only some capabilities, as+ * the RichText surfaces do, read them here (spec:AST-064 FR4, DEC-6).+ */+export function getMarkdownPluginCapabilities(+ plugin: MarkdownPluginEntry,+): MarkdownPluginCapabilities {+ const definition = getMarkdownPluginDefinition(plugin);+ return Object.freeze({+ syntax: 'syntax' in definition && definition.syntax != null,+ transform: definition.transform != null,+ });+}+function deepFreezeConfig<T>(value: T, seen: Set<object> = new Set()): T {if (value != null && typeof value === 'object' && !seen.has(value)) {seen.add(value);diff --git a/scripts/sync-exports.js b/scripts/sync-exports.jsindex cc97ac95b7..b91cea4617 100644--- a/scripts/sync-exports.js+++ b/scripts/sync-exports.js@@ -100,9 +100,14 @@ const STATIC_EXPORTS = {},};-/** Nested modules backed by an index.ts entry point. */+/**+ * Nested modules backed by an index.ts entry point. `Markdown/plugin-renderer`+ * is client-only (its entry starts with 'use client'); the plugin protocol and+ * parser entries stay server-safe (spec:AST-064 DEC-6).+ */const DIRECTORY_MODULE_SUBPATH_EXPORTS = ['Markdown/plugins',+ 'Markdown/plugin-renderer','Markdown/parser',];