@rslib/core 0.0.0 → 0.0.2

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.
package/dist/index.cjs DELETED
@@ -1,1131 +0,0 @@
1
- "use strict";
2
- var __create = Object.create;
3
- var __defProp = Object.defineProperty;
4
- var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
- var __getOwnPropNames = Object.getOwnPropertyNames;
6
- var __getProtoOf = Object.getPrototypeOf;
7
- var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __export = (target, all) => {
9
- for (var name in all)
10
- __defProp(target, name, { get: all[name], enumerable: true });
11
- };
12
- var __copyProps = (to, from, except, desc) => {
13
- if (from && typeof from === "object" || typeof from === "function") {
14
- for (let key of __getOwnPropNames(from))
15
- if (!__hasOwnProp.call(to, key) && key !== except)
16
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
- }
18
- return to;
19
- };
20
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
- // If the importer is in node compatibility mode or this is not an ESM
22
- // file that has been converted to a CommonJS file using a Babel-
23
- // compatible transform (i.e. "__esModule" has not been set), then set
24
- // "default" to the CommonJS "module.exports" for node compatibility.
25
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
- mod
27
- ));
28
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
-
30
- // src/index.ts
31
- var src_exports = {};
32
- __export(src_exports, {
33
- build: () => build,
34
- defineConfig: () => defineConfig,
35
- loadConfig: () => loadConfig,
36
- logger: () => logger,
37
- prepareCli: () => prepareCli,
38
- runCli: () => runCli,
39
- version: () => version
40
- });
41
- module.exports = __toCommonJS(src_exports);
42
-
43
- // ../../node_modules/.pnpm/rslog@1.2.2/node_modules/rslog/dist/index.mjs
44
- var import_process = __toESM(require("process"), 1);
45
- var import_os = __toESM(require("os"), 1);
46
- var import_tty = __toESM(require("tty"), 1);
47
- function hasFlag(flag, argv = globalThis.Deno ? globalThis.Deno.args : import_process.default.argv) {
48
- const prefix = flag.startsWith("-") ? "" : flag.length === 1 ? "-" : "--";
49
- const position = argv.indexOf(prefix + flag);
50
- const terminatorPosition = argv.indexOf("--");
51
- return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition);
52
- }
53
- var { env } = import_process.default;
54
- var flagForceColor;
55
- if (hasFlag("no-color") || hasFlag("no-colors") || hasFlag("color=false") || hasFlag("color=never")) {
56
- flagForceColor = 0;
57
- } else if (hasFlag("color") || hasFlag("colors") || hasFlag("color=true") || hasFlag("color=always")) {
58
- flagForceColor = 1;
59
- }
60
- function envForceColor() {
61
- if ("FORCE_COLOR" in env) {
62
- if (env.FORCE_COLOR === "true") {
63
- return 1;
64
- }
65
- if (env.FORCE_COLOR === "false") {
66
- return 0;
67
- }
68
- return env.FORCE_COLOR.length === 0 ? 1 : Math.min(Number.parseInt(env.FORCE_COLOR, 10), 3);
69
- }
70
- }
71
- function translateLevel(level) {
72
- if (level === 0) {
73
- return false;
74
- }
75
- return {
76
- level,
77
- hasBasic: true,
78
- has256: level >= 2,
79
- has16m: level >= 3
80
- };
81
- }
82
- function _supportsColor(haveStream, { streamIsTTY, sniffFlags = true } = {}) {
83
- const noFlagForceColor = envForceColor();
84
- if (noFlagForceColor !== void 0) {
85
- flagForceColor = noFlagForceColor;
86
- }
87
- const forceColor = sniffFlags ? flagForceColor : noFlagForceColor;
88
- if (forceColor === 0) {
89
- return 0;
90
- }
91
- if (sniffFlags) {
92
- if (hasFlag("color=16m") || hasFlag("color=full") || hasFlag("color=truecolor")) {
93
- return 3;
94
- }
95
- if (hasFlag("color=256")) {
96
- return 2;
97
- }
98
- }
99
- if ("TF_BUILD" in env && "AGENT_NAME" in env) {
100
- return 1;
101
- }
102
- if (haveStream && !streamIsTTY && forceColor === void 0) {
103
- return 0;
104
- }
105
- const min = forceColor || 0;
106
- if (env.TERM === "dumb") {
107
- return min;
108
- }
109
- if (import_process.default.platform === "win32") {
110
- const osRelease = import_os.default.release().split(".");
111
- if (Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) {
112
- return Number(osRelease[2]) >= 14931 ? 3 : 2;
113
- }
114
- return 1;
115
- }
116
- if ("CI" in env) {
117
- if ("GITHUB_ACTIONS" in env || "GITEA_ACTIONS" in env) {
118
- return 3;
119
- }
120
- if (["TRAVIS", "CIRCLECI", "APPVEYOR", "GITLAB_CI", "BUILDKITE", "DRONE"].some((sign) => sign in env) || env.CI_NAME === "codeship") {
121
- return 1;
122
- }
123
- return min;
124
- }
125
- if ("TEAMCITY_VERSION" in env) {
126
- return /^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0;
127
- }
128
- if (env.COLORTERM === "truecolor") {
129
- return 3;
130
- }
131
- if (env.TERM === "xterm-kitty") {
132
- return 3;
133
- }
134
- if ("TERM_PROGRAM" in env) {
135
- const version2 = Number.parseInt((env.TERM_PROGRAM_VERSION || "").split(".")[0], 10);
136
- switch (env.TERM_PROGRAM) {
137
- case "iTerm.app": {
138
- return version2 >= 3 ? 3 : 2;
139
- }
140
- case "Apple_Terminal": {
141
- return 2;
142
- }
143
- }
144
- }
145
- if (/-256(color)?$/i.test(env.TERM)) {
146
- return 2;
147
- }
148
- if (/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) {
149
- return 1;
150
- }
151
- if ("COLORTERM" in env) {
152
- return 1;
153
- }
154
- return min;
155
- }
156
- function createSupportsColor(stream, options = {}) {
157
- const level = _supportsColor(stream, {
158
- streamIsTTY: stream && stream.isTTY,
159
- ...options
160
- });
161
- return translateLevel(level);
162
- }
163
- var supportsColor = {
164
- stdout: createSupportsColor({ isTTY: import_tty.default.isatty(1) }),
165
- stderr: createSupportsColor({ isTTY: import_tty.default.isatty(2) })
166
- };
167
- var supports_color_default = supportsColor;
168
- var colorLevel = supports_color_default.stdout ? supports_color_default.stdout.level : 0;
169
- var errorStackRegExp = /at\s.*:\d+:\d+[\s\)]*$/;
170
- var anonymousErrorStackRegExp = /^\s*at\s.*\(<anonymous>\)$/;
171
- var isErrorStackMessage = (message) => errorStackRegExp.test(message) || anonymousErrorStackRegExp.test(message);
172
- var formatter = (open, close, replace = open) => colorLevel >= 2 ? (input) => {
173
- let string = "" + input;
174
- let index = string.indexOf(close, open.length);
175
- return ~index ? open + replaceClose(string, close, replace, index) + close : open + string + close;
176
- } : String;
177
- var replaceClose = (string, close, replace, index) => {
178
- let start = string.substring(0, index) + replace;
179
- let end = string.substring(index + close.length);
180
- let nextIndex = end.indexOf(close);
181
- return ~nextIndex ? start + replaceClose(end, close, replace, nextIndex) : start + end;
182
- };
183
- var bold = formatter("\x1B[1m", "\x1B[22m", "\x1B[22m\x1B[1m");
184
- var red = formatter("\x1B[31m", "\x1B[39m");
185
- var green = formatter("\x1B[32m", "\x1B[39m");
186
- var yellow = formatter("\x1B[33m", "\x1B[39m");
187
- var magenta = formatter("\x1B[35m", "\x1B[39m");
188
- var cyan = formatter("\x1B[36m", "\x1B[39m");
189
- var gray = formatter("\x1B[90m", "\x1B[39m");
190
- var startColor = [189, 255, 243];
191
- var endColor = [74, 194, 154];
192
- var isWord = (char) => !/[\s\n]/.test(char);
193
- var gradient = (message) => {
194
- if (colorLevel < 3) {
195
- return colorLevel === 2 ? bold(cyan(message)) : message;
196
- }
197
- let chars = [...message];
198
- let steps = chars.filter(isWord).length;
199
- let r = startColor[0];
200
- let g = startColor[1];
201
- let b = startColor[2];
202
- let rStep = (endColor[0] - r) / steps;
203
- let gStep = (endColor[1] - g) / steps;
204
- let bStep = (endColor[2] - b) / steps;
205
- let output = "";
206
- for (let char of chars) {
207
- if (isWord(char)) {
208
- r += rStep;
209
- g += gStep;
210
- b += bStep;
211
- }
212
- output += `\x1B[38;2;${Math.round(r)};${Math.round(g)};${Math.round(
213
- b
214
- )}m${char}\x1B[39m`;
215
- }
216
- return bold(output);
217
- };
218
- var LOG_LEVEL = {
219
- error: 0,
220
- warn: 1,
221
- info: 2,
222
- log: 3,
223
- verbose: 4
224
- };
225
- var LOG_TYPES = {
226
- // Level error
227
- error: {
228
- label: "error",
229
- level: "error",
230
- color: red
231
- },
232
- // Level warn
233
- warn: {
234
- label: "warn",
235
- level: "warn",
236
- color: yellow
237
- },
238
- // Level info
239
- info: {
240
- label: "info",
241
- level: "info",
242
- color: cyan
243
- },
244
- start: {
245
- label: "start",
246
- level: "info",
247
- color: cyan
248
- },
249
- ready: {
250
- label: "ready",
251
- level: "info",
252
- color: green
253
- },
254
- success: {
255
- label: "success",
256
- level: "info",
257
- color: green
258
- },
259
- // Level log
260
- log: {
261
- level: "log"
262
- },
263
- // Level debug
264
- debug: {
265
- label: "debug",
266
- level: "verbose",
267
- color: magenta
268
- }
269
- };
270
- var createLogger = (options = {}) => {
271
- let maxLevel = options.level || "log";
272
- let log = (type, message, ...args) => {
273
- if (LOG_LEVEL[LOG_TYPES[type].level] > LOG_LEVEL[maxLevel]) {
274
- return;
275
- }
276
- if (message === void 0 || message === null) {
277
- return console.log();
278
- }
279
- let logType = LOG_TYPES[type];
280
- let label = "";
281
- let text = "";
282
- if ("label" in logType) {
283
- label = (logType.label || "").padEnd(7);
284
- label = bold(logType.color ? logType.color(label) : label);
285
- }
286
- if (message instanceof Error) {
287
- if (message.stack) {
288
- let [name, ...rest] = message.stack.split("\n");
289
- if (name.startsWith("Error: ")) {
290
- name = name.slice(7);
291
- }
292
- text = `${name}
293
- ${gray(rest.join("\n"))}`;
294
- } else {
295
- text = message.message;
296
- }
297
- } else if (logType.level === "error" && typeof message === "string") {
298
- let lines = message.split("\n");
299
- text = lines.map((line) => isErrorStackMessage(line) ? gray(line) : line).join("\n");
300
- } else {
301
- text = `${message}`;
302
- }
303
- console.log(label.length ? `${label} ${text}` : text, ...args);
304
- };
305
- let logger2 = {
306
- greet: (message) => log("log", gradient(message))
307
- };
308
- Object.keys(LOG_TYPES).forEach((key) => {
309
- logger2[key] = (...args) => log(key, ...args);
310
- });
311
- Object.defineProperty(logger2, "level", {
312
- get: () => maxLevel,
313
- set(val) {
314
- maxLevel = val;
315
- }
316
- });
317
- logger2.override = (customLogger) => {
318
- Object.assign(logger2, customLogger);
319
- };
320
- return logger2;
321
- };
322
- var logger = createLogger();
323
-
324
- // src/utils/helper.ts
325
- var import_node_fs = __toESM(require("fs"));
326
- var import_promises = __toESM(require("fs/promises"));
327
- var import_node_path = __toESM(require("path"));
328
- var import_picocolors = __toESM(require("../compiled/picocolors/index.js"));
329
- var nodeBuiltInModules = [
330
- "assert",
331
- "assert/strict",
332
- "async_hooks",
333
- "buffer",
334
- "child_process",
335
- "cluster",
336
- "console",
337
- "constants",
338
- "crypto",
339
- "dgram",
340
- "diagnostics_channel",
341
- "dns",
342
- "dns/promises",
343
- "domain",
344
- "events",
345
- "fs",
346
- "fs/promises",
347
- "http",
348
- "http2",
349
- "https",
350
- "inspector",
351
- "inspector/promises",
352
- "module",
353
- "net",
354
- "os",
355
- "path",
356
- "path/posix",
357
- "path/win32",
358
- "perf_hooks",
359
- "process",
360
- "punycode",
361
- "querystring",
362
- "readline",
363
- "readline/promises",
364
- "repl",
365
- "stream",
366
- "stream/consumers",
367
- "stream/promises",
368
- "stream/web",
369
- "string_decoder",
370
- "sys",
371
- "timers",
372
- "timers/promises",
373
- "tls",
374
- "trace_events",
375
- "tty",
376
- "url",
377
- "util",
378
- "util/types",
379
- "v8",
380
- "vm",
381
- "wasi",
382
- "worker_threads",
383
- "zlib",
384
- /^node:/,
385
- // cspell:word pnpapi
386
- // Yarn PnP adds pnpapi as "builtin"
387
- "pnpapi"
388
- ];
389
- async function calcLongestCommonPath(absPaths) {
390
- if (absPaths.length === 0) {
391
- return null;
392
- }
393
- const sep = import_node_path.default.posix.sep;
394
- const splitPaths = absPaths.map((p) => p.split(sep));
395
- let lcaFragments = splitPaths[0];
396
- for (let i = 1; i < splitPaths.length; i++) {
397
- const currentPath = splitPaths[i];
398
- const minLength = Math.min(lcaFragments.length, currentPath.length);
399
- let j = 0;
400
- while (j < minLength && lcaFragments[j] === currentPath[j]) {
401
- j++;
402
- }
403
- lcaFragments = lcaFragments.slice(0, j);
404
- }
405
- let lca = lcaFragments.length > 0 ? lcaFragments.join(sep) : sep;
406
- const stats = await import_promises.default.stat(lca);
407
- if (stats?.isFile()) {
408
- lca = import_node_path.default.dirname(lca);
409
- }
410
- return lca;
411
- }
412
- var readPackageJson = (rootPath) => {
413
- const pkgJsonPath = import_node_path.default.resolve(rootPath, "./package.json");
414
- if (!import_node_fs.default.existsSync(pkgJsonPath)) {
415
- logger.warn(`package.json does not exist in the ${rootPath} directory`);
416
- return;
417
- }
418
- try {
419
- return JSON.parse(import_node_fs.default.readFileSync(pkgJsonPath, "utf8"));
420
- } catch (err) {
421
- logger.warn(`Failed to parse ${pkgJsonPath}, it might not be valid JSON`);
422
- return;
423
- }
424
- };
425
- var isObject = (obj) => Object.prototype.toString.call(obj) === "[object Object]";
426
-
427
- // src/utils/logger.ts
428
- if (process.env.DEBUG) {
429
- logger.level = "verbose";
430
- }
431
-
432
- // src/cli/prepare.ts
433
- function initNodeEnv() {
434
- if (!process.env.NODE_ENV) {
435
- const command = process.argv[2] ?? "";
436
- process.env.NODE_ENV = ["build"].includes(command) ? "production" : "development";
437
- }
438
- }
439
- function prepareCli() {
440
- initNodeEnv();
441
- const { npm_execpath } = process.env;
442
- if (!npm_execpath || npm_execpath.includes("npx-cli.js") || npm_execpath.includes(".bun")) {
443
- console.log();
444
- }
445
- logger.greet(` ${`Rslib v${"0.0.0"}`}
446
- `);
447
- }
448
-
449
- // src/cli/commands.ts
450
- var import_commander = require("../compiled/commander/index.js");
451
-
452
- // src/config.ts
453
- var import_node_fs2 = __toESM(require("fs"));
454
- var import_node_path2 = __toESM(require("path"));
455
- var import_core = require("@rsbuild/core");
456
- var import_fast_glob = __toESM(require("../compiled/fast-glob/index.js"));
457
-
458
- // src/constant.ts
459
- var DEFAULT_CONFIG_NAME = "rslib.config";
460
- var DEFAULT_EXTENSIONS = [
461
- ".js",
462
- ".ts",
463
- ".mjs",
464
- ".mts",
465
- ".cjs",
466
- ".cts"
467
- ];
468
-
469
- // src/utils/extension.ts
470
- var getDefaultExtension = (options) => {
471
- const { format, pkgJson, autoExtension } = options;
472
- let jsExtension = ".js";
473
- let dtsExtension = ".d.ts";
474
- if (!autoExtension) {
475
- return {
476
- jsExtension,
477
- dtsExtension
478
- };
479
- }
480
- if (!pkgJson) {
481
- logger.warn(
482
- "autoExtension configuration will not be applied due to read package.json failed"
483
- );
484
- return {
485
- jsExtension,
486
- dtsExtension
487
- };
488
- }
489
- const isModule = pkgJson.type === "module";
490
- if (isModule && format === "cjs") {
491
- jsExtension = ".cjs";
492
- dtsExtension = ".d.cts";
493
- }
494
- if (!isModule && format === "esm") {
495
- jsExtension = ".mjs";
496
- dtsExtension = ".d.mts";
497
- }
498
- return {
499
- jsExtension,
500
- dtsExtension,
501
- isModule
502
- };
503
- };
504
-
505
- // src/utils/syntax.ts
506
- var ESX_TO_BROWSERSLIST = {
507
- es6: {
508
- Chrome: "63.0.0",
509
- Edge: "79.0.0",
510
- Firefox: "67.0.0",
511
- iOS: "13.0.0",
512
- Node: ["node > 12.20.0 and node < 13.0.0", "node > 13.2.0"],
513
- Opera: "50.0.0",
514
- Safari: "13.0.0"
515
- },
516
- es2015: {
517
- Chrome: "63.0.0",
518
- Edge: "79.0.0",
519
- Firefox: "67.0.0",
520
- iOS: "13.0.0",
521
- Node: "10.0.0",
522
- Opera: "50.0.0",
523
- Safari: "13.0.0"
524
- },
525
- es2016: {
526
- Chrome: "52.0.0",
527
- Edge: "14.0.0",
528
- Firefox: "52.0.0",
529
- iOS: "10.3.0",
530
- Node: "7.0.0",
531
- Opera: "39.0.0",
532
- Safari: "10.1.0"
533
- },
534
- es2017: {
535
- Chrome: "55.0.0",
536
- Edge: "15.0.0",
537
- Firefox: "52.0.0",
538
- iOS: "11.0.0",
539
- Node: "7.6.0",
540
- Opera: "42.0.0",
541
- Safari: "11.0.0"
542
- },
543
- es2018: {
544
- Chrome: "64.0.0",
545
- Edge: "79.0.0",
546
- Firefox: "78.0.0",
547
- iOS: "16.4.0",
548
- Node: [
549
- "node > 18.20.0 and node < 19.0.0",
550
- "node > 20.12.0 and node < 21.0.0",
551
- "node > 21.3.0"
552
- ],
553
- Opera: "51.0.0",
554
- Safari: "16.4.0"
555
- },
556
- es2019: {
557
- Chrome: "66.0.0",
558
- Edge: "79.0.0",
559
- Firefox: "58.0.0",
560
- iOS: "11.3.0",
561
- Node: "10.0.0",
562
- Opera: "53.0.0",
563
- Safari: "11.1.0"
564
- },
565
- es2020: {
566
- Chrome: "91.0.0",
567
- Edge: "91.0.0",
568
- Firefox: "80.0.0",
569
- iOS: "14.5.0",
570
- Node: "16.1.0",
571
- Opera: "77.0.0",
572
- Safari: "14.1.0"
573
- },
574
- es2021: {
575
- Chrome: "85.0.0",
576
- Edge: "85.0.0",
577
- Firefox: "79.0.0",
578
- iOS: "14.0.0",
579
- Node: "15.0.0",
580
- Opera: "71.0.0",
581
- Safari: "14.0.0"
582
- },
583
- es2022: {
584
- Chrome: "91.0.0",
585
- Edge: "94.0.0",
586
- Firefox: "93.0.0",
587
- iOS: "16.4.0",
588
- Node: "16.11.0",
589
- Opera: "80.0.0",
590
- Safari: "16.4.0"
591
- },
592
- es2023: {
593
- Chrome: "74.0.0",
594
- Edge: "79.0.0",
595
- Firefox: "67.0.0",
596
- iOS: "13.4.0",
597
- Node: "12.5.0",
598
- Opera: "62.0.0",
599
- Safari: "13.1.0"
600
- },
601
- es2024: {},
602
- esnext: {},
603
- es5: {
604
- Chrome: "5.0.0",
605
- Edge: "12.0.0",
606
- Firefox: "2.0.0",
607
- ie: "9.0.0",
608
- iOS: "6.0.0",
609
- Node: "0.4.0",
610
- Opera: "10.10.0",
611
- Safari: "3.1.0"
612
- }
613
- };
614
- var transformSyntaxToBrowserslist = (syntax) => {
615
- if (typeof syntax === "string" && syntax.toLowerCase().startsWith("es")) {
616
- if (syntax.toLowerCase() in ESX_TO_BROWSERSLIST) {
617
- return Object.entries(ESX_TO_BROWSERSLIST[syntax]).flatMap(
618
- ([engine, version2]) => {
619
- if (Array.isArray(version2)) {
620
- return version2;
621
- }
622
- return `${engine} >= ${version2}`;
623
- }
624
- );
625
- }
626
- throw new Error(`Unsupported ES version: ${syntax}`);
627
- }
628
- if (Array.isArray(syntax)) {
629
- return syntax;
630
- }
631
- throw new Error(`Unsupported syntax: ${syntax}`);
632
- };
633
-
634
- // src/config.ts
635
- function defineConfig(config) {
636
- return config;
637
- }
638
- var findConfig = (basePath) => {
639
- return DEFAULT_EXTENSIONS.map((ext) => basePath + ext).find(import_node_fs2.default.existsSync);
640
- };
641
- var resolveConfigPath = (root, customConfig) => {
642
- if (customConfig) {
643
- const customConfigPath = (0, import_node_path2.isAbsolute)(customConfig) ? customConfig : (0, import_node_path2.join)(root, customConfig);
644
- if (import_node_fs2.default.existsSync(customConfigPath)) {
645
- return customConfigPath;
646
- }
647
- logger.warn(`Cannot find config file: ${import_picocolors.default.dim(customConfigPath)}
648
- `);
649
- }
650
- const configFilePath = findConfig((0, import_node_path2.join)(root, DEFAULT_CONFIG_NAME));
651
- if (configFilePath) {
652
- return configFilePath;
653
- }
654
- return void 0;
655
- };
656
- async function loadConfig(customConfig, envMode) {
657
- const root = process.cwd();
658
- const configFilePath = resolveConfigPath(root, customConfig);
659
- const { content } = await (0, import_core.loadConfig)({
660
- cwd: (0, import_node_path2.dirname)(configFilePath),
661
- path: configFilePath,
662
- envMode
663
- });
664
- return content;
665
- }
666
- var composeAutoExternalConfig = (options) => {
667
- const { autoExternal, pkgJson, userExternals } = options;
668
- if (!autoExternal) {
669
- return {};
670
- }
671
- if (!pkgJson) {
672
- logger.warn(
673
- "autoExternal configuration will not be applied due to read package.json failed"
674
- );
675
- return {};
676
- }
677
- const externalOptions = {
678
- dependencies: true,
679
- peerDependencies: true,
680
- devDependencies: false,
681
- ...autoExternal === true ? {} : autoExternal
682
- };
683
- const userExternalKeys = userExternals && isObject(userExternals) ? Object.keys(userExternals) : [];
684
- const externals = ["dependencies", "peerDependencies", "devDependencies"].reduce((prev, type) => {
685
- if (externalOptions[type]) {
686
- return pkgJson[type] ? prev.concat(Object.keys(pkgJson[type])) : prev;
687
- }
688
- return prev;
689
- }, []).filter((name) => !userExternalKeys.includes(name));
690
- const uniqueExternals = Array.from(new Set(externals));
691
- return externals.length ? {
692
- output: {
693
- externals: [
694
- // Exclude dependencies, e.g. `react`, `react/jsx-runtime`
695
- ...uniqueExternals.map((dep) => new RegExp(`^${dep}($|\\/|\\\\)`)),
696
- ...uniqueExternals
697
- ]
698
- }
699
- } : {};
700
- };
701
- async function createInternalRsbuildConfig() {
702
- return (0, import_core.defineConfig)({
703
- mode: "production",
704
- dev: {
705
- progressBar: false
706
- },
707
- tools: {
708
- htmlPlugin: false,
709
- rspack: {
710
- optimization: {
711
- moduleIds: "named"
712
- },
713
- experiments: {
714
- rspackFuture: {
715
- bundlerInfo: {
716
- force: false
717
- }
718
- }
719
- }
720
- }
721
- },
722
- output: {
723
- filenameHash: false,
724
- // TODO: easy to development at the moment
725
- minify: false,
726
- distPath: {
727
- js: "./"
728
- }
729
- }
730
- });
731
- }
732
- var composeFormatConfig = (format) => {
733
- switch (format) {
734
- case "esm":
735
- return {
736
- tools: {
737
- rspack: {
738
- externalsType: "module-import",
739
- output: {
740
- module: true,
741
- chunkFormat: "module",
742
- library: {
743
- type: "modern-module"
744
- }
745
- },
746
- module: {
747
- parser: {
748
- javascript: {
749
- importMeta: false
750
- }
751
- }
752
- },
753
- optimization: {
754
- concatenateModules: true
755
- },
756
- experiments: {
757
- outputModule: true
758
- }
759
- }
760
- }
761
- };
762
- case "cjs":
763
- return {
764
- tools: {
765
- rspack: {
766
- externalsType: "commonjs",
767
- output: {
768
- iife: false,
769
- chunkFormat: "commonjs",
770
- library: {
771
- type: "commonjs"
772
- }
773
- }
774
- }
775
- }
776
- };
777
- case "umd":
778
- return {
779
- tools: {
780
- rspack: {
781
- externalsType: "umd",
782
- output: {
783
- library: {
784
- type: "umd"
785
- }
786
- }
787
- }
788
- }
789
- };
790
- default:
791
- throw new Error(`Unsupported format: ${format}`);
792
- }
793
- };
794
- var composeAutoExtensionConfig = (format, autoExtension, pkgJson) => {
795
- const { jsExtension, dtsExtension } = getDefaultExtension({
796
- format,
797
- pkgJson,
798
- autoExtension
799
- });
800
- return {
801
- config: {
802
- output: {
803
- filename: {
804
- js: `[name]${jsExtension}`
805
- }
806
- }
807
- },
808
- jsExtension,
809
- dtsExtension
810
- };
811
- };
812
- var composeSyntaxConfig = (syntax, target) => {
813
- if (syntax) {
814
- return {
815
- tools: {
816
- rspack: (config) => {
817
- config.target = ["es5"];
818
- return config;
819
- }
820
- },
821
- output: {
822
- overrideBrowserslist: transformSyntaxToBrowserslist(syntax)
823
- }
824
- };
825
- }
826
- const lastTargetVersions = {
827
- node: ["last 1 node versions"],
828
- web: [
829
- "last 1 Chrome versions",
830
- "last 1 Firefox versions",
831
- "last 1 Edge versions",
832
- "last 1 Safari versions",
833
- "last 1 ios_saf versions",
834
- "not dead"
835
- ]
836
- };
837
- return {
838
- tools: {
839
- rspack: (config) => {
840
- config.target = ["es2022"];
841
- return config;
842
- }
843
- },
844
- output: {
845
- overrideBrowserslist: target === "web" ? lastTargetVersions.web : target === "node" ? lastTargetVersions.node : [...lastTargetVersions.node, ...lastTargetVersions.web]
846
- }
847
- };
848
- };
849
- var composeEntryConfig = async (entries, bundle, root) => {
850
- if (!entries) {
851
- return {};
852
- }
853
- if (bundle !== false) {
854
- return {
855
- source: {
856
- entry: entries
857
- }
858
- };
859
- }
860
- const resolvedEntries = {};
861
- for (const key of Object.keys(entries)) {
862
- const entry = entries[key];
863
- const entryFiles = Array.isArray(entry) ? entry : typeof entry === "string" ? [entry] : null;
864
- if (!entryFiles) {
865
- throw new Error(
866
- "Entry can only be a string or an array of strings for now"
867
- );
868
- }
869
- const resolvedEntryFiles = await (0, import_fast_glob.default)(entryFiles, {
870
- cwd: root
871
- });
872
- if (resolvedEntryFiles.length === 0) {
873
- throw new Error(`Cannot find ${resolvedEntryFiles}`);
874
- }
875
- const lcp = await calcLongestCommonPath(resolvedEntryFiles);
876
- const outBase = lcp === null ? root : lcp;
877
- for (const file of resolvedEntryFiles) {
878
- const { dir, name } = import_node_path2.default.parse(import_node_path2.default.relative(outBase, file));
879
- const entryFileName = import_node_path2.default.join(dir, name);
880
- resolvedEntries[entryFileName] = file;
881
- }
882
- }
883
- return {
884
- source: {
885
- entry: resolvedEntries
886
- }
887
- };
888
- };
889
- var composeBundleConfig = (jsExtension, bundle = true) => {
890
- if (bundle)
891
- return {};
892
- return {
893
- output: {
894
- externals: [
895
- (data, callback) => {
896
- if (data.contextInfo.issuer) {
897
- return callback(
898
- null,
899
- data.request[0] === "." ? `${data.request}${jsExtension}` : data.request
900
- );
901
- }
902
- callback();
903
- }
904
- ]
905
- }
906
- };
907
- };
908
- var composeDtsConfig = async (libConfig, dtsExtension) => {
909
- const { dts, bundle, output, autoExternal } = libConfig;
910
- if (dts === false || dts === void 0)
911
- return {};
912
- const { pluginDts } = await import("rsbuild-plugin-dts");
913
- return {
914
- plugins: [
915
- pluginDts({
916
- bundle: dts?.bundle ?? bundle,
917
- distPath: dts?.distPath ?? output?.distPath?.root ?? "./dist",
918
- abortOnError: dts?.abortOnError ?? true,
919
- dtsExtension,
920
- autoExternal
921
- })
922
- ]
923
- };
924
- };
925
- var composeTargetConfig = (target = "web") => {
926
- switch (target) {
927
- case "web":
928
- return {
929
- tools: {
930
- rspack: {
931
- target: ["web"]
932
- }
933
- }
934
- };
935
- case "node":
936
- return {
937
- tools: {
938
- rspack: {
939
- target: ["node"]
940
- // "__dirname" and "__filename" shims will automatically be enabled when `output.module` is `true`,
941
- // and leave them as-is in the rest of the cases.
942
- // { node: { __dirname: ..., __filename: ... } }
943
- }
944
- },
945
- output: {
946
- // When output.target is 'node', Node.js's built-in will be treated as externals of type `node-commonjs`.
947
- // Simply override the built-in modules to make them external.
948
- // https://github.com/webpack/webpack/blob/dd44b206a9c50f4b4cb4d134e1a0bd0387b159a3/lib/node/NodeTargetPlugin.js#L81
949
- externals: nodeBuiltInModules,
950
- target: "node"
951
- }
952
- };
953
- case "neutral":
954
- return {
955
- tools: {
956
- rspack: {
957
- target: ["web", "node"]
958
- }
959
- }
960
- };
961
- default:
962
- throw new Error(`Unsupported platform: ${target}`);
963
- }
964
- };
965
- async function composeLibRsbuildConfig(libConfig, rsbuildConfig, configPath) {
966
- const config = (0, import_core.mergeRsbuildConfig)(rsbuildConfig, libConfig);
967
- const rootPath = (0, import_node_path2.dirname)(configPath);
968
- const pkgJson = readPackageJson(rootPath);
969
- const { format, autoExtension = true, autoExternal = true } = config;
970
- const formatConfig = composeFormatConfig(format);
971
- const {
972
- config: autoExtensionConfig,
973
- jsExtension,
974
- dtsExtension
975
- } = composeAutoExtensionConfig(format, autoExtension, pkgJson);
976
- const bundleConfig = composeBundleConfig(jsExtension, config.bundle);
977
- const targetConfig = composeTargetConfig(config.output?.target);
978
- const syntaxConfig = composeSyntaxConfig(
979
- config.output?.syntax,
980
- config.output?.target
981
- );
982
- const autoExternalConfig = composeAutoExternalConfig({
983
- autoExternal,
984
- pkgJson,
985
- userExternals: rsbuildConfig.output?.externals
986
- });
987
- const entryConfig = await composeEntryConfig(
988
- config.source?.entry,
989
- config.bundle,
990
- (0, import_node_path2.dirname)(configPath)
991
- );
992
- const dtsConfig = await composeDtsConfig(config, dtsExtension);
993
- return (0, import_core.mergeRsbuildConfig)(
994
- formatConfig,
995
- autoExtensionConfig,
996
- autoExternalConfig,
997
- syntaxConfig,
998
- bundleConfig,
999
- targetConfig,
1000
- entryConfig,
1001
- dtsConfig
1002
- );
1003
- }
1004
- async function composeCreateRsbuildConfig(rslibConfig, path3) {
1005
- const internalRsbuildConfig = await createInternalRsbuildConfig();
1006
- const configPath = path3 ?? rslibConfig._privateMeta?.configFilePath;
1007
- const { lib: libConfigsArray, ...sharedRsbuildConfig } = rslibConfig;
1008
- if (!libConfigsArray) {
1009
- throw new Error(
1010
- `Expect lib field to be an array, but got ${libConfigsArray}.`
1011
- );
1012
- }
1013
- const libConfigPromises = libConfigsArray.map(async (libConfig) => {
1014
- const { format, ...overrideRsbuildConfig } = libConfig;
1015
- const baseRsbuildConfig = (0, import_core.mergeRsbuildConfig)(
1016
- sharedRsbuildConfig,
1017
- overrideRsbuildConfig
1018
- );
1019
- const libRsbuildConfig = await composeLibRsbuildConfig(
1020
- libConfig,
1021
- baseRsbuildConfig,
1022
- configPath
1023
- );
1024
- baseRsbuildConfig.source ?? (baseRsbuildConfig.source = {});
1025
- baseRsbuildConfig.source.entry = {};
1026
- return {
1027
- format,
1028
- config: (0, import_core.mergeRsbuildConfig)(
1029
- baseRsbuildConfig,
1030
- libRsbuildConfig,
1031
- // Merge order matters, keep `internalRsbuildConfig` at the last position
1032
- // to ensure that the internal config is not overridden by user's config.
1033
- internalRsbuildConfig
1034
- )
1035
- };
1036
- });
1037
- const composedRsbuildConfig = await Promise.all(libConfigPromises);
1038
- return composedRsbuildConfig;
1039
- }
1040
- async function initRsbuild(rslibConfig) {
1041
- const rsbuildConfigObject = await composeCreateRsbuildConfig(rslibConfig);
1042
- const environments = {};
1043
- const formatCount = rsbuildConfigObject.reduce(
1044
- (acc, { format }) => {
1045
- acc[format] = (acc[format] ?? 0) + 1;
1046
- return acc;
1047
- },
1048
- {}
1049
- );
1050
- const formatIndex = {
1051
- esm: 0,
1052
- cjs: 0,
1053
- umd: 0
1054
- };
1055
- for (const { format, config } of rsbuildConfigObject) {
1056
- const currentFormatCount = formatCount[format];
1057
- const currentFormatIndex = formatIndex[format]++;
1058
- environments[currentFormatCount === 1 ? format : `${format}${currentFormatIndex}`] = config;
1059
- }
1060
- return (0, import_core.createRsbuild)({
1061
- rsbuildConfig: {
1062
- environments
1063
- }
1064
- });
1065
- }
1066
-
1067
- // src/build.ts
1068
- async function build(config, options) {
1069
- const rsbuildInstance = await initRsbuild(config);
1070
- await rsbuildInstance.build({
1071
- watch: options?.watch
1072
- });
1073
- return rsbuildInstance;
1074
- }
1075
-
1076
- // src/cli/commands.ts
1077
- var applyCommonOptions = (command) => {
1078
- command.option(
1079
- "-c --config <config>",
1080
- "specify the configuration file, can be a relative or absolute path"
1081
- ).option(
1082
- "--env-mode <mode>",
1083
- "specify the env mode to load the `.env.[mode]` file"
1084
- );
1085
- };
1086
- function runCli() {
1087
- import_commander.program.name("rslib").usage("<command> [options]").version("0.0.0");
1088
- const buildCommand = import_commander.program.command("build");
1089
- const inspectCommand = import_commander.program.command("inspect");
1090
- [buildCommand, inspectCommand].forEach(applyCommonOptions);
1091
- buildCommand.option("-w --watch", "turn on watch mode, watch for changes and rebuild").description("build the library for production").action(async (options) => {
1092
- try {
1093
- const rslibConfig = await loadConfig(options.config, options.envMode);
1094
- await build(rslibConfig, options);
1095
- } catch (err) {
1096
- logger.error("Failed to build.");
1097
- logger.error(err);
1098
- process.exit(1);
1099
- }
1100
- });
1101
- inspectCommand.description("inspect the Rslib / Rsbuild / Rspack configs").option("--env <env>", "specify env mode", "development").option("--output <output>", "specify inspect content output path", "./").option("--verbose", "show full function definitions in output").action(async (options) => {
1102
- try {
1103
- const rslibConfig = await loadConfig(options.config, options.envMode);
1104
- const rsbuildInstance = await initRsbuild(rslibConfig);
1105
- await rsbuildInstance.inspectConfig({
1106
- mode: options.mode,
1107
- verbose: options.verbose,
1108
- outputPath: options.output,
1109
- writeToDisk: true
1110
- });
1111
- } catch (err) {
1112
- logger.error("Failed to inspect config.");
1113
- logger.error(err);
1114
- process.exit(1);
1115
- }
1116
- });
1117
- import_commander.program.parse();
1118
- }
1119
-
1120
- // src/index.ts
1121
- var version = "0.0.0";
1122
- // Annotate the CommonJS export names for ESM import in node:
1123
- 0 && (module.exports = {
1124
- build,
1125
- defineConfig,
1126
- loadConfig,
1127
- logger,
1128
- prepareCli,
1129
- runCli,
1130
- version
1131
- });