@rslib/core 0.7.1 → 0.9.0

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.js CHANGED
@@ -3,7 +3,7 @@ import * as __WEBPACK_EXTERNAL_MODULE_node_fs_5ea92f0c__ from "node:fs";
3
3
  import * as __WEBPACK_EXTERNAL_MODULE_node_fs_promises_153e37e0__ from "node:fs/promises";
4
4
  import * as __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__ from "node:path";
5
5
  import * as __WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js_ea7a20e9__ from "../compiled/picocolors/index.js";
6
- import * as __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js_bca3ceaa__ from "../compiled/commander/index.js";
6
+ import * as __WEBPACK_EXTERNAL_MODULE_events__ from "events";
7
7
  import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__ from "@rsbuild/core";
8
8
  import * as __WEBPACK_EXTERNAL_MODULE_tinyglobby__ from "tinyglobby";
9
9
  import * as __WEBPACK_EXTERNAL_MODULE_node_module_ab9f2194__ from "node:module";
@@ -181,8 +181,493 @@ function prepareCli() {
181
181
  initNodeEnv();
182
182
  const { npm_execpath } = process.env;
183
183
  if (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) console.log();
184
- __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger.greet(` Rslib v0.7.1\n`);
184
+ __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger.greet(` Rslib v0.9.0\n`);
185
185
  }
186
+ function toArr(any) {
187
+ return null == any ? [] : Array.isArray(any) ? any : [
188
+ any
189
+ ];
190
+ }
191
+ function toVal(out, key, val, opts) {
192
+ var x, old = out[key], nxt = ~opts.string.indexOf(key) ? null == val || true === val ? '' : String(val) : 'boolean' == typeof val ? val : ~opts.boolean.indexOf(key) ? 'false' === val ? false : 'true' === val || (out._.push((x = +val, 0 * x === 0) ? x : val), !!val) : (x = +val, 0 * x === 0) ? x : val;
193
+ out[key] = null == old ? nxt : Array.isArray(old) ? old.concat(nxt) : [
194
+ old,
195
+ nxt
196
+ ];
197
+ }
198
+ function mri2(args, opts) {
199
+ args = args || [];
200
+ opts = opts || {};
201
+ var k, arr, arg, name, val, out = {
202
+ _: []
203
+ };
204
+ var i = 0, j = 0, idx = 0, len = args.length;
205
+ const alibi = void 0 !== opts.alias;
206
+ const strict = void 0 !== opts.unknown;
207
+ const defaults = void 0 !== opts.default;
208
+ opts.alias = opts.alias || {};
209
+ opts.string = toArr(opts.string);
210
+ opts.boolean = toArr(opts.boolean);
211
+ if (alibi) for(k in opts.alias){
212
+ arr = opts.alias[k] = toArr(opts.alias[k]);
213
+ for(i = 0; i < arr.length; i++)(opts.alias[arr[i]] = arr.concat(k)).splice(i, 1);
214
+ }
215
+ for(i = opts.boolean.length; i-- > 0;){
216
+ arr = opts.alias[opts.boolean[i]] || [];
217
+ for(j = arr.length; j-- > 0;)opts.boolean.push(arr[j]);
218
+ }
219
+ for(i = opts.string.length; i-- > 0;){
220
+ arr = opts.alias[opts.string[i]] || [];
221
+ for(j = arr.length; j-- > 0;)opts.string.push(arr[j]);
222
+ }
223
+ if (defaults) for(k in opts.default){
224
+ name = typeof opts.default[k];
225
+ arr = opts.alias[k] = opts.alias[k] || [];
226
+ if (void 0 !== opts[name]) {
227
+ opts[name].push(k);
228
+ for(i = 0; i < arr.length; i++)opts[name].push(arr[i]);
229
+ }
230
+ }
231
+ const keys = strict ? Object.keys(opts.alias) : [];
232
+ for(i = 0; i < len; i++){
233
+ arg = args[i];
234
+ if ('--' === arg) {
235
+ out._ = out._.concat(args.slice(++i));
236
+ break;
237
+ }
238
+ for(j = 0; j < arg.length && 45 === arg.charCodeAt(j); j++);
239
+ if (0 === j) out._.push(arg);
240
+ else if ('no-' === arg.substring(j, j + 3)) {
241
+ name = arg.substring(j + 3);
242
+ if (strict && !~keys.indexOf(name)) return opts.unknown(arg);
243
+ out[name] = false;
244
+ } else {
245
+ for(idx = j + 1; idx < arg.length && 61 !== arg.charCodeAt(idx); idx++);
246
+ name = arg.substring(j, idx);
247
+ val = arg.substring(++idx) || i + 1 === len || 45 === ('' + args[i + 1]).charCodeAt(0) || args[++i];
248
+ arr = 2 === j ? [
249
+ name
250
+ ] : name;
251
+ for(idx = 0; idx < arr.length; idx++){
252
+ name = arr[idx];
253
+ if (strict && !~keys.indexOf(name)) return opts.unknown('-'.repeat(j) + name);
254
+ toVal(out, name, idx + 1 < arr.length || val, opts);
255
+ }
256
+ }
257
+ }
258
+ if (defaults) {
259
+ for(k in opts.default)if (void 0 === out[k]) out[k] = opts.default[k];
260
+ }
261
+ if (alibi) for(k in out){
262
+ arr = opts.alias[k] || [];
263
+ while(arr.length > 0)out[arr.shift()] = out[k];
264
+ }
265
+ return out;
266
+ }
267
+ const removeBrackets = (v)=>v.replace(/[<[].+/, "").trim();
268
+ const findAllBrackets = (v)=>{
269
+ const ANGLED_BRACKET_RE_GLOBAL = /<([^>]+)>/g;
270
+ const SQUARE_BRACKET_RE_GLOBAL = /\[([^\]]+)\]/g;
271
+ const res = [];
272
+ const parse = (match)=>{
273
+ let variadic = false;
274
+ let value = match[1];
275
+ if (value.startsWith("...")) {
276
+ value = value.slice(3);
277
+ variadic = true;
278
+ }
279
+ return {
280
+ required: match[0].startsWith("<"),
281
+ value,
282
+ variadic
283
+ };
284
+ };
285
+ let angledMatch;
286
+ while(angledMatch = ANGLED_BRACKET_RE_GLOBAL.exec(v))res.push(parse(angledMatch));
287
+ let squareMatch;
288
+ while(squareMatch = SQUARE_BRACKET_RE_GLOBAL.exec(v))res.push(parse(squareMatch));
289
+ return res;
290
+ };
291
+ const getMriOptions = (options)=>{
292
+ const result = {
293
+ alias: {},
294
+ boolean: []
295
+ };
296
+ for (const [index, option] of options.entries()){
297
+ if (option.names.length > 1) result.alias[option.names[0]] = option.names.slice(1);
298
+ if (option.isBoolean) if (option.negated) {
299
+ const hasStringTypeOption = options.some((o, i)=>i !== index && o.names.some((name)=>option.names.includes(name)) && "boolean" == typeof o.required);
300
+ if (!hasStringTypeOption) result.boolean.push(option.names[0]);
301
+ } else result.boolean.push(option.names[0]);
302
+ }
303
+ return result;
304
+ };
305
+ const findLongest = (arr)=>arr.sort((a, b)=>a.length > b.length ? -1 : 1)[0];
306
+ const padRight = (str, length)=>str.length >= length ? str : `${str}${" ".repeat(length - str.length)}`;
307
+ const camelcase = (input)=>input.replace(/([a-z])-([a-z])/g, (_, p1, p2)=>p1 + p2.toUpperCase());
308
+ const setDotProp = (obj, keys, val)=>{
309
+ let i = 0;
310
+ let length = keys.length;
311
+ let t = obj;
312
+ let x;
313
+ for(; i < length; ++i){
314
+ x = t[keys[i]];
315
+ t = t[keys[i]] = i === length - 1 ? val : null != x ? x : !~keys[i + 1].indexOf(".") && +keys[i + 1] > -1 ? [] : {};
316
+ }
317
+ };
318
+ const setByType = (obj, transforms)=>{
319
+ for (const key of Object.keys(transforms)){
320
+ const transform = transforms[key];
321
+ if (transform.shouldTransform) {
322
+ obj[key] = Array.prototype.concat.call([], obj[key]);
323
+ if ("function" == typeof transform.transformFunction) obj[key] = obj[key].map(transform.transformFunction);
324
+ }
325
+ }
326
+ };
327
+ const getFileName = (input)=>{
328
+ const m = /([^\\\/]+)$/.exec(input);
329
+ return m ? m[1] : "";
330
+ };
331
+ const camelcaseOptionName = (name)=>name.split(".").map((v, i)=>0 === i ? camelcase(v) : v).join(".");
332
+ class CACError extends Error {
333
+ constructor(message){
334
+ super(message);
335
+ this.name = this.constructor.name;
336
+ if ("function" == typeof Error.captureStackTrace) Error.captureStackTrace(this, this.constructor);
337
+ else this.stack = new Error(message).stack;
338
+ }
339
+ }
340
+ class Option {
341
+ constructor(rawName, description, config){
342
+ this.rawName = rawName;
343
+ this.description = description;
344
+ this.config = Object.assign({}, config);
345
+ rawName = rawName.replace(/\.\*/g, "");
346
+ this.negated = false;
347
+ this.names = removeBrackets(rawName).split(",").map((v)=>{
348
+ let name = v.trim().replace(/^-{1,2}/, "");
349
+ if (name.startsWith("no-")) {
350
+ this.negated = true;
351
+ name = name.replace(/^no-/, "");
352
+ }
353
+ return camelcaseOptionName(name);
354
+ }).sort((a, b)=>a.length > b.length ? 1 : -1);
355
+ this.name = this.names[this.names.length - 1];
356
+ if (this.negated && null == this.config.default) this.config.default = true;
357
+ if (rawName.includes("<")) this.required = true;
358
+ else if (rawName.includes("[")) this.required = false;
359
+ else this.isBoolean = true;
360
+ }
361
+ }
362
+ const processArgs = process.argv;
363
+ const platformInfo = `${process.platform}-${process.arch} node-${process.version}`;
364
+ class Command {
365
+ constructor(rawName, description, config = {}, cli){
366
+ this.rawName = rawName;
367
+ this.description = description;
368
+ this.config = config;
369
+ this.cli = cli;
370
+ this.options = [];
371
+ this.aliasNames = [];
372
+ this.name = removeBrackets(rawName);
373
+ this.args = findAllBrackets(rawName);
374
+ this.examples = [];
375
+ }
376
+ usage(text) {
377
+ this.usageText = text;
378
+ return this;
379
+ }
380
+ allowUnknownOptions() {
381
+ this.config.allowUnknownOptions = true;
382
+ return this;
383
+ }
384
+ ignoreOptionDefaultValue() {
385
+ this.config.ignoreOptionDefaultValue = true;
386
+ return this;
387
+ }
388
+ version(version, customFlags = "-v, --version") {
389
+ this.versionNumber = version;
390
+ this.option(customFlags, "Display version number");
391
+ return this;
392
+ }
393
+ example(example) {
394
+ this.examples.push(example);
395
+ return this;
396
+ }
397
+ option(rawName, description, config) {
398
+ const option = new Option(rawName, description, config);
399
+ this.options.push(option);
400
+ return this;
401
+ }
402
+ alias(name) {
403
+ this.aliasNames.push(name);
404
+ return this;
405
+ }
406
+ action(callback) {
407
+ this.commandAction = callback;
408
+ return this;
409
+ }
410
+ isMatched(name) {
411
+ return this.name === name || this.aliasNames.includes(name);
412
+ }
413
+ get isDefaultCommand() {
414
+ return "" === this.name || this.aliasNames.includes("!");
415
+ }
416
+ get isGlobalCommand() {
417
+ return this instanceof GlobalCommand;
418
+ }
419
+ hasOption(name) {
420
+ name = name.split(".")[0];
421
+ return this.options.find((option)=>option.names.includes(name));
422
+ }
423
+ outputHelp() {
424
+ const { name, commands } = this.cli;
425
+ const { versionNumber, options: globalOptions, helpCallback } = this.cli.globalCommand;
426
+ let sections = [
427
+ {
428
+ body: `${name}${versionNumber ? `/${versionNumber}` : ""}`
429
+ }
430
+ ];
431
+ sections.push({
432
+ title: "Usage",
433
+ body: ` $ ${name} ${this.usageText || this.rawName}`
434
+ });
435
+ const showCommands = (this.isGlobalCommand || this.isDefaultCommand) && commands.length > 0;
436
+ if (showCommands) {
437
+ const longestCommandName = findLongest(commands.map((command)=>command.rawName));
438
+ sections.push({
439
+ title: "Commands",
440
+ body: commands.map((command)=>` ${padRight(command.rawName, longestCommandName.length)} ${command.description}`).join("\n")
441
+ });
442
+ sections.push({
443
+ title: "For more info, run any command with the `--help` flag",
444
+ body: commands.map((command)=>` $ ${name}${"" === command.name ? "" : ` ${command.name}`} --help`).join("\n")
445
+ });
446
+ }
447
+ let options = this.isGlobalCommand ? globalOptions : [
448
+ ...this.options,
449
+ ...globalOptions || []
450
+ ];
451
+ if (!this.isGlobalCommand && !this.isDefaultCommand) options = options.filter((option)=>"version" !== option.name);
452
+ if (options.length > 0) {
453
+ const longestOptionName = findLongest(options.map((option)=>option.rawName));
454
+ sections.push({
455
+ title: "Options",
456
+ body: options.map((option)=>` ${padRight(option.rawName, longestOptionName.length)} ${option.description} ${void 0 === option.config.default ? "" : `(default: ${option.config.default})`}`).join("\n")
457
+ });
458
+ }
459
+ if (this.examples.length > 0) sections.push({
460
+ title: "Examples",
461
+ body: this.examples.map((example)=>{
462
+ if ("function" == typeof example) return example(name);
463
+ return example;
464
+ }).join("\n")
465
+ });
466
+ if (helpCallback) sections = helpCallback(sections) || sections;
467
+ console.log(sections.map((section)=>section.title ? `${section.title}:
468
+ ${section.body}` : section.body).join("\n\n"));
469
+ }
470
+ outputVersion() {
471
+ const { name } = this.cli;
472
+ const { versionNumber } = this.cli.globalCommand;
473
+ if (versionNumber) console.log(`${name}/${versionNumber} ${platformInfo}`);
474
+ }
475
+ checkRequiredArgs() {
476
+ const minimalArgsCount = this.args.filter((arg)=>arg.required).length;
477
+ if (this.cli.args.length < minimalArgsCount) throw new CACError(`missing required args for command \`${this.rawName}\``);
478
+ }
479
+ checkUnknownOptions() {
480
+ const { options, globalCommand } = this.cli;
481
+ if (!this.config.allowUnknownOptions) {
482
+ for (const name of Object.keys(options))if ("--" !== name && !this.hasOption(name) && !globalCommand.hasOption(name)) throw new CACError(`Unknown option \`${name.length > 1 ? `--${name}` : `-${name}`}\``);
483
+ }
484
+ }
485
+ checkOptionValue() {
486
+ const { options: parsedOptions, globalCommand } = this.cli;
487
+ const options = [
488
+ ...globalCommand.options,
489
+ ...this.options
490
+ ];
491
+ for (const option of options){
492
+ const value = parsedOptions[option.name.split(".")[0]];
493
+ if (option.required) {
494
+ const hasNegated = options.some((o)=>o.negated && o.names.includes(option.name));
495
+ if (true === value || false === value && !hasNegated) throw new CACError(`option \`${option.rawName}\` value is missing`);
496
+ }
497
+ }
498
+ }
499
+ }
500
+ class GlobalCommand extends Command {
501
+ constructor(cli){
502
+ super("@@global@@", "", {}, cli);
503
+ }
504
+ }
505
+ var __assign = Object.assign;
506
+ class CAC extends __WEBPACK_EXTERNAL_MODULE_events__.EventEmitter {
507
+ constructor(name = ""){
508
+ super();
509
+ this.name = name;
510
+ this.commands = [];
511
+ this.rawArgs = [];
512
+ this.args = [];
513
+ this.options = {};
514
+ this.globalCommand = new GlobalCommand(this);
515
+ this.globalCommand.usage("<command> [options]");
516
+ }
517
+ usage(text) {
518
+ this.globalCommand.usage(text);
519
+ return this;
520
+ }
521
+ command(rawName, description, config) {
522
+ const command = new Command(rawName, description || "", config, this);
523
+ command.globalCommand = this.globalCommand;
524
+ this.commands.push(command);
525
+ return command;
526
+ }
527
+ option(rawName, description, config) {
528
+ this.globalCommand.option(rawName, description, config);
529
+ return this;
530
+ }
531
+ help(callback) {
532
+ this.globalCommand.option("-h, --help", "Display this message");
533
+ this.globalCommand.helpCallback = callback;
534
+ this.showHelpOnExit = true;
535
+ return this;
536
+ }
537
+ version(version, customFlags = "-v, --version") {
538
+ this.globalCommand.version(version, customFlags);
539
+ this.showVersionOnExit = true;
540
+ return this;
541
+ }
542
+ example(example) {
543
+ this.globalCommand.example(example);
544
+ return this;
545
+ }
546
+ outputHelp() {
547
+ if (this.matchedCommand) this.matchedCommand.outputHelp();
548
+ else this.globalCommand.outputHelp();
549
+ }
550
+ outputVersion() {
551
+ this.globalCommand.outputVersion();
552
+ }
553
+ setParsedInfo({ args, options }, matchedCommand, matchedCommandName) {
554
+ this.args = args;
555
+ this.options = options;
556
+ if (matchedCommand) this.matchedCommand = matchedCommand;
557
+ if (matchedCommandName) this.matchedCommandName = matchedCommandName;
558
+ return this;
559
+ }
560
+ unsetMatchedCommand() {
561
+ this.matchedCommand = void 0;
562
+ this.matchedCommandName = void 0;
563
+ }
564
+ parse(argv = processArgs, { run = true } = {}) {
565
+ this.rawArgs = argv;
566
+ if (!this.name) this.name = argv[1] ? getFileName(argv[1]) : "cli";
567
+ let shouldParse = true;
568
+ for (const command of this.commands){
569
+ const parsed = this.mri(argv.slice(2), command);
570
+ const commandName = parsed.args[0];
571
+ if (command.isMatched(commandName)) {
572
+ shouldParse = false;
573
+ const parsedInfo = __assign(__assign({}, parsed), {
574
+ args: parsed.args.slice(1)
575
+ });
576
+ this.setParsedInfo(parsedInfo, command, commandName);
577
+ this.emit(`command:${commandName}`, command);
578
+ }
579
+ }
580
+ if (shouldParse) {
581
+ for (const command of this.commands)if ("" === command.name) {
582
+ shouldParse = false;
583
+ const parsed = this.mri(argv.slice(2), command);
584
+ this.setParsedInfo(parsed, command);
585
+ this.emit("command:!", command);
586
+ }
587
+ }
588
+ if (shouldParse) {
589
+ const parsed = this.mri(argv.slice(2));
590
+ this.setParsedInfo(parsed);
591
+ }
592
+ if (this.options.help && this.showHelpOnExit) {
593
+ this.outputHelp();
594
+ run = false;
595
+ this.unsetMatchedCommand();
596
+ }
597
+ if (this.options.version && this.showVersionOnExit && null == this.matchedCommandName) {
598
+ this.outputVersion();
599
+ run = false;
600
+ this.unsetMatchedCommand();
601
+ }
602
+ const parsedArgv = {
603
+ args: this.args,
604
+ options: this.options
605
+ };
606
+ if (run) this.runMatchedCommand();
607
+ if (!this.matchedCommand && this.args[0]) this.emit("command:*");
608
+ return parsedArgv;
609
+ }
610
+ mri(argv, command) {
611
+ const cliOptions = [
612
+ ...this.globalCommand.options,
613
+ ...command ? command.options : []
614
+ ];
615
+ const mriOptions = getMriOptions(cliOptions);
616
+ let argsAfterDoubleDashes = [];
617
+ const doubleDashesIndex = argv.indexOf("--");
618
+ if (doubleDashesIndex > -1) {
619
+ argsAfterDoubleDashes = argv.slice(doubleDashesIndex + 1);
620
+ argv = argv.slice(0, doubleDashesIndex);
621
+ }
622
+ let parsed = mri2(argv, mriOptions);
623
+ parsed = Object.keys(parsed).reduce((res, name)=>__assign(__assign({}, res), {
624
+ [camelcaseOptionName(name)]: parsed[name]
625
+ }), {
626
+ _: []
627
+ });
628
+ const args = parsed._;
629
+ const options = {
630
+ "--": argsAfterDoubleDashes
631
+ };
632
+ const ignoreDefault = command && command.config.ignoreOptionDefaultValue ? command.config.ignoreOptionDefaultValue : this.globalCommand.config.ignoreOptionDefaultValue;
633
+ let transforms = Object.create(null);
634
+ for (const cliOption of cliOptions){
635
+ if (!ignoreDefault && void 0 !== cliOption.config.default) for (const name of cliOption.names)options[name] = cliOption.config.default;
636
+ if (Array.isArray(cliOption.config.type)) {
637
+ if (void 0 === transforms[cliOption.name]) {
638
+ transforms[cliOption.name] = Object.create(null);
639
+ transforms[cliOption.name]["shouldTransform"] = true;
640
+ transforms[cliOption.name]["transformFunction"] = cliOption.config.type[0];
641
+ }
642
+ }
643
+ }
644
+ for (const key of Object.keys(parsed))if ("_" !== key) {
645
+ const keys = key.split(".");
646
+ setDotProp(options, keys, parsed[key]);
647
+ setByType(options, transforms);
648
+ }
649
+ return {
650
+ args,
651
+ options
652
+ };
653
+ }
654
+ runMatchedCommand() {
655
+ const { args, options, matchedCommand: command } = this;
656
+ if (!command || !command.commandAction) return;
657
+ command.checkUnknownOptions();
658
+ command.checkOptionValue();
659
+ command.checkRequiredArgs();
660
+ const actionArgs = [];
661
+ command.args.forEach((arg, index)=>{
662
+ if (arg.variadic) actionArgs.push(args.slice(index));
663
+ else actionArgs.push(args[index]);
664
+ });
665
+ actionArgs.push(options);
666
+ return command.commandAction.apply(this, actionArgs);
667
+ }
668
+ }
669
+ const cac = (name = "")=>new CAC(name);
670
+ const dist = cac;
186
671
  const DEFAULT_CONFIG_NAME = 'rslib.config';
187
672
  const DEFAULT_CONFIG_EXTENSIONS = [
188
673
  '.js',
@@ -1165,7 +1650,7 @@ const not_found_result = {
1165
1650
  tsconfigFile: null,
1166
1651
  tsconfig: {}
1167
1652
  };
1168
- async function parse(filename, options) {
1653
+ async function parse_parse(filename, options) {
1169
1654
  const cache = options?.cache;
1170
1655
  if (cache?.hasParseResult(filename)) return getParsedDeep(filename, cache, options);
1171
1656
  const { resolve, reject, promise } = util_makePromise();
@@ -1273,7 +1758,10 @@ async function parseExtends(result, cache) {
1273
1758
  for (const ext of result.extended.slice(1))extendTSConfig(result, ext);
1274
1759
  }
1275
1760
  function resolveExtends(extended, from) {
1276
- if ('..' === extended) extended = '../tsconfig.json';
1761
+ if ([
1762
+ '.',
1763
+ '..'
1764
+ ].includes(extended)) extended += '/tsconfig.json';
1277
1765
  const req = (0, __WEBPACK_EXTERNAL_MODULE_module__.createRequire)(from);
1278
1766
  let error;
1279
1767
  try {
@@ -1368,7 +1856,7 @@ async function loadTsconfig(root, tsconfigPath = 'tsconfig.json') {
1368
1856
  configName: (0, __WEBPACK_EXTERNAL_MODULE_node_path_c5b9b54f__.basename)(tsconfigPath)
1369
1857
  });
1370
1858
  if (tsconfigFileName) {
1371
- const { tsconfig } = await parse(tsconfigFileName);
1859
+ const { tsconfig } = await parse_parse(tsconfigFileName);
1372
1860
  return tsconfig;
1373
1861
  }
1374
1862
  return {};
@@ -1764,6 +2252,34 @@ const composeFormatConfig = ({ format, bundle = true, umdName, pkgJson })=>{
1764
2252
  };
1765
2253
  return config;
1766
2254
  }
2255
+ case 'iife':
2256
+ {
2257
+ if (false === bundle) throw new Error('When using "iife" format, "bundle" must be set to "true". Since the default value for "bundle" is "true", so you can either explicitly set it to "true" or remove the field entirely.');
2258
+ const config = {
2259
+ tools: {
2260
+ rspack: {
2261
+ module: {
2262
+ parser: {
2263
+ javascript: {
2264
+ importMeta: false
2265
+ }
2266
+ }
2267
+ },
2268
+ output: {
2269
+ iife: true,
2270
+ asyncChunks: false,
2271
+ library: {
2272
+ type: 'modern-module'
2273
+ }
2274
+ },
2275
+ optimization: {
2276
+ nodeEnv: process.env.NODE_ENV
2277
+ }
2278
+ }
2279
+ }
2280
+ };
2281
+ return config;
2282
+ }
1767
2283
  case 'mf':
1768
2284
  if (false === bundle) throw new Error('When using "mf" format, "bundle" must be set to "true". Since the default value for "bundle" is "true", so you can either explicitly set it to "true" or remove the field entirely.');
1769
2285
  return {
@@ -1849,6 +2365,7 @@ const composeShimsConfig = (format, shims)=>{
1849
2365
  };
1850
2366
  break;
1851
2367
  case 'umd':
2368
+ case 'iife':
1852
2369
  case 'mf':
1853
2370
  break;
1854
2371
  default:
@@ -1865,26 +2382,41 @@ const composeExternalsConfig = (format, externals)=>{
1865
2382
  esm: 'module-import',
1866
2383
  cjs: 'commonjs-import',
1867
2384
  umd: 'umd',
1868
- mf: 'global'
2385
+ mf: 'global',
2386
+ iife: 'global'
2387
+ };
2388
+ const globalObjectMap = {
2389
+ esm: void 0,
2390
+ cjs: void 0,
2391
+ umd: void 0,
2392
+ mf: void 0,
2393
+ iife: 'globalThis'
1869
2394
  };
2395
+ const rspackConfig = {};
2396
+ const rsbuildConfig = {};
1870
2397
  switch(format){
1871
2398
  case 'esm':
1872
2399
  case 'cjs':
1873
2400
  case 'umd':
1874
2401
  case 'mf':
1875
- return {
1876
- output: externals ? {
1877
- externals
1878
- } : {},
1879
- tools: {
1880
- rspack: {
1881
- externalsType: externalsTypeMap[format]
1882
- }
1883
- }
2402
+ case 'iife':
2403
+ rsbuildConfig.output = externals ? {
2404
+ externals
2405
+ } : {};
2406
+ rspackConfig.externalsType = externalsTypeMap[format];
2407
+ if (globalObjectMap[format]) rspackConfig.output = {
2408
+ globalObject: globalObjectMap[format]
1884
2409
  };
2410
+ break;
1885
2411
  default:
1886
2412
  throw new Error(`Unsupported format: ${format}`);
1887
2413
  }
2414
+ return {
2415
+ ...rsbuildConfig,
2416
+ tools: {
2417
+ rspack: rspackConfig
2418
+ }
2419
+ };
1888
2420
  };
1889
2421
  const composeAutoExtensionConfig = (config, format, autoExtension, pkgJson)=>{
1890
2422
  const { jsExtension, dtsExtension } = getDefaultExtension({
@@ -2318,7 +2850,7 @@ async function composeRsbuildEnvironments(rslibConfig) {
2318
2850
  };
2319
2851
  }
2320
2852
  const pruneEnvironments = (environments, libs)=>{
2321
- if (!libs) return environments;
2853
+ if (!libs || 0 === libs.length) return environments;
2322
2854
  const filteredEnvironments = Object.fromEntries(Object.entries(environments).filter(([name])=>libs.includes(name)));
2323
2855
  if (0 === Object.keys(filteredEnvironments).length) throw new Error(`The following libs are not found: ${libs.map((lib)=>`"${lib}"`).join(', ')}.`);
2324
2856
  return filteredEnvironments;
@@ -2438,7 +2970,7 @@ async function initMFRsbuild(config, options = {}) {
2438
2970
  const { environments, environmentWithInfos } = await composeRsbuildEnvironments(config);
2439
2971
  const selectedEnvironmentIds = environmentWithInfos.filter((env)=>{
2440
2972
  const isMf = 'mf' === env.format;
2441
- if (!options?.lib) return isMf;
2973
+ if (!options?.lib || 0 === options.lib.length) return isMf;
2442
2974
  return env.id && options.lib.includes(env.id);
2443
2975
  }).map((env)=>env.id);
2444
2976
  if (!selectedEnvironmentIds.length) throw new Error(`No mf format found in ${options.lib ? `libs ${options.lib.map((lib)=>`"${lib}"`).join(', ')}` : 'your config'}, please check your config to ensure that the mf format is enabled correctly.`);
@@ -2458,23 +2990,23 @@ async function initMFRsbuild(config, options = {}) {
2458
2990
  onBeforeRestart(devServer.server.close);
2459
2991
  return rsbuildInstance;
2460
2992
  }
2461
- const applyCommonOptions = (command)=>{
2462
- command.option('-c --config <config>', 'specify the configuration file, can be a relative or absolute path').option('-r --root <root>', 'specify the project root directory, can be an absolute path or a path relative to cwd').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file').option('--env-dir <dir>', 'specify the directory to load `.env` files').option('--lib <id>', 'specify the library (repeatable, e.g. --lib esm --lib cjs)', repeatableOption);
2993
+ const applyCommonOptions = (cli)=>{
2994
+ cli.option('-c, --config <config>', 'specify the configuration file, can be a relative or absolute path').option('-r, --root <root>', 'specify the project root directory, can be an absolute path or a path relative to cwd').option('--env-mode <mode>', 'specify the env mode to load the `.env.[mode]` file').option('--env-dir <dir>', 'specify the directory to load `.env` files').option('--lib <id>', 'specify the library (repeatable, e.g. --lib esm --lib cjs)', {
2995
+ type: [
2996
+ String
2997
+ ],
2998
+ default: []
2999
+ });
2463
3000
  };
2464
- const repeatableOption = (value, previous)=>(previous ?? []).concat([
2465
- value
2466
- ]);
2467
3001
  function runCli() {
2468
- __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js_bca3ceaa__.program.name('rslib').usage('<command> [options]').version("0.7.1");
2469
- const buildCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js_bca3ceaa__.program.command('build');
2470
- const inspectCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js_bca3ceaa__.program.command('inspect');
2471
- const mfDevCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js_bca3ceaa__.program.command('mf-dev');
2472
- [
2473
- buildCommand,
2474
- inspectCommand,
2475
- mfDevCommand
2476
- ].forEach(applyCommonOptions);
2477
- buildCommand.option('-w --watch', 'turn on watch mode, watch for changes and rebuild').description('build the library for production').action(async (options)=>{
3002
+ const cli = dist('rslib');
3003
+ cli.help();
3004
+ cli.version("0.9.0");
3005
+ applyCommonOptions(cli);
3006
+ const buildCommand = cli.command('build', 'build the library for production');
3007
+ const inspectCommand = cli.command('inspect', 'inspect the Rsbuild / Rspack configs of Rslib projects');
3008
+ const mfDevCommand = cli.command('mf-dev', 'start Rsbuild dev server of Module Federation format');
3009
+ buildCommand.option('-w, --watch', 'turn on watch mode, watch for changes and rebuild').action(async (options)=>{
2478
3010
  try {
2479
3011
  const cliBuild = async ()=>{
2480
3012
  const { config, watchFiles } = await init(options);
@@ -2491,7 +3023,9 @@ function runCli() {
2491
3023
  process.exit(1);
2492
3024
  }
2493
3025
  });
2494
- inspectCommand.description('inspect the Rsbuild / Rspack configs of Rslib projects').option('--output <output>', 'specify inspect content output path', '.rsbuild').option('--verbose', 'show full function definitions in output').action(async (options)=>{
3026
+ inspectCommand.option('--output <output>', 'specify inspect content output path', {
3027
+ default: '.rsbuild'
3028
+ }).option('--verbose', 'show full function definitions in output').action(async (options)=>{
2495
3029
  try {
2496
3030
  const { config } = await init(options);
2497
3031
  await inspect(config, {
@@ -2506,7 +3040,7 @@ function runCli() {
2506
3040
  process.exit(1);
2507
3041
  }
2508
3042
  });
2509
- mfDevCommand.description('start Rsbuild dev server of Module Federation format').action(async (options)=>{
3043
+ mfDevCommand.action(async (options)=>{
2510
3044
  try {
2511
3045
  const cliMfDev = async ()=>{
2512
3046
  const { config, watchFiles } = await init(options);
@@ -2524,9 +3058,9 @@ function runCli() {
2524
3058
  process.exit(1);
2525
3059
  }
2526
3060
  });
2527
- __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js_bca3ceaa__.program.parse();
3061
+ cli.parse();
2528
3062
  }
2529
- const src_version = "0.7.1";
3063
+ const src_version = "0.9.0";
2530
3064
  var __webpack_exports__logger = __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js_c302f6e3__.logger;
2531
3065
  var __webpack_exports__rspack = __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__.rspack;
2532
3066
  export { build, defineConfig, inspect, loadConfig, prepareCli, __WEBPACK_EXTERNAL_MODULE__rsbuild_core_1b356efc__ as rsbuild, runCli, startMFDevServer, composeCreateRsbuildConfig as unstable_composeCreateRsbuildConfig, src_version as version, __webpack_exports__logger as logger, __webpack_exports__rspack as rspack };