MCPcopy Index your code
hub / github.com/npmx-dev/npmx.dev / detectModuleFormat

Function detectModuleFormat

shared/utils/package-analysis.ts:48–105  ·  view source on GitHub ↗
(pkg: ExtendedPackageJson)

Source from the content-addressed store, hash-verified

46 * Detect the module format of a package based on package.json fields
47 */
48export function detectModuleFormat(pkg: ExtendedPackageJson): ModuleFormat {
49 const hasExports = pkg.exports != null
50 const hasModule = !!pkg.module
51 const hasMain = !!pkg.main
52 const isTypeModule = pkg.type === 'module'
53 const isTypeCommonjs = pkg.type === 'commonjs' || !pkg.type
54
55 // Check exports field for dual format indicators
56 if (hasExports && pkg.exports) {
57 const exportInfo = analyzeExports(pkg.exports)
58
59 if (exportInfo.hasImport && exportInfo.hasRequire) {
60 return 'dual'
61 }
62
63 if (exportInfo.hasImport || exportInfo.hasModule) {
64 // Has ESM exports, check if also has CJS
65 if (hasMain && !isTypeModule) {
66 return 'dual'
67 }
68 return 'esm'
69 }
70
71 if (exportInfo.hasRequire) {
72 // Has CJS exports, check if also has ESM
73 if (hasModule) {
74 return 'dual'
75 }
76 return 'cjs'
77 }
78
79 // exports field exists but doesn't use import/require conditions
80 // Fall through to other detection methods
81 }
82
83 // Legacy detection without exports field
84 if (hasModule && hasMain) {
85 // Check for dual packages (has module field and main points to cjs)
86 const mainIsCJS = pkg.main?.endsWith('.cjs') || (pkg.main?.endsWith('.js') && !isTypeModule)
87
88 return mainIsCJS ? 'dual' : 'esm'
89 }
90
91 const mainIsWASM = pkg.main?.endsWith('.wasm')
92 if (mainIsWASM) {
93 return 'wasm'
94 }
95
96 if (hasModule || isTypeModule) {
97 return 'esm'
98 }
99
100 if (hasMain || isTypeCommonjs) {
101 return 'cjs'
102 }
103
104 return 'unknown'
105}

Callers 2

analyzePackageFunction · 0.85

Calls 1

analyzeExportsFunction · 0.85

Tested by

no test coverage detected