Skip to main content
Core utilities for working with AST nodes, including indentation detection, scope resolution, and code manipulation.

Indentation Utilities

detectIndentUnit

Detects the indentation unit used in source code (\t or spaces).
string
required
The source code to analyze
Returns: string - The indentation unit ('\t' for tabs or a string of spaces)
The function analyzes all indented lines and uses the greatest common divisor (GCD) to determine the space-based indentation unit.

getLineIndent

Returns the indentation prefix for the line containing the given character index.
string
required
The source code
number
required
The character index within the source code
Returns: string - The indentation string (spaces or tabs) at the start of the line

Scope Resolution

getScope

Finds the enclosing scope for a node (e.g., statement_block or program).
SgNode<Js>
required
The AST node to find the scope for
string
Optional custom parent node type to stop at
Returns: SgNode<Js> | null - The scope node or null if not found

Shebang Utilities

getShebang

Returns the Node.js shebang line node when present (e.g., #!/usr/bin/env node).
SgRoot
required
The root AST node to search
Returns: SgNode | null - The shebang node if found, otherwise null
Only returns shebangs that appear at the start of the file (line 0) and contain “node” or “node.exe”.

replaceNodeJsArgs (shebang)

Replaces Node.js arguments in shebang lines.
SgRoot
required
The root AST node to search
Record<string, string>
required
A mapping of argument names to their replacement values. Use empty string to remove an argument.
Returns: Edit[] - Array of edit operations to apply

Code Manipulation

removeLines

Safely removes multiple line ranges from source code, handling overlaps and duplicates.
string
required
The original source code as a single string
Range[]
required
An array of ranges to remove. Each range has start and end with line and column properties.
Returns: string - The modified source code with the specified ranges removed
The function automatically handles duplicate and overlapping ranges by normalizing them before applying removals.

Import/Require Identifier Extraction

getDefaultImportIdentifier

Returns the identifier node for a default import (e.g., import fs from 'fs').
SgNode<Js>
required
The import_statement or import_clause node
Returns: SgNode<Js> | null - The identifier node for the default import, or null if none

getRequireNamespaceIdentifier

Returns the identifier node for namespace-style require (e.g., const util = require('util')).
SgNode<Js>
required
The variable_declarator node containing the require call
Returns: SgNode<Js> | null - The identifier node for the namespace binding, or null for destructured requires

Usage Examples

Preserving Indentation When Adding Code

Finding and Modifying Shebang Lines

Cleaning Up Multiple Import Statements