1+ import path from "node:path" ;
2+ import isBuiltinModule from "is-builtin-module" ;
3+ import resolveFrom from "resolve-from" ;
4+ import { readPackageUpSync } from "read-pkg-up" ;
5+
6+ /**
7+ * found module dir path
8+ * - if module is builtin, Convert module name to directory name.
9+ * - if module is not builtin, return module dir path.
10+ *
11+ * @param name module id
12+ * @param cwd dir
13+ * @returns module entry file path or package.json path
14+ */
15+ export function findModuleDir ( name , cwd ) {
16+ if ( isBuiltinModule ( name ) ) {
17+ throw new Error ( `Built-in module '${ name } ' cannot has no package.json` ) ;
18+ }
19+ let anchorPointFilePath ;
20+ try {
21+ // if target module is builtin module, Convert module name to directory name.
22+ // Please note that if you have not used a polyfill, an error of 'cannot find module 'xxx/package.json'' will be thrown.
23+ anchorPointFilePath = resolveFrom ( cwd , name ) ;
24+ } catch ( error ) {
25+ /**
26+ * because of target module is not configured entry in package.json
27+ * - not configured 'main' 'module' and 'exports' field
28+ */
29+ anchorPointFilePath = resolveFrom ( cwd , `${ name } /package.json` ) ;
30+ }
31+ return path . dirname ( anchorPointFilePath ) ;
32+ }
33+
34+ /**
35+ * fix terser package.json path
36+ * because of terser has multiple package.json , so read-pkg-up return wrong package.json
37+ @example
38+ ```
39+ .
40+ ├── CHANGELOG.md
41+ ├── LICENSE
42+ ├── PATRONS.md
43+ ├── README.md
44+ ├── bin
45+ ├── dist
46+ │ ├── bundle.min.js
47+ │ └── package.json // <--- this is wrong package.json
48+ ├── lib
49+ ├── main.js
50+ ├── node_modules
51+ ├── package.json // <--- this is correct package.json
52+ └── tools
53+ ```
54+ *
55+ * @param readResult {@see NormalizedReadResult }
56+ * @returns {@see NormalizedReadResult }
57+ */
58+ export function fixTerser ( readResult ) {
59+ if ( readResult . packageJson . private !== true ) {
60+ return readResult ;
61+ }
62+ const terserReadResult = readPackageUpSync ( {
63+ cwd : path . join ( path . dirname ( readResult . path ) , ".." )
64+ } ) ;
65+ return terserReadResult ;
66+ }
0 commit comments