Skip to content

Commit 23ea19c

Browse files
authored
fix(openapi-inference): strip tsconfig comments and trailing commas in linear time (#2502)
## What `stripJsonComments` in `packages/openapi-inference/src/project.ts` removed trailing commas with the lookahead `,(?=\s*(?:\/\/[^\n]*\s*|\/\*[\s\S]*?\*\/\s*)*[\]}])`. When the next real token after a comma isn't `]` or `}`, the lookahead fails and V8 tries every way to split the following run of comments between the `(...)*` iterations, which takes exponential time. `readReferencePaths` runs this on a solution tsconfig (the documented `"files": []` with `references` setup) and on every tsconfig it references. So a referenced tsconfig with a `////` banner after `"strict": true,` hangs project loading: 40 slashes took 1.3 s, 46 took 23.8 s, and an 80-column banner never finishes. Back-to-back block comments do the same. ## Fix Replace the regex with a scanner that reads the text once from start to end: - strings are copied as they are, escapes included - `//` and `/* */` comments are dropped - it remembers the last comma it saw and drops it when the next token, past whitespace and comments, is `]` or `}`; anything else in between keeps it The work now grows with the file's length, whatever the input. ## Tests In `project.test.ts`: - A solution tsconfig with 40 back-to-back block comments, referencing an app tsconfig with an 80-column `/` banner and 40 lines of block comments. With the old regex this hangs (killed by a 60 s timeout). - A reference path `"./*/../a,b//c"` (contains `/*`, a comma and `//`) followed by trailing commas before line and block comments, to check that strings are kept and trailing commas are still dropped. For reviewers: without the fix the banner test hangs rather than failing, since Vitest can't time out a test that blocks synchronously. `pnpm check` passes. `pnpm exec vitest run` passes except `openapi-generator.test.ts` > "names the nearest tsconfig when it does not include the file, and why", which also fails on `main`.
1 parent 0bb8c10 commit 23ea19c

2 files changed

Lines changed: 92 additions & 4 deletions

File tree

‎packages/openapi-inference/src/project.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,58 @@ describe('openTypeScriptProject', () => {
105105
).toEqual([`Using the compiler options of "${path.join(root, 'app/tsconfig.json')}".`])
106106
})
107107

108+
// the old trailing comma regex backtracked exponentially on these, never finishing
109+
it('reads the references of tsconfigs with a slash banner and back-to-back block comments', () => {
110+
write(
111+
'tsconfig.json',
112+
`{
113+
"files": [],
114+
"references": [{ "path": "./app" }],
115+
${'/* reference */'.repeat(40)}
116+
}`,
117+
)
118+
write(
119+
'app/tsconfig.json',
120+
`{
121+
"compilerOptions": {
122+
"strict": true,
123+
${'/'.repeat(80)}
124+
"noEmit": true,
125+
${' /* option */\n'.repeat(40)}
126+
},
127+
"include": ["."],
128+
}`,
129+
)
130+
write('app/router.ts', 'export const router = 1\n')
131+
132+
expect(
133+
open({ file: path.join(root, 'app/router.ts'), tsconfig: root }, (project) =>
134+
project.describeConfig(),
135+
),
136+
).toEqual([`Using the compiler options of "${path.join(root, 'app/tsconfig.json')}".`])
137+
})
138+
139+
it('reads the references of a solution tsconfig keeping strings with comment markers and commas', () => {
140+
write(
141+
'tsconfig.json',
142+
`{
143+
"files": [],
144+
"references": [
145+
{ "path": "./*/../a,b//c", }, // trailing commas before comments
146+
/* and */
147+
],
148+
}`,
149+
)
150+
write('a,b/c/tsconfig.json', JSON.stringify({ include: ['.'] }))
151+
write('a,b/c/router.ts', 'export const router = 1\n')
152+
153+
expect(
154+
open({ file: path.join(root, 'a,b/c/router.ts'), tsconfig: root }, (project) =>
155+
project.describeConfig(),
156+
),
157+
).toEqual([`Using the compiler options of "${path.join(root, 'a,b/c/tsconfig.json')}".`])
158+
})
159+
108160
it('lists no exports of a script, read from a path relative to the current working directory', () => {
109161
write('tsconfig.json', JSON.stringify({ include: ['*.ts'] }))
110162
write('script.ts', 'const router = 1\n')

‎packages/openapi-inference/src/project.ts‎

Lines changed: 40 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -306,10 +306,46 @@ function readReferencePaths(tsconfig: string): string[] {
306306

307307
/**
308308
* Removes the comments and trailing commas of JSON with comments, keeping strings as they are.
309+
* Scans the text once, dropping a comma when the next token past whitespace and comments closes
310+
* an array or object, so no input can make it backtrack.
309311
*/
310312
function stripJsonComments(text: string): string {
311-
return text.replace(
312-
/("(?:[^"\\]|\\.)*")|\/\/[^\n]*|\/\*[\s\S]*?\*\/|,(?=\s*(?:\/\/[^\n]*\s*|\/\*[\s\S]*?\*\/\s*)*[\]}])/gu,
313-
(_match, string: string | undefined) => string ?? '',
314-
)
313+
const output: string[] = []
314+
let pendingComma: number | undefined
315+
let index = 0
316+
317+
while (index < text.length) {
318+
const char = text[index]!
319+
const next = text[index + 1]
320+
321+
if (char === '"') {
322+
let end = index + 1
323+
while (end < text.length && text[end] !== '"') {
324+
end += text[end] === '\\' ? 2 : 1
325+
}
326+
end = Math.min(end + 1, text.length)
327+
output.push(text.slice(index, end))
328+
pendingComma = undefined
329+
index = end
330+
} else if (char === '/' && next === '/') {
331+
const end = text.indexOf('\n', index + 2)
332+
index = end === -1 ? text.length : end
333+
} else if (char === '/' && next === '*') {
334+
const end = text.indexOf('*/', index + 2)
335+
index = end === -1 ? text.length : end + 2
336+
} else {
337+
if (char === ',') {
338+
pendingComma = output.length
339+
} else if ((char === ']' || char === '}') && pendingComma !== undefined) {
340+
output[pendingComma] = ''
341+
pendingComma = undefined
342+
} else if (!/\s/u.test(char)) {
343+
pendingComma = undefined
344+
}
345+
output.push(char)
346+
index++
347+
}
348+
}
349+
350+
return output.join('')
315351
}

0 commit comments

Comments
 (0)