mdast utility that turns markdown into a syntax tree
- What is this?
- When should I use this?
- Install
- Use
- API
- Types
- List of extensions
- Syntax
- Syntax tree
- Security
- Related
- Contribute
This package is a utility that takes markdown input and turns it into a markdown abstract syntax tree.
This utility uses micromark, which turns markdown into tokens, and then turns those tokens into nodes.
If you want to handle syntax trees manually, use this.
When you just want to turn markdown into HTML, use micromark instead.
For an easier time processing content, use the remark ecosystem instead.
This package is ESM only.
In Node.js (version 18+) with yarn:
yarn add @flex-development/mdast-util-from-markdownSee Git - Protocols | Yarn for details regarding installing from Git.
In Deno with esm.sh:
import { fromMarkdown } from 'https://esm.sh/@flex-development/mdast-util-from-markdown'In browsers with esm.sh:
<script type="module">
import { fromMarkdown } from 'https://esm.sh/@flex-development/mdast-util-from-markdown'
</script>Say we have the following markdown file example.md:
## Hello, *World*!…and our module example.mjs looks as follows:
import { fromMarkdown } from '@flex-development/mdast-util-from-markdown'
import { inspect } from '@flex-development/unist-util-inspect'
import { read } from 'to-vfile'
const file = await read('example.md')
const tree = fromMarkdown(String(file))
console.log(inspect(tree))…now running node example.mjs yields:
root[1] (1:1-2:1, 0-19)
└─0 heading[3] (1:1-1:19, 0-18)
│ depth: 2
├─0 text "Hello, " (1:4-1:11, 3-10)
├─1 emphasis[1] (1:11-1:18, 10-17)
│ └─0 text "World" (1:12-1:17, 11-16)
└─2 text "!" (1:18-1:19, 17-18)This package exports the identifiers fromMarkdown, compiler,
preprocess, and takeExtension.
The default export is fromMarkdown.
Additional exports are located at @flex-development/mdast-util-from-markdown/creators
and @flex-development/mdast-util-from-markdown/handles.
Turn markdown into a syntax tree.
(value: Value | null | undefined, encoding?: Encoding | null | undefined, options?: Options) => Root(value: Value | null | undefined, options?: Options | null | undefined) => Root
value(Value|null|undefined) — the markdown to parseencoding(Encoding|null|undefined, optional) — the character encoding for whenvalueisUint8Array- default:
'utf8'
- default:
options(Options|null|undefined, optional) — the configuration options
(Root) mdast
Create an mdast compiler.
👉 The compiler only understands complete buffering, not streaming.
options(Options|null|undefined, optional) — the configuration options
(Compiler) The mdast compiler
Prepare events before compilation begins.
this(mark.Context) — the event compilation contextevents(mark.Event[]) — the current list of events
(undefined) Nothing
Merge extension into the combined configuration.
combined(mark.Config) — the current configurationextension(mark.Extension) — the extension to mergefield(keyof mark.Extension|undefined, optional) — the currentextensionfield
(undefined) Nothing
@flex-development/mdast-util-markdown/creators exports default Node factories by name.
@flex-development/mdast-util-markdown/handles exports default token Handles by name.
This package is fully typed with TypeScript.
Start capturing output into a temporary node (type).
type Buffer = (this: CompileContext) => undefinedthis(CompileContext) — the event compilation context
(undefined) Nothing
Union of character reference types (type).
type CharacterReferenceType =
| 'characterReferenceMarkerHexadecimal'
| 'characterReferenceMarkerNumeric'The event compilation context (interface).
Event compilation consumes the Events of a parser to produce a syntax tree.
During compilation, event handlers orchestrate Node creation, enter nodes onto the stack,
and exit them later.
The compilation config defines how TokenTypes map to compilation behavior.
After the initial compilation, Transforms can be applied to manipulate the final tree.
buffer(Buffer) — start capturing output into a temporary node.
captured values can later be serialized withresumeconfig(Config) — the compilation configurationdata(CompileData) — info passed around; key/value storeenter(Enter) — enter a nodeexit(Exit) — exit a noderesume(Resume) — stopbuffering and serialize the captured nodesliceSerialize(TokenizeContext['sliceSerialize']) — get the string value of a tokenstack(Node[]) — the node stacktokenStack(StackedToken[]) — the token stack
Interface of tracked data (interface).
interface CompileData {/* see code */}When developing extensions that use more data, augment CompileData to register custom fields:
declare module 'mdast-util-from-markdown' {
interface CompileData {
mathFlowInside?: boolean | undefined
}
}To sync native augmentations, import @flex-development/mdast-util-from-markdown/mdast:
import type {} from '@flex-development/mdast-util-from-markdown/mdast'Turn micromark events into a syntax tree (type).
type Compiler = (this: void, events?: Event[] | null | undefined) => Rootevents(Event[]|null|undefined, optional) — the list of events
(Root) mdast
The event compilation configuration (interface).
afterEnter(Handle[]) — the list of listeners to call after a token isenteredafterExit(Handle[]) — the list of listeners to call after a token isexitededbeforeEnter(Handle[]) — the list of listeners to call before a token isenteredbeforeExit(Handle[]) — the list of listeners to call before a token isexitededcanContainEols(string[]) — the list of token types where line endings are usedenter(Handles) — record, where each key is aTokenTypeand each value is the handler to call when entering a tokenexit(Handles) — record, where each key is aTokenTypeand each value is the handler to call when exiting a tokentransforms(Transform[]) — the list of tree transforms to apply
Encodings supported by TextEncoder (type).
See micromark-util-types for more info.
type Encoding =
| 'utf-8' // always supported in node
| 'utf-16le' // always supported in node
| 'utf-16be' // not supported when ICU is disabled
| (string & {}) // everything else (depends on browser, or full ICU data)Enter a node (type).
type Enter = (
this: CompileContext,
node: Node,
token: Token,
onError?: OnEnterError | null | undefined
) => undefinedthis(CompileContext) — the event compilation contextnode(Node) — the node to entertoken(Token) — the token associated withnodeonError(OnEnterError|null|undefined, optional) — handle the case where another token is open, but closed by something else
(undefined) Nothing
The start or end of a token amongst other events (type).
See micromark-util-types for more info.
type Event = ['enter' | 'exit', Token, TokenizeContext]Exit a node (type).
type Exit = (
this: CompileContext,
token: Token,
onError?: OnExitError | null | undefined
) => undefinedthis(CompileContext) — the event compilation contexttoken(Token) — the token associated with the nodeonError(OnExitError|null|undefined, optional) — handle the case where another token is open
(undefined) Nothing
A compiler extension (interface).
Compiler extensions can be used to change how tokens are turned into nodes, as well as apply transformations to the final syntax tree.
afterEnter(Handle|Handle[]|null|undefined, optional) — the listener, or listeners, to call after a token isenteredafterExit(Handle|Handle[]|null|undefined, optional) — the listener, or listeners, to call after a token isexitededbeforeEnter(Handle|Handle[]|null|undefined, optional) — the listener, or listeners, to call before a token isenteredbeforeExit(Handle|Handle[]|null|undefined, optional) — the listener, or listeners, to call before a token isexitededcanContainEols(string[]|null|undefined, optional) — the list of token types where line endings are usedenter(Handles|null|undefined, optional) — record, where each key is aTokenTypeand each value is the handler to call when entering a tokenexit(Handles|null|undefined, optional) — record, where each key is aTokenTypeand each value is the handler to call when exiting a tokentransforms(Transform[]|null|undefined, optional) — the list of tree transforms to apply
A temporary node (interface).
children(mdast.PhrasingContent[]) — the list of childrentype('fragment') — the node type
Handle a token (type).
type Handle = (this: CompileContext, token: Token) => undefined | voidthis(CompileContext) — the event compilation contexttoken(Token) — the token to handle
(undefined | void) Nothing
Record, where each key is a TokenType and each value is an event handler (type).
type Handles = Partial<Record<TokenType, Handle>>Union of nodes that can be created during event compilation (type).
👉 Note: Also exported as
StackedNode.
type Node = Fragment | Root | RootContentHandle the case where the right token is open,
but is closed by the left token, or because end of content was reached (type).
type OnEnterError = (
this: Omit<CompileContext, 'sliceSerialize'>,
left: Token | undefined,
right: Token
) => undefinedthis(Omit<CompileContext, 'sliceSerialize'>) — the event compilation contextleft(Token|undefined) — the exiting tokenright(Token) — the open token
(undefined) Nothing
Handle the case where the right token is open, but is closed by exiting the left token (type).
type OnExitError = (
this: Omit<CompileContext, 'sliceSerialize'>,
left: Token,
right: Token
) => undefinedthis(Omit<CompileContext, 'sliceSerialize'>) — the event compilation contextleft(Token) — the exiting tokenright(Token) — the open token
(undefined) Nothing
Configuration options (interface).
extensions(micromark.Extension[]|null|undefined, optional) — extensions formicromarkto change how tokens are producedfrom(StartPoint|null|undefined, optional) — the point before the first character in the content.
node positions will be relative to this point- default:
{ column: 1, line: 1, offset: 0 }
- default:
mdastExtensions((Extension | Extension[])[]|null|undefined, optional) — extensions for this utility to change how tokens are turned into nodes
Options for parsing markdown (interface).
See micromark-util-types for more info.
A location in the source document and chunk (interface).
See micromark-util-types for more info.
Stop capturing output and serialize the captured node (type).
type Resume = (this: CompileContext) => stringthis(CompileContext) — the event compilation context
(string) The serialized node
A document fragment or a whole document (interface).
See mdast for more info.
List containing an open token on the stack,
and an optional error handler to use if the token isn't closed properly (type).
👉 Note: Also exported as
TokenTuple.
type StackedToken = [token: Token, handler: OnEnterError | undefined]The point before the first character in the content (type).
type StartPoint = Omit<Point, '_bufferIndex' | '_index'>A span of chunks (interface).
See micromark-util-types for more info.
A context object that helps with tokenizing markdown constructs (interface).
See micromark-util-types for more info.
Union of registered token types (type).
See micromark-util-types for more info.
Transform the syntax tree (type).
👉 Note: Returning
null,undefined, orvoidwill preservetree.
type Transform = (this: void, tree: Root) => Root | null | undefined | voidRoot(Root) — the tree to transform
(Root | null | undefined | void) The serialized node
The contents of a file.
See micromark-util-types for more info.
type Value = Uint8Array | stringmdast-util-directive— directivesmdast-util-frontmatter— frontmatter (YAML, TOML, more)mdast-util-gfm— GFMmdast-util-gfm-autolink-literal— GFM autolink literalsmdast-util-gfm-footnote— GFM footnotesmdast-util-gfm-strikethrough— GFM strikethroughmdast-util-gfm-table— GFM tablesmdast-util-gfm-task-list-item— GFM task list itemssyntax-tree/mdast-util-math— mathsyntax-tree/mdast-util-mdx— MDXsyntax-tree/mdast-util-mdx-expression— MDX expressionssyntax-tree/mdast-util-mdx-jsx— MDX JSXsyntax-tree/mdast-util-mdxjs-esm— MDX ESM
Markdown is parsed according to CommonMark. Extensions can add support for other syntax. If you’re interested in extending markdown, more information is available in micromark’s readme.
The syntax tree is mdast.
As markdown is sometimes used for HTML, and improper use of HTML can open you up to a cross-site scripting (XSS)
attack, use of mdast-util-from-markdown can also be unsafe.
When going to HTML, use this utility in combination with hast-util-sanitize
to make the tree safe.
mdast-util-to-markdown— serialize mdast as markdownmicromark— parse markdownremark— process markdown
See CONTRIBUTING.md.
