Registry / serialization / unist-util-visit-parents

unist-util-visit-parents

JSON →
library6.0.2jsnpmunverified

unist-util-visit-parents is a robust utility within the unist (Universal Syntax Tree) ecosystem designed for deeply traversing ASTs (Abstract Syntax Trees) while providing a full lineage of parent nodes for each visited node. This functionality is crucial for transformations or analyses that require contextual information about a node's position within the tree. The current stable version is 6.0.2, with active development evidenced by frequent minor and major releases, particularly focusing on TypeScript type improvements and ESM compatibility. It differentiates itself from `unist-util-visit` by offering an array of parent nodes, making it indispensable for scenarios where ancestral context is necessary, such as scope analysis or complex rewrite operations. The library is ESM-only and requires Node.js 16 or higher, adhering to modern JavaScript module standards.

npm install unist-util-visit-parents
INSTALL
IMPORT
SIG · UNIST-UTIL-VISIT-P
U
unist-util-visit-parents
serializationjavascriptv6.0.2
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

visitParents
import { visitParents } from 'unist-util-visit-parents'
const visitParents = require('unist-util-visit-parents').visitParents
The package is ESM-only since v6.0.0 and must be imported using ES modules syntax. CommonJS `require` will result in an `ERR_REQUIRE_ESM` error.
CONTINUE
import { CONTINUE } from 'unist-util-visit-parents'
import { Action } from 'unist-util-visit-parents'
`CONTINUE`, `EXIT`, and `SKIP` are named exports representing specific actions for visitor functions. `Action` is a TypeScript type, not a runtime value.
Visitor
import type { Visitor } from 'unist-util-visit-parents'
import { Visitor } from 'unist-util-visit-parents'
When importing types like `Visitor`, `Action`, or `Test`, use `import type` to clearly distinguish them from runtime values and avoid bundling issues.

Demonstrates how to use `visitParents` to traverse a Markdown AST, log node types with ancestral paths, modify nodes, and control traversal flow using `SKIP`.

import { visitParents, SKIP } from 'unist-util-visit-parents'; import { fromMarkdown } from 'mdast-util-from-markdown'; import type { Root, Paragraph, Strong, PhrasingContent } from 'mdast'; const markdownInput = 'This is a *test* with **strong** emphasis and `code` blocks.'; const tree: Root = fromMarkdown(markdownInput); console.log('Original Tree:'); console.log(JSON.stringify(tree, null, 2)); // Example 1: Log all nodes and their direct parent types visitParents(tree, (node, ancestors) => { const parentTypes = ancestors.length > 0 ? ancestors.map(p => p.type).join(' > ') : 'Root'; console.log(`- Node Type: ${node.type}, Parents: ${parentTypes}`); }); // Example 2: Skip children of 'strong' nodes and modify content visitParents<Strong>(tree, 'strong', (node, ancestors) => { console.log(`\nVisiting strong node: ${node.value || ''}`); if (node.children && node.children.length > 0 && node.children[0].type === 'text') { node.children[0].value = (node.children[0].value || '') + ' (MODIFIED)'; console.log(` Modified strong text. Skipping its children for further traversal.`); } return SKIP; // Do not traverse children of this 'strong' node }); console.log('\nModified Tree (strong nodes updated and their children skipped):'); console.log(JSON.stringify(tree, null, 2)); // Example 3: Find a specific node type and its ancestors, then exit let foundCode = false; visitParents<PhrasingContent>(tree, 'inlineCode', (node, ancestors) => { console.log(`\nFound inlineCode: ${node.value}`); console.log(' Ancestors:', ancestors.map(a => a.type)); foundCode = true; return true; // Use true (CONTINUE) or EXIT to stop, depending on requirement }); if (!foundCode) { console.log('\nNo inlineCode nodes found.'); }
Debug
Known issues
breakingVersion 6.0.0 changed the package to be ESM-only, removing CommonJS support. It also updated the required Node.js version to 16 or higher.
fix
Migrate your project to use ES modules (`import`/`export`) or ensure your build tools correctly transpile if targeting older environments. Update your Node.js runtime to version 16 or newer. Do not use `require()` for this package.
affects: >=6.0.0
breakingWith version 6.0.0, the package now uses an `exports` map in `package.json`. This may affect how the package is resolved in older bundlers or Node.js environments that do not fully support `exports` maps, or if you were relying on undocumented deep imports.
fix
Ensure your tooling supports `exports` maps. Always import symbols directly from the main package entrypoint (`unist-util-visit-parents`) rather than relying on private or deep paths.
affects: >=6.0.0
breakingVersion 6.0.0 removed the `complex-types.d.ts` file, consolidating types into the main export. TypeScript projects relying on this specific file for type imports will break.
fix
Update your TypeScript imports to use types directly from the main `unist-util-visit-parents` export. TypeScript's inference capabilities have also improved, often making explicit type imports less necessary for visitor arguments.
affects: >=6.0.0
breakingVersion 5.0.0 introduced a breaking change to TypeScript types, specifically how the `visitor` function's arguments are typed, basing them on the `tree` type. This might cause type errors in existing TypeScript projects.
fix
Review your `visitor` function signatures. TypeScript should now correctly infer types, but you might need to adjust explicit type annotations to align with the new base typing logic. Consider using type parameters with `visitParents<SpecificNodeType>(...)` for better type inference.
affects: >=5.0.0 <6.0.0
gotchaThe `reverse` option (the fourth argument to `visitParents`) changes the traversal order from preorder (NLR) to reverse preorder (NRL). Using this incorrectly can lead to unexpected processing order for nodes.
fix
Carefully consider the implications of traversal order for your specific task. Preorder is generally suitable for most transformations; `reverse` is for specific cases where children need to be processed before their parents, but still in a depth-first manner.
affects: >=1.0.0
gotchaThis utility is a high-level abstraction for AST traversal. For optimal performance in complex scenarios, avoid walking the tree multiple times. Instead, perform a single walk and use `unist-util-is` inside your visitor function to test for different node types and apply multiple operations.
fix
Structure your visitors to handle multiple conditions within a single traversal loop. For example: `visitParents(tree, (node, parents) => { if (is(node, 'paragraph')) { ... } if (is(node, 'strong')) { ... } })`
affects: >=1.0.0
Errors
Common errors & fixes
ERR_REQUIRE_ESM
Attempting to `require()` an ESM-only package like `unist-util-visit-parents`.
fix
Change `const { visitParents } = require('unist-util-visit-parents');` to `import { visitParents } from 'unist-util-visit-parents';` and ensure your environment supports ES modules (e.g., Node.js 16+ or a bundler).
TypeError: Cannot read properties of undefined (reading 'exports')
This error often occurs in older Node.js versions or build environments when an ESM-only package (like `unist-util-visit-parents@6`) is incorrectly treated as a CommonJS module, particularly when there's an `exports` map involved.
fix
Ensure you are running Node.js 16 or newer. If using a bundler (e.g., Webpack, Rollup), update it to a version that fully supports ESM and `exports` maps. Verify your `tsconfig.json` (if applicable) is configured for a modern module system (e.g., `"module": "Node16"` or `"ES2022"`).
TypeError: visitParents is not a function
This usually indicates that the import failed to correctly resolve `visitParents`. This can happen if you're using CommonJS `require()` or if there's a mismatch between how the module is exported and imported (e.g., trying to import a default export when only named exports exist).
fix
Confirm your import statement is `import { visitParents } from 'unist-util-visit-parents';`. If you're in a CommonJS context, you cannot use this package directly; you must transition to ESM or use an older version if available (though not recommended).
Argument of type '...' is not assignable to parameter of type 'Test'.
TypeScript error related to the `test` argument of `visitParents` or the `visitor` function's node types not matching the expected `Node` interface or a more specific unist node type.
fix
Ensure you are using a compatible version of `@types/unist` for your unist package. For specific node types, use type parameters with `visitParents<SpecificNodeType>(tree, 'type', visitor)` or `is()` from `unist-util-is` for more robust type checking within the visitor. Update `@types/unist` if needed, as `unist-util-visit-parents` v6.0.0 updated its dependency.
Upgrade
Version history
6.0.2latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
16 hits · last 30 days
node
14
OpenAI (training)
1
Resources