Skip to content

Commit 6d73750

Browse files
committed
Improve traverse logic and error handling for safer translation parsing
- Add safety check for missing argument nodes to prevent runtime errors - Conditionally log unexpected node types based on debug flag - Minor cleanup and consistency improvements
1 parent 0fec020 commit 6d73750

1 file changed

Lines changed: 12 additions & 6 deletions

File tree

src/parser/tree.ts

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -136,10 +136,11 @@ export function doTree(
136136
*/
137137
function traverse(node: SyntaxNode): void {
138138
// Walk the tree
139-
if (node?.children.length)
139+
if (node?.children.length) {
140140
for (const child of node.children) {
141141
traverse(child);
142142
}
143+
}
143144

144145
// Check if the node matches
145146
if (node?.type === typeToMatch) {
@@ -165,6 +166,10 @@ export function doTree(
165166
// Get the whole gettext translation string
166167
// eslint-disable-next-line @typescript-eslint/no-unused-vars
167168
const [_fn, raw] = node.children;
169+
170+
// Safety check: verify we actually have an arguments node
171+
if (!raw) return;
172+
168173
const translation: Partial<{
169174
msgctxt: string;
170175
msgid: string;
@@ -187,7 +192,6 @@ export function doTree(
187192
// Get the translation from the arguments
188193
for (const child of children) {
189194
let node = child;
190-
let nodeValue: string | string[] = node.text;
191195

192196
// unwrap the argument node, which is used in PHP.
193197
if (child.type === "argument") {
@@ -221,10 +225,12 @@ export function doTree(
221225
nodeValue = node.text;
222226
} else {
223227
// Whenever we get an unexpected node type this string is not translatable and should be skipped
224-
console.error(
225-
`Unexpected node type ${node?.type} identified as ${translationKeys[translationKeyIndex]} with value ${nodeValue} in ${filepath} at ${node.startPosition.row + 1} pos ${node.startPosition.column + 1}`,
226-
);
227-
return; // Parse error, skip this translation.
228+
if (debugEnabled) {
229+
console.error(
230+
`Unexpected node type ${node?.type} identified as ${translationKeys[translationKeyIndex]} with value ${nodeValue} in ${filepath} at ${node.startPosition.row + 1} pos ${node.startPosition.column + 1}`,
231+
);
232+
}
233+
return; // Parse error, skip this translation.
228234
}
229235

230236
// the value of that key

0 commit comments

Comments
 (0)