An open source design system that's fully customizable and agent ready
TypeScript
feat(Markdown): add heading links identity foundation (#6911)
Cindy Zhangd69321e72b0b
diff --git a/.changeset/markdown-heading-permalinks.md b/.changeset/markdown-heading-permalinks.mdnew file mode 100644index 0000000000..987da1deeb--- /dev/null+++ b/.changeset/markdown-heading-permalinks.md@@ -0,0 +1,9 @@+---+'@astryxdesign/core': patch+---++[feat] Add the first-party Markdown heading-links identity module.++`createMarkdownHeadingLinks()` is exported from `@astryxdesign/core/Markdown/plugins` and gives every rendered h1–h6 a deterministic, collision-safe ID after transforms, including headings nested in blockquotes and lists. Its frozen, versioned entry carries the caller namespace across compatible Core package copies without module-local state. The same opaque plugin entry keeps Markdown-derived Outline aligned, supports Unicode NFKC slugs and an optional caller-owned namespace, and leaves default Markdown plus custom heading anatomy unchanged.++@cixzhang @vjeuxdiff --git a/docs/specs/AST-002/spec.md b/docs/specs/AST-002/spec.mdindex 01f352aae5..67dce20c29 100644--- a/docs/specs/AST-002/spec.md+++ b/docs/specs/AST-002/spec.md@@ -7,7 +7,7 @@ authority: currentarchive_reason: nullsuperseded_by: nullapproved_by: cixzhang-approved_at: 2026-09-01+approved_at: 2026-10-03phase: acceptedowners: [cixzhang, imdreamrunner]affects_architecture: []@@ -208,6 +208,10 @@ A public API proposal is admitted only when it passes both gates:hooks and utilities they explicitly co-own. Family, architecture, and systemrecords own their respective shared semantics. The component's `.doc.mjs`remains the consumer syntax and reference authority.+- `module:Markdown/headingLinks` applies FR18 and DEC-8 to one admitted public+ module: its factory returns an opaque entry for the existing plugin list rather+ than adding a broad Markdown prop. The module record owns the API and behavior;+ this system record owns only that admission result.- Component specs inherit current family contracts and record only local publicconcepts, additions, and explicit exceptions; they do not copy shared rules.- Public module and utility function review compares the verb with the function'sdiff --git a/docs/specs/AST-036/spec.md b/docs/specs/AST-036/spec.mdindex a8b571d430..533d5adcfe 100644--- a/docs/specs/AST-036/spec.md+++ b/docs/specs/AST-036/spec.md@@ -7,7 +7,7 @@ authority: currentarchive_reason: nullsuperseded_by: nullapproved_by: cixzhang-approved_at: 2026-09-22+approved_at: 2026-10-03phase: acceptedowners: [cixzhang]affects_architecture:@@ -170,7 +170,7 @@ Compatibility is explicit per plugin and tested version. “Remark-compatible”- **FR14 — Extension rendering is complete and local.** Every extension kind a plugin may introduce has an owning renderer and perceivable-text projection. Missing or failed rendering preserves exact authored source for source-backed leaves, the required projection for synthetic leaves, or validated Markdown children for containers; siblings continue running.- **FR15 — Core semantics remain authoritative.** Plugins cannot replace the document root or override Core-owned heading level/ID, navigation, image policy, list semantics, table semantics, or built-in accessibility behavior. Trusted renderer-created links and resources remain renderer-owned.-- **FR16 — One heading projection.** Markdown and Markdown-derived Outline use the same syntax list, transform list, text projection, slugger, collision allocator, and released top-level heading traversal. Renderer output cannot change identity. A heading nested in an extension container behaves like one nested in a blockquote: it does not create an Outline entry or extend heading-ID traversal unless a later owner contract permits it.+- **FR16 — One selected heading projection.** Markdown and Markdown-derived Outline use the same syntax list, transform list, text projection, and installed heading projection. The released projection remains top-level; `module:Markdown/headingLinks` may opt into its separately owned projection through the same opaque plugin list without changing Outline selection. Renderer output cannot change identity.- **FR17 — Existing code override remains compatible.** A semantic-fence helper may annotate an eligible original code node but cannot replace its source. Rendering resolves `components.code` first; only when absent may the helper proposal render. Ordinary copyable code is always the local fallback.### Remark compatibility@@ -188,7 +188,7 @@ Compatibility is explicit per plugin and tested version. “Remark-compatible”### Extension containers, ownership, and node data-- **FR25 — Extension nodes declare their content.** Every extension kind declares `'none'`, `'phrasing'`, `'flow'`, or an explicit allowlist with optional finite cardinality bounds. An allowlist narrows the category its `display` already implies and never widens it, and an extension kind's name may not collide with a supported built-in node name. Core validates the declaration at admission and the actual children at every transform boundary. A container produced by syntax declares an inner source span that Core parses; no plugin supplies children built from raw source. Containers count toward the built-in container-depth bound, neither restart nor extend the heading traversal in FR16, and keep their children when their renderer fails.+- **FR25 — Extension nodes declare their content.** Every extension kind declares `'none'`, `'phrasing'`, `'flow'`, or an explicit allowlist with optional finite cardinality bounds. An allowlist narrows the category its `display` already implies and never widens it, and an extension kind's name may not collide with a supported built-in node name. Core validates the declaration at admission and the actual children at every transform boundary. A container produced by syntax declares an inner source span that Core parses; no plugin supplies children built from raw source. Containers count toward the built-in container-depth bound, neither restart nor independently scope the heading projection selected under FR16, and keep their children when their renderer fails.- **FR26 — Ownership is minting and editing, not existence.** A transform may read another plugin's extension nodes and may remove them, including removing a subtree that contains them. It may not create, edit, reorder the internals of, or duplicate a node owned by another plugin. A source heading may be removed or inserted but its depth may not change and its identity may not be forged or duplicated. Every rejection under this rule reports a diagnostic that names the ownership rule and the owning plugin rather than a generic invalid-document code.- **FR27 — Plugins declare the plugins they read.** `dependsOn` lists plugin names whose extension nodes a plugin reads. Preparation validates that each named plugin is present and ordered earlier. An unmet or misordered dependency is a failure local to the declaring plugin: its transform does not run, its syntax and renderers remain active, and one diagnostic distinguishes missing from misordered. Declaring no dependency keeps array-order-only behavior.- **FR28 — Core-internal per-node state lives in one reserved data namespace.** Core's own per-node bookkeeping is a documented reserved key of node `data`, not a hidden, non-enumerable, or signature-matched channel. Plugin data lives under the owning plugin's key. Plugins may read reserved data; authoring, editing, forging, or removing it is rejected with a diagnostic.@@ -215,7 +215,7 @@ Compatibility is explicit per plugin and tested version. “Remark-compatible”### Planned first-party scope-- **FR40 — First-party plugins use the public protocol.** Astryx ships a small first-party set — a soft-breaks plugin, a configurable entity-reference plugin, and a callout container — built only on the public protocol, each owning its semantics and evidence in its own module record and serving as canonical documentation examples. No first-party plugin receives a capability, validation exemption, ordering privilege, or type affordance unavailable to a third party; an internal fast path is permitted only where it is observationally identical, per FR23.+- **FR40 — First-party plugins use the public protocol.** Astryx ships a small first-party set — soft breaks, heading links, configurable entity references, and callout containers — through the public opaque plugin list, each owning its semantics and evidence in its own module record and serving as a canonical documentation example. No first-party plugin receives a public capability, validation exemption, ordering privilege, or type affordance unavailable to a third party; an internal composition seam or fast path is permitted only where its module record owns the behavior and the empty pipeline stays unchanged, per FR3.- **FR41 — Footnotes, definitions, and references stay Core scope.** They are not a plugin surface: their identity is document-level ID allocation, collision handling, and back-reference navigation that Core owns under FR15 and FR16, and a plugin owning them would fork the identity system Markdown and Outline share. Until a separately approved contract adds them as Core syntax, they are unsupported, the adapter rejects them, and consumer documentation names the gap explicitly rather than implying a plugin workaround.## Performance evidence protocol@@ -253,19 +253,19 @@ The new decisions are additive and opt-in. `components` swaps supported built-in## Verification-| Contract | Verification | Representative states | Mutation or failure expectation |-| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |-| FR1–FR5 | Public type/export fixtures, DOM/AST snapshots, duplicated-Core-copy fixture, and the callsite matrix above | Omitted, explicit empty, stable/recreated lists, every released prop and parser overload, two Core copies in one graph | Removing empty parity, changing a released signature, or rejecting an entry created by a compatible second Core copy fails. |-| FR6–FR13 | Syntax claim matrix; typed narrowing; transform replacement/insertion/removal/annotation; inline-shape, mutation, cycle, raw, async, and provenance rejection | Full, inline, terminal, incremental partial/final, syntax-only update, transform-only update, prior snapshots | Reordering transforms changes ordered evidence; adding tokenizer calls, mutating a prior snapshot, or leaking a rejection fails. |-| FR14–FR17 | Renderer/fallback matrix, semantic-owner matrix, heading/Outline identity, code override precedence, server rendering | Source-backed and synthetic extensions, containers, duplicate headings, cross-base headings, custom code override present/absent | Failed render preserves exact source, required projection, or children; helper data never outranks `components.code`. |-| FR18–FR20 | One real compatible transform plus rejected async, parser-extension, raw-HTML, unsupported-node, forged-position, processor-state, and metadata fixtures | Every supported matrix row, constrained file messages/data, protected contexts, server rendering | Silent field loss, unsupported-node acceptance, source loss, or an escaping rejection fails closed fixtures. |-| FR21–FR24 | Canonical linked parser budgets, callback work counts, guard-traversal counts, bundle inspection, and the exact paired protocol above | 200/500 sections, stable/recreated lists, helper and plugin-authored zero-work and representative sets, streaming set | Any unmatched callback, duplicate claim callback, repeated whole-document guard, parser-budget regression, or breach fails. |-| FR25–FR28 | Content-declaration admission/tree validation, ownership matrix, dependency preparation, reserved-data rejection | Leaf, phrasing, flow, allowlist; nested containers at depth bound; foreign read/remove/mint/edit; unmet/misordered dependencies | Plugin-built raw-source children, invalid content, foreign mint/edit, or generic ownership diagnostics fail. |-| FR29–FR30 | Diagnostic fixtures in development/production and admission parity across entrypoints | Every phase/code, advisories, rate suppression, no-handler default, malformed list, duplicate Core, version skew | Silent production failure, document content in diagnostics, module-scope throw, or entrypoint divergence fails. |-| FR31–FR35 | Inference fixtures without explicit type arguments, canonical/server imports, conformance-kit self-test, documentation checks | Syntax-only, transform-only, renderer-only, heterogeneous lists, server import, third-party kit run | Explicit-type workarounds, client references in server entry, or undocumented rejected categories fail. |-| FR36–FR39 | Streaming no-oscillation, theme reachability, prepared-reuse counts, stability-policy docs | Chunk boundaries, final-only effects, themed/unthemed output, equal new-identity lists, version skew | Oscillation, unreachable opted-in output, per-render re-preparation, or unpublished policy fails. |-| FR40–FR41 | First-party module records/evidence and unsupported-node fixtures | Soft breaks, configurable entity references, callouts; footnote/definition/reference source through parser and adapter | First-party privilege or plugin-owned footnote/definition support fails. |-| Repository integrity | Knowledge validation, public-content checks, typecheck, formatting, and changed-file review | Specification and every implementation PR | Internal content, stale owner records, unrelated paths, or formatting/type failures block merge. |+| Contract | Verification | Representative states | Mutation or failure expectation |+| -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------- |+| FR1–FR5 | Public type/export fixtures, DOM/AST snapshots, duplicated-Core-copy fixture, and the callsite matrix above | Omitted, explicit empty, stable/recreated lists, every released prop and parser overload, two Core copies in one graph | Removing empty parity, changing a released signature, or rejecting an entry created by a compatible second Core copy fails. |+| FR6–FR13 | Syntax claim matrix; typed narrowing; transform replacement/insertion/removal/annotation; inline-shape, mutation, cycle, raw, async, and provenance rejection | Full, inline, terminal, incremental partial/final, syntax-only update, transform-only update, prior snapshots | Reordering transforms changes ordered evidence; adding tokenizer calls, mutating a prior snapshot, or leaking a rejection fails. |+| FR14–FR17 | Renderer/fallback matrix, semantic-owner matrix, heading/Outline identity, code override precedence, server rendering | Source-backed and synthetic extensions, containers, duplicate headings, cross-base headings, custom code override present/absent | Failed render preserves exact source, required projection, or children; helper data never outranks `components.code`. |+| FR18–FR20 | One real compatible transform plus rejected async, parser-extension, raw-HTML, unsupported-node, forged-position, processor-state, and metadata fixtures | Every supported matrix row, constrained file messages/data, protected contexts, server rendering | Silent field loss, unsupported-node acceptance, source loss, or an escaping rejection fails closed fixtures. |+| FR21–FR24 | Canonical linked parser budgets, callback work counts, guard-traversal counts, bundle inspection, and the exact paired protocol above | 200/500 sections, stable/recreated lists, helper and plugin-authored zero-work and representative sets, streaming set | Any unmatched callback, duplicate claim callback, repeated whole-document guard, parser-budget regression, or breach fails. |+| FR25–FR28 | Content-declaration admission/tree validation, ownership matrix, dependency preparation, reserved-data rejection | Leaf, phrasing, flow, allowlist; nested containers at depth bound; foreign read/remove/mint/edit; unmet/misordered dependencies | Plugin-built raw-source children, invalid content, foreign mint/edit, or generic ownership diagnostics fail. |+| FR29–FR30 | Diagnostic fixtures in development/production and admission parity across entrypoints | Every phase/code, advisories, rate suppression, no-handler default, malformed list, duplicate Core, version skew | Silent production failure, document content in diagnostics, module-scope throw, or entrypoint divergence fails. |+| FR31–FR35 | Inference fixtures without explicit type arguments, canonical/server imports, conformance-kit self-test, documentation checks | Syntax-only, transform-only, renderer-only, heterogeneous lists, server import, third-party kit run | Explicit-type workarounds, client references in server entry, or undocumented rejected categories fail. |+| FR36–FR39 | Streaming no-oscillation, theme reachability, prepared-reuse counts, stability-policy docs | Chunk boundaries, final-only effects, themed/unthemed output, equal new-identity lists, version skew | Oscillation, unreachable opted-in output, per-render re-preparation, or unpublished policy fails. |+| FR40–FR41 | First-party module records/evidence and unsupported-node fixtures | Soft breaks, heading links, configurable entity references, callouts; footnote/definition/reference source through parser and adapter | First-party public privilege, changed empty-pipeline behavior, or plugin-owned footnote/definition support fails. |+| Repository integrity | Knowledge validation, public-content checks, typecheck, formatting, and changed-file review | Specification and every implementation PR | Internal content, stale owner records, unrelated paths, or formatting/type failures block merge. |## Related owner prerequisites@@ -279,7 +279,7 @@ Before implementation acceptance, current owner clauses must cover:6. the diagnostic channel on the component and parser options;7. the opt-in extension theme target in Markdown's theming anatomy;8. server-safe parser and conformance-kit package entries;-9. first-party plugin module owners for soft breaks, configurable entity references, and callouts.+9. first-party plugin module owners for soft breaks, heading links, configurable entity references, and callouts.## Decision log@@ -331,7 +331,7 @@ Rejected: object identity as parse identity, transform-driven reparsing, a publi**Reference:** `spec:AST-036/DEC-5`**Direction owner:** `cixzhang`, `2026-09-16`-Callouts, admonitions, details, tabs, cards, and columns require real Markdown children. An extension therefore declares leaf, phrasing, flow, or narrowed allowlist content, and Core validates children. Core parses syntax-container inner spans; plugins never build children from raw source, so provenance and protected contexts stay Core-owned. This deliberately does not widen heading identity: a heading inside a callout behaves like one inside a blockquote. A failed container renderer still exposes its validated children.+Callouts, admonitions, details, tabs, cards, and columns require real Markdown children. An extension therefore declares leaf, phrasing, flow, or narrowed allowlist content, and Core validates children. Core parses syntax-container inner spans; plugins never build children from raw source, so provenance and protected contexts stay Core-owned. A container never selects or independently scopes heading identity; it participates only in the projection already selected under FR16. A failed container renderer still exposes its validated children.Rejected: leaf-only extension nodes; independent nested document shells; plugin-authored parsed children; unbounded nesting.@@ -385,7 +385,7 @@ Rejected: first- or third-party footnote plugins; adapter translation into ordin**Reference:** `spec:AST-036/DEC-11`**Direction owner:** `cixzhang`, `2026-09-22`-Soft breaks, configurable entity references, and callout examples use only the public protocol, own their semantics and evidence in module records, and receive no capability, exemption, ordering privilege, or type affordance unavailable to third parties. An internal fast path is allowed only when observationally identical.+Soft breaks, heading links, configurable entity references, and callout examples use the public opaque plugin list, own their semantics and evidence in module records, and receive no public capability, exemption, ordering privilege, or type affordance unavailable to third parties. An internal composition seam or fast path is allowed only when its module record owns the result and the empty pipeline remains observationally unchanged.Rejected: privileged first-party capabilities; demos that exercise private paths; a public protocol with no real first-party consumers.diff --git a/packages/core/src/Markdown/Markdown.doc.mjs b/packages/core/src/Markdown/Markdown.doc.mjsindex 0104a6accf..802a4f385c 100644--- a/packages/core/src/Markdown/Markdown.doc.mjs+++ b/packages/core/src/Markdown/Markdown.doc.mjs@@ -11,7 +11,7 @@ const anatomy = [name: 'Heading',required: false,description:- 'Rendered heading block; a custom heading renderer replaces the default part.',+ 'Rendered semantic heading block; a custom heading renderer replaces the built-in part.',},{name: 'Paragraph',@@ -305,7 +305,12 @@ export const docs = {{guidance: true,description:- 'Pair with Outline and useOutlineFromMarkdown for section navigation: headings render generated id attributes that match the outline item ids, so hash links scroll to their target.',+ 'Install createMarkdownHeadingLinks() through plugins when a document needs deterministic h1–h6 fragment IDs at every nesting depth. The returned entry carries its validated namespace across compatible Core package copies. The no-plugin path stays unchanged; the plugin shares one depth-first identity projection with Markdown-derived Outline.',+ },+ {+ guidance: true,+ description:+ 'For multiple documents, create one heading-links plugin per document with headingIdPrefix and pass that same plugin to Markdown and useOutlineFromMarkdown. Use the same stable value for Markdown id when the root also needs a DOM id.',},{guidance: false,@@ -334,6 +339,30 @@ import {Text} from '@astryxdesign/core/Text';{'Visit https://example.com or email [email protected]. ' +'You can also bracket links: <https://docs.example.com>.'}</Markdown>;+`,+ },+ {+ label: 'Linkable headings',+ code: `+import {Markdown} from '@astryxdesign/core/Markdown';+import {createMarkdownHeadingLinks} from '@astryxdesign/core/Markdown/plugins';+import {Outline, useOutlineFromMarkdown} from '@astryxdesign/core/Outline';++const documentId = 'guide';+const headingLinks = createMarkdownHeadingLinks({+ headingIdPrefix: documentId,+});+const plugins = [headingLinks];++function Guide({source}) {+ const items = useOutlineFromMarkdown(source, {plugins});+ return (+ <>+ <Markdown id={documentId} plugins={plugins}>{source}</Markdown>+ <Outline items={items} />+ </>+ );+}`,},{@@ -781,7 +810,12 @@ export const docsZh = {{guidance: true,description:- 'Pair with Outline and useOutlineFromMarkdown for section navigation: headings render generated id attributes that match the outline item ids, so hash links scroll to their target.',+ 'Install createMarkdownHeadingLinks() through plugins when a document needs deterministic h1–h6 fragment IDs at every nesting depth. The returned entry carries its validated namespace across compatible Core package copies. The no-plugin path stays unchanged; the plugin shares one depth-first identity projection with Markdown-derived Outline.',+ },+ {+ guidance: true,+ description:+ 'For multiple documents, create one heading-links plugin per document with headingIdPrefix and pass that same plugin to Markdown and useOutlineFromMarkdown. Use the same stable value for Markdown id when the root also needs a DOM id.',},{guidance: false,@@ -868,7 +902,7 @@ export const docsDense = {{guidance: true,description:- 'Headings render id attributes matching useOutlineFromMarkdown ids; pair with Outline for hash navigation.',+ 'Install createMarkdownHeadingLinks() through plugins to add all-depth stable IDs. Pass the same plugin entry to Markdown-derived Outline; use headingIdPrefix for multiple instances.',},{guidance: false,@@ -895,7 +929,7 @@ export const docsDense = {contentAlign:"'start'|'center'. Prose alignment when contentWidth < container. Default: 'start'.",plugins:- 'readonly MarkdownPluginEntry[]. Ordered syntax, immutable AST transforms, and typed extension renderers from createMarkdownPlugin(). Narrow observed extensions with isMarkdownExtensionNode(); renderer callbacks are pure. Default: omitted or empty.',+ 'readonly MarkdownPluginEntry[]. Ordered syntax, immutable AST transforms, and typed extension renderers from createMarkdownPlugin(), plus first-party helpers such as createMarkdownHeadingLinks(). Default: omitted or empty.',inlinePlugins:'MarkdownInlinePlugin[]. Regex matches in text nodes -> custom inline React elements. Skips inline/fenced code and math.',autolink:diff --git a/packages/core/src/Markdown/Markdown.public.test.ts b/packages/core/src/Markdown/Markdown.public.test.tsindex adb91a5244..306cf8ae9f 100644--- a/packages/core/src/Markdown/Markdown.public.test.ts+++ b/packages/core/src/Markdown/Markdown.public.test.ts@@ -17,6 +17,7 @@ import {} from './index';import {createMarkdownFenceTransform,+ createMarkdownHeadingLinks,createMarkdownPlugin,createMarkdownTextTransform,isMarkdownExtensionNode,@@ -25,6 +26,7 @@ import {import type {MarkdownExtensionNode,MarkdownFenceTransformOptions,+ MarkdownHeadingLinksOptions,MarkdownPluginEntry,MarkdownSyntaxPluginDefinition,MarkdownTransform,@@ -198,9 +200,17 @@ describe('Markdown public parser types', () => {},} satisfies MarkdownSyntaxPluginDefinition<'public-demo', PublicNode>;const plugin = createMarkdownPlugin<'public-demo', PublicNode>(definition);+ const headingLinksOptions: MarkdownHeadingLinksOptions = {+ headingIdPrefix: 'article',+ };+ const headingLinks = createMarkdownHeadingLinks(headingLinksOptions);const nodes = parseInline('plain', {plugins: [plugin] as const});expectTypeOf(nodes).toEqualTypeOf<InlineNode<PublicNode>[]>();+ expectTypeOf(headingLinks).toEqualTypeOf<MarkdownPluginEntry<never>>();+ expectTypeOf(createMarkdownHeadingLinks)+ .parameter(0)+ .toEqualTypeOf<MarkdownHeadingLinksOptions | undefined>();expectTypeOf(visitMarkdownNodes).toBeFunction();expectTypeOf(createMarkdownTextTransform).toBeFunction();expectTypeOf(markdownSoftBreaksPlugin).toEqualTypeOf<diff --git a/packages/core/src/Markdown/Markdown.spec.md b/packages/core/src/Markdown/Markdown.spec.mdindex b4eccecd37..b05c9a3b0a 100644--- a/packages/core/src/Markdown/Markdown.spec.md+++ b/packages/core/src/Markdown/Markdown.spec.md@@ -7,7 +7,7 @@ authority: currentarchive_reason: nullsuperseded_by: nullapproved_by: cixzhang-approved_at: 2026-09-25+approved_at: 2026-10-03owners: [cixzhang]review_triggers: [api, theming, behavior, layout, accessibility]verified_by:@@ -24,7 +24,12 @@ verified_by:packages/core/src/theme/themingTargets.test.ts,scripts/check-knowledge.mjs,]-modules: [module:Markdown/remark, module:Markdown/softBreaks]+modules:+ [+ module:Markdown/headingLinks,+ module:Markdown/remark,+ module:Markdown/softBreaks,+ ]families: [family:navigation-destinations]design_specs: []architecture:@@ -138,8 +143,9 @@ phases. Frontmatter is document metadata: it has no renderer, uses a boundedfirst-party key/value grammar rather than Remark compatibility, and exposes typedmetadata through the helper that created it. `spec:AST-036`owns the shared protocol and limited Remark compatibility profile,-`module:Markdown/remark` owns that profile's adapter, and this component owns-aggregate application and fallback.+`module:Markdown/remark` owns that profile's adapter,+`module:Markdown/headingLinks` owns its opt-in identity projection, and this+component owns aggregate application and fallback.### Acceptance and implementation state@@ -180,8 +186,8 @@ unions. Enabled calls return the explicit `InlineNodeWithMath` and| FR13 | Plugin-enabled parsing follows built-in lexical shields and ordered syntax claims, then uses one stable, strictly typed, MDAST-aligned canonical tree for transforms, rendering, and Outline. `MarkdownAstNodeMap` and `visitMarkdownNodes` narrow callbacks by node kind. Released parser functions preserve their existing result shape through a compatibility projection. Every returned root is finite, acyclic, representable, validated, and frozen before later plugins or rendering observe it. || FR14 | Plugin failures preserve the last valid document and readable authored source. Core retains heading, navigation, image, list, table, and document semantics and exposes no raw-markup parser channel, registry, package discovery, mutable shared AST, or unrestricted DOM hook. URL-like plugin data remains untrusted; Astryx-owned sinks follow `family:navigation-destinations`. || FR15 | Incremental parse identity contains every parse-affecting Markdown option and only ordered syntax-bearing plugin name, protocol version, and `parseKey`. Transform or renderer changes reuse settled parse output, rerun transformation, and do not remount unaffected extension output. |-| FR16 | Plugin-enabled Markdown and Markdown-derived Outline use the same parse options, ordered transforms, extension text projection, slugger, and collision allocator so every visible heading, Outline label, heading ID, and target agree. A limited Remark adapter may run only synchronous transform plugins whose input and output round-trip through the documented supported MDAST subset. |-| FR17 | An extension node declares `content` as `'none'`, `'phrasing'`, `'flow'`, or an explicit `{allow, min?, max?}` allowlist that narrows the category its `display` implies. Markdown parses every container's inner source span under the same grammar and shields, validates children at each transform boundary, renders children through the same built-in renderers and `components` seams, counts nesting toward the built-in depth bound, leaves FR16 heading traversal unchanged, and renders children in place when a container renderer fails. |+| FR16 | Plugin-enabled Markdown and Markdown-derived Outline use the same parse options, ordered transforms, extension text projection, and installed heading projection so every Outline target agrees with rendered identity. A first-party module may compose a different heading projection only under its own current module contract; Markdown owns only this shared invocation seam. A limited Remark adapter may run only synchronous transform plugins whose input and output round-trip through the documented supported MDAST subset. |+| FR17 | An extension node declares `content` as `'none'`, `'phrasing'`, `'flow'`, or an explicit `{allow, min?, max?}` allowlist that narrows the category its `display` implies. Markdown parses every container's inner source span under the same grammar and shields, validates children at each transform boundary, renders children through the same built-in renderers and `components` seams, counts nesting toward the built-in depth bound, uses the FR16 projection, and renders children in place when a container renderer fails. || FR18 | A transform may read and remove another plugin's extension nodes, including a subtree containing them, and may insert or remove headings; it may not create, edit, internally reorder, or duplicate another plugin's nodes, change a source heading's depth, or forge or duplicate heading identity. `dependsOn` is validated at preparation; an unmet or misordered dependency skips only that plugin's transform. Every rejection names the rule and owning plugin. || FR19 | `onPluginDiagnostic` is available on the component and parser options and receives one source-free event — plugin, phase, stable code, severity — per failure, advisory, or silent degradation, in development and production, rate-limited with a suppression code. Admission, duplicate-name, and protocol-version failures behave identically through the component and every parser entrypoint: the call succeeds with the last valid configuration and never throws into the caller. || FR20 | `parseMarkdownAst()` and `parseInlineAst()` return the canonical tree and accept the same options and plugin list as the component; `@astryxdesign/core/Markdown/parser` exposes parsing, canonical AST types, and plugin admission with no client boundary. `createMarkdownPlugin()` infers the extension-node union, so no callsite needs explicit type arguments, and a declaration that yields no usable extension type is a type error rather than a silent `never`. |@@ -354,6 +360,9 @@ and this change preserves the existing spelling exactly.- `spec:AST-005/DEC-2` keeps embedded-resource policy separate. Markdown mayreject a broader set of image/resource URLs without narrowing the sharednavigation contract.+- `module:Markdown/headingLinks` owns its opt-in public factory and heading+ identity projection. Markdown supplies only the generic plugin and built-in/custom+ heading ID application seams.- `spec:AST-036` owns the opaque syntax/transform/renderer protocol, immutable ASTvalidation, limited Remark compatibility, performance, and resource boundaries.This record owns aggregate Markdown behavior in FR12–FR22;@@ -443,7 +452,7 @@ This projects `spec:AST-036/DEC-1` through `DEC-4` into the component owner. It**Reference:** `component:Markdown/DEC-3`**Decider:** `cixzhang`, `2026-09-16`-Markdown parses every extension container's inner span itself and validates children against the plugin's declared content shape, so a callout holds real Markdown while heading identity, protected contexts, navigation policy, and Outline scope stay Core-owned. Containers change what a document can express, not which headings have identity: the released top-level traversal shared by heading IDs and Outline is untouched. A failed container renderer shows its children rather than literal source. Ownership rejections name the rule and owner; removal of another plugin's nodes is permitted and only minting, editing, internal reordering, duplication, and identity forgery are not.+Markdown parses every extension container's inner span itself and validates children against the plugin's declared content shape, so a callout holds real Markdown while heading identity, protected contexts, navigation policy, and Outline scope stay Core-owned. Containers change what a document can express, not which projection owns heading identity: the released top-level traversal remains the default, and any opt-in widening belongs to a separate current module contract. A failed container renderer shows its children rather than literal source. Ownership rejections name the rule and owner; removal of another plugin's nodes is permitted and only minting, editing, internal reordering, duplication, and identity forgery are not.Markdown also owns the protocol's observability and entry surface: `onPluginDiagnostic` makes every failure visible in production without carrying document content, admission failures degrade instead of throwing at any entrypoint, canonical parse entrypoints and a server-safe parser entry exist beside the released projection, extension types are inferred, and extension output may opt into one theme target without becoming default anatomy.diff --git a/packages/core/src/Markdown/Markdown.test.tsx b/packages/core/src/Markdown/Markdown.test.tsxindex f3c33c0474..9f60398f1a 100644--- a/packages/core/src/Markdown/Markdown.test.tsx+++ b/packages/core/src/Markdown/Markdown.test.tsx@@ -115,7 +115,6 @@ describe('Markdown', () => {);expect(received).toEqual(['overview', 'overview-1']);});-it('does not assign ids to headings nested inside blockquotes', () => {// parseOutlineFromMarkdown only lists top-level headings. If nested// headings consumed slugs too, duplicate numbering would drift and@@ -128,6 +127,7 @@ describe('Markdown', () => {expect(container.querySelector('blockquote')).toContainElement(nested);expect(nested).not.toHaveAttribute('id');expect(topLevel).toHaveAttribute('id', 'quoted');+ expect(screen.queryByRole('link', {name: /Permalink to/})).toBeNull();});});diff --git a/packages/core/src/Markdown/Markdown.tsx b/packages/core/src/Markdown/Markdown.tsxindex 108bf1b04d..60bef44ba9 100644--- a/packages/core/src/Markdown/Markdown.tsx+++ b/packages/core/src/Markdown/Markdown.tsx@@ -53,11 +53,9 @@ import {parseMarkdownAstIncremental,createIncrementalState,trimStreamingArtifacts,- slugify,- uniqueSlug,} from './parser';import type {IncrementalState, MathParseOptions, ParseOptions} from './parser';-import {getMarkdownAstLegacyCodeLanguage, markdownAstText} from './ast';+import {getMarkdownAstLegacyCodeLanguage} from './ast';import type {MarkdownAstBlockContent,MarkdownAstPhrasingContent,@@ -77,6 +75,10 @@ import type {PreparedMarkdownPlugins,} from './plugins/protocol';import {sanitizeMarkdownLinkUrl, sanitizeMarkdownUrl} from './url';+import {+ projectMarkdownHeadings,+ type MarkdownHeadingProjection,+} from './headingProjection';import {themeProps} from '../utils/themeProps';import {useTranslator, type TranslatorFn} from '../i18n';@@ -143,11 +145,10 @@ export interface MarkdownComponents {level: 1 | 2 | 3 | 4 | 5 | 6;children: React.ReactNode;/**- * Generated slug for this heading, matching the ids produced by- * useOutlineFromMarkdown / parseOutlineFromMarkdown. Render it as the- * element's `id` to keep Outline hash navigation working. Undefined for- * headings nested inside blockquotes or list items (the outline only- * lists top-level headings).+ * Generated stable id for this heading, matching Markdown-derived Outline.+ * Released output supplies it to root headings; createMarkdownHeadingLinks()+ * expands the shared allocator to headings nested in blockquotes and lists.+ * Custom renderers own their output and should apply the id they receive.*/id?: string;}>;@@ -1304,7 +1305,7 @@ function renderBlock(components: Partial<MarkdownComponents> | undefined,preparedPlugins: PreparedMarkdownPlugins | undefined,t: TranslatorFn,- headingIdMap?: ReadonlyMap<RenderBlockNode, string>,+ headingProjection?: MarkdownHeadingProjection,): SyncReactNode {const blockAlignMargin = BLOCK_ALIGN_MARGIN[contentAlign];const blockAlignStyle =@@ -1332,11 +1333,7 @@ function renderBlock(preparedPlugins,),);- // Only top-level headings get an id: the map is built from the same- // traversal parseOutlineFromMarkdown uses (which skips headings nested- // in blockquotes / list items), so rendered ids and outline ids stay- // identical — including duplicate-slug numbering.- const headingId = headingIdMap?.get(node);+ const headingId = headingProjection?.ids.get(node);const HeadingComp = components?.heading;if (HeadingComp) {return (@@ -1517,6 +1514,7 @@ function renderBlock(components,preparedPlugins,t,+ headingProjection,),);return <BlockquoteComp key={index}>{bqC}</BlockquoteComp>;@@ -1553,6 +1551,7 @@ function renderBlock(components,preparedPlugins,t,+ headingProjection,),)}</Blockquote>@@ -1630,6 +1629,7 @@ function renderBlock(components,preparedPlugins,t,+ headingProjection,),)}</>@@ -1714,6 +1714,7 @@ function renderBlock(components,preparedPlugins,t,+ headingProjection,),)}</>@@ -1969,6 +1970,7 @@ export function Markdown<xstyle,className,style,+ id: rootId,'data-testid': testId,...props}: MarkdownProps<Plugins>): React.ReactElement {@@ -2084,27 +2086,17 @@ export function Markdown<[parsedBlocks, preparedPlugins, transformSource, isStreaming],);- // Assign each top-level heading the slug that parseOutlineFromMarkdown- // would derive for it, so Outline hash links built from the same source- // always find a matching DOM id. Mirrors that function's traversal exactly:- // top-level blocks only, one shared duplicate-numbering sequence.- // NOTE: must stay above the `display === 'inline'` early return below —- // hooks cannot be conditional.- const headingIdMap = useMemo(() => {+ // Resolve one post-transform projection for Markdown and derived Outline.+ // The default remains root-only; installed first-party modules own any+ // alternative projection returned through this narrow integration seam.+ const headingProjection = useMemo(() => {if (display === 'inline' || blocks.length === 0) {return undefined;}- const map = new Map<RenderBlockNode, string>();- const counts = new Map<string, number>();- for (const block of blocks) {- if (block.type === 'heading') {- const label = markdownAstText(block.children, node =>- markdownExtensionText(preparedPlugins, node),- ).trim();- map.set(block, uniqueSlug(slugify(label), counts));- }- }- return map;+ return projectMarkdownHeadings(+ {type: 'root', children: blocks},+ preparedPlugins,+ );}, [display, blocks, preparedPlugins]);const parsedInlineNodes = useMemo(() => {@@ -2207,6 +2199,7 @@ export function Markdown<ref={ref}// Consumer props first: what the component sets for itself wins.{...props}+ id={rootId}data-testid={testId}{...mergeProps(themeProps('markdown', {density}),@@ -2243,6 +2236,7 @@ export function Markdown<// Consumer props first: what the component sets for itself — the// document role included — wins.{...props}+ id={rootId}role="document"data-testid={testId}{...mergeProps(@@ -2272,7 +2266,7 @@ export function Markdown<components,preparedPlugins,t,- headingIdMap,+ headingProjection,),)}</div>diff --git a/packages/core/src/Markdown/headingProjection.ts b/packages/core/src/Markdown/headingProjection.tsnew file mode 100644index 0000000000..0a363c6939--- /dev/null+++ b/packages/core/src/Markdown/headingProjection.ts@@ -0,0 +1,70 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file headingProjection.ts+ * @input A transformed Markdown AST and prepared plugins+ * @output Released heading identity plus narrow first-party module composition+ * @position Internal Markdown/Outline heading projection seam+ */++import {markdownAstText} from './ast';+import type {MarkdownAstHeading, MarkdownAstRoot} from './ast';+import {slugify, uniqueSlug} from './parser';+import {projectMarkdownHeadingLinks} from './plugins/headingLinks';+import {markdownExtensionText} from './plugins/protocol';+import type {+ MarkdownExtensionNode,+ PreparedMarkdownPlugins,+} from './plugins/protocol';+import type {OutlineItem} from '../Outline/types';++type Heading = MarkdownAstHeading<MarkdownExtensionNode>;++export interface MarkdownHeadingProjection {+ /** Headings with generated ids. */+ readonly ids: ReadonlyMap<Heading, string>;+ /** Plain-text labels for generated headings. */+ readonly labels: ReadonlyMap<Heading, string>;+ /** Root headings only, preserving the released Outline scope. */+ readonly outline: ReadonlyArray<OutlineItem>;+}++/** Project ids once after every Markdown transform has run. */+export function projectMarkdownHeadings(+ root: MarkdownAstRoot<MarkdownExtensionNode>,+ preparedPlugins?: PreparedMarkdownPlugins,+): MarkdownHeadingProjection {+ const rootHeadings = root.children.filter(+ (node): node is Heading => node.type === 'heading',+ );+ const headingLinks = projectMarkdownHeadingLinks(root, preparedPlugins);++ if (headingLinks != null) {+ return {+ ...headingLinks,+ outline: rootHeadings.map(heading => {+ const id = headingLinks.ids.get(heading);+ const label = headingLinks.labels.get(heading);+ if (id == null || label == null) {+ throw new Error('Heading-links projection omitted a root heading');+ }+ return {id, label, level: heading.depth};+ }),+ };+ }++ const ids = new Map<Heading, string>();+ const labels = new Map<Heading, string>();+ const counts = new Map<string, number>();+ const outline = rootHeadings.map(heading => {+ const label = markdownAstText(heading.children, node =>+ markdownExtensionText(preparedPlugins, node),+ ).trim();+ const id = uniqueSlug(slugify(label), counts);+ ids.set(heading, id);+ labels.set(heading, label);+ return {id, label, level: heading.depth};+ });++ return {ids, labels, outline};+}diff --git a/packages/core/src/Markdown/modules/headingLinks.spec.md b/packages/core/src/Markdown/modules/headingLinks.spec.mdnew file mode 100644index 0000000000..f7456ec926--- /dev/null+++ b/packages/core/src/Markdown/modules/headingLinks.spec.md@@ -0,0 +1,257 @@+---+schema_version: 3+template_version: 2+kind: module+id: module:Markdown/headingLinks+authority: current+archive_reason: null+superseded_by: null+approved_by: cixzhang+approved_at: 2026-10-03+owners: [cixzhang]+review_triggers: [public-api, behavior]+verified_by:+ [+ packages/core/src/Markdown/plugins/headingLinks.test.tsx,+ packages/core/src/Markdown/plugins/headingLinks.ssr.test.tsx,+ packages/core/src/Markdown/Markdown.public.test.ts,+ packages/core/src/Outline/parseOutlineFromMarkdown.test.ts,+ ]+parent_component: component:Markdown+references:+ [+ component:Markdown/DEC-2,+ module:Outline/parseOutlineFromMarkdown,+ spec:AST-002/DEC-8,+ spec:AST-036/DEC-11,+ ]+---++# Markdown heading-links identity contract++## Contract at a glance++| Area | Contract |+| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Public contract | `createMarkdownHeadingLinks(options?)` returns one first-party entry exported from `@astryxdesign/core/Markdown/plugins`. |+| Behavior | Installing the entry gives every rendered h1–h6 a deterministic, collision-safe ID after transforms. |+| End-user impact | Documents gain stable fragment targets at every heading depth without changing heading content, semantics, or visual anatomy. |+| Builder impact | Builders explicitly install one entry and may supply a stable heading namespace. The same entry keeps Markdown-derived Outline IDs aligned and root-only. |+| Compatibility | Additive and default-off. Without this module, released Markdown/Outline heading traversal, IDs, DOM, styling, and custom heading ownership remain unchanged. |+| Review checks | Reject default-on behavior, a Markdown prop, an Outline-only namespace, runtime IDs, module-local entry state, unvalidated lookalikes, imposed visual anatomy, product identity, or host-specific navigation logic. |++This table is a review projection; the body below is authoritative.++## Intent++Builders who publish documents should be able to opt into one portable heading+identity projection without turning document identity into a permanent Markdown prop.+This foundation owns the public factory, Unicode slugging, collision allocation, and+Markdown/Outline integration. It intentionally adds no permalink renderer or visual UI.++## Compatibility and migration++- Released default preserved: `yes`+- Compatibility class: additive and opt-in+- Migration decision: `spec:AST-002/DEC-8`+- Existing builders do nothing. A builder that wants all-depth heading identities+ creates one stable entry and passes it to Markdown and any Outline derivation of the+ same source.++## Ownership boundary++**Owns**++- `createMarkdownHeadingLinks()` and `MarkdownHeadingLinksOptions`.+- The stable internal plugin name and a frozen, versioned, structurally validated+ configuration carried by the opaque entry across compatible Core package copies.+- NFKC Unicode slugging, fallback, emitted-ID reservation, namespace composition,+ and all-depth post-transform projection.+- The shared IDs and labels consumed by Markdown and Markdown-derived Outline.+- The built-in renderer extension's observable copy/reveal contract: an honest+ `type="button"` shows an inline trailing `#`, copies the canonical permalink without+ navigating, scrolling, or mutating the hash, and is visually hidden at fine-pointer+ rest. The heading row owns the standard `useContainerReveal` trigger; row hover and+ focus-within reveal the mounted button; keyboard and coarse-pointer behavior follow+ that hook's accessibility contract.+- Module-focused unit, integration, SSR, and delegated renderer browser evidence.++**Does not own / non-goals**++- Markdown's generic plugin protocol, parser, transform order, default heading styles,+ or released no-plugin root-heading projection.+- Outline's root-only item selection, hook API, or memoization framework.+- A caller's custom `components.heading` DOM, styling, or accessibility.+- Permalink rendering, interaction, i18n, styles, and browser evidence belong to the+ renderer extension, which obeys the module-owned reveal contract below without+ changing this public API.+- Product-specific document identity, versioning, host URL construction, viewer+ scrolling, callbacks, or routing.++## Public API and concepts++| Concept | Closed values or states | Meaning | Default | Owner | Stability |+| ------------------------------ | -------------------------------------------------- | ---------------------------------------------------------------------------------------- | ---------- | ------------------------------ | --------- |+| `createMarkdownHeadingLinks()` | one factory returning `MarkdownPluginEntry<never>` | Installs a portable module entry recognized by compatible Core copies. | absent | `module:Markdown/headingLinks` | stable |+| `headingIdPrefix` | string or omitted | Caller-owned stable namespace prepended as `<prefix>--<slug>`. | unprefixed | caller | stable |+| Heading projection | absent or installed | Released root-only identity when absent; module-owned all-depth identity when installed. | absent | module | stable |+| Custom heading renderer | caller replacement | Receives the generated ID at every depth and otherwise keeps complete output ownership. | built-in | caller | stable |++## Behavioral contract++| ID | Invariant | Basis |+| --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------ |+| FR1 | The factory and options type are exported only through the server-safe `@astryxdesign/core/Markdown/plugins` entry point. The ordinary opaque `MarkdownPluginEntry<never>` carries a frozen, versioned module configuration inside the shared structurally validated `Symbol.for` protocol envelope, so a compatible Core copy can recognize it without module-local identity or state. | `spec:AST-036` FR1–FR5, DEC-11 |+| FR2 | `headingIdPrefix` accepts only a string when present and travels on the entry. It is caller-owned stable data, not derived from runtime tree position or React `useId`. Consumers recognize only the exact compatible module configuration. A valid generic same-name plugin with malformed, missing, older, or newer module data remains subject to ordinary plugin ordering but is not treated as heading links, so its configuration cannot affect IDs. A malformed generic entry follows the existing consumer fail-soft path: Markdown and Outline report the configuration failure and preserve released behavior rather than throwing during render. Direct invalid factory arguments may still throw. Another valid plugin is never treated as this module. | `spec:AST-002/DEC-8` |+| FR3 | After transforms, every heading at every depth participates once in document order. Labels use the canonical extension text projection. Slugs use NFKC, lowercase Unicode letters/numbers, quote removal, collapsed hyphens, and `section`. | `component:Markdown` FR13, FR16 |+| FR4 | Every emitted ID is reserved. A natural numeric suffix can never collide with or re-emit an earlier generated ID. | module identity ownership |+| FR5 | Omitting the module preserves released root-heading IDs, nested-heading behavior, DOM, styles, Outline results, and custom-renderer ownership. | `component:Markdown` FR12 |+| FR6 | Passing the same entry to Markdown and Markdown-derived Outline shares one projection. Nested headings consume identity and collisions, while Outline continues to select root headings only. | `module:Outline/parseOutlineFromMarkdown` |+| FR7 | Built-in and custom headings receive the projected ID at every depth without an imposed wrapper or sibling UI. | `component:Markdown` FR2–FR3 |+| FR8 | IDs are deterministic across synchronous SSR, hydration, multiple namespaced instances, reordering, and independent rendering. | module identity ownership |+| FR9 | The public entry remains server-safe and tree-shakeable. Product identity, URL/version/scroll/callback/routing logic never enters the factory or projection. | package export and side-effect conventions |++## Accessibility contract++- **AR1 — semantics stay intact.** The foundation changes only the `id` attribute on+ existing semantic h1–h6 output; heading role, level, content, and accessible name do+ not change.+- **AR2 — custom ownership stays intact.** A custom heading receives identity only and+ remains responsible for all anatomy, styling, and accessibility beyond the ID.+- **AR3 — the renderer extension uses the canonical reveal primitive.** Its copy+ button stays mounted, named, in the accessibility tree, and in tab order while+ visually hidden at fine-pointer rest. Hovering anywhere in the heading row or moving+ keyboard focus into it reveals the marker immediately. Coarse-pointer/touch+ visibility, reduced motion, and focus safeguards follow `useContainerReveal`; the+ module must not add a parallel media-query, marker, token, or public reveal API.++## Copy-button reveal extension contract++The renderer extension spreads+`useContainerReveal().getContainerProps()` on the built-in heading row (the reveal+owner) and `getContentRevealProps({isLayoutPreserved: true})` on its honest sibling+`type="button"`. This produces the exact observable states: hidden at fine-pointer+rest; visible when any part of the heading row is hovered; visible when the button or+another row descendant owns focus; keyboard reachable without `display: none` or+`visibility`; and visible on coarse/touch input under the hook's existing supported+semantics. The in-flow control box has the computed block-size of its adjacent heading+line, so it never raises the heading line-height or changes wrapping. One stable logical+inline slot at the final visual line end keeps heading text, the control, and adjacent+controls disjoint in either direction; reveal and the `#`/check swap change no row+geometry or spacing. On coarse input, the interactive and focus geometry meets the+24px AA target minimum, centered on that line-height box through overflow-visible+internal geometry rather than block-size in flow. The extension remains unclipped and cannot overlap or+steal input from heading text, neighboring controls, or preceding/following lines.+Pointer activation does not paint a keyboard focus-visible ring; keyboard focus paints+exactly one canonical, unclipped Astryx ring.++Unmodified click, tap, Enter, or Space copies the canonical absolute permalink and+never navigates, scrolls, or mutates the current hash. The heading ID remains the+incoming fragment target. Success replaces `#` with Astryx's check icon for 1.5+seconds and announces localized `Link copied` once through the canonical polite live+region; failure stays silent and leaves `#` unchanged. Modified/non-primary pointer+activation does not copy, and the button exposes no anchor, open-in-new-tab, or link+context-menu semantics. Custom headings remain outside this renderer contract.++## Design relationships++| State | Design requirement | Representation authority | Module contract |+| ------------------ | ------------------------------------------------------------------------------- | --------------------------- | --------------- |+| Built-in heading | Preserve existing anatomy and styles while adding the projected `id`. | Current source and Markdown | FR5, FR7 |+| Custom heading | Forward the projected `id` without wrapping or adding sibling presentation. | Caller | FR7 |+| No-plugin Markdown | Preserve released root-only identity and nested-heading behavior byte-for-byte. | Current source and Markdown | FR5 |++The foundation adds no visual part, private layout, theme target, i18n message, or+interaction state.++## Parent and system relationships++- `component:Markdown` owns the generic plugin seam, transformed tree, built-in+ heading part, default no-plugin projection, and custom-renderer replacement seam.+- `module:Outline/parseOutlineFromMarkdown` owns root-only item selection and consumes+ this module's projection only when the same entry is installed.+- `spec:AST-036` owns the opaque plugin protocol; this first-party module uses it+ without a privileged public capability.+- `spec:AST-002/DEC-8` admits this factory instead of a broad Markdown prop because+ installation and namespace are caller decisions Astryx cannot derive.++## Implementation plan and boundaries++1. Keep the server-safe factory and identity projection in+ `plugins/headingLinks.ts`; carry normalized module configuration inside the shared+ portable plugin envelope, and export only the factory and options type from+ `plugins/index.ts`.+2. Let Markdown's existing built-in and custom heading paths consume the projected ID+ without visual composition. Keep the default path unchanged.+3. Keep identity tests, SSR proof, and Outline integration named and located with the+ module; keep generic/no-plugin tests in Markdown and root selection in Outline.++## Verification map++| Contract | Verification | Representative states | Failure expectation |+| ---------- | -------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1–FR4 | `plugins/headingLinks.test.tsx`, core typecheck, export/package checks | public entry/type, duplicate Core copies, lookalike/malformed/other plugins, h1–h6, Unicode, empty label, suffix collisions | Export drift, lost options, false recognition, unstable slug, duplicate ID, or non-server-safe construction fails. |+| FR5–FR7 | module tests plus Markdown and Outline integration tests | omitted/installed plugin, root/nested, custom heading, namespace, root ID | Default behavior changes, custom output is wrapped, or Markdown/Outline IDs diverge. |+| FR8–FR9 | `plugins/headingLinks.ssr.test.tsx`, package checks, plus delegated renderer Storybook/Chromium evidence | duplicate Core copy, two namespaces, SSR/hydration, honest button, no navigation/hash/scroll, copy/check/announcement, hidden rest, row hover, keyboard focus, coarse/touch hook semantics | IDs/options drift, hydration recovers, construction imports a client boundary, the control fakes link semantics, or the renderer bypasses `useContainerReveal`. |+| Repository | formatting, ESLint, knowledge/sync, Changeset validation, core typecheck, focused tests, pre-commit | module files, Markdown/Outline seams, docs/specs | Stale authority, duplicate ownership, type/lint failure, or unrelated diff blocks. |++## Decision log++### DEC-1 — Ship one first-party plugin factory++**Reference:** `module:Markdown/headingLinks/DEC-1`+**Decider:** `cixzhang`, `2026-10-03`++One factory preserves the opaque plugin list while exposing only installation and an+optional stable namespace. Its configuration rides the existing portable, versioned+plugin envelope rather than a creating module's WeakMap or object identity, so duplicate+compatible Core copies agree. A broad Markdown prop or separate Outline option would+make one projection into permanent parallel API and could drift across surfaces.++Compatible duplicate copies consume the exact envelope. A valid generic same-name plugin+with absent or incompatible module data stays an ordinary plugin in the caller's declared+order, but never gains this module's ID projection. A malformed generic envelope follows+the existing consumer fail-soft path, so Markdown and Outline preserve released behavior+instead of throwing during render. Invalid direct factory arguments remain programmer+errors.++Rejected: module-local option state; elevating same-name lookalikes into this module;+render-time crashes for package-version skew; default-on behavior; a Markdown boolean or+namespace prop; a separate Outline identity option; product-specific factory options.++### DEC-2 — Own one all-depth identity projection++**Reference:** `module:Markdown/headingLinks/DEC-2`+**Decider:** `cixzhang`, `2026-10-03`++Every transformed heading participates depth-first so rendered targets and root+Outline entries share one collision sequence. NFKC Unicode slugging and emitted-ID+reservation produce durable readable fragments. Caller namespace is stable data;+runtime tree position and `useId` are not.++Rejected: root-only plugin allocation; separate Markdown/Outline sluggers; ASCII-only+slugs; collision counting that can re-emit a natural numeric suffix; runtime IDs.++### DEC-3 — The renderer extension is an honest revealed copy button++**Reference:** `module:Markdown/headingLinks/DEC-3`+**Decider:** `cixzhang`, `2026-10-03`++The renderer extension uses an inline trailing `#` sibling with baseline/logical+spacing, secondary color, and inherited typography. Its primary action is copy, so it is+a real button rather than an anchor that suppresses navigation. `useContainerReveal`+owns fine-pointer rest, heading-row hover, focus-within, coarse/touch, and motion+semantics. The heading ID remains the incoming fragment target.++Rejected: native fragment navigation; a copy-plus-navigation anchor hybrid; bespoke+reveal media logic; product routing; a new public reveal API.++## Content boundary++The module reads only transformed heading nodes and the caller-supplied configuration+carried by the validated plugin entry for the current document invocation. It does not+persist document content, labels, options, or generated IDs in module-local state.++## Open questions++None.diff --git a/packages/core/src/Markdown/plugins/headingLinks.ssr.test.tsx b/packages/core/src/Markdown/plugins/headingLinks.ssr.test.tsxnew file mode 100644index 0000000000..bda740dda6--- /dev/null+++ b/packages/core/src/Markdown/plugins/headingLinks.ssr.test.tsx@@ -0,0 +1,143 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file headingLinks.ssr.test.tsx+ * @input Markdown server markup and React hydration+ * @output Proves heading fragments are deterministic across instances and hydration+ * @position SSR acceptance test for module:Markdown/headingLinks+ */++import {act} from 'react';+import {afterEach, describe, expect, it, vi} from 'vitest';+import {hydrateRoot} from 'react-dom/client';+import {renderToString} from 'react-dom/server';+import {Markdown} from '../Markdown';+import {createMarkdownPlugin} from './protocol';+import type {MarkdownPluginEntry} from './protocol';++const SOURCE = '# Overview\n\n> ## Details';++afterEach(() => {+ document.body.replaceChildren();+});++describe('Markdown heading links — SSR', () => {+ it('keeps duplicate-copy namespaced ids stable across SSR and hydration', async () => {+ vi.resetModules();+ const duplicateCore = await import('./headingLinks');+ const articleAHeadingLinks = duplicateCore.createMarkdownHeadingLinks({+ headingIdPrefix: 'article-a',+ });+ const articleBHeadingLinks = duplicateCore.createMarkdownHeadingLinks({+ headingIdPrefix: 'article-b',+ });+ const tree = (+ <>+ <Markdown id="article-a" plugins={[articleAHeadingLinks]}>+ {SOURCE}+ </Markdown>+ <Markdown id="article-b" plugins={[articleBHeadingLinks]}>+ {SOURCE}+ </Markdown>+ </>+ );+ const serverHTML = renderToString(tree);+ expect(serverHTML).toContain('id="article-a--overview"');+ expect(serverHTML).toContain('id="article-a--details"');+ expect(serverHTML).toContain('id="article-b--overview"');+ expect(serverHTML).toContain('id="article-b--details"');++ const container = document.createElement('div');+ container.innerHTML = serverHTML;+ document.body.appendChild(container);+ const before = Array.from(container.querySelectorAll('h1,h2')).map(+ heading => heading.id,+ );++ const consoleError = vi+ .spyOn(console, 'error')+ .mockImplementation(() => {});+ const recoverableErrors: unknown[] = [];+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree, {+ onRecoverableError: error => recoverableErrors.push(error),+ });+ });++ expect(+ consoleError.mock.calls.filter(call =>+ String(call[0] ?? '')+ .toLowerCase()+ .includes('hydrat'),+ ),+ ).toEqual([]);+ expect(recoverableErrors).toEqual([]);+ expect(+ Array.from(container.querySelectorAll('h1,h2')).map(+ heading => heading.id,+ ),+ ).toEqual(before);+ expect(new Set(before).size).toBe(before.length);++ await act(async () => {+ root.unmount();+ });+ consoleError.mockRestore();+ });++ it('fails soft across SSR and hydration for unsupported same-name entries', async () => {+ const missingConfig = createMarkdownPlugin({+ name: 'heading-links',+ apiVersion: 1,+ transform: root => root,+ });+ const malformed = Object.freeze({+ name: 'heading-links',+ apiVersion: 2,+ }) as unknown as MarkdownPluginEntry;+ const tree = (+ <Markdown plugins={[missingConfig, malformed]}>{SOURCE}</Markdown>+ );++ const serverHTML = renderToString(tree);+ const container = document.createElement('div');+ container.innerHTML = serverHTML;+ document.body.appendChild(container);+ const headings = container.querySelectorAll('h1,h2');+ expect(headings).toHaveLength(2);+ expect(headings[0]).toHaveAttribute('id', 'overview');+ expect(headings[1]).not.toHaveAttribute('id');+ expect(container.querySelector('button, a[href*="#"]')).toBeNull();++ const consoleError = vi+ .spyOn(console, 'error')+ .mockImplementation(() => {});+ const recoverableErrors: unknown[] = [];+ let root!: ReturnType<typeof hydrateRoot>;+ await act(async () => {+ root = hydrateRoot(container, tree, {+ onRecoverableError: error => recoverableErrors.push(error),+ });+ });++ expect(recoverableErrors).toEqual([]);+ expect(+ consoleError.mock.calls.filter(call =>+ String(call[0] ?? '')+ .toLowerCase()+ .includes('hydrat'),+ ),+ ).toEqual([]);+ expect(+ Array.from(container.querySelectorAll('h1,h2')).map(heading =>+ heading.getAttribute('id'),+ ),+ ).toEqual(['overview', null]);++ await act(async () => {+ root.unmount();+ });+ consoleError.mockRestore();+ });+});diff --git a/packages/core/src/Markdown/plugins/headingLinks.test.tsx b/packages/core/src/Markdown/plugins/headingLinks.test.tsxnew file mode 100644index 0000000000..3ee03ffc40--- /dev/null+++ b/packages/core/src/Markdown/plugins/headingLinks.test.tsx@@ -0,0 +1,296 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file headingLinks.test.tsx+ * @input Markdown and Outline with the first-party heading-links plugin+ * @output Identity, projection, compatibility, and custom-renderer evidence+ * @position Acceptance tests for module:Markdown/headingLinks+ */++import {render, screen} from '@testing-library/react';+import type {ReactNode} from 'react';+import {describe, expect, expectTypeOf, it, vi} from 'vitest';+import {parseOutlineFromMarkdown} from '../../Outline/parseOutlineFromMarkdown';+import {Markdown} from '../Markdown';+import {createMarkdownHeadingLinks} from './index';+import {createMarkdownPlugin} from './protocol';+import type {MarkdownPluginEntry} from './protocol';++const headingLinks = createMarkdownHeadingLinks();+const markdownPluginBrand = Symbol.for(+ '@astryxdesign/core/MarkdownPluginEntry',+);+const headingLinksConfigBrand = Symbol.for(+ '@astryxdesign/core/MarkdownHeadingLinksConfig',+);++function createBrandedSameNameEntry({+ pluginApiVersion = 1,+ config,+}: {+ readonly pluginApiVersion?: number;+ readonly config?: unknown;+}): MarkdownPluginEntry {+ const definition: Record<PropertyKey, unknown> = {+ name: 'heading-links',+ apiVersion: pluginApiVersion,+ transform: (root: {readonly type: string}) => root,+ };+ if (config !== undefined) {+ Object.defineProperty(definition, headingLinksConfigBrand, {+ configurable: false,+ enumerable: false,+ value: Object.freeze(config),+ writable: false,+ });+ }+ Object.freeze(definition);+ return Object.freeze({+ name: 'heading-links',+ apiVersion: pluginApiVersion,+ [markdownPluginBrand]: Object.freeze({+ kind: '@astryxdesign/core/MarkdownPluginEntry',+ apiVersion: pluginApiVersion,+ definition,+ }),+ }) as unknown as MarkdownPluginEntry;+}++function createConfig(+ overrides: Readonly<Record<string, unknown>> = {},+): Record<string, unknown> {+ return {+ kind: '@astryxdesign/core/MarkdownHeadingLinksConfig',+ apiVersion: 1,+ headingIdPrefix: 'ignored',+ permalinkBaseUrl: '',+ ...overrides,+ };+}++const incompatibleHeadingLinksEntries: ReadonlyArray<+ readonly [string, MarkdownPluginEntry]+> = [+ [+ 'same-name plugin without module configuration',+ createMarkdownPlugin({+ name: 'heading-links',+ apiVersion: 1,+ transform: root => root,+ }),+ ],+ [+ 'malformed generic envelope',+ Object.freeze({+ name: 'heading-links',+ apiVersion: 1,+ }) as unknown as MarkdownPluginEntry,+ ],+ ['older plugin protocol', createBrandedSameNameEntry({pluginApiVersion: 0})],+ ['newer plugin protocol', createBrandedSameNameEntry({pluginApiVersion: 2})],+ [+ 'older module configuration',+ createBrandedSameNameEntry({config: createConfig({apiVersion: 0})}),+ ],+ [+ 'newer module configuration',+ createBrandedSameNameEntry({config: createConfig({apiVersion: 2})}),+ ],+ [+ 'wrong module configuration shape',+ createBrandedSameNameEntry({+ config: createConfig({headingIdPrefix: 42}),+ }),+ ],+];++describe('createMarkdownHeadingLinks', () => {+ it('returns an ordinary public plugin entry', () => {+ expectTypeOf(headingLinks).toMatchTypeOf<MarkdownPluginEntry<never>>();+ });++ it('carries its namespace across a duplicate compatible Core copy', async () => {+ vi.resetModules();+ const duplicateCore = await import('./headingLinks');+ const portableEntry = duplicateCore.createMarkdownHeadingLinks({+ headingIdPrefix: 'portable',+ });+ const source = '> # Nested\n\n# Root';++ render(<Markdown plugins={[portableEntry]}>{source}</Markdown>);++ expect(screen.getByRole('heading', {name: 'Nested'})).toHaveAttribute(+ 'id',+ 'portable--nested',+ );+ expect(screen.getByRole('heading', {name: 'Root'})).toHaveAttribute(+ 'id',+ 'portable--root',+ );+ expect(+ parseOutlineFromMarkdown(source, {plugins: [portableEntry]}),+ ).toEqual([{id: 'portable--root', label: 'Root', level: 1}]);+ });++ it.each(incompatibleHeadingLinksEntries)(+ 'fails soft for %s across Markdown and Outline',+ (_label, incompatibleEntry) => {+ const source = '> # Nested\n\n# Root';+ const {container} = render(+ <Markdown plugins={[incompatibleEntry]}>{source}</Markdown>,+ );+ const [nested, root] = screen.getAllByRole('heading');++ expect(nested).not.toHaveAttribute('id');+ expect(root).toHaveAttribute('id', 'root');+ expect(container.querySelector('button, a[href*="#"]')).toBeNull();+ expect(+ parseOutlineFromMarkdown(source, {plugins: [incompatibleEntry]}),+ ).toEqual([{id: 'root', label: 'Root', level: 1}]);+ },+ );++ it('does not treat another valid plugin as heading-links configuration', () => {+ const otherPlugin = createMarkdownPlugin({+ name: 'other-plugin',+ apiVersion: 1,+ transform: root => root,+ });+ render(+ <Markdown plugins={[otherPlugin]}>{'> # Nested\n\n# Root'}</Markdown>,+ );+ const [nested, root] = screen.getAllByRole('heading');++ expect(nested).not.toHaveAttribute('id');+ expect(root).toHaveAttribute('id', 'root');+ });++ it('projects a stable id for every semantic heading level without permalink UI', () => {+ render(+ <Markdown plugins={[headingLinks]}>+ {Array.from(+ {length: 6},+ (_, index) => `${'#'.repeat(index + 1)} Level ${index + 1}`,+ ).join('\n\n')}+ </Markdown>,+ );++ for (let level = 1; level <= 6; level += 1) {+ expect(+ screen.getByRole('heading', {level, name: `Level ${level}`}),+ ).toHaveAttribute('id', `level-${level}`);+ }+ expect(screen.queryByRole('link')).toBeNull();+ });++ it('shares one depth-first allocator while Outline remains root-only', () => {+ const source = '> # Quoted\n\n# Quoted';+ const {container} = render(+ <Markdown plugins={[headingLinks]}>{source}</Markdown>,+ );+ const [nested, topLevel] = screen.getAllByText('Quoted');++ expect(container.querySelector('blockquote')).toContainElement(nested);+ expect(nested).toHaveAttribute('id', 'quoted');+ expect(topLevel).toHaveAttribute('id', 'quoted-1');+ expect(parseOutlineFromMarkdown(source, {plugins: [headingLinks]})).toEqual(+ [{id: 'quoted-1', label: 'Quoted', level: 1}],+ );+ });++ it('reserves emitted ids across natural numeric-suffix collisions', () => {+ render(+ <Markdown plugins={[headingLinks]}>+ {'# Foo\n\n# Foo\n\n# Foo-1'}+ </Markdown>,+ );+ expect(screen.getAllByRole('heading').map(heading => heading.id)).toEqual([+ 'foo',+ 'foo-1',+ 'foo-1-1',+ ]);+ expect(+ parseOutlineFromMarkdown('# Foo-1\n\n# Foo\n\n# Foo', {+ plugins: [headingLinks],+ }).map(item => item.id),+ ).toEqual(['foo-1', 'foo', 'foo-2']);+ });++ it('normalizes Unicode letters and numbers while stripping emoji', () => {+ render(+ <Markdown plugins={[headingLinks]}>+ {'# Hello Привет 你好 😄 123'}+ </Markdown>,+ );+ expect(screen.getByRole('heading')).toHaveAttribute(+ 'id',+ 'hello-привет-你好-123',+ );+ });++ it('uses a stable section fallback when the label has no slug text', () => {+ render(+ <Markdown plugins={[headingLinks]} sources={{cite: {title: 'Citation'}}}>+ {'# [cite]'}+ </Markdown>,+ );+ expect(screen.getByRole('heading')).toHaveAttribute('id', 'section');+ });++ it('uses a caller-owned namespace across Markdown and Outline', () => {+ const source = '# Overview\n\n## Details';+ const namespaced = createMarkdownHeadingLinks({+ headingIdPrefix: 'article',+ });+ const {container} = render(+ <Markdown id="article" plugins={[namespaced]}>+ {source}+ </Markdown>,+ );++ expect(container.firstElementChild).toHaveAttribute('id', 'article');+ expect(screen.getAllByRole('heading').map(heading => heading.id)).toEqual([+ 'article--overview',+ 'article--details',+ ]);+ expect(parseOutlineFromMarkdown(source, {plugins: [namespaced]})).toEqual([+ {id: 'article--overview', label: 'Overview', level: 1},+ {id: 'article--details', label: 'Details', level: 2},+ ]);+ });++ it('rejects a non-string namespace', () => {+ expect(() =>+ createMarkdownHeadingLinks({headingIdPrefix: 42 as unknown as string}),+ ).toThrow(/headingIdPrefix must be a string/);+ });++ it('gives custom heading renderers ids at every depth without imposing anatomy', () => {+ const received: (string | undefined)[] = [];+ const {container} = render(+ <Markdown+ plugins={[headingLinks]}+ components={{+ heading: ({children, id}: {children: ReactNode; id?: string}) => {+ received.push(id);+ return <h2 id={id}>{children}</h2>;+ },+ }}>+ {'> # Nested\n\n# Root'}+ </Markdown>,+ );++ expect(received).toEqual(['nested', 'root']);+ expect(container.querySelectorAll('h2')).toHaveLength(2);+ expect(screen.queryByRole('link')).toBeNull();+ });++ it('preserves released no-plugin identity and nested-heading behavior', () => {+ render(<Markdown>{'> # Nested\n\n# Root'}</Markdown>);+ const [nested, root] = screen.getAllByRole('heading');++ expect(nested).not.toHaveAttribute('id');+ expect(root).toHaveAttribute('id', 'root');+ expect(screen.queryByRole('link')).toBeNull();+ });+});diff --git a/packages/core/src/Markdown/plugins/headingLinks.ts b/packages/core/src/Markdown/plugins/headingLinks.tsnew file mode 100644index 0000000000..ce56be4793--- /dev/null+++ b/packages/core/src/Markdown/plugins/headingLinks.ts@@ -0,0 +1,193 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file headingLinks.ts+ * @input Transformed Markdown headings plus an optional caller namespace+ * @output First-party heading-links plugin and its deterministic identity projection+ * @position Public server-safe module built on the canonical Markdown plugin protocol+ */++import {markdownAstText, visitMarkdownNodes} from '../ast';+import type {MarkdownAstHeading, MarkdownAstRoot} from '../ast';+import {+ createMarkdownPlugin,+ getMarkdownPluginDefinition,+ markdownExtensionText,+ markMarkdownTransformTrusted,+ type MarkdownExtensionNode,+ type MarkdownPluginEntry,+ type PreparedMarkdownPlugins,+} from './protocol';++const PLUGIN_NAME = 'heading-links';+const PORTABLE_CONFIG_KIND = '@astryxdesign/core/MarkdownHeadingLinksConfig';+const portableConfigKey = Symbol.for(PORTABLE_CONFIG_KIND);+type Heading = MarkdownAstHeading<MarkdownExtensionNode>;++export interface MarkdownHeadingLinksOptions {+ /**+ * Stable caller-owned namespace for generated heading ids. Use the same+ * value for the Markdown root `id` when each document needs its own fragment+ * namespace. Omit it to keep unprefixed fragments for a single document.+ */+ readonly headingIdPrefix?: string;+}++interface PortableMarkdownHeadingLinksConfig {+ readonly kind: typeof PORTABLE_CONFIG_KIND;+ readonly apiVersion: 1;+ readonly headingIdPrefix?: string;+ /** Reserved for the separately reviewed renderer layer. */+ readonly permalinkBaseUrl: string;+}++/** @internal Module-owned projection consumed by Markdown and Outline. */+export interface MarkdownHeadingLinksProjection {+ readonly ids: ReadonlyMap<Heading, string>;+ readonly labels: ReadonlyMap<Heading, string>;+}++const identityTransform = markMarkdownTransformTrusted(root => root);++function fail(message: string): never {+ throw new TypeError(`Markdown heading links: ${message}`);+}++function headingSlug(value: string): string {+ return value+ .normalize('NFKC')+ .trim()+ .toLowerCase()+ .replace(/['"]/gu, '')+ .replace(/[^\p{Letter}\p{Number}]+/gu, '-')+ .replace(/^-+|-+$/gu, '');+}++function uniqueHeadingSlug(+ baseSlug: string,+ counts: Map<string, number>,+): string {+ const fallbackSlug = baseSlug || 'section';+ let count = counts.get(fallbackSlug) ?? 0;+ let candidate = count === 0 ? fallbackSlug : `${fallbackSlug}-${count}`;+ while (counts.has(candidate)) {+ count++;+ candidate = `${fallbackSlug}-${count}`;+ }+ counts.set(fallbackSlug, count + 1);+ counts.set(candidate, 0);+ return candidate;+}++function createPortableConfig(+ headingIdPrefix: string | undefined,+): PortableMarkdownHeadingLinksConfig {+ return Object.freeze({+ kind: PORTABLE_CONFIG_KIND,+ apiVersion: 1 as const,+ headingIdPrefix,+ permalinkBaseUrl: '',+ });+}++function readPortableConfig(+ entry: MarkdownPluginEntry,+): PortableMarkdownHeadingLinksConfig | undefined {+ const definition = getMarkdownPluginDefinition(entry);+ if (definition.name !== PLUGIN_NAME) {+ return undefined;+ }++ const config = (definition as unknown as Record<PropertyKey, unknown>)[+ portableConfigKey+ ] as Partial<PortableMarkdownHeadingLinksConfig> | undefined;+ if (+ config == null ||+ typeof config !== 'object' ||+ Object.getPrototypeOf(config) !== Object.prototype ||+ Reflect.ownKeys(config).length !== 4 ||+ !Object.isFrozen(config) ||+ config.kind !== PORTABLE_CONFIG_KIND ||+ config.apiVersion !== 1 ||+ (config.headingIdPrefix !== undefined &&+ typeof config.headingIdPrefix !== 'string') ||+ typeof config.permalinkBaseUrl !== 'string'+ ) {+ return undefined;+ }+ return config as PortableMarkdownHeadingLinksConfig;+}++/**+ * Create the opt-in plugin that gives every rendered h1–h6 a stable identity.+ * The entry is safe to share between Markdown and Markdown-derived Outline,+ * including consumers loaded from another compatible Core package copy.+ */+export function createMarkdownHeadingLinks(+ options: MarkdownHeadingLinksOptions = {},+): MarkdownPluginEntry<never> {+ if (+ options.headingIdPrefix !== undefined &&+ typeof options.headingIdPrefix !== 'string'+ ) {+ fail('headingIdPrefix must be a string');+ }++ const definition = {+ name: PLUGIN_NAME,+ apiVersion: 1 as const,+ transform: identityTransform,+ };+ Object.defineProperty(definition, portableConfigKey, {+ configurable: false,+ enumerable: false,+ value: createPortableConfig(options.headingIdPrefix),+ writable: false,+ });+ return createMarkdownPlugin(definition);+}++function getHeadingLinksConfig(+ plugins: PreparedMarkdownPlugins | undefined,+): PortableMarkdownHeadingLinksConfig | undefined {+ if (plugins == null) {+ return undefined;+ }+ for (const entry of plugins.entries) {+ const config = readPortableConfig(entry);+ if (config != null) {+ return config;+ }+ }+ return undefined;+}++/** @internal Project the module's all-depth identity after transforms run. */+export function projectMarkdownHeadingLinks(+ root: MarkdownAstRoot<MarkdownExtensionNode>,+ preparedPlugins?: PreparedMarkdownPlugins,+): MarkdownHeadingLinksProjection | undefined {+ const config = getHeadingLinksConfig(preparedPlugins);+ if (config == null) {+ return undefined;+ }++ const ids = new Map<Heading, string>();+ const labels = new Map<Heading, string>();+ const counts = new Map<string, number>();++ visitMarkdownNodes(root, 'heading', heading => {+ const label = markdownAstText(heading.children, node =>+ markdownExtensionText(preparedPlugins, node),+ ).trim();+ const slug = uniqueHeadingSlug(headingSlug(label), counts);+ const id =+ config.headingIdPrefix != null && config.headingIdPrefix !== ''+ ? `${config.headingIdPrefix}--${slug}`+ : slug;+ ids.set(heading, id);+ labels.set(heading, label);+ });++ return {ids, labels};+}diff --git a/packages/core/src/Markdown/plugins/index.ts b/packages/core/src/Markdown/plugins/index.tsindex 687ba62772..234db27951 100644--- a/packages/core/src/Markdown/plugins/index.ts+++ b/packages/core/src/Markdown/plugins/index.ts@@ -29,6 +29,8 @@ export type {} from './sourceDecoration';export {createMarkdownFrontmatter} from './frontmatter';export {markdownSoftBreaksPlugin} from './softBreaks';+export {createMarkdownHeadingLinks} from './headingLinks';+export type {MarkdownHeadingLinksOptions} from './headingLinks';export type {MarkdownFrontmatter,MarkdownFrontmatterOptions,diff --git a/packages/core/src/Markdown/plugins/protocol.ts b/packages/core/src/Markdown/plugins/protocol.tsindex e94a7106b7..538dfe8b1d 100644--- a/packages/core/src/Markdown/plugins/protocol.ts+++ b/packages/core/src/Markdown/plugins/protocol.ts@@ -292,7 +292,11 @@ interface InternalMarkdownPluginEntry<readonly [markdownPluginDefinition]: MarkdownPluginBrand<Node>;}-function getMarkdownPluginDefinition(+/**+ * @internal Validates an opaque entry and returns its frozen definition for+ * first-party modules that carry their own Symbol.for-branded portable data.+ */+export function getMarkdownPluginDefinition(publicEntry: MarkdownPluginEntry,): MarkdownPluginDefinition<string, MarkdownExtensionNode> {if (diff --git a/packages/core/src/Outline/Outline.doc.mjs b/packages/core/src/Outline/Outline.doc.mjsindex ee9526aea4..64a725dfab 100644--- a/packages/core/src/Outline/Outline.doc.mjs+++ b/packages/core/src/Outline/Outline.doc.mjs@@ -194,16 +194,29 @@ function ControlledOutline() {{label: 'Generate items from markdown',code: `+import {Markdown} from '@astryxdesign/core/Markdown';+import {createMarkdownHeadingLinks} from '@astryxdesign/core/Markdown/plugins';import {Outline, useOutlineFromMarkdown} from '@astryxdesign/core/Outline';-function MarkdownOutline({markdown, plugins, isStreaming}) {- // Pass the same plugins and finality to Markdown and Outline so transformed- // headings share labels and ids while content streams.+const markdownRootId = 'guide';+const plugins = [+ createMarkdownHeadingLinks({headingIdPrefix: markdownRootId}),+];++function MarkdownOutline({markdown, isStreaming}) {+ // Pass the same plugin entry and finality to Markdown and Outline. Nested+ // headings consume the shared depth-first sequence, while Outline continues+ // to return root headings only.const items = useOutlineFromMarkdown(markdown, {plugins,isFinal: !isStreaming,});- return <Outline items={items} />;+ return (+ <>+ <Markdown id={markdownRootId} plugins={plugins}>{markdown}</Markdown>+ <Outline items={items} />+ </>+ );}`,},@@ -263,7 +276,7 @@ function FlashOnArrival() {{guidance: true, description: 'Pass a flat ordered list of headings and let level control indentation.'},{guidance: true, description: 'Use activeId when custom scroll logic owns the active section.'},{guidance: true, description: 'Use density="compact" in dense sidebars where vertical space is tight.'},- {guidance: true, description: 'Use useOutlineFromMarkdown or useOutlineFromDOM when headings are generated from content.'},+ {guidance: true, description: 'Use useOutlineFromMarkdown or useOutlineFromDOM when headings are generated from content. For linkable Markdown headings, pass the same createMarkdownHeadingLinks() entry to Markdown and Outline; configure headingIdPrefix on that plugin for multiple roots.'},{guidance: true, description: 'Pass scrollContainerRef when the content scrolls in a split pane, modal, or panel instead of the viewport.'},{guidance: true, description: 'Set offset to the height of a fixed header that overlays the content, so headings land below it instead of underneath it.'},{guidance: false, description: 'Use Outline for application navigation - use SideNav or TopNav for routes.'},@@ -365,7 +378,7 @@ export const docsZh = {{guidance: true, description: 'Pass a flat ordered list of headings and let level control indentation.'},{guidance: true, description: 'Use activeId when custom scroll logic owns the active section.'},{guidance: true, description: 'Use density="compact" in dense sidebars where vertical space is tight.'},- {guidance: true, description: 'Use useOutlineFromMarkdown or useOutlineFromDOM when headings are generated from content.'},+ {guidance: true, description: 'Use useOutlineFromMarkdown or useOutlineFromDOM when headings are generated from content. For linkable Markdown headings, pass the same createMarkdownHeadingLinks() entry to Markdown and Outline; configure headingIdPrefix on that plugin for multiple roots.'},{guidance: false, description: 'Use Outline for application navigation - use SideNav or TopNav for routes.'},{guidance: false, description: 'Use Outline for expandable hierarchy - use TreeList when nodes need expand and collapse.'},],@@ -384,7 +397,7 @@ export const docsDense = {{guidance: true, description: 'Pass a flat ordered list of headings and let level control indentation.'},{guidance: true, description: 'Use activeId when custom scroll logic owns the active section.'},{guidance: true, description: 'Use density="compact" in dense sidebars where vertical space is tight.'},- {guidance: true, description: 'Use useOutlineFromMarkdown or useOutlineFromDOM when headings are generated from content.'},+ {guidance: true, description: 'Use useOutlineFromMarkdown or useOutlineFromDOM when headings are generated from content. For linkable Markdown headings, pass the same createMarkdownHeadingLinks() entry to Markdown and Outline; configure headingIdPrefix on that plugin for multiple roots.'},{guidance: true, description: 'Pass scrollContainerRef when the content scrolls in a split pane, modal, or panel instead of the viewport.'},{guidance: true, description: 'Set offset to the height of a fixed header that overlays the content, so headings land below it instead of underneath it.'},{guidance: false, description: 'Use Outline for application navigation - use SideNav or TopNav for routes.'},diff --git a/packages/core/src/Outline/modules/parseOutlineFromMarkdown.spec.md b/packages/core/src/Outline/modules/parseOutlineFromMarkdown.spec.mdindex dd6ca4fd7a..ba816a0c0e 100644--- a/packages/core/src/Outline/modules/parseOutlineFromMarkdown.spec.md+++ b/packages/core/src/Outline/modules/parseOutlineFromMarkdown.spec.md@@ -7,13 +7,18 @@ authority: currentarchive_reason: nullsuperseded_by: nullapproved_by: cixzhang-approved_at: 2026-09-15+approved_at: 2026-10-03owners: [cixzhang]review_triggers: [public-api, behavior]verified_by: [packages/core/src/Outline/parseOutlineFromMarkdown.test.ts]parent_component: component:Outlinereferences:- [architecture:public-component-api, component:Markdown, spec:AST-036]+ [+ architecture:public-component-api,+ component:Markdown,+ module:Markdown/headingLinks,+ spec:AST-036,+ ]---# parseOutlineFromMarkdown module contract@@ -55,27 +60,29 @@ component's anatomy or theming.`useOutlineFromMarkdown(source, options?)` memoizes the same derivation for Reactcallers. `options.plugins` uses the canonical opaque Markdown plugin entries. Thesame ordered transforms run before heading selection; inline extension-node `toText`-projections then contribute to heading labels and IDs.+projections then contribute to heading labels and IDs. When the same first-party+entry is installed on both surfaces, this module consumes the projection owned by+`module:Markdown/headingLinks`; it does not copy that module's options or behavior.## Behavioral contract| ID | Invariant | Basis | Acceptance and implementation state || --- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------- | ----------------------------------- |-| FR1 | Both utilities accept the same Markdown parser options and ordered plugin list as the rendered Markdown document. | `spec:AST-036` FR13, FR16 | pending implementation |-| FR2 | Both utilities apply the same validated immutable transforms before selecting headings, without allowing renderer output to affect identity. | `spec:AST-036` FR13, FR16 | pending implementation |-| FR3 | Plugin-enabled labels and IDs use the same extension `toText` projection, slugger, and cross-base collision allocator as Markdown, producing unique matching targets. | `spec:AST-036` FR16 | pending implementation |-| FR4 | An extension node never creates an Outline entry of its own, and extension containers do not change heading traversal: entries come from the same blocks Markdown assigns heading IDs to, so a heading nested in a container is omitted exactly as one nested in a blockquote or list item is. A container never restarts, extends, or re-scopes heading identity or slug allocation. | `spec:AST-036` FR16, FR25 | pending implementation |-| FR5 | Omitting plugins and passing an empty list preserve released heading selection, labels, levels, IDs, return type, and memoization behavior. | `spec:AST-036` FR2 | pending implementation |-| FR6 | The hook memoizes against source and every parse-affecting or transform-affecting option so changed configuration cannot return stale headings. | `component:Markdown` FR15–FR16 | pending implementation |-| FR7 | A transform that removes a heading removes its Outline entry, and a transform that inserts a synthetic heading adds one, in both surfaces identically. Source-backed heading depth cannot change, so an entry's level always matches the rendered heading. | `spec:AST-036` FR26 | pending implementation |-| FR8 | When a plugin fails, derivation uses the same last valid root the rendered document uses, so labels, levels, and IDs still agree. Failures are reported through the shared diagnostic channel; this module adds no failure mode, fallback, or throw of its own. | `spec:AST-036` FR12, FR29 | pending implementation |-| FR9 | Derivation runs on the canonical tree through the shared parse path and requires no DOM, renderer, client boundary, or second parser. Because transforms are idempotent under streaming, an outline derived from a growing source prefix converges rather than oscillates. | `spec:AST-036` FR32, FR33, FR36 | pending implementation |+| FR1 | Both utilities accept the same Markdown parser options and ordered plugin list as the rendered Markdown document. | `spec:AST-036` FR13, FR16 | current implementation |+| FR2 | Both utilities apply the same validated immutable transforms before selecting headings, without allowing renderer output to affect identity. | `spec:AST-036` FR13, FR16 | current implementation |+| FR3 | Plugin-enabled labels and IDs use the same extension `toText` projection, slugger, and cross-base collision allocator as Markdown, producing unique matching targets. | `spec:AST-036` FR16 | current implementation |+| FR4 | An extension node never creates an Outline entry of its own. Outline selection stays root-only; when `module:Markdown/headingLinks` is installed, this module consumes its separately owned identity projection without restating or modifying that contract. A container never restarts or independently scopes the selected projection. It never emits nested Outline entries here. | `module:Markdown/headingLinks` | current implementation |+| FR5 | Omitting plugins and passing an empty list preserve released heading selection, labels, levels, IDs, return type, and memoization behavior. | `spec:AST-036` FR2 | current implementation |+| FR6 | The hook memoizes against source and every parse-affecting or transform-affecting option so changed configuration cannot return stale headings. | `component:Markdown` FR15–FR16 | current implementation |+| FR7 | A transform that removes a heading removes its Outline entry, and a transform that inserts a synthetic heading adds one, in both surfaces identically. Source-backed heading depth cannot change, so an entry's level always matches the rendered heading. | `spec:AST-036` FR26 | current implementation |+| FR8 | When a plugin fails, derivation uses the same last valid root the rendered document uses, so labels, levels, and IDs still agree. Failures are reported through the shared diagnostic channel; this module adds no failure mode, fallback, or throw of its own. | `spec:AST-036` FR12, FR29 | current implementation |+| FR9 | Derivation runs on the canonical tree through the shared parse path and requires no DOM, renderer, client boundary, or second parser. Because transforms are idempotent under streaming, an outline derived from a growing source prefix converges rather than oscillates. | `spec:AST-036` FR32, FR33, FR36 | current implementation |### Transformation and precedence orderMarkdown parse configuration → ordered immutable transforms → heading nodes →-shared perceivable-text projection → shared slug normalization → document-order-collision allocation → Outline items.+shared perceivable-text projection → selected heading projection → root-heading+selection → Outline items.### Performance and resources@@ -96,18 +103,20 @@ No visual representation is owned by this parser utility.## Parent and system relationships-- `component:Markdown` owns aggregate parsing, heading rendering, and the shared- projection/collision rules.+- `component:Markdown` owns aggregate parsing, heading rendering, and the generic+ shared-projection invocation seam.+- `module:Markdown/headingLinks` owns its optional projection; this module consumes+ it while retaining root-only Outline selection.- `spec:AST-036` owns the canonical plugin protocol and cross-surface parity.- Draft `component:Outline` owns presentation only after its separate anatomy andtheming decisions become current.## Verification map-| Contract | Verification | Representative states | Mutation or failure expectation |-| -------- | ----------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------- |-| FR1–FR6 | Outline parser tests, plugin transform parity tests, and Core typecheck | transformed, formatted, and extension headings; headings nested in extension containers, blockquotes, and list items; duplicate and cross-base slugs; omitted/empty plugins | A transform is skipped, a label/ID diverges from Markdown, a container changes which headings have identity, or default output changes. |-| FR7–FR9 | Heading insert/remove parity, failure parity, and streaming derivation | headings removed with/without sections; inserted synthetic headings; failing transform; growing source prefix; server derivation | Outline/document disagreement, divergent fallback, a throw, stale IDs, or streamed oscillation. |+| Contract | Verification | Representative states | Mutation or failure expectation |+| -------- | --------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |+| FR1–FR6 | Outline parser tests, plugin transform parity tests, heading-links module tests, and Core typecheck | omitted/empty/installed plugin lists; selected projection changes; transformed and formatted root headings; root/nested containers | A transform is skipped, a root label/ID diverges from Markdown, nested headings enter Outline, selected projection goes stale, or default output changes. |+| FR7–FR9 | Heading insert/remove parity, failure parity, and streaming derivation | headings removed with/without sections; inserted synthetic headings; failing transform; growing source prefix; server derivation | Outline/document disagreement, divergent fallback, a throw, stale IDs, or streamed oscillation. |## Decision log@@ -126,9 +135,9 @@ output to navigation identity.**Reference:** `module:Outline/parseOutlineFromMarkdown/DEC-2`**Decider:** cixzhang, 2026-09-16-Extension containers hold ordinary Markdown but do not change which headings have identity. Markdown assigns IDs by one traversal and this module reads the same one, so Outline never links to a heading Markdown did not identify. A heading inside a container remains omitted like one inside a blockquote or list item, and the extension node is never an Outline entry. Widening traversal is a separate decision.+Extension containers hold ordinary Markdown but do not select a second identity system. Markdown and this module consume the same projection chosen by the installed plugin list, so Outline never links to a root heading Markdown did not identify. The Outline result remains root-only, and an extension node is never an Outline entry.-Transforms may remove and insert headings, so Outline follows the rendered document rather than source: a dropped heading disappears, an inserted heading appears, and immutable source-backed depth keeps levels aligned. Both surfaces run the same pipeline rather than independent rules.+Transforms may remove and insert headings, so Outline follows the rendered document rather than source: a dropped root heading disappears, an inserted root heading appears, and immutable source-backed depth keeps levels aligned. Both surfaces run the same pipeline rather than independent rules.Rejected: a container-only traversal exception; extension nodes as Outline entries; source-only derivation; module-local plugin failure fallback.diff --git a/packages/core/src/Outline/parseOutlineFromMarkdown.test.ts b/packages/core/src/Outline/parseOutlineFromMarkdown.test.tsindex 6718f135b4..69b0c76e8a 100644--- a/packages/core/src/Outline/parseOutlineFromMarkdown.test.ts+++ b/packages/core/src/Outline/parseOutlineFromMarkdown.test.ts@@ -1,7 +1,12 @@// Copyright (c) Meta Platforms, Inc. and affiliates.import {describe, expect, it} from 'vitest';+import {renderHook} from '@testing-library/react';import {parseOutlineFromMarkdown} from './parseOutlineFromMarkdown';+import {useOutlineFromMarkdown} from './useOutlineFromMarkdown';+import {createMarkdownHeadingLinks} from '../Markdown/plugins/headingLinks';++const headingLinks = createMarkdownHeadingLinks();describe('parseOutlineFromMarkdown', () => {it('returns an empty outline for content with no headings', () => {@@ -49,6 +54,25 @@ describe('parseOutlineFromMarkdown', () => {expect(outline.every(i => i.label === 'Setup')).toBe(true);});+ it('lets nested headings consume ids without adding them to the outline', () => {+ const source = '> # Quoted\n\n# Quoted';+ expect(parseOutlineFromMarkdown(source, {plugins: [headingLinks]})).toEqual(+ [{id: 'quoted-1', label: 'Quoted', level: 1}],+ );+ });++ it('updates the hook result when the plugin namespace changes', () => {+ const first = [createMarkdownHeadingLinks({headingIdPrefix: 'first'})];+ const second = [createMarkdownHeadingLinks({headingIdPrefix: 'second'})];+ const {result, rerender} = renderHook(+ ({plugins}) => useOutlineFromMarkdown('# Overview', {plugins}),+ {initialProps: {plugins: first}},+ );+ expect(result.current[0].id).toBe('first--overview');+ rerender({plugins: second});+ expect(result.current[0].id).toBe('second--overview');+ });+it('falls back to "section" when a heading slugifies to empty', () => {const outline = parseOutlineFromMarkdown(['# !!!', '# @@@'].join('\n\n'));expect(outline.map(i => i.id)).toEqual(['section', 'section-1']);diff --git a/packages/core/src/Outline/parseOutlineFromMarkdown.ts b/packages/core/src/Outline/parseOutlineFromMarkdown.tsindex 4e1f12b9c5..a3ade90ad0 100644--- a/packages/core/src/Outline/parseOutlineFromMarkdown.ts+++ b/packages/core/src/Outline/parseOutlineFromMarkdown.ts@@ -11,19 +11,16 @@* - /packages/core/src/Outline/index.ts*/+import {parseMarkdownAstInternal} from '../Markdown/parser';+import {projectMarkdownHeadings} from '../Markdown/headingProjection';import {- parseMarkdownAstInternal,- slugify,- uniqueSlug,-} from '../Markdown/parser';-import {markdownAstText} from '../Markdown/ast';-import {- markdownExtensionText,prepareMarkdownPlugins,+ reportMarkdownPluginFailure,} from '../Markdown/plugins/protocol';import type {MarkdownExtensionNode,MarkdownPluginEntry,+ PreparedMarkdownPlugins,} from '../Markdown/plugins/protocol';import type {OutlineItem} from './types';@@ -49,25 +46,18 @@ export function parseOutlineFromMarkdown<markdown: string,options?: ParseOutlineFromMarkdownOptions<Node>,): OutlineItem[] {- const prepared =- options?.plugins == null- ? undefined- : prepareMarkdownPlugins(options.plugins);- const counts = new Map<string, number>();- return parseMarkdownAstInternal(+ let plugins = options?.plugins;+ let prepared: PreparedMarkdownPlugins | undefined;+ try {+ prepared = plugins == null ? undefined : prepareMarkdownPlugins(plugins);+ } catch (error) {+ reportMarkdownPluginFailure('configuration', 'transform', error);+ plugins = undefined;+ }+ const root = parseMarkdownAstInternal(markdown,- {plugins: options?.plugins},+ {plugins},options?.isFinal ?? true,- )- .children.filter(block => block.type === 'heading')- .map(block => {- const label = markdownAstText(block.children, node =>- markdownExtensionText(prepared, node),- ).trim();- return {- id: uniqueSlug(slugify(label), counts),- label,- level: block.depth,- };- });+ );+ return [...projectMarkdownHeadings(root, prepared).outline];}diff --git a/packages/core/src/Outline/useOutlineFromMarkdown.ts b/packages/core/src/Outline/useOutlineFromMarkdown.tsindex e007904ab0..0f9bfc2bd0 100644--- a/packages/core/src/Outline/useOutlineFromMarkdown.ts+++ b/packages/core/src/Outline/useOutlineFromMarkdown.ts@@ -29,7 +29,11 @@ export function useOutlineFromMarkdown<const plugins = options?.plugins;const isFinal = options?.isFinal;return useMemo(- () => parseOutlineFromMarkdown(markdown, {plugins, isFinal}),+ () =>+ parseOutlineFromMarkdown(markdown, {+ plugins,+ isFinal,+ }),[markdown, plugins, isFinal],);}