This commit is contained in:
2024-03-22 03:47:51 +05:30
parent 8bcf3d211e
commit 89819f6fe2
28440 changed files with 3211033 additions and 2 deletions

242
node_modules/mdast-util-directive/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,242 @@
import type {
Data,
Parent,
BlockContent,
DefinitionContent,
PhrasingContent
} from 'mdast'
export {directiveFromMarkdown, directiveToMarkdown} from './lib/index.js'
/**
* Fields shared by directives.
*/
interface DirectiveFields {
/**
* Directive name.
*/
name: string
/**
* Directive attributes.
*/
attributes?: Record<string, string | null | undefined> | null | undefined
}
/**
* Markdown directive (container form).
*/
export interface ContainerDirective extends Parent, DirectiveFields {
/**
* Node type of container directive.
*/
type: 'containerDirective'
/**
* Children of container directive.
*/
children: Array<BlockContent | DefinitionContent>
/**
* Data associated with the mdast container directive.
*/
data?: ContainerDirectiveData | undefined
}
/**
* Info associated with mdast container directive nodes by the ecosystem.
*/
export interface ContainerDirectiveData extends Data {}
/**
* Markdown directive (leaf form).
*/
export interface LeafDirective extends Parent, DirectiveFields {
/**
* Node type of leaf directive.
*/
type: 'leafDirective'
/**
* Children of leaf directive.
*/
children: PhrasingContent[]
/**
* Data associated with the mdast leaf directive.
*/
data?: LeafDirectiveData | undefined
}
/**
* Info associated with mdast leaf directive nodes by the ecosystem.
*/
export interface LeafDirectiveData extends Data {}
/**
* Markdown directive (text form).
*/
export interface TextDirective extends Parent, DirectiveFields {
/**
* Node type of text directive.
*/
type: 'textDirective'
/**
* Children of text directive.
*/
children: PhrasingContent[]
/**
* Data associated with the text leaf directive.
*/
data?: TextDirectiveData | undefined
}
/**
* Info associated with mdast text directive nodes by the ecosystem.
*/
export interface TextDirectiveData extends Data {}
/**
* Union of registered mdast directive nodes.
*
* It is not possible to register custom mdast directive node types.
*/
export type Directives = ContainerDirective | LeafDirective | TextDirective
// Add custom data tracked to turn markdown into a tree.
declare module 'mdast-util-from-markdown' {
interface CompileData {
/**
* Attributes for current directive.
*/
directiveAttributes?: Array<[string, string]> | undefined
}
}
// Add custom data tracked to turn a syntax tree into markdown.
declare module 'mdast-util-to-markdown' {
interface ConstructNameMap {
/**
* Whole container directive.
*
* ```markdown
* > | :::a
* ^^^^
* > | :::
* ^^^
* ```
*/
containerDirective: 'containerDirective'
/**
* Label of a container directive.
*
* ```markdown
* > | :::a[b]
* ^^^
* | :::
* ```
*/
containerDirectiveLabel: 'containerDirectiveLabel'
/**
* Whole leaf directive.
*
* ```markdown
* > | ::a
* ^^^
* ```
*/
leafDirective: 'leafDirective'
/**
* Label of a leaf directive.
*
* ```markdown
* > | ::a[b]
* ^^^
* ```
*/
leafDirectiveLabel: 'leafDirectiveLabel'
/**
* Whole text directive.
*
* ```markdown
* > | :a
* ^^
* ```
*/
textDirective: 'textDirective'
/**
* Label of a text directive.
*
* ```markdown
* > | :a[b]
* ^^^
* ```
*/
textDirectiveLabel: 'textDirectiveLabel'
}
}
// Add nodes to content, register `data` on paragraph.
declare module 'mdast' {
interface BlockContentMap {
/**
* Directive in flow content (such as in the root document, or block
* quotes), which contains further flow content.
*/
containerDirective: ContainerDirective
/**
* Directive in flow content (such as in the root document, or block
* quotes), which contains nothing.
*/
leafDirective: LeafDirective
}
interface ParagraphData {
/**
* Field set on the first paragraph which is a child of a container
* directive.
* When this is `true`, that means the paragraph represents the *label*:
*
* ```markdown
* :::a[This is the label]
* This is further things.
* :::
* ```
*/
directiveLabel?: boolean | null | undefined
}
interface PhrasingContentMap {
/**
* Directive in phrasing content (such as in paragraphs, headings).
*/
textDirective: TextDirective
}
interface RootContentMap {
/**
* Directive in flow content (such as in the root document, or block
* quotes), which contains further flow content.
*/
containerDirective: ContainerDirective
/**
* Directive in flow content (such as in the root document, or block
* quotes), which contains nothing.
*/
leafDirective: LeafDirective
/**
* Directive in phrasing content (such as in paragraphs, headings).
*/
textDirective: TextDirective
}
}

2
node_modules/mdast-util-directive/index.js generated vendored Normal file
View File

@@ -0,0 +1,2 @@
// Note: types exposed from `index.d.ts`.
export {directiveFromMarkdown, directiveToMarkdown} from './lib/index.js'

29
node_modules/mdast-util-directive/lib/index.d.ts generated vendored Normal file
View File

@@ -0,0 +1,29 @@
/**
* Create an extension for `mdast-util-from-markdown` to enable directives in
* markdown.
*
* @returns {FromMarkdownExtension}
* Extension for `mdast-util-from-markdown` to enable directives.
*/
export function directiveFromMarkdown(): FromMarkdownExtension
/**
* Create an extension for `mdast-util-to-markdown` to enable directives in
* markdown.
*
* @returns {ToMarkdownExtension}
* Extension for `mdast-util-to-markdown` to enable directives.
*/
export function directiveToMarkdown(): ToMarkdownExtension
export type Nodes = import('mdast').Nodes
export type Paragraph = import('mdast').Paragraph
export type CompileContext = import('mdast-util-from-markdown').CompileContext
export type FromMarkdownExtension = import('mdast-util-from-markdown').Extension
export type FromMarkdownHandle = import('mdast-util-from-markdown').Handle
export type Token = import('mdast-util-from-markdown').Token
export type ConstructName = import('mdast-util-to-markdown').ConstructName
export type ToMarkdownHandle = import('mdast-util-to-markdown').Handle
export type ToMarkdownExtension = import('mdast-util-to-markdown').Options
export type State = import('mdast-util-to-markdown').State
export type Directives = import('../index.js').Directives
export type LeafDirective = import('../index.js').LeafDirective
export type TextDirective = import('../index.js').TextDirective

477
node_modules/mdast-util-directive/lib/index.js generated vendored Normal file
View File

@@ -0,0 +1,477 @@
/**
* @typedef {import('mdast').Nodes} Nodes
* @typedef {import('mdast').Paragraph} Paragraph
*
* @typedef {import('mdast-util-from-markdown').CompileContext} CompileContext
* @typedef {import('mdast-util-from-markdown').Extension} FromMarkdownExtension
* @typedef {import('mdast-util-from-markdown').Handle} FromMarkdownHandle
* @typedef {import('mdast-util-from-markdown').Token} Token
*
* @typedef {import('mdast-util-to-markdown').ConstructName} ConstructName
* @typedef {import('mdast-util-to-markdown').Handle} ToMarkdownHandle
* @typedef {import('mdast-util-to-markdown').Options} ToMarkdownExtension
* @typedef {import('mdast-util-to-markdown').State} State
*
* @typedef {import('../index.js').Directives} Directives
* @typedef {import('../index.js').LeafDirective} LeafDirective
* @typedef {import('../index.js').TextDirective} TextDirective
*/
import {ok as assert} from 'devlop'
import {parseEntities} from 'parse-entities'
import {stringifyEntitiesLight} from 'stringify-entities'
import {visitParents} from 'unist-util-visit-parents'
const own = {}.hasOwnProperty
const shortcut = /^[^\t\n\r "#'.<=>`}]+$/
handleDirective.peek = peekDirective
/**
* Create an extension for `mdast-util-from-markdown` to enable directives in
* markdown.
*
* @returns {FromMarkdownExtension}
* Extension for `mdast-util-from-markdown` to enable directives.
*/
export function directiveFromMarkdown() {
return {
canContainEols: ['textDirective'],
enter: {
directiveContainer: enterContainer,
directiveContainerAttributes: enterAttributes,
directiveContainerLabel: enterContainerLabel,
directiveLeaf: enterLeaf,
directiveLeafAttributes: enterAttributes,
directiveText: enterText,
directiveTextAttributes: enterAttributes
},
exit: {
directiveContainer: exit,
directiveContainerAttributeClassValue: exitAttributeClassValue,
directiveContainerAttributeIdValue: exitAttributeIdValue,
directiveContainerAttributeName: exitAttributeName,
directiveContainerAttributeValue: exitAttributeValue,
directiveContainerAttributes: exitAttributes,
directiveContainerLabel: exitContainerLabel,
directiveContainerName: exitName,
directiveLeaf: exit,
directiveLeafAttributeClassValue: exitAttributeClassValue,
directiveLeafAttributeIdValue: exitAttributeIdValue,
directiveLeafAttributeName: exitAttributeName,
directiveLeafAttributeValue: exitAttributeValue,
directiveLeafAttributes: exitAttributes,
directiveLeafName: exitName,
directiveText: exit,
directiveTextAttributeClassValue: exitAttributeClassValue,
directiveTextAttributeIdValue: exitAttributeIdValue,
directiveTextAttributeName: exitAttributeName,
directiveTextAttributeValue: exitAttributeValue,
directiveTextAttributes: exitAttributes,
directiveTextName: exitName
}
}
}
/**
* Create an extension for `mdast-util-to-markdown` to enable directives in
* markdown.
*
* @returns {ToMarkdownExtension}
* Extension for `mdast-util-to-markdown` to enable directives.
*/
export function directiveToMarkdown() {
return {
unsafe: [
{
character: '\r',
inConstruct: ['leafDirectiveLabel', 'containerDirectiveLabel']
},
{
character: '\n',
inConstruct: ['leafDirectiveLabel', 'containerDirectiveLabel']
},
{
before: '[^:]',
character: ':',
after: '[A-Za-z]',
inConstruct: ['phrasing']
},
{atBreak: true, character: ':', after: ':'}
],
handlers: {
containerDirective: handleDirective,
leafDirective: handleDirective,
textDirective: handleDirective
}
}
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterContainer(token) {
enter.call(this, 'containerDirective', token)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterLeaf(token) {
enter.call(this, 'leafDirective', token)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterText(token) {
enter.call(this, 'textDirective', token)
}
/**
* @this {CompileContext}
* @param {Directives['type']} type
* @param {Token} token
*/
function enter(type, token) {
this.enter({type, name: '', attributes: {}, children: []}, token)
}
/**
* @this {CompileContext}
* @param {Token} token
*/
function exitName(token) {
const node = this.stack[this.stack.length - 1]
assert(
node.type === 'containerDirective' ||
node.type === 'leafDirective' ||
node.type === 'textDirective'
)
node.name = this.sliceSerialize(token)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterContainerLabel(token) {
this.enter(
{type: 'paragraph', data: {directiveLabel: true}, children: []},
token
)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitContainerLabel(token) {
this.exit(token)
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function enterAttributes() {
this.data.directiveAttributes = []
this.buffer() // Capture EOLs
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitAttributeIdValue(token) {
const list = this.data.directiveAttributes
assert(list, 'expected `directiveAttributes`')
list.push([
'id',
parseEntities(this.sliceSerialize(token), {
attribute: true
})
])
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitAttributeClassValue(token) {
const list = this.data.directiveAttributes
assert(list, 'expected `directiveAttributes`')
list.push([
'class',
parseEntities(this.sliceSerialize(token), {
attribute: true
})
])
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitAttributeValue(token) {
const list = this.data.directiveAttributes
assert(list, 'expected `directiveAttributes`')
list[list.length - 1][1] = parseEntities(this.sliceSerialize(token), {
attribute: true
})
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitAttributeName(token) {
const list = this.data.directiveAttributes
assert(list, 'expected `directiveAttributes`')
// Attribute names in CommonMark are significantly limited, so character
// references cant exist.
list.push([this.sliceSerialize(token), ''])
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exitAttributes() {
const list = this.data.directiveAttributes
assert(list, 'expected `directiveAttributes`')
/** @type {Record<string, string>} */
const cleaned = {}
let index = -1
while (++index < list.length) {
const attribute = list[index]
if (attribute[0] === 'class' && cleaned.class) {
cleaned.class += ' ' + attribute[1]
} else {
cleaned[attribute[0]] = attribute[1]
}
}
this.data.directiveAttributes = undefined
this.resume() // Drop EOLs
const node = this.stack[this.stack.length - 1]
assert(
node.type === 'containerDirective' ||
node.type === 'leafDirective' ||
node.type === 'textDirective'
)
node.attributes = cleaned
}
/**
* @this {CompileContext}
* @type {FromMarkdownHandle}
*/
function exit(token) {
this.exit(token)
}
/**
* @type {ToMarkdownHandle}
* @param {Directives} node
*/
function handleDirective(node, _, state, info) {
const tracker = state.createTracker(info)
const sequence = fence(node)
const exit = state.enter(node.type)
let value = tracker.move(sequence + (node.name || ''))
/** @type {LeafDirective | Paragraph | TextDirective | undefined} */
let label
if (node.type === 'containerDirective') {
const head = (node.children || [])[0]
label = inlineDirectiveLabel(head) ? head : undefined
} else {
label = node
}
if (label && label.children && label.children.length > 0) {
const exit = state.enter('label')
/** @type {ConstructName} */
const labelType = `${node.type}Label`
const subexit = state.enter(labelType)
value += tracker.move('[')
value += tracker.move(
// @ts-expect-error: `containerPhrasing` is typed correctly, but TS
// generates *hardcoded* types, which means that our dynamically added
// directives are not present.
// At some point, TS should fix that, and `from-markdown` should be fine.
state.containerPhrasing(label, {
...tracker.current(),
before: value,
after: ']'
})
)
value += tracker.move(']')
subexit()
exit()
}
value += tracker.move(attributes(node, state))
if (node.type === 'containerDirective') {
const head = (node.children || [])[0]
let shallow = node
if (inlineDirectiveLabel(head)) {
shallow = Object.assign({}, node, {children: node.children.slice(1)})
}
if (shallow && shallow.children && shallow.children.length > 0) {
value += tracker.move('\n')
value += tracker.move(state.containerFlow(shallow, tracker.current()))
}
value += tracker.move('\n' + sequence)
}
exit()
return value
}
/** @type {ToMarkdownHandle} */
function peekDirective() {
return ':'
}
/**
* @param {Directives} node
* @param {State} state
* @returns {string}
*/
function attributes(node, state) {
const quote = state.options.quote || '"'
const subset = node.type === 'textDirective' ? [quote] : [quote, '\n', '\r']
const attrs = node.attributes || {}
/** @type {Array<string>} */
const values = []
/** @type {string | undefined} */
let classesFull
/** @type {string | undefined} */
let classes
/** @type {string | undefined} */
let id
/** @type {string} */
let key
for (key in attrs) {
if (
own.call(attrs, key) &&
attrs[key] !== undefined &&
attrs[key] !== null
) {
const value = String(attrs[key])
if (key === 'id') {
id = shortcut.test(value) ? '#' + value : quoted('id', value)
} else if (key === 'class') {
const list = value.split(/[\t\n\r ]+/g)
/** @type {Array<string>} */
const classesFullList = []
/** @type {Array<string>} */
const classesList = []
let index = -1
while (++index < list.length) {
;(shortcut.test(list[index]) ? classesList : classesFullList).push(
list[index]
)
}
classesFull =
classesFullList.length > 0
? quoted('class', classesFullList.join(' '))
: ''
classes = classesList.length > 0 ? '.' + classesList.join('.') : ''
} else {
values.push(quoted(key, value))
}
}
}
if (classesFull) {
values.unshift(classesFull)
}
if (classes) {
values.unshift(classes)
}
if (id) {
values.unshift(id)
}
return values.length > 0 ? '{' + values.join(' ') + '}' : ''
/**
* @param {string} key
* @param {string} value
* @returns {string}
*/
function quoted(key, value) {
return (
key +
(value
? '=' + quote + stringifyEntitiesLight(value, {subset}) + quote
: '')
)
}
}
/**
* @param {Nodes} node
* @returns {node is Paragraph & {data: {directiveLabel: true}}}
*/
function inlineDirectiveLabel(node) {
return Boolean(
node && node.type === 'paragraph' && node.data && node.data.directiveLabel
)
}
/**
* @param {Directives} node
* @returns {string}
*/
function fence(node) {
let size = 0
if (node.type === 'containerDirective') {
visitParents(node, function (node, parents) {
if (node.type === 'containerDirective') {
let index = parents.length
let nesting = 0
while (index--) {
if (parents[index].type === 'containerDirective') {
nesting++
}
}
if (nesting > size) size = nesting
}
})
size += 3
} else if (node.type === 'leafDirective') {
size = 2
} else {
size = 1
}
return ':'.repeat(size)
}

22
node_modules/mdast-util-directive/license generated vendored Normal file
View File

@@ -0,0 +1,22 @@
(The MIT License)
Copyright (c) 2020 Titus Wormer <tituswormer@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

102
node_modules/mdast-util-directive/package.json generated vendored Normal file
View File

@@ -0,0 +1,102 @@
{
"name": "mdast-util-directive",
"version": "3.0.0",
"description": "mdast extension to parse and serialize generic directives (`:cite[smith04]`)",
"license": "MIT",
"keywords": [
"unist",
"mdast",
"mdast-util",
"util",
"utility",
"markdown",
"markup",
"generic",
"directive",
"container",
"extension"
],
"repository": "syntax-tree/mdast-util-directive",
"bugs": "https://github.com/syntax-tree/mdast-util-directive/issues",
"funding": {
"type": "opencollective",
"url": "https://opencollective.com/unified"
},
"author": "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)",
"contributors": [
"Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
],
"sideEffects": false,
"type": "module",
"exports": "./index.js",
"files": [
"lib/",
"index.d.ts",
"index.js"
],
"dependencies": {
"@types/mdast": "^4.0.0",
"@types/unist": "^3.0.0",
"devlop": "^1.0.0",
"mdast-util-from-markdown": "^2.0.0",
"mdast-util-to-markdown": "^2.0.0",
"parse-entities": "^4.0.0",
"stringify-entities": "^4.0.0",
"unist-util-visit-parents": "^6.0.0"
},
"devDependencies": {
"@types/node": "^20.0.0",
"c8": "^8.0.0",
"micromark-extension-directive": "^3.0.0",
"prettier": "^2.0.0",
"remark-cli": "^11.0.0",
"remark-preset-wooorm": "^9.0.0",
"type-coverage": "^2.0.0",
"typescript": "^5.0.0",
"unist-util-remove-position": "^5.0.0",
"xo": "^0.54.0"
},
"scripts": {
"prepack": "npm run build && npm run format",
"build": "tsc --build --clean && tsc --build && type-coverage",
"format": "remark . -qfo && prettier . -w --loglevel warn && xo --fix",
"test-api-prod": "node --conditions production test.js",
"test-api-dev": "node --conditions development test.js",
"test-api": "npm run test-api-dev && npm run test-api-prod",
"test-coverage": "c8 --100 --reporter lcov npm run test-api",
"test": "npm run build && npm run format && npm run test-coverage"
},
"prettier": {
"bracketSpacing": false,
"semi": false,
"singleQuote": true,
"tabWidth": 2,
"trailingComma": "none",
"useTabs": false
},
"remarkConfig": {
"plugins": [
"remark-preset-wooorm"
]
},
"typeCoverage": {
"atLeast": 100,
"detail": true,
"ignoreCatch": true,
"strict": true
},
"xo": {
"overrides": [
{
"files": [
"**/*.ts"
],
"rules": {
"@typescript-eslint/ban-types": "off",
"@typescript-eslint/consistent-type-definitions": "off"
}
}
],
"prettier": true
}
}

571
node_modules/mdast-util-directive/readme.md generated vendored Normal file
View File

@@ -0,0 +1,571 @@
# mdast-util-directive
[![Build][build-badge]][build]
[![Coverage][coverage-badge]][coverage]
[![Downloads][downloads-badge]][downloads]
[![Size][size-badge]][size]
[![Sponsors][sponsors-badge]][collective]
[![Backers][backers-badge]][collective]
[![Chat][chat-badge]][chat]
[mdast][] extensions to parse and serialize [generic directives proposal][prop]
(`:cite[smith04]`, `::youtube[Video of a cat in a box]{v=01ab2cd3efg}`, and
such).
## Contents
* [What is this?](#what-is-this)
* [When to use this](#when-to-use-this)
* [Install](#install)
* [Use](#use)
* [API](#api)
* [`directiveFromMarkdown()`](#directivefrommarkdown)
* [`directiveToMarkdown()`](#directivetomarkdown)
* [`ContainerDirective`](#containerdirective)
* [`Directives`](#directives)
* [`LeafDirective`](#leafdirective)
* [`TextDirective`](#textdirective)
* [HTML](#html)
* [Syntax](#syntax)
* [Syntax tree](#syntax-tree)
* [Nodes](#nodes)
* [Mixin](#mixin)
* [Types](#types)
* [Compatibility](#compatibility)
* [Related](#related)
* [Contribute](#contribute)
* [License](#license)
## What is this?
This package contains two extensions that add support for directive syntax in
markdown to [mdast][].
These extensions plug into
[`mdast-util-from-markdown`][mdast-util-from-markdown] (to support parsing
directives in markdown into a syntax tree) and
[`mdast-util-to-markdown`][mdast-util-to-markdown] (to support serializing
directives in syntax trees to markdown).
## When to use this
Directives are one of the four ways to extend markdown: an arbitrary extension
syntax (see [Extending markdown][extending-markdown] in micromarks docs for
the alternatives and more info).
This mechanism works well when you control the content: who authors it, what
tools handle it, and where its displayed.
When authors can read a guide on how to embed a tweet but are not expected to
know the ins and outs of HTML or JavaScript.
Directives dont work well if you dont know who authors content, what tools
handle it, and where it ends up.
Example use cases are a docs website for a project or product, or blogging tools
and static site generators.
You can use these extensions when you are working with
`mdast-util-from-markdown` and `mdast-util-to-markdown` already.
When working with `mdast-util-from-markdown`, you must combine this package
with [`micromark-extension-directive`][extension].
When you dont need a syntax tree, you can use [`micromark`][micromark]
directly with `micromark-extension-directive`.
All these packages are used [`remark-directive`][remark-directive], which
focusses on making it easier to transform content by abstracting these
internals away.
This package only handles the syntax tree.
For example, it does not handle how markdown is turned to HTML.
You can use this with some more code to match your specific needs, to allow for
anything from callouts, citations, styled blocks, forms, embeds, spoilers, etc.
[Traverse the tree][traversal] to change directives to whatever you please.
## Install
This package is [ESM only][esm].
In Node.js (version 16+), install with [npm][]:
```sh
npm install mdast-util-directive
```
In Deno with [`esm.sh`][esmsh]:
```js
import {directiveFromMarkdown, directiveToMarkdown} from 'https://esm.sh/mdast-util-directive@3'
```
In browsers with [`esm.sh`][esmsh]:
```html
<script type="module">
import {directiveFromMarkdown, directiveToMarkdown} from 'https://esm.sh/mdast-util-directive@3?bundle'
</script>
```
## Use
Say our document `example.md` contains:
```markdown
A lovely language know as :abbr[HTML]{title="HyperText Markup Language"}.
```
…and our module `example.js` looks as follows:
```js
import fs from 'node:fs/promises'
import {fromMarkdown} from 'mdast-util-from-markdown'
import {toMarkdown} from 'mdast-util-to-markdown'
import {directive} from 'micromark-extension-directive'
import {directiveFromMarkdown, directiveToMarkdown} from 'mdast-util-directive'
const doc = await fs.readFile('example.md')
const tree = fromMarkdown(doc, {
extensions: [directive()],
mdastExtensions: [directiveFromMarkdown()]
})
console.log(tree)
const out = toMarkdown(tree, {extensions: [directiveToMarkdown()]})
console.log(out)
```
…now running `node example.js` yields (positional info removed for brevity):
```js
{
type: 'root',
children: [
{
type: 'paragraph',
children: [
{type: 'text', value: 'A lovely language know as '},
{
type: 'textDirective',
name: 'abbr',
attributes: {title: 'HyperText Markup Language'},
children: [{type: 'text', value: 'HTML'}]
},
{type: 'text', value: '.'}
]
}
]
}
```
```markdown
A lovely language know as :abbr[HTML]{title="HyperText Markup Language"}.
```
## API
This package exports the identifiers
[`directiveFromMarkdown`][api-directive-from-markdown] and
[`directiveToMarkdown`][api-directive-to-markdown].
There is no default export.
### `directiveFromMarkdown()`
Create an extension for [`mdast-util-from-markdown`][mdast-util-from-markdown]
to enable directives in markdown.
###### Returns
Extension for `mdast-util-from-markdown` to enable directives
([`FromMarkdownExtension`][from-markdown-extension]).
### `directiveToMarkdown()`
Create an extension for [`mdast-util-to-markdown`][mdast-util-to-markdown]
to enable directives in markdown.
There are no options, but passing [`options.quote`][quote] to
`mdast-util-to-markdown` is honored for attributes.
###### Returns
Extension for `mdast-util-to-markdown` to enable directives
([`ToMarkdownExtension`][to-markdown-extension]).
### `ContainerDirective`
Directive in flow content (such as in the root document, or block quotes),
which contains further flow content (TypeScript type).
###### Type
```ts
import type {BlockContent, DefinitionContent, Parent} from 'mdast'
interface ContainerDirective extends Parent {
type: 'containerDirective'
name: string
attributes?: Record<string, string | null | undefined> | null | undefined
children: Array<BlockContent | DefinitionContent>
}
```
### `Directives`
The different directive nodes (TypeScript type).
###### Type
```ts
type Directives = ContainerDirective | LeafDirective | TextDirective
```
### `LeafDirective`
Directive in flow content (such as in the root document, or block quotes),
which contains nothing (TypeScript type).
###### Type
```ts
import type {PhrasingContent, Parent} from 'mdast'
interface LeafDirective extends Parent {
type: 'leafDirective'
name: string
attributes?: Record<string, string | null | undefined> | null | undefined
children: Array<PhrasingContent>
}
```
### `TextDirective`
Directive in phrasing content (such as in paragraphs, headings) (TypeScript
type).
###### Type
```ts
import type {PhrasingContent, Parent} from 'mdast'
interface TextDirective extends Parent {
type: 'textDirective'
name: string
attributes?: Record<string, string | null | undefined> | null | undefined
children: Array<PhrasingContent>
}
```
## HTML
This utility does not handle how markdown is turned to HTML.
You can use this with some more code to match your specific needs, to allow for
anything from callouts, citations, styled blocks, forms, embeds, spoilers, etc.
[Traverse the tree][traversal] to change directives to whatever you please.
## Syntax
See [Syntax in `micromark-extension-directive`][syntax].
## Syntax tree
The following interfaces are added to **[mdast][]** by this utility.
### Nodes
#### `TextDirective`
```idl
interface TextDirective <: Parent {
type: 'textDirective'
children: [PhrasingContent]
}
TextDirective includes Directive
```
**TextDirective** (**[Parent][dfn-parent]**) is a directive.
It can be used where **[phrasing][dfn-phrasing-content]** content is expected.
Its content model is also **[phrasing][dfn-phrasing-content]** content.
It includes the mixin **[Directive][dfn-mxn-directive]**.
For example, the following Markdown:
```markdown
:name[Label]{#x.y.z key=value}
```
Yields:
```js
{
type: 'textDirective',
name: 'name',
attributes: {id: 'x', class: 'y z', key: 'value'},
children: [{type: 'text', value: 'Label'}]
}
```
#### `LeafDirective`
```idl
interface LeafDirective <: Parent {
type: 'leafDirective'
children: [PhrasingContent]
}
LeafDirective includes Directive
```
**LeafDirective** (**[Parent][dfn-parent]**) is a directive.
It can be used where **[flow][dfn-flow-content]** content is expected.
Its content model is **[phrasing][dfn-phrasing-content]** content.
It includes the mixin **[Directive][dfn-mxn-directive]**.
For example, the following Markdown:
```markdown
::youtube[Label]{v=123}
```
Yields:
```js
{
type: 'leafDirective',
name: 'youtube',
attributes: {v: '123'},
children: [{type: 'text', value: 'Label'}]
}
```
#### `ContainerDirective`
```idl
interface ContainerDirective <: Parent {
type: 'containerDirective'
children: [FlowContent]
}
ContainerDirective includes Directive
```
**ContainerDirective** (**[Parent][dfn-parent]**) is a directive.
It can be used where **[flow][dfn-flow-content]** content is expected.
Its content model is also **[flow][dfn-flow-content]** content.
It includes the mixin **[Directive][dfn-mxn-directive]**.
The phrasing in the label is, when available, added as a paragraph with a
`directiveLabel: true` field, as the head of its content.
For example, the following Markdown:
```markdown
:::spoiler[Open at your own peril]
He dies.
:::
```
Yields:
```js
{
type: 'containerDirective',
name: 'spoiler',
attributes: {},
children: [
{
type: 'paragraph',
data: {directiveLabel: true},
children: [{type: 'text', value: 'Open at your own peril'}]
},
{
type: 'paragraph',
children: [{type: 'text', value: 'He dies.'}]
}
]
}
```
### Mixin
#### `Directive`
```idl
interface mixin Directive {
name: string
attributes: Attributes?
}
interface Attributes {}
typedef string AttributeName
typedef string AttributeValue
```
**Directive** represents something defined by an extension.
The `name` field must be present and represents an identifier of an extension.
The `attributes` field represents information associated with the node.
The value of the `attributes` field implements the **Attributes** interface.
In the **Attributes** interface, every field must be an `AttributeName` and
every value an `AttributeValue`.
The fields and values can be anything: there are no semantics (such as by HTML
or hast).
> In JSON, the value `null` must be treated as if the attribute was not
> included.
> In JavaScript, both `null` and `undefined` must be similarly ignored.
## Types
This package is fully typed with [TypeScript][].
It exports the additional types [`ContainerDirective`][api-container-directive],
[`Directives`][api-directives], [`LeafDirective`][api-leaf-directive], and
[`TextDirective`][api-text-directive].
It also registers the node types with `@types/mdast`.
If youre working with the syntax tree, make sure to import this utility
somewhere in your types, as that registers the new node types in the tree.
```js
/**
* @typedef {import('mdast-util-directive')}
*/
import {visit} from 'unist-util-visit'
/** @type {import('mdast').Root} */
const tree = getMdastNodeSomeHow()
visit(tree, function (node) {
// `node` can now be one of the nodes for directives.
})
```
## Compatibility
Projects maintained by the unified collective are compatible with maintained
versions of Node.js.
When we cut a new major release, we drop support for unmaintained versions of
Node.
This means we try to keep the current release line, `mdast-util-directive@^3`,
compatible with Node.js 16.
This utility works with `mdast-util-from-markdown` version 2+ and
`mdast-util-to-markdown` version 2+.
## Related
* [`remarkjs/remark-directive`][remark-directive]
— remark plugin to support generic directives
* [`micromark/micromark-extension-directive`][extension]
— micromark extension to parse directives
## Contribute
See [`contributing.md`][contributing] in [`syntax-tree/.github`][health] for
ways to get started.
See [`support.md`][support] for ways to get help.
This project has a [code of conduct][coc].
By interacting with this repository, organization, or community you agree to
abide by its terms.
## License
[MIT][license] © [Titus Wormer][author]
<!-- Definitions -->
[build-badge]: https://github.com/syntax-tree/mdast-util-directive/workflows/main/badge.svg
[build]: https://github.com/syntax-tree/mdast-util-directive/actions
[coverage-badge]: https://img.shields.io/codecov/c/github/syntax-tree/mdast-util-directive.svg
[coverage]: https://codecov.io/github/syntax-tree/mdast-util-directive
[downloads-badge]: https://img.shields.io/npm/dm/mdast-util-directive.svg
[downloads]: https://www.npmjs.com/package/mdast-util-directive
[size-badge]: https://img.shields.io/badge/dynamic/json?label=minzipped%20size&query=$.size.compressedSize&url=https://deno.bundlejs.com/?q=mdast-util-directive
[size]: https://bundlejs.com/?q=mdast-util-directive
[sponsors-badge]: https://opencollective.com/unified/sponsors/badge.svg
[backers-badge]: https://opencollective.com/unified/backers/badge.svg
[collective]: https://opencollective.com/unified
[chat-badge]: https://img.shields.io/badge/chat-discussions-success.svg
[chat]: https://github.com/syntax-tree/unist/discussions
[npm]: https://docs.npmjs.com/cli/install
[esm]: https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c
[esmsh]: https://esm.sh
[typescript]: https://www.typescriptlang.org
[license]: license
[author]: https://wooorm.com
[health]: https://github.com/syntax-tree/.github
[contributing]: https://github.com/syntax-tree/.github/blob/main/contributing.md
[support]: https://github.com/syntax-tree/.github/blob/main/support.md
[coc]: https://github.com/syntax-tree/.github/blob/main/code-of-conduct.md
[mdast]: https://github.com/syntax-tree/mdast
[mdast-util-from-markdown]: https://github.com/syntax-tree/mdast-util-from-markdown
[mdast-util-to-markdown]: https://github.com/syntax-tree/mdast-util-to-markdown
[quote]: https://github.com/syntax-tree/mdast-util-to-markdown#optionsquote
[micromark]: https://github.com/micromark/micromark
[extension]: https://github.com/micromark/micromark-extension-directive
[syntax]: https://github.com/micromark/micromark-extension-directive#syntax
[remark-directive]: https://github.com/remarkjs/remark-directive
[extending-markdown]: https://github.com/micromark/micromark#extending-markdown
[prop]: https://talk.commonmark.org/t/generic-directives-plugins-syntax/444
[traversal]: https://unifiedjs.com/learn/recipe/tree-traversal/
[dfn-parent]: https://github.com/syntax-tree/mdast#parent
[dfn-flow-content]: https://github.com/syntax-tree/mdast#flowcontent
[dfn-phrasing-content]: https://github.com/syntax-tree/mdast#phrasingcontent
[from-markdown-extension]: https://github.com/syntax-tree/mdast-util-from-markdown#extension
[to-markdown-extension]: https://github.com/syntax-tree/mdast-util-to-markdown#options
[api-directive-from-markdown]: #directivefrommarkdown
[api-directive-to-markdown]: #directivetomarkdown
[api-container-directive]: #containerdirective
[api-directives]: #directives
[api-leaf-directive]: #leafdirective
[api-text-directive]: #textdirective
[dfn-mxn-directive]: #directive