File size: 9,221 Bytes
064bfd6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | import memoize from 'lodash-es/memoize.js'
import {
extractOutputRedirections,
splitCommandWithOperators,
} from './commands.js'
import type { Node } from './parser.js'
import {
analyzeCommand,
type TreeSitterAnalysis,
} from './treeSitterAnalysis.js'
export type OutputRedirection = {
target: string
operator: '>' | '>>'
}
/**
* Interface for parsed command implementations.
* Both tree-sitter and regex fallback implementations conform to this.
*/
export interface IParsedCommand {
readonly originalCommand: string
toString(): string
getPipeSegments(): string[]
withoutOutputRedirections(): string
getOutputRedirections(): OutputRedirection[]
/**
* Returns tree-sitter analysis data if available.
* Returns null for the regex fallback implementation.
*/
getTreeSitterAnalysis(): TreeSitterAnalysis | null
}
/**
* @deprecated Legacy regex/shell-quote path. Only used when tree-sitter is
* unavailable. The primary gate is parseForSecurity (ast.ts).
*
* Regex-based fallback implementation using shell-quote parser.
* Used when tree-sitter is not available.
* Exported for testing purposes.
*/
export class RegexParsedCommand_DEPRECATED implements IParsedCommand {
readonly originalCommand: string
constructor(command: string) {
this.originalCommand = command
}
toString(): string {
return this.originalCommand
}
getPipeSegments(): string[] {
try {
const parts = splitCommandWithOperators(this.originalCommand)
const segments: string[] = []
let currentSegment: string[] = []
for (const part of parts) {
if (part === '|') {
if (currentSegment.length > 0) {
segments.push(currentSegment.join(' '))
currentSegment = []
}
} else {
currentSegment.push(part)
}
}
if (currentSegment.length > 0) {
segments.push(currentSegment.join(' '))
}
return segments.length > 0 ? segments : [this.originalCommand]
} catch {
return [this.originalCommand]
}
}
withoutOutputRedirections(): string {
if (!this.originalCommand.includes('>')) {
return this.originalCommand
}
const { commandWithoutRedirections, redirections } =
extractOutputRedirections(this.originalCommand)
return redirections.length > 0
? commandWithoutRedirections
: this.originalCommand
}
getOutputRedirections(): OutputRedirection[] {
const { redirections } = extractOutputRedirections(this.originalCommand)
return redirections
}
getTreeSitterAnalysis(): TreeSitterAnalysis | null {
return null
}
}
type RedirectionNode = OutputRedirection & {
startIndex: number
endIndex: number
}
function visitNodes(node: Node, visitor: (node: Node) => void): void {
visitor(node)
for (const child of node.children) {
visitNodes(child, visitor)
}
}
function extractPipePositions(rootNode: Node): number[] {
const pipePositions: number[] = []
visitNodes(rootNode, node => {
if (node.type === 'pipeline') {
for (const child of node.children) {
if (child.type === '|') {
pipePositions.push(child.startIndex)
}
}
}
})
// visitNodes is depth-first. For `a | b && c | d`, the outer `list` nests
// the second pipeline as a sibling of the first, so the outer `|` is
// visited before the inner one — positions arrive out of order.
// getPipeSegments iterates them to slice left-to-right, so sort here.
return pipePositions.sort((a, b) => a - b)
}
function extractRedirectionNodes(rootNode: Node): RedirectionNode[] {
const redirections: RedirectionNode[] = []
visitNodes(rootNode, node => {
if (node.type === 'file_redirect') {
const children = node.children
const op = children.find(c => c.type === '>' || c.type === '>>')
const target = children.find(c => c.type === 'word')
if (op && target) {
redirections.push({
startIndex: node.startIndex,
endIndex: node.endIndex,
target: target.text,
operator: op.type as '>' | '>>',
})
}
}
})
return redirections
}
class TreeSitterParsedCommand implements IParsedCommand {
readonly originalCommand: string
// Tree-sitter's startIndex/endIndex are UTF-8 byte offsets, but JS
// String.slice() uses UTF-16 code-unit indices. For ASCII they coincide;
// for multi-byte code points (e.g. `—` U+2014: 3 UTF-8 bytes, 1 code unit)
// they diverge and slicing the string directly lands mid-token. Slicing
// the UTF-8 Buffer with tree-sitter's byte offsets and decoding back to
// string is correct regardless of code-point width.
private readonly commandBytes: Buffer
private readonly pipePositions: number[]
private readonly redirectionNodes: RedirectionNode[]
private readonly treeSitterAnalysis: TreeSitterAnalysis
constructor(
command: string,
pipePositions: number[],
redirectionNodes: RedirectionNode[],
treeSitterAnalysis: TreeSitterAnalysis,
) {
this.originalCommand = command
this.commandBytes = Buffer.from(command, 'utf8')
this.pipePositions = pipePositions
this.redirectionNodes = redirectionNodes
this.treeSitterAnalysis = treeSitterAnalysis
}
toString(): string {
return this.originalCommand
}
getPipeSegments(): string[] {
if (this.pipePositions.length === 0) {
return [this.originalCommand]
}
const segments: string[] = []
let currentStart = 0
for (const pipePos of this.pipePositions) {
const segment = this.commandBytes
.subarray(currentStart, pipePos)
.toString('utf8')
.trim()
if (segment) {
segments.push(segment)
}
currentStart = pipePos + 1
}
const lastSegment = this.commandBytes
.subarray(currentStart)
.toString('utf8')
.trim()
if (lastSegment) {
segments.push(lastSegment)
}
return segments
}
withoutOutputRedirections(): string {
if (this.redirectionNodes.length === 0) return this.originalCommand
const sorted = [...this.redirectionNodes].sort(
(a, b) => b.startIndex - a.startIndex,
)
let result = this.commandBytes
for (const redir of sorted) {
result = Buffer.concat([
result.subarray(0, redir.startIndex),
result.subarray(redir.endIndex),
])
}
return result.toString('utf8').trim().replace(/\s+/g, ' ')
}
getOutputRedirections(): OutputRedirection[] {
return this.redirectionNodes.map(({ target, operator }) => ({
target,
operator,
}))
}
getTreeSitterAnalysis(): TreeSitterAnalysis {
return this.treeSitterAnalysis
}
}
const getTreeSitterAvailable = memoize(async (): Promise<boolean> => {
try {
const { parseCommand } = await import('./parser.js')
const testResult = await parseCommand('echo test')
return testResult !== null
} catch {
return false
}
})
/**
* Build a TreeSitterParsedCommand from a pre-parsed AST root. Lets callers
* that already have the tree skip the redundant native.parse that
* ParsedCommand.parse would do.
*/
export function buildParsedCommandFromRoot(
command: string,
root: Node,
): IParsedCommand {
const pipePositions = extractPipePositions(root)
const redirectionNodes = extractRedirectionNodes(root)
const analysis = analyzeCommand(root, command)
return new TreeSitterParsedCommand(
command,
pipePositions,
redirectionNodes,
analysis,
)
}
async function doParse(command: string): Promise<IParsedCommand | null> {
if (!command) return null
const treeSitterAvailable = await getTreeSitterAvailable()
if (treeSitterAvailable) {
try {
const { parseCommand } = await import('./parser.js')
const data = await parseCommand(command)
if (data) {
// Native NAPI parser returns plain JS objects (no WASM handles);
// nothing to free — extract directly.
return buildParsedCommandFromRoot(command, data.rootNode)
}
} catch {
// Fall through to regex implementation
}
}
// Fallback to regex implementation
return new RegexParsedCommand_DEPRECATED(command)
}
// Single-entry cache: legacy callers (bashCommandIsSafeAsync,
// buildSegmentWithoutRedirections) may call ParsedCommand.parse repeatedly
// with the same command string. Each parse() is ~1 native.parse + ~6 tree
// walks, so caching the most recent command skips the redundant work.
// Size-1 bound avoids leaking TreeSitterParsedCommand instances.
let lastCmd: string | undefined
let lastResult: Promise<IParsedCommand | null> | undefined
/**
* ParsedCommand provides methods for working with shell commands.
* Uses tree-sitter when available for quote-aware parsing,
* falls back to regex-based parsing otherwise.
*/
export const ParsedCommand = {
/**
* Parse a command string and return a ParsedCommand instance.
* Returns null if parsing fails completely.
*/
parse(command: string): Promise<IParsedCommand | null> {
if (command === lastCmd && lastResult !== undefined) {
return lastResult
}
lastCmd = command
lastResult = doParse(command)
return lastResult
},
}
|