|
| 1 | +/** |
| 2 | + * Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. |
| 3 | + * |
| 4 | + * This source code is licensed under the MIT license found in the |
| 5 | + * LICENSE file in the root directory of this source tree. |
| 6 | + */ |
| 7 | + |
| 8 | +import {dirname, extname} from 'path'; |
| 9 | +// @ts-ignore: experimental, not added to the types |
| 10 | +import {SourceTextModule} from 'vm'; |
| 11 | +import type {Config} from '@jest/types'; |
| 12 | +import readPkgUp = require('read-pkg-up'); |
| 13 | + |
| 14 | +const runtimeSupportsVmModules = typeof SourceTextModule === 'function'; |
| 15 | + |
| 16 | +const cachedFileLookups = new Map<string, boolean>(); |
| 17 | +const cachedDirLookups = new Map<string, boolean>(); |
| 18 | + |
| 19 | +export function clearCachedLookups(): void { |
| 20 | + cachedFileLookups.clear(); |
| 21 | + cachedDirLookups.clear(); |
| 22 | +} |
| 23 | + |
| 24 | +export default function cachedShouldLoadAsEsm(path: Config.Path): boolean { |
| 25 | + let cachedLookup = cachedFileLookups.get(path); |
| 26 | + |
| 27 | + if (cachedLookup === undefined) { |
| 28 | + cachedLookup = shouldLoadAsEsm(path); |
| 29 | + cachedFileLookups.set(path, cachedLookup); |
| 30 | + } |
| 31 | + |
| 32 | + return cachedLookup; |
| 33 | +} |
| 34 | + |
| 35 | +// this is a bad version of what https://github.com/nodejs/modules/issues/393 would provide |
| 36 | +function shouldLoadAsEsm(path: Config.Path): boolean { |
| 37 | + if (!runtimeSupportsVmModules) { |
| 38 | + return false; |
| 39 | + } |
| 40 | + |
| 41 | + const extension = extname(path); |
| 42 | + |
| 43 | + if (extension === '.mjs') { |
| 44 | + return true; |
| 45 | + } |
| 46 | + |
| 47 | + if (extension === '.cjs') { |
| 48 | + return false; |
| 49 | + } |
| 50 | + |
| 51 | + // this isn't correct - we might wanna load any file as a module (using synthetic module) |
| 52 | + // do we need an option to Jest so people can opt in to ESM for non-js? |
| 53 | + if (extension !== '.js') { |
| 54 | + return false; |
| 55 | + } |
| 56 | + |
| 57 | + const cwd = dirname(path); |
| 58 | + |
| 59 | + let cachedLookup = cachedDirLookups.get(cwd); |
| 60 | + |
| 61 | + if (cachedLookup === undefined) { |
| 62 | + cachedLookup = cachedPkgCheck(cwd); |
| 63 | + cachedFileLookups.set(cwd, cachedLookup); |
| 64 | + } |
| 65 | + |
| 66 | + return cachedLookup; |
| 67 | +} |
| 68 | + |
| 69 | +function cachedPkgCheck(cwd: Config.Path): boolean { |
| 70 | + // TODO: can we cache lookups somehow? |
| 71 | + const pkg = readPkgUp.sync({cwd, normalize: false}); |
| 72 | + |
| 73 | + if (!pkg) { |
| 74 | + return false; |
| 75 | + } |
| 76 | + |
| 77 | + return pkg.packageJson.type === 'module'; |
| 78 | +} |
0 commit comments