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