Skip to content

Commit 1cfd694

Browse files
authored
perf: cache parsed tsconfig per directory (#571)
1 parent 995c881 commit 1cfd694

2 files changed

Lines changed: 160 additions & 2 deletions

File tree

‎lib/util/get-tsconfig.js‎

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,11 @@
1+
import { dirname, isAbsolute, resolve } from "node:path"
12
import { getTsconfig, parseTsconfig } from "get-tsconfig"
23
const fsCache = new Map()
4+
// fsCache only caches file reads; get-tsconfig still re-parses the config on every call
5+
/** @type {Map<string, import("get-tsconfig").TsConfigJsonResolved>} */
6+
const parsedCache = new Map()
7+
/** @type {Map<string, import("get-tsconfig").TsConfigResult | null>} */
8+
const directoryCache = new Map()
39

410
/**
511
* Attempts to get the ExtensionMap from the tsconfig given the path to the tsconfig file.
@@ -8,7 +14,13 @@ const fsCache = new Map()
814
* @returns {import("get-tsconfig").TsConfigJsonResolved}
915
*/
1016
function getTSConfig(filename) {
11-
return parseTsconfig(filename, fsCache)
17+
const absoluteFilename = resolve(filename)
18+
let config = parsedCache.get(absoluteFilename)
19+
if (config === undefined) {
20+
config = parseTsconfig(filename, fsCache)
21+
parsedCache.set(absoluteFilename, config)
22+
}
23+
return config
1224
}
1325

1426
/**
@@ -18,7 +30,16 @@ function getTSConfig(filename) {
1830
* @returns {import("get-tsconfig").TsConfigResult | null}
1931
*/
2032
function getTSConfigForFile(filename) {
21-
return getTsconfig(filename, "tsconfig.json", fsCache)
33+
// Files in one directory share a lookup; relative paths only walk up to the cwd, so they are keyed by it too
34+
const key = isAbsolute(filename)
35+
? dirname(filename)
36+
: `${process.cwd()}\0${dirname(filename)}`
37+
let result = directoryCache.get(key)
38+
if (result === undefined) {
39+
result = getTsconfig(filename, "tsconfig.json", fsCache)
40+
directoryCache.set(key, result)
41+
}
42+
return result
2243
}
2344

2445
/**

‎tests/lib/get-tsconfig.js‎

Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
import assert from "node:assert/strict"
2+
import fs from "node:fs"
3+
import os from "node:os"
4+
import path from "node:path"
5+
import { getTSConfig, getTSConfigForFile } from "../../lib/util/get-tsconfig.js"
6+
7+
let freshImports = 0
8+
9+
/**
10+
* Relative lookups share the module-level fs cache, so tests that change the cwd load their own copy
11+
* @returns {Promise<typeof import("../../lib/util/get-tsconfig.js")>}
12+
*/
13+
function importFresh() {
14+
freshImports += 1
15+
return import(`../../lib/util/get-tsconfig.js?fresh=${freshImports}`)
16+
}
17+
18+
/**
19+
* @param {string} dir
20+
* @param {Record<string, string[]>} paths
21+
*/
22+
function writeTSConfig(dir, paths) {
23+
fs.mkdirSync(dir, { recursive: true })
24+
fs.writeFileSync(
25+
path.join(dir, "tsconfig.json"),
26+
JSON.stringify({ compilerOptions: { paths } })
27+
)
28+
}
29+
30+
describe("getTSConfigForFile", () => {
31+
/** @type {string} */
32+
let root
33+
34+
beforeEach(() => {
35+
root = fs.mkdtempSync(path.join(os.tmpdir(), "n-tsconfig-"))
36+
})
37+
38+
afterEach(() => {
39+
fs.rmSync(root, { recursive: true, force: true })
40+
})
41+
42+
it("resolves the nearest tsconfig for each directory", () => {
43+
writeTSConfig(root, { "@root/*": ["./src/*"] })
44+
writeTSConfig(path.join(root, "packages", "a"), {
45+
"@a/*": ["./src/*"],
46+
})
47+
48+
const fromRoot = getTSConfigForFile(path.join(root, "src", "index.ts"))
49+
const fromPackage = getTSConfigForFile(
50+
path.join(root, "packages", "a", "src", "index.ts")
51+
)
52+
const fromSibling = getTSConfigForFile(
53+
path.join(root, "packages", "b", "src", "index.ts")
54+
)
55+
56+
assert.equal(
57+
path.resolve(fromRoot?.path ?? ""),
58+
path.join(root, "tsconfig.json")
59+
)
60+
assert.equal(
61+
path.resolve(fromPackage?.path ?? ""),
62+
path.join(root, "packages", "a", "tsconfig.json")
63+
)
64+
assert.ok(fromPackage?.config.compilerOptions?.paths?.["@a/*"])
65+
assert.equal(
66+
path.resolve(fromSibling?.path ?? ""),
67+
path.join(root, "tsconfig.json")
68+
)
69+
})
70+
71+
it("reuses the parsed tsconfig for files in the same directory", () => {
72+
writeTSConfig(root, { "@root/*": ["./src/*"] })
73+
74+
const first = getTSConfigForFile(path.join(root, "src", "a.ts"))
75+
const second = getTSConfigForFile(path.join(root, "src", "b.ts"))
76+
77+
assert.ok(first)
78+
assert.equal(second, first)
79+
})
80+
81+
it("resolves relative filenames against the current working directory", async () => {
82+
const { getTSConfigForFile } = await importFresh()
83+
const originalCwd = process.cwd()
84+
writeTSConfig(path.join(root, "one"), { "@one/*": ["./*"] })
85+
writeTSConfig(path.join(root, "two"), { "@two/*": ["./*"] })
86+
87+
try {
88+
process.chdir(path.join(root, "one"))
89+
const fromOne = getTSConfigForFile("index.ts")
90+
process.chdir(path.join(root, "two"))
91+
const fromTwo = getTSConfigForFile("index.ts")
92+
93+
assert.ok(fromOne?.config.compilerOptions?.paths?.["@one/*"])
94+
assert.ok(fromTwo?.config.compilerOptions?.paths?.["@two/*"])
95+
} finally {
96+
process.chdir(originalCwd)
97+
}
98+
})
99+
100+
it("keeps relative lookups separate from absolute ones in the same directory", async () => {
101+
const { getTSConfigForFile } = await importFresh()
102+
const originalCwd = process.cwd()
103+
const child = path.join(root, "child")
104+
writeTSConfig(root, { "@root/*": ["./*"] })
105+
fs.mkdirSync(child)
106+
107+
try {
108+
process.chdir(child)
109+
// An absolute path walks up to the filesystem root, a relative one only to the cwd
110+
const absolute = getTSConfigForFile(path.join(child, "index.ts"))
111+
const relative = getTSConfigForFile("<text>")
112+
113+
assert.equal(
114+
path.resolve(absolute?.path ?? ""),
115+
path.join(root, "tsconfig.json")
116+
)
117+
assert.equal(relative, null)
118+
} finally {
119+
process.chdir(originalCwd)
120+
}
121+
})
122+
})
123+
124+
describe("getTSConfig", () => {
125+
it("reuses the parsed tsconfig for a path", () => {
126+
const root = fs.mkdtempSync(path.join(os.tmpdir(), "n-tsconfig-"))
127+
128+
try {
129+
writeTSConfig(root, { "@root/*": ["./src/*"] })
130+
const tsconfigPath = path.join(root, "tsconfig.json")
131+
132+
assert.equal(getTSConfig(tsconfigPath), getTSConfig(tsconfigPath))
133+
} finally {
134+
fs.rmSync(root, { recursive: true, force: true })
135+
}
136+
})
137+
})

0 commit comments

Comments
 (0)