(url: string, code: string)
| 124 | } |
| 125 | |
| 126 | export function resolveModuleFormat(url: string, code: string): 'module' | 'commonjs' | undefined { |
| 127 | const ext = extname(url) |
| 128 | |
| 129 | if (ext === '.cjs' || ext === '.cts') { |
| 130 | return 'commonjs' |
| 131 | } |
| 132 | else if (ext === '.mjs' || ext === '.mts') { |
| 133 | return 'module' |
| 134 | } |
| 135 | // https://nodejs.org/api/packages.html#syntax-detection |
| 136 | else if (ext === '.js' || ext === '.ts' || ext === '') { |
| 137 | if (!module.findPackageJSON) { |
| 138 | throw new Error(`Cannot parse the module format of '${url}' because "module.findPackageJSON" is not available. Upgrade to Node 22.14 to use this feature. This is NOT a bug of Vitest.`) |
| 139 | } |
| 140 | const pkgJsonPath = module.findPackageJSON(url) |
| 141 | const pkgJson = pkgJsonPath ? JSON.parse(readFileSync(pkgJsonPath, 'utf-8')) : {} |
| 142 | if (pkgJson?.type === 'module') { |
| 143 | return 'module' |
| 144 | } |
| 145 | else if (pkgJson?.type === 'commonjs') { |
| 146 | return 'commonjs' |
| 147 | } |
| 148 | else { |
| 149 | // Ambiguous input! Check if it has ESM syntax. Node.js is much smarter here, |
| 150 | // but we don't need to run the code, so we can be more relaxed |
| 151 | if (hasESM(filterOutComments(code))) { |
| 152 | return 'module' |
| 153 | } |
| 154 | else { |
| 155 | return 'commonjs' |
| 156 | } |
| 157 | } |
| 158 | } |
| 159 | return undefined |
| 160 | } |
| 161 | |
| 162 | let __globalRequire: NodeJS.Require | undefined |
| 163 | function getBuiltinModule(moduleId: string) { |
no test coverage detected