Skip to content

Commit

Permalink
perf: remove ts resolved module cache file
Browse files Browse the repository at this point in the history
  • Loading branch information
jsaguet authored and ahnpnl committed May 19, 2024
1 parent 0785348 commit 4c88da5
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 99 deletions.
75 changes: 2 additions & 73 deletions src/legacy/ts-jest-transformer.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,13 @@ import fs from 'fs'
import path from 'path'

import { LogLevels } from 'bs-logger'
import { removeSync, writeFileSync } from 'fs-extra'
import { removeSync } from 'fs-extra'

import { createConfigSet } from '../__helpers__/fakers'
import { logTargetMock } from '../__helpers__/mocks'
import type { DepGraphInfo } from '../types'
import { stringify } from '../utils'
import { importer } from '../utils/importer'
import { sha1 } from '../utils/sha1'

import { TsJestCompiler } from './compiler'
import { CACHE_KEY_EL_SEPARATOR, TsJestTransformer } from './ts-jest-transformer'
import { TsJestTransformer } from './ts-jest-transformer'

const SOURCE_MAPPING_PREFIX = 'sourceMappingURL='

Expand Down Expand Up @@ -50,7 +46,6 @@ describe('TsJestTransformer', () => {
"transformerCfgStr",
"compiler",
"depGraphs",
"tsResolvedModulesCachePath",
"watchMode",
]
`)
Expand Down Expand Up @@ -79,72 +74,6 @@ describe('TsJestTransformer', () => {

expect(cs2).toBe(cs1)
})

test(`should not read disk cache with isolatedModules true`, () => {
const tr = new TsJestTransformer()
const cs = createConfigSet({
jestConfig: {
globals: { 'ts-jest': { isolatedModules: true } },
},
})
const readFileSyncSpy = jest.spyOn(fs, 'readFileSync')

// @ts-expect-error testing purpose
tr._getFsCachedResolvedModules(cs)

expect(readFileSyncSpy).not.toHaveBeenCalled()

readFileSyncSpy.mockRestore()
})

test(`should not read disk cache with isolatedModules false and no jest cache`, () => {
const tr = new TsJestTransformer()
const cs = createConfigSet({
jestConfig: {
globals: { 'ts-jest': { isolatedModules: false } },
},
})
const readFileSyncSpy = jest.spyOn(fs, 'readFileSync')

// @ts-expect-error testing purpose
tr._getFsCachedResolvedModules(cs)

expect(readFileSyncSpy).not.toHaveBeenCalled()

readFileSyncSpy.mockRestore()
})

test(`should read disk cache with isolatedModules false and use jest cache`, () => {
const readFileSyncSpy = jest.spyOn(fs, 'readFileSync')
const fileName = 'foo.ts'
const tr = new TsJestTransformer()
const cs = createConfigSet({
jestConfig: {
cache: true,
cacheDirectory: cacheDir,
globals: { 'ts-jest': { isolatedModules: false } },
},
})
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const tsCacheDir = cs.tsCacheDir!
const depGraphs: Map<string, DepGraphInfo> = new Map<string, DepGraphInfo>()
depGraphs.set(fileName, {
fileContent: 'const foo = 1',
resolvedModuleNames: [],
})
const resolvedModulesCacheDir = path.join(tsCacheDir, sha1('ts-jest-resolved-modules', CACHE_KEY_EL_SEPARATOR))
fs.mkdirSync(tsCacheDir, { recursive: true })
writeFileSync(resolvedModulesCacheDir, stringify([...depGraphs]))

// @ts-expect-error testing purpose
tr._getFsCachedResolvedModules(cs)

// @ts-expect-error testing purpose
expect(tr._depGraphs.has(fileName)).toBe(true)
expect(readFileSyncSpy.mock.calls).toEqual(expect.arrayContaining([[resolvedModulesCacheDir, 'utf-8']]))

removeSync(cacheDir)
})
})

describe('getCacheKey', () => {
Expand Down
29 changes: 3 additions & 26 deletions src/legacy/ts-jest-transformer.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { existsSync, readFileSync, statSync, writeFileSync, mkdirSync } from 'fs'
import { existsSync, statSync } from 'fs'
import path from 'path'

import type { SyncTransformer, TransformedSource } from '@jest/transform'
Expand All @@ -12,7 +12,7 @@ import type {
TsJestTransformerOptions,
TsJestTransformOptions,
} from '../types'
import { parse, stringify, JsonableValue, rootLogger } from '../utils'
import { stringify, JsonableValue, rootLogger } from '../utils'
import { importer } from '../utils/importer'
import { Deprecations, Errors, interpolate } from '../utils/messages'
import { sha1 } from '../utils/sha1'
Expand All @@ -27,7 +27,6 @@ interface CachedConfigSet {
transformerCfgStr: string
compiler: CompilerInstance
depGraphs: Map<string, DepGraphInfo>
tsResolvedModulesCachePath: string | undefined
watchMode: boolean
}

Expand All @@ -50,7 +49,6 @@ export class TsJestTransformer implements SyncTransformer<TsJestTransformerOptio
private static readonly _cachedConfigSets: CachedConfigSet[] = []
private readonly _logger: Logger
protected _compiler!: CompilerInstance
private _tsResolvedModulesCachePath: string | undefined
private _transformCfgStr!: string
private _depGraphs: Map<string, DepGraphInfo> = new Map<string, DepGraphInfo>()
private _watchMode = false
Expand Down Expand Up @@ -81,7 +79,6 @@ export class TsJestTransformer implements SyncTransformer<TsJestTransformerOptio
this._transformCfgStr = ccs.transformerCfgStr
this._compiler = ccs.compiler
this._depGraphs = ccs.depGraphs
this._tsResolvedModulesCachePath = ccs.tsResolvedModulesCachePath
this._watchMode = ccs.watchMode
configSet = ccs.configSet
} else {
Expand All @@ -98,7 +95,6 @@ export class TsJestTransformer implements SyncTransformer<TsJestTransformerOptio
this._transformCfgStr = serializedCcs.transformerCfgStr
this._compiler = serializedCcs.compiler
this._depGraphs = serializedCcs.depGraphs
this._tsResolvedModulesCachePath = serializedCcs.tsResolvedModulesCachePath
this._watchMode = serializedCcs.watchMode
configSet = serializedCcs.configSet
} else {
Expand Down Expand Up @@ -129,15 +125,13 @@ export class TsJestTransformer implements SyncTransformer<TsJestTransformerOptio
jest.cacheDirectory = undefined as any // eslint-disable-line @typescript-eslint/no-explicit-any
this._transformCfgStr = `${new JsonableValue(jest).serialized}${configSet.cacheSuffix}`
this._createCompiler(configSet, cacheFS)
this._getFsCachedResolvedModules(configSet)
this._watchMode = process.argv.includes('--watch')
TsJestTransformer._cachedConfigSets.push({
jestConfig: new JsonableValue(config),
configSet,
transformerCfgStr: this._transformCfgStr,
compiler: this._compiler,
depGraphs: this._depGraphs,
tsResolvedModulesCachePath: this._tsResolvedModulesCachePath,
watchMode: this._watchMode,
})
}
Expand Down Expand Up @@ -321,7 +315,7 @@ export class TsJestTransformer implements SyncTransformer<TsJestTransformerOptio
CACHE_KEY_EL_SEPARATOR,
filePath,
]
if (!configs.isolatedModules && this._tsResolvedModulesCachePath) {
if (!configs.isolatedModules && configs.tsCacheDir) {
let resolvedModuleNames: string[]
if (this._depGraphs.get(filePath)?.fileContent === fileContent) {
this._logger.debug(
Expand All @@ -346,7 +340,6 @@ export class TsJestTransformer implements SyncTransformer<TsJestTransformerOptio
fileContent,
resolvedModuleNames,
})
writeFileSync(this._tsResolvedModulesCachePath, stringify([...this._depGraphs]))
}
resolvedModuleNames.forEach((moduleName) => {
constructingCacheKeyElements.push(
Expand All @@ -368,20 +361,4 @@ export class TsJestTransformer implements SyncTransformer<TsJestTransformerOptio
): Promise<string> {
return Promise.resolve(this.getCacheKey(sourceText, sourcePath, transformOptions))
}

/**
* Subclasses extends `TsJestTransformer` can call this method to get resolved module disk cache
*/
private _getFsCachedResolvedModules(configSet: ConfigSet): void {
const cacheDir = configSet.tsCacheDir
if (!configSet.isolatedModules && cacheDir) {
// Make sure the cache directory exists before continuing.
mkdirSync(cacheDir, { recursive: true })
this._tsResolvedModulesCachePath = path.join(cacheDir, sha1('ts-jest-resolved-modules', CACHE_KEY_EL_SEPARATOR))
try {
const cachedTSResolvedModules = readFileSync(this._tsResolvedModulesCachePath, 'utf-8')
this._depGraphs = new Map(parse(cachedTSResolvedModules))
} catch (e) {}
}
}
}

0 comments on commit 4c88da5

Please sign in to comment.