prebundle 1.2.4 → 1.2.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,8 @@
1
+ export declare const DIST_DIR = "compiled";
2
+ export declare const DEFAULT_EXTERNALS: {
3
+ './package.json': string;
4
+ '../package.json': string;
5
+ '../../package.json': string;
6
+ };
7
+ export declare const NODE_BUILTINS: string[];
8
+ export declare const cwd: string;
@@ -0,0 +1,12 @@
1
+ import type { Config, DependencyConfig, ParsedTask } from './types.js';
2
+ export declare function findDepPath(name: string): string | null;
3
+ export declare const resolveConfig: () => Promise<Config>;
4
+ export declare function parseTasks(dependencies: Array<string | DependencyConfig>, globalPrettier?: boolean): ParsedTask[];
5
+ export declare function pick<T, U extends keyof T>(obj: T, keys: ReadonlyArray<U>): Pick<T, U>;
6
+ export declare function replaceFileContent(filePath: string, replaceFn: (content: string) => string): void;
7
+ export declare function pkgNameToAtTypes(name: string): string;
8
+ /**
9
+ * Find the direct type file for a given file path.
10
+ * @param filepath
11
+ */
12
+ export declare function findDirectTypeFile(filepath: string): string | undefined;
@@ -0,0 +1,2 @@
1
+ export declare function run(): Promise<void>;
2
+ export type { Config } from './types.js';
package/dist/index.js ADDED
@@ -0,0 +1,365 @@
1
+ import * as __WEBPACK_EXTERNAL_MODULE_node_path__ from "node:path";
2
+ import * as __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__ from "../compiled/fs-extra/index.js";
3
+ import * as __WEBPACK_EXTERNAL_MODULE_node_module__ from "node:module";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_node_url__ from "node:url";
5
+ import * as __WEBPACK_EXTERNAL_MODULE__vercel_ncc__ from "@vercel/ncc";
6
+ import * as __WEBPACK_EXTERNAL_MODULE__compiled_fast_glob_index_js__ from "../compiled/fast-glob/index.js";
7
+ import * as __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__ from "../compiled/rslog/index.js";
8
+ import * as __WEBPACK_EXTERNAL_MODULE_rollup_plugin_dts__ from "rollup-plugin-dts";
9
+ import * as __WEBPACK_EXTERNAL_MODULE_rollup__ from "rollup";
10
+ import * as __WEBPACK_EXTERNAL_MODULE_terser__ from "terser";
11
+ import * as __WEBPACK_EXTERNAL_MODULE_prettier__ from "prettier";
12
+ const DIST_DIR = 'compiled';
13
+ const DEFAULT_EXTERNALS = {
14
+ // ncc bundled wrong package.json, using external to avoid this problem
15
+ './package.json': './package.json',
16
+ '../package.json': './package.json',
17
+ '../../package.json': './package.json'
18
+ };
19
+ const NODE_BUILTINS = [
20
+ '_stream_duplex',
21
+ '_stream_passthrough',
22
+ '_stream_readable',
23
+ '_stream_transform',
24
+ '_stream_writable',
25
+ 'assert',
26
+ 'buffer',
27
+ 'child_process',
28
+ 'cluster',
29
+ 'console',
30
+ 'constants',
31
+ 'crypto',
32
+ 'dgram',
33
+ 'dns',
34
+ 'domain',
35
+ 'events',
36
+ 'fs',
37
+ 'http',
38
+ 'https',
39
+ 'module',
40
+ 'net',
41
+ 'os',
42
+ 'path',
43
+ 'process',
44
+ 'punycode',
45
+ 'querystring',
46
+ 'readline',
47
+ 'repl',
48
+ 'stream',
49
+ 'string_decoder',
50
+ 'sys',
51
+ 'timers',
52
+ 'tls',
53
+ 'tty',
54
+ 'url',
55
+ 'util',
56
+ 'vm',
57
+ 'zlib'
58
+ ];
59
+ const cwd = process.cwd();
60
+ const helper_require = (0, __WEBPACK_EXTERNAL_MODULE_node_module__.createRequire)(import.meta.url);
61
+ function findDepPath(name) {
62
+ try {
63
+ let entry = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(helper_require.resolve((0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(name), {
64
+ paths: [
65
+ cwd
66
+ ]
67
+ }));
68
+ while(!(0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(entry).endsWith('node_modules'))entry = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(entry);
69
+ if (name.includes('/')) return (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)((0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(entry), name);
70
+ return entry;
71
+ } catch (err) {
72
+ return null;
73
+ }
74
+ }
75
+ const resolveConfig = async ()=>{
76
+ const configPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(cwd, 'prebundle.config.mjs');
77
+ const config = await import((0, __WEBPACK_EXTERNAL_MODULE_node_url__.pathToFileURL)(configPath).href);
78
+ return config.default;
79
+ };
80
+ function parseTasks(dependencies, globalPrettier) {
81
+ const result = [];
82
+ for (const dep of dependencies){
83
+ const depName = 'string' == typeof dep ? dep : dep.name;
84
+ const importPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(cwd, DIST_DIR, depName);
85
+ const distPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(cwd, DIST_DIR, depName);
86
+ const depPath = findDepPath(depName);
87
+ if (!depPath) throw new Error(`Failed to resolve dependency: ${depName}`);
88
+ const depEntry = helper_require.resolve(depName, {
89
+ paths: [
90
+ cwd
91
+ ]
92
+ });
93
+ const info = {
94
+ depName,
95
+ depPath,
96
+ depEntry,
97
+ distPath,
98
+ importPath
99
+ };
100
+ if ('string' == typeof dep) result.push({
101
+ minify: false,
102
+ target: 'es2019',
103
+ externals: {},
104
+ dtsExternals: [],
105
+ emitFiles: [],
106
+ packageJsonField: [],
107
+ prettier: globalPrettier,
108
+ ...info
109
+ });
110
+ else result.push({
111
+ minify: dep.minify ?? false,
112
+ target: dep.target ?? 'es2019',
113
+ ignoreDts: dep.ignoreDts,
114
+ externals: dep.externals ?? {},
115
+ dtsExternals: dep.dtsExternals ?? [],
116
+ emitFiles: dep.emitFiles ?? [],
117
+ prettier: dep.prettier ?? globalPrettier,
118
+ afterBundle: dep.afterBundle,
119
+ beforeBundle: dep.beforeBundle,
120
+ packageJsonField: dep.packageJsonField ?? [],
121
+ ...info
122
+ });
123
+ }
124
+ return result;
125
+ }
126
+ function pick(obj, keys) {
127
+ return keys.reduce((ret, key)=>{
128
+ if (void 0 !== obj[key]) ret[key] = obj[key];
129
+ return ret;
130
+ }, {});
131
+ }
132
+ function pkgNameToAtTypes(name) {
133
+ const mangled = name.replace(/^@([^\/]+)\/([^\/]+)/, '$1__$2');
134
+ return `@types/${mangled}`;
135
+ }
136
+ /**
137
+ * Find the direct type file for a given file path.
138
+ * @param filepath
139
+ */ function findDirectTypeFile(filepath) {
140
+ if (/\.d\.[cm]?ts/.test(filepath)) return filepath;
141
+ const ext = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.extname)(filepath);
142
+ const base = filepath.slice(0, -ext.length);
143
+ const _find = (list)=>{
144
+ for (const f of list)try {
145
+ return helper_require.resolve(f, {
146
+ paths: [
147
+ cwd
148
+ ]
149
+ });
150
+ } catch {}
151
+ };
152
+ switch(ext){
153
+ case '.js':
154
+ case '.ts':
155
+ return _find([
156
+ base + '.d.ts'
157
+ ]);
158
+ case '.mjs':
159
+ case '.mts':
160
+ return _find([
161
+ base + '.d.mts',
162
+ base + '.d.ts'
163
+ ]);
164
+ case '.cjs':
165
+ case '.cts':
166
+ return _find([
167
+ base + '.d.cts',
168
+ base + '.d.ts'
169
+ ]);
170
+ default:
171
+ }
172
+ }
173
+ const { logger } = __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__["default"];
174
+ function emitAssets(assets, distPath) {
175
+ for (const key of Object.keys(assets)){
176
+ const asset = assets[key];
177
+ __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].outputFileSync((0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(distPath, key), asset.source);
178
+ }
179
+ }
180
+ async function emitIndex(code, distPath, prettier) {
181
+ const distIndex = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(distPath, 'index.js');
182
+ // use terser to strip comments and use prettier to format the code
183
+ if (prettier) {
184
+ const minimized = await (0, __WEBPACK_EXTERNAL_MODULE_terser__.minify)(code, {
185
+ compress: false,
186
+ mangle: false,
187
+ ecma: 2019
188
+ });
189
+ if (!minimized.code) throw new Error('terser minify failed');
190
+ const formatted = await (0, __WEBPACK_EXTERNAL_MODULE_prettier__.format)(minimized.code, {
191
+ filepath: distIndex
192
+ });
193
+ await __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].outputFile(distIndex, formatted);
194
+ } else await __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].outputFile(distIndex, code);
195
+ }
196
+ async function emitDts(task, externals) {
197
+ const outputDefaultDts = ()=>{
198
+ __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].outputFileSync((0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(task.distPath, 'index.d.ts'), 'export = any;\n');
199
+ };
200
+ if (task.ignoreDts) {
201
+ outputDefaultDts();
202
+ return;
203
+ }
204
+ const getTypes = (json)=>{
205
+ var _json_exports;
206
+ return json && (json.types || json.typing || json.typings || // for those who use `exports` only
207
+ getTypes(null === (_json_exports = json.exports) || void 0 === _json_exports ? void 0 : _json_exports['.'])) || null;
208
+ };
209
+ const getInput = ()=>{
210
+ const pkgPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(task.depPath, 'package.json');
211
+ const pkgJson = __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].readJsonSync(pkgPath, 'utf-8');
212
+ const types = getTypes(pkgJson);
213
+ if (types) return (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(task.depPath, types);
214
+ const directTypeFile = findDirectTypeFile(task.depEntry);
215
+ if (directTypeFile) return directTypeFile;
216
+ const depTypesPath = findDepPath(`${pkgNameToAtTypes(task.depName)}/package.json`);
217
+ if (!depTypesPath) return null;
218
+ const depTypesPkg = __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].readJsonSync(depTypesPath, 'utf-8');
219
+ const depTypes = getTypes(depTypesPkg);
220
+ return depTypes ? (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)((0, __WEBPACK_EXTERNAL_MODULE_node_path__.dirname)(depTypesPath), depTypes) : null;
221
+ };
222
+ const input = getInput();
223
+ if (!input) {
224
+ outputDefaultDts();
225
+ return;
226
+ }
227
+ try {
228
+ const inputConfig = {
229
+ input,
230
+ external: [
231
+ ...Object.keys(externals),
232
+ ...task.dtsExternals,
233
+ ...NODE_BUILTINS
234
+ ],
235
+ plugins: [
236
+ (0, __WEBPACK_EXTERNAL_MODULE_rollup_plugin_dts__.dts)({
237
+ respectExternal: true,
238
+ compilerOptions: {
239
+ skipLibCheck: true,
240
+ // https://github.com/Swatinem/rollup-plugin-dts/issues/143,
241
+ // but it will cause error when bundle ts which import another ts file.
242
+ preserveSymlinks: false,
243
+ // https://github.com/Swatinem/rollup-plugin-dts/issues/127
244
+ composite: false,
245
+ // https://github.com/Swatinem/rollup-plugin-dts/issues/113
246
+ declarationMap: false,
247
+ // Ensure ".d.ts" modules are generated
248
+ declaration: true,
249
+ // Skip ".js" generation
250
+ noEmit: false,
251
+ emitDeclarationOnly: true,
252
+ // Skip code generation when error occurs
253
+ noEmitOnError: true,
254
+ // Avoid extra work
255
+ checkJs: false,
256
+ // Ensure we can parse the latest code
257
+ // @ts-expect-error
258
+ target: task.target
259
+ }
260
+ })
261
+ ]
262
+ };
263
+ const outputConfig = {
264
+ dir: task.distPath,
265
+ format: 'esm',
266
+ exports: 'named',
267
+ entryFileNames: 'index.d.ts'
268
+ };
269
+ const bundle = await (0, __WEBPACK_EXTERNAL_MODULE_rollup__.rollup)(inputConfig);
270
+ await bundle.write(outputConfig);
271
+ } catch (error) {
272
+ logger.error(`rollup-plugin-dts failed: ${task.depName}`);
273
+ logger.error(error);
274
+ }
275
+ }
276
+ function emitPackageJson(task, assets) {
277
+ const packageJsonPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(task.depPath, 'package.json');
278
+ const packageJson = __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].readJsonSync(packageJsonPath, 'utf-8');
279
+ const outputPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(task.distPath, 'package.json');
280
+ const pickedPackageJson = pick(packageJson, [
281
+ 'name',
282
+ 'author',
283
+ 'version',
284
+ 'funding',
285
+ 'license',
286
+ ...task.packageJsonField
287
+ ]);
288
+ if (task.depName !== pickedPackageJson.name) pickedPackageJson.name = task.depName;
289
+ pickedPackageJson.types = 'index.d.ts';
290
+ pickedPackageJson.type = 'commonjs';
291
+ if (assets['package.json']) try {
292
+ Object.assign(pickedPackageJson, pick(JSON.parse(assets['package.json'].source), [
293
+ 'type'
294
+ ]));
295
+ } catch {}
296
+ __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].writeJSONSync(outputPath, pickedPackageJson);
297
+ }
298
+ function emitLicense(task) {
299
+ const licensePath = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(task.depPath, 'LICENSE');
300
+ if (__WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].existsSync(licensePath)) __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].copySync(licensePath, (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(task.distPath, 'license'));
301
+ }
302
+ function emitExtraFiles(task) {
303
+ const { emitFiles } = task;
304
+ for (const item of emitFiles){
305
+ const path = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(task.distPath, item.path);
306
+ __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].outputFileSync(path, item.content);
307
+ }
308
+ }
309
+ function removeSourceMap(task) {
310
+ const maps = __WEBPACK_EXTERNAL_MODULE__compiled_fast_glob_index_js__["default"].sync((0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(task.distPath, '**/*.map'));
311
+ for (const mapPath of maps)__WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].removeSync(mapPath);
312
+ }
313
+ function renameDistFolder(task) {
314
+ const pkgPath = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(task.distPath, 'package.json');
315
+ const pkgJson = __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].readJsonSync(pkgPath, 'utf-8');
316
+ for (const key of [
317
+ 'types',
318
+ 'typing',
319
+ 'typings'
320
+ ]){
321
+ var _pkgJson_key;
322
+ if (null === (_pkgJson_key = pkgJson[key]) || void 0 === _pkgJson_key ? void 0 : _pkgJson_key.startsWith('dist/')) {
323
+ pkgJson[key] = pkgJson[key].replace('dist/', 'types/');
324
+ const distFolder = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(task.distPath, 'dist');
325
+ const typesFolder = (0, __WEBPACK_EXTERNAL_MODULE_node_path__.join)(task.distPath, 'types');
326
+ if (__WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].existsSync(distFolder)) __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].renameSync(distFolder, typesFolder);
327
+ }
328
+ }
329
+ __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].writeJSONSync(pkgPath, pkgJson);
330
+ }
331
+ const pkgName = process.argv[2];
332
+ async function prebundle(task) {
333
+ let commonExternals = arguments.length > 1 && void 0 !== arguments[1] ? arguments[1] : {};
334
+ if (pkgName && task.depName !== pkgName) return;
335
+ logger.start(`prebundle: ${task.depName}`);
336
+ __WEBPACK_EXTERNAL_MODULE__compiled_fs_extra_index_js__["default"].removeSync(task.distPath);
337
+ if (task.beforeBundle) await task.beforeBundle(task);
338
+ const mergedExternals = {
339
+ ...DEFAULT_EXTERNALS,
340
+ ...commonExternals,
341
+ ...task.externals
342
+ };
343
+ const { code, assets } = await (0, __WEBPACK_EXTERNAL_MODULE__vercel_ncc__["default"])(task.depEntry, {
344
+ minify: task.minify,
345
+ target: task.target,
346
+ externals: mergedExternals,
347
+ assetBuilds: false
348
+ });
349
+ await emitIndex(code, task.distPath, task.prettier);
350
+ emitAssets(assets, task.distPath);
351
+ await emitDts(task, mergedExternals);
352
+ emitLicense(task);
353
+ emitPackageJson(task, assets);
354
+ removeSourceMap(task);
355
+ renameDistFolder(task);
356
+ emitExtraFiles(task);
357
+ if (task.afterBundle) await task.afterBundle(task);
358
+ logger.success(`prebundle: ${task.depName}\n\n`);
359
+ }
360
+ async function run() {
361
+ const config = await resolveConfig();
362
+ const parsedTasks = parseTasks(config.dependencies, config.prettier);
363
+ for (const task of parsedTasks)await prebundle(task, config.externals);
364
+ }
365
+ export { run };
@@ -0,0 +1,2 @@
1
+ import type { ParsedTask } from './types.js';
2
+ export declare function prebundle(task: ParsedTask, commonExternals?: Record<string, string>): Promise<void>;
@@ -0,0 +1,53 @@
1
+ export type ImportMap = {
2
+ path: string;
3
+ content: string;
4
+ };
5
+ export type DependencyConfig = {
6
+ /** Name of dependency */
7
+ name: string;
8
+ /** Whether to minify the code. */
9
+ minify?: boolean;
10
+ /** Externals to leave as requires of the build. */
11
+ externals?: Record<string, string>;
12
+ /** Externals types */
13
+ dtsExternals?: Array<string | RegExp>;
14
+ /** Whether to prettier the code and strip comments */
15
+ prettier?: boolean;
16
+ /** Emit extra entry files to map imports. */
17
+ emitFiles?: ImportMap[];
18
+ /** Copy extra fields from original package.json to target package.json. */
19
+ packageJsonField?: string[];
20
+ /** Whether to ignore type definitions */
21
+ ignoreDts?: boolean;
22
+ /** Target ECMA version */
23
+ target?: string;
24
+ beforeBundle?: (task: ParsedTask) => void | Promise<void>;
25
+ afterBundle?: (task: ParsedTask) => void | Promise<void>;
26
+ };
27
+ export type Config = {
28
+ /**
29
+ * Configure externals for all packages,
30
+ * will be merged with dependencies[i].externals.
31
+ */
32
+ externals?: Record<string, string>;
33
+ dependencies: Array<string | DependencyConfig>;
34
+ /** Whether to prettier the code and strip comments */
35
+ prettier?: boolean;
36
+ };
37
+ export type ParsedTask = {
38
+ depPath: string;
39
+ depEntry: string;
40
+ distPath: string;
41
+ importPath: string;
42
+ ignoreDts?: boolean;
43
+ prettier?: boolean;
44
+ target: NonNullable<DependencyConfig['target']>;
45
+ minify: NonNullable<DependencyConfig['minify']>;
46
+ depName: NonNullable<DependencyConfig['name']>;
47
+ externals: NonNullable<DependencyConfig['externals']>;
48
+ dtsExternals: NonNullable<DependencyConfig['dtsExternals']>;
49
+ emitFiles: NonNullable<DependencyConfig['emitFiles']>;
50
+ afterBundle?: NonNullable<DependencyConfig['afterBundle']>;
51
+ beforeBundle?: NonNullable<DependencyConfig['beforeBundle']>;
52
+ packageJsonField: NonNullable<DependencyConfig['packageJsonField']>;
53
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "prebundle",
3
- "version": "1.2.4",
3
+ "version": "1.2.5",
4
4
  "repository": {
5
5
  "type": "git",
6
6
  "url": "https://github.com/rspack-contrib/prebundle"
@@ -19,7 +19,7 @@
19
19
  "build": "rslib build",
20
20
  "dev": "rslib build --watch",
21
21
  "prebundle": "node ./bin.js",
22
- "prepublishOnly": "npm run build",
22
+ "prepare": "npm run build",
23
23
  "bump": "npx bumpp"
24
24
  },
25
25
  "dependencies": {