|
| 1 | +const vueJest = require('vue-jest') as Transformer // vue-jest does not also provide types ... |
| 2 | +import * as fs from 'fs' |
| 3 | +import * as path from 'path' |
| 4 | +import { createHash } from 'crypto' |
| 5 | +import { parseComponent } from 'vue-template-compiler' |
| 6 | +import { debug as Debug } from 'debug' |
| 7 | +import generate from './generate' |
| 8 | + |
| 9 | +// impor jest types |
| 10 | +import { Config } from '@jest/types' |
| 11 | +import { RawSourceMap } from 'source-map' |
| 12 | +import { Transformer } from '@jest/transform' |
| 13 | +interface FixedRawSourceMap extends Omit<RawSourceMap, 'version'> { |
| 14 | + version: number |
| 15 | +} |
| 16 | +type TransformedSource = { |
| 17 | + code: string |
| 18 | + map?: FixedRawSourceMap | string | null |
| 19 | +} |
| 20 | +type TransformOptions = { |
| 21 | + instrument: boolean |
| 22 | +} |
| 23 | +type CacheKeyOptions = { |
| 24 | + config: Config.ProjectConfig |
| 25 | + instrument: boolean |
| 26 | + rootDir: string |
| 27 | +} |
| 28 | + |
| 29 | +const THIS_FILE = fs.readFileSync(__filename) |
| 30 | + |
| 31 | +const debug = Debug('vue-i18n-jest') |
| 32 | + |
| 33 | +debug(`getCacheKey: ${vueJest.getCacheKey ? 'vue-jest' : 'vue-i18n-jest'}`) |
| 34 | + |
| 35 | +function jestProcess ( |
| 36 | + sourceText: string, |
| 37 | + sourcePath: Config.Path, |
| 38 | + config: Config.ProjectConfig, |
| 39 | + options?: TransformOptions |
| 40 | +): string | TransformedSource { |
| 41 | + const { code, map } = vueJest.process(sourceText, sourcePath, config, options) as TransformedSource |
| 42 | + const { customBlocks } = parseComponent(sourceText, { pad: true }) |
| 43 | + |
| 44 | + let coding = ';\n' |
| 45 | + if (customBlocks) { |
| 46 | + coding += generate(customBlocks) |
| 47 | + } |
| 48 | + |
| 49 | + const retCode = code + coding |
| 50 | + debug('process', retCode) |
| 51 | + |
| 52 | + return { code: retCode, map } |
| 53 | +} |
| 54 | + |
| 55 | +function getCacheKey ( |
| 56 | + fileData: string, |
| 57 | + filePath: Config.Path, |
| 58 | + configStr: string, |
| 59 | + options: CacheKeyOptions |
| 60 | +): string { |
| 61 | + const hash = createHash('md5') |
| 62 | + .update(THIS_FILE) |
| 63 | + .update('\0', 'utf8') |
| 64 | + .update(fileData) |
| 65 | + .update('\0', 'utf8') |
| 66 | + .update(path.relative(options.rootDir, filePath)) |
| 67 | + .update('\0', 'utf8') |
| 68 | + .update(configStr) |
| 69 | + .update('\0', 'utf8') |
| 70 | + .update(process.env.NODE_ENV || '') |
| 71 | + .digest('hex') |
| 72 | + debug('getCacheKey', hash) |
| 73 | + return hash |
| 74 | +} |
| 75 | + |
| 76 | +const transformer: Transformer = { |
| 77 | + getCacheKey: vueJest.getCacheKey || getCacheKey, |
| 78 | + process: jestProcess |
| 79 | +} |
| 80 | + |
| 81 | +export default transformer |
0 commit comments