diff --git a/index.js b/index.js index a79b708..2ac3b41 100644 --- a/index.js +++ b/index.js @@ -1 +1,5 @@ +/** + * @typedef {import('./lib/index.js').GetDefinition} GetDefinition + */ + export {definitions} from './lib/index.js' diff --git a/lib/index.js b/lib/index.js index 4dd5c14..3528fd1 100644 --- a/lib/index.js +++ b/lib/index.js @@ -1,28 +1,44 @@ /** - * @typedef {import('mdast').Root|import('mdast').Content} Node + * @typedef {import('mdast').Root} Root + * @typedef {import('mdast').Content} Content * @typedef {import('mdast').Definition} Definition */ +/** + * @typedef {Root | Content} Node + * + * @callback GetDefinition + * Get a definition by identifier. + * @param {string | null | undefined} [identifier] + * Identifier of definition. + * @returns {Definition | null} + * Definition corresponding to `identifier`, if found. + */ + import {visit} from 'unist-util-visit' const own = {}.hasOwnProperty /** * Find definitions in `node`. + * * Uses CommonMark precedence, which means that earlier definitions are * preferred over duplicate later definitions. * - * @param {Node} node + * @param {Node} tree + * Tree to check. + * @returns {GetDefinition} + * Getter. */ -export function definitions(node) { +export function definitions(tree) { /** @type {Record} */ const cache = Object.create(null) - if (!node || !node.type) { + if (!tree || !tree.type) { throw new Error('mdast-util-definitions expected node') } - visit(node, 'definition', (definition) => { + visit(tree, 'definition', (definition) => { const id = clean(definition.identifier) if (id && !own.call(cache, id)) { cache[id] = definition @@ -31,12 +47,7 @@ export function definitions(node) { return definition - /** - * Get a node from the bound definition cache. - * - * @param {string} identifier - * @returns {Definition|null} - */ + /** @type {GetDefinition} */ function definition(identifier) { const id = clean(identifier) return id && own.call(cache, id) ? cache[id] : null @@ -44,7 +55,7 @@ export function definitions(node) { } /** - * @param {string} [value] + * @param {string | null | undefined} [value] * @returns {string} */ function clean(value) {