-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathhelper.ts
More file actions
175 lines (155 loc) · 4.41 KB
/
helper.ts
File metadata and controls
175 lines (155 loc) · 4.41 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
import { dirname, extname, join, resolve } from 'node:path';
import fs from '../compiled/fs-extra/index.js';
import { cwd, DIST_DIR } from './constant.js';
import type { Config, DependencyConfig, ParsedTask } from './types.js';
import { createRequire } from 'node:module';
import { pathToFileURL } from 'node:url';
const require = createRequire(import.meta.url);
export function findDepPath(name: string) {
try {
let entry = dirname(require.resolve(name, { paths: [cwd] }));
while (!dirname(entry).endsWith('node_modules')) {
entry = dirname(entry);
}
if (name.includes('/')) {
return join(dirname(entry), name);
}
return entry;
} catch (err) {
return null;
}
}
export const resolveConfig = async (configFile?: string) => {
const configFiles = configFile
? [resolve(cwd, configFile)]
: (
[
'prebundle.config.ts',
'prebundle.config.mts',
'prebundle.config.mjs',
'prebundle.config.js',
] as const
).map((filename) => join(cwd, filename));
for (const filename of configFiles) {
if (fs.existsSync(filename)) {
const config = await import(pathToFileURL(filename).href);
return (config.default ?? config) as Config;
}
}
if (configFile) {
throw new Error(`Unable to locate prebundle config file at: ${configFile}`);
}
throw new Error('Unable to locate prebundle config file.');
};
export function parseTasks(
dependencies: Array<string | DependencyConfig>,
globalPrettier?: boolean,
) {
const result: ParsedTask[] = [];
for (const dep of dependencies) {
const depName = typeof dep === 'string' ? dep : dep.name;
const dtsOnly = typeof dep === 'string' ? false : (dep.dtsOnly ?? false);
const importPath = join(cwd, DIST_DIR, depName);
const distPath = join(cwd, DIST_DIR, depName);
const depPath = dtsOnly ? null : findDepPath(depName);
if (!depPath && !dtsOnly) {
throw new Error(`Failed to resolve dependency: ${depName}`);
}
const depEntry = dtsOnly ? '' : require.resolve(depName, { paths: [cwd] });
const info = {
depName,
depPath: depPath ?? '',
depEntry,
distPath,
importPath,
};
if (typeof dep === 'string') {
result.push({
minify: false,
target: 'es2019',
externals: {},
dtsExternals: [],
emitFiles: [],
packageJsonField: [],
prettier: globalPrettier,
...info,
});
} else {
result.push({
minify: dep.minify ?? false,
target: dep.target ?? 'es2019',
ignoreDts: dep.ignoreDts,
copyDts: dep.copyDts,
externals: dep.externals ?? {},
dtsOnly: dep.dtsOnly ?? false,
dtsExternals: dep.dtsExternals ?? [],
emitFiles: dep.emitFiles ?? [],
prettier: dep.prettier ?? globalPrettier,
afterBundle: dep.afterBundle,
beforeBundle: dep.beforeBundle,
packageJsonField: dep.packageJsonField ?? [],
...info,
});
}
}
return result;
}
export function pick<T, U extends keyof T>(obj: T, keys: ReadonlyArray<U>) {
return keys.reduce(
(ret, key) => {
if (obj[key] !== undefined) {
ret[key] = obj[key];
}
return ret;
},
{} as Pick<T, U>,
);
}
export function replaceFileContent(
filePath: string,
replaceFn: (content: string) => string,
) {
const content = fs.readFileSync(filePath, 'utf-8');
const newContent = replaceFn(content);
if (newContent !== content) {
fs.writeFileSync(filePath, newContent);
}
}
export function pkgNameToAtTypes(name: string) {
const mangled = name.replace(
// 111111 222222
/^@([^\/]+)\/([^\/]+)/,
'$1__$2',
);
return `@types/${mangled}`;
}
/**
* Find the direct type file for a given file path.
* @param filepath
*/
export function findDirectTypeFile(filepath: string) {
if (/\.d\.[cm]?ts/.test(filepath)) {
return filepath;
}
const ext = extname(filepath);
const base = filepath.slice(0, -ext.length);
const _find = (list: string[]) => {
for (const f of list) {
try {
return require.resolve(f, { paths: [cwd] });
} catch {}
}
};
switch (ext) {
case '.js':
case '.ts':
return _find([base + '.d.ts']);
case '.mjs':
case '.mts':
return _find([base + '.d.mts', base + '.d.ts']);
case '.cjs':
case '.cts':
return _find([base + '.d.cts', base + '.d.ts']);
default:
}
}