Skip to content

syntax-tree/mdast-zone

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

mdast-zone

Build Coverage Downloads Size Sponsors Backers Chat

mdast utility to treat HTML comments as ranges.

Useful in remark plugins.

Install

npm:

npm install mdast-zone

Use

Say we have the following file, example.md:

<!--foo start-->

Foo

<!--foo end-->

And our script, example.js, looks as follows:

var vfile = require('to-vfile')
var remark = require('remark')
var zone = require('mdast-zone')

remark()
  .use(plugin)
  .process(vfile.readSync('example.md'), function(err, file) {
    if (err) throw err
    console.log(String(file))
  })

function plugin() {
  return transform

  function transform(tree) {
    zone(tree, 'foo', mutate)
  }

  function mutate(start, nodes, end) {
    return [
      start,
      {type: 'paragraph', children: [{type: 'text', value: 'Bar'}]},
      end
    ]
  }
}

Now, running node example yields:

<!--foo start-->

Bar

<!--foo end-->

API

zone(tree, name, handler)

Search tree for comment ranges (“zones”).

Parameters
  • tree (Node) — Tree to search for ranges
  • name (string) — Name of ranges to search for
  • handler (Function) — Function invoked for each found range

function handler(start, nodes, end)

Invoked with the two markers that determine a range: the first start and the last end, and the content inside.

Parameters
  • start (Node) — Start of range (an HTML comment node)
  • nodes (Array.<Node>) — Nodes between start and end
  • end (Node) — End of range (an HTML comment node)
Returns

Array.<Node>? — List of nodes to replace start, nodes, and end with, optional.

Security

Improper use of handler can open you up to a cross-site scripting (XSS) attack as the value it returns is injected into the syntax tree. This can become a problem if the tree is later transformed to hast. The following example shows how a script is injected that could run when loaded in a browser.

function handler(start, nodes, end) {
  return [start, {type: 'html', value: 'alert(1)'}, end]
}

Yields:

<!--foo start-->

<script>alert(1)</script>

<!--foo end-->

Either do not use user input or use hast-util-santize.

Contribute

See contributing.md in syntax-tree/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Titus Wormer

About

utility to treat HTML comments as ranges or markers in mdast

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Contributors 4

  •  
  •  
  •  
  •