MCPcopy
hub / github.com/vitest-dev/vitest / resolveModuleFormat

Function resolveModuleFormat

packages/mocker/src/node/parsers.ts:126–160  ·  view source on GitHub ↗
(url: string, code: string)

Source from the content-addressed store, hash-verified

124}
125
126export 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
162let __globalRequire: NodeJS.Require | undefined
163function getBuiltinModule(moduleId: string) {

Callers 2

automockModuleFunction · 0.90
parseModuleFunction · 0.85

Calls 3

filterOutCommentsFunction · 0.90
readFileSyncFunction · 0.85
hasESMFunction · 0.85

Tested by

no test coverage detected