@rslib/core 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2012 Paul Miller (https://paulmillr.com), Elan Shanker
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the “Software”), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1 @@
1
+ {"name":"chokidar","author":"Paul Miller (https://paulmillr.com)","version":"4.0.1","funding":"https://paulmillr.com/funding/","license":"MIT","types":"index.d.ts","type":"commonjs"}
@@ -39,7 +39,7 @@ function splitFromFirstLine(text) {
39
39
  text.slice(match.index)
40
40
  ];
41
41
  }
42
- const entryModuleLoader_loader = function(source) {
42
+ const entryModuleLoader_rslib_entry_loader = function(source) {
43
43
  let result = source;
44
44
  if (this.resourceQuery === `?${RSLIB_ENTRY_QUERY}`) {
45
45
  const [firstLine1, rest] = splitFromFirstLine(result);
@@ -49,5 +49,5 @@ const entryModuleLoader_loader = function(source) {
49
49
  }
50
50
  return result;
51
51
  };
52
- /* ESM default export */ const entryModuleLoader = entryModuleLoader_loader;
53
- export { entryModuleLoader as default };
52
+ /* ESM default export */ const entryModuleLoader_rslib_entry_ = entryModuleLoader_rslib_entry_loader;
53
+ export { entryModuleLoader_rslib_entry_ as default };
package/dist/index.js CHANGED
@@ -8,6 +8,7 @@ import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core__ from "@rsbuild/core";
8
8
  import * as __WEBPACK_EXTERNAL_MODULE_tinyglobby__ from "tinyglobby";
9
9
  import * as __WEBPACK_EXTERNAL_MODULE_node_module__ from "node:module";
10
10
  import * as __WEBPACK_EXTERNAL_MODULE_module__ from "module";
11
+ import * as __WEBPACK_EXTERNAL_MODULE__compiled_chokidar_index_js__ from "../compiled/chokidar/index.js";
11
12
  /**
12
13
  * Node.js built-in modules.
13
14
  * Copied from https://github.com/webpack/webpack/blob/dd44b206a9c50f4b4cb4d134e1a0bd0387b159a3/lib/node/NodeTargetPlugin.js#L12-L72
@@ -138,6 +139,18 @@ function checkMFPlugin(config) {
138
139
  }
139
140
  return added;
140
141
  }
142
+ function debounce(func, wait) {
143
+ let timeoutId = null;
144
+ return (...args)=>{
145
+ if (null !== timeoutId) clearTimeout(timeoutId);
146
+ timeoutId = setTimeout(()=>{
147
+ func(...args);
148
+ }, wait);
149
+ };
150
+ }
151
+ /**
152
+ * Check if running in a TTY context
153
+ */ const isTTY = (type = 'stdout')=>('stdin' === type ? process.stdin.isTTY : process.stdout.isTTY) && !process.env.CI;
141
154
  // setup the logger level
142
155
  if (process.env.DEBUG) __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.level = 'verbose';
143
156
  function initNodeEnv() {
@@ -154,7 +167,7 @@ function prepareCli() {
154
167
  // Some package managers automatically output a blank line, some do not.
155
168
  const { npm_execpath } = process.env;
156
169
  if (!npm_execpath || npm_execpath.includes('npx-cli.js') || npm_execpath.includes('.bun')) console.log();
157
- __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.greet(` Rslib v0.1.0\n`);
170
+ __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.greet(` Rslib v0.1.1\n`);
158
171
  }
159
172
  const DEFAULT_CONFIG_NAME = 'rslib.config';
160
173
  const DEFAULT_CONFIG_EXTENSIONS = [
@@ -1434,7 +1447,10 @@ async function loadConfig({ cwd = process.cwd(), path, envMode }) {
1434
1447
  path: configFilePath,
1435
1448
  envMode
1436
1449
  });
1437
- return content;
1450
+ return {
1451
+ content: content,
1452
+ filePath: configFilePath
1453
+ };
1438
1454
  }
1439
1455
  const composeExternalsWarnConfig = (format, ...externalsArray)=>{
1440
1456
  if ('esm' !== format) return {};
@@ -1807,9 +1823,9 @@ const composeFormatConfig = ({ format, bundle = true, umdName, pkgJson })=>{
1807
1823
  },
1808
1824
  // can not set nodeEnv to false, because mf format should build shared module.
1809
1825
  // If nodeEnv is false, the process.env.NODE_ENV in third-party packages's will not be replaced
1810
- // now we have not provide dev mode for users, so we can always set nodeEnv as 'production'
1811
1826
  optimization: {
1812
- nodeEnv: 'production'
1827
+ nodeEnv: 'production',
1828
+ moduleIds: 'deterministic'
1813
1829
  }
1814
1830
  }
1815
1831
  },
@@ -1961,7 +1977,14 @@ const composeSyntaxConfig = (target, syntax)=>{
1961
1977
  };
1962
1978
  const appendEntryQuery = (entry)=>{
1963
1979
  const newEntry = {};
1964
- for(const key in entry)newEntry[key] = `${entry[key]}?${RSLIB_ENTRY_QUERY}`;
1980
+ for (const [key, value] of Object.entries(entry)){
1981
+ let result = value;
1982
+ result = 'string' == typeof value ? `${value}?${RSLIB_ENTRY_QUERY}` : Array.isArray(value) ? value.map((item)=>`${item}?${RSLIB_ENTRY_QUERY}`) : {
1983
+ ...value,
1984
+ import: 'string' == typeof value.import ? `${value.import}?${RSLIB_ENTRY_QUERY}` : value.import.map((item)=>`${item}?${RSLIB_ENTRY_QUERY}`)
1985
+ };
1986
+ newEntry[key] = result;
1987
+ }
1965
1988
  return newEntry;
1966
1989
  };
1967
1990
  const composeEntryConfig = async (entries, bundle, root, cssModulesAuto)=>{
@@ -2282,6 +2305,47 @@ const pruneEnvironments = (environments, libs)=>{
2282
2305
  if (!libs) return environments;
2283
2306
  return Object.fromEntries(Object.entries(environments).filter(([name])=>libs.includes(name)));
2284
2307
  };
2308
+ async function watchFilesForRestart(files, restart) {
2309
+ if (!files.length) return;
2310
+ const watcher = __WEBPACK_EXTERNAL_MODULE__compiled_chokidar_index_js__["default"].watch(files, {
2311
+ ignoreInitial: true,
2312
+ // If watching fails due to read permissions, the errors will be suppressed silently.
2313
+ ignorePermissionErrors: true,
2314
+ ignored: [
2315
+ '**/node_modules/**',
2316
+ '**/.git/**',
2317
+ '**/.DS_Store/**'
2318
+ ]
2319
+ });
2320
+ const callback = debounce(async (filePath)=>{
2321
+ watcher.close();
2322
+ await beforeRestart({
2323
+ filePath
2324
+ });
2325
+ await restart();
2326
+ }, 300);
2327
+ watcher.on('add', callback);
2328
+ watcher.on('change', callback);
2329
+ watcher.on('unlink', callback);
2330
+ }
2331
+ let cleaners = [];
2332
+ /**
2333
+ * Add a cleaner to handle side effects
2334
+ */ const onBeforeRestart = (cleaner)=>{
2335
+ cleaners.push(cleaner);
2336
+ };
2337
+ const clearConsole = ()=>{
2338
+ if (isTTY() && !process.env.DEBUG) process.stdout.write('\x1B[H\x1B[2J');
2339
+ };
2340
+ const beforeRestart = async ({ filePath, clear = true } = {})=>{
2341
+ if (clear) clearConsole();
2342
+ if (filePath) {
2343
+ const filename = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].basename(filePath);
2344
+ __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.info(`Restart because ${__WEBPACK_EXTERNAL_MODULE__compiled_picocolors_index_js__["default"].yellow(filename)} is changed.\n`);
2345
+ } else __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.info('Restarting...\n');
2346
+ for (const cleaner of cleaners)await cleaner();
2347
+ cleaners = [];
2348
+ };
2285
2349
  async function build(config, options = {}) {
2286
2350
  const environments = await composeRsbuildEnvironments(config);
2287
2351
  const rsbuildInstance = await (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.createRsbuild)({
@@ -2289,20 +2353,21 @@ async function build(config, options = {}) {
2289
2353
  environments: pruneEnvironments(environments, options.lib)
2290
2354
  }
2291
2355
  });
2292
- await rsbuildInstance.build({
2356
+ const buildInstance = await rsbuildInstance.build({
2293
2357
  watch: options.watch
2294
2358
  });
2359
+ if (options.watch) onBeforeRestart(buildInstance.close);
2360
+ else await buildInstance.close();
2295
2361
  return rsbuildInstance;
2296
2362
  }
2297
2363
  async function loadRslibConfig(options) {
2298
2364
  const cwd = process.cwd();
2299
2365
  const root = options.root ? getAbsolutePath(cwd, options.root) : cwd;
2300
- const rslibConfig = await loadConfig({
2366
+ return loadConfig({
2301
2367
  cwd: root,
2302
2368
  path: options.config,
2303
2369
  envMode: options.envMode
2304
2370
  });
2305
- return rslibConfig;
2306
2371
  }
2307
2372
  async function inspect(config, options = {}) {
2308
2373
  const environments = await composeRsbuildEnvironments(config);
@@ -2332,7 +2397,8 @@ async function initMFRsbuild(rslibConfig) {
2332
2397
  const rsbuildInstance = await (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.createRsbuild)({
2333
2398
  rsbuildConfig: mfRsbuildConfig.config
2334
2399
  });
2335
- await rsbuildInstance.startDevServer();
2400
+ const devServer = await rsbuildInstance.startDevServer();
2401
+ onBeforeRestart(devServer.server.close);
2336
2402
  return rsbuildInstance;
2337
2403
  }
2338
2404
  function changeEnvToDev(rsbuildConfig) {
@@ -2344,7 +2410,8 @@ function changeEnvToDev(rsbuildConfig) {
2344
2410
  tools: {
2345
2411
  rspack: {
2346
2412
  optimization: {
2347
- nodeEnv: 'development'
2413
+ nodeEnv: 'development',
2414
+ moduleIds: 'named'
2348
2415
  }
2349
2416
  }
2350
2417
  }
@@ -2357,7 +2424,7 @@ const repeatableOption = (value, previous)=>(previous ?? []).concat([
2357
2424
  value
2358
2425
  ]);
2359
2426
  function runCli() {
2360
- __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.name('rslib').usage('<command> [options]').version("0.1.0");
2427
+ __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.name('rslib').usage('<command> [options]').version("0.1.1");
2361
2428
  const buildCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.command('build');
2362
2429
  const inspectCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.command('inspect');
2363
2430
  const mfDevCommand = __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.command('mf dev');
@@ -2368,11 +2435,16 @@ function runCli() {
2368
2435
  ].forEach(applyCommonOptions);
2369
2436
  buildCommand.option('--lib <id>', 'build the specified library (may be repeated)', repeatableOption).option('-w --watch', 'turn on watch mode, watch for changes and rebuild').description('build the library for production').action(async (options)=>{
2370
2437
  try {
2371
- const rslibConfig = await loadRslibConfig(options);
2372
- await build(rslibConfig, {
2373
- lib: options.lib,
2374
- watch: options.watch
2375
- });
2438
+ const cliBuild = async ()=>{
2439
+ const { content: rslibConfig, filePath } = await loadRslibConfig(options);
2440
+ await build(rslibConfig, options);
2441
+ if (options.watch) watchFilesForRestart([
2442
+ filePath
2443
+ ], async ()=>{
2444
+ await cliBuild();
2445
+ });
2446
+ };
2447
+ await cliBuild();
2376
2448
  } catch (err) {
2377
2449
  __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.error('Failed to build.');
2378
2450
  __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.error(err);
@@ -2382,7 +2454,7 @@ function runCli() {
2382
2454
  inspectCommand.description('inspect the Rsbuild / Rspack configs of Rslib projects').option('--lib <id>', 'inspect the specified library (may be repeated)', repeatableOption).option('--output <output>', 'specify inspect content output path', '.rsbuild').option('--verbose', 'show full function definitions in output').action(async (options)=>{
2383
2455
  try {
2384
2456
  // TODO: inspect should output Rslib's config
2385
- const rslibConfig = await loadRslibConfig(options);
2457
+ const { content: rslibConfig } = await loadRslibConfig(options);
2386
2458
  await inspect(rslibConfig, {
2387
2459
  lib: options.lib,
2388
2460
  mode: options.mode,
@@ -2397,9 +2469,17 @@ function runCli() {
2397
2469
  });
2398
2470
  mfDevCommand.description('start Rsbuild dev server of Module Federation format').action(async (options)=>{
2399
2471
  try {
2400
- const rslibConfig = await loadRslibConfig(options);
2401
- // TODO: support lib option in mf dev server
2402
- await startMFDevServer(rslibConfig);
2472
+ const cliMfDev = async ()=>{
2473
+ const { content: rslibConfig, filePath } = await loadRslibConfig(options);
2474
+ // TODO: support lib option in mf dev server
2475
+ await startMFDevServer(rslibConfig);
2476
+ watchFilesForRestart([
2477
+ filePath
2478
+ ], async ()=>{
2479
+ await cliMfDev();
2480
+ });
2481
+ };
2482
+ await cliMfDev();
2403
2483
  } catch (err) {
2404
2484
  __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.error('Failed to start mf dev.');
2405
2485
  __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger.error(err);
@@ -2408,6 +2488,6 @@ function runCli() {
2408
2488
  });
2409
2489
  __WEBPACK_EXTERNAL_MODULE__compiled_commander_index_js__.program.parse();
2410
2490
  }
2411
- const src_version = "0.1.0";
2491
+ const src_rslib_entry_version = "0.1.1";
2412
2492
  var __webpack_exports__logger = __WEBPACK_EXTERNAL_MODULE__compiled_rslog_index_js__.logger;
2413
- export { build, defineConfig, inspect, loadConfig, prepareCli, runCli, startMFDevServer, composeCreateRsbuildConfig as unstable_composeCreateRsbuildConfig, src_version as version, __webpack_exports__logger as logger };
2493
+ export { build, defineConfig, inspect, loadConfig, prepareCli, runCli, startMFDevServer, composeCreateRsbuildConfig as unstable_composeCreateRsbuildConfig, src_rslib_entry_version as version, __webpack_exports__logger as logger };
@@ -9,7 +9,7 @@ import * as __WEBPACK_EXTERNAL_MODULE_node_path__ from "node:path";
9
9
  function stringifyLocal(value) {
10
10
  return 'function' == typeof value ? value.toString() : JSON.stringify(value);
11
11
  }
12
- const libCssExtractLoader_loader = function(content) {
12
+ const libCssExtractLoader_rslib_entry_loader = function(content) {
13
13
  if (this._compiler?.options?.experiments?.css && this._module && ('css' === this._module.type || 'css/auto' === this._module.type || 'css/global' === this._module.type || 'css/module' === this._module.type)) return content;
14
14
  };
15
15
  const pitch = function(request, _, _data) {
@@ -121,5 +121,5 @@ const pitch = function(request, _, _data) {
121
121
  handleExports(exports);
122
122
  });
123
123
  };
124
- /* ESM default export */ const libCssExtractLoader = libCssExtractLoader_loader;
125
- export { libCssExtractLoader as default, pitch };
124
+ /* ESM default export */ const libCssExtractLoader_rslib_entry_ = libCssExtractLoader_rslib_entry_loader;
125
+ export { libCssExtractLoader_rslib_entry_ as default, pitch };
@@ -1,3 +1,6 @@
1
1
  import type { RslibConfig } from '../types';
2
2
  import type { CommonOptions } from './commands';
3
- export declare function loadRslibConfig(options: CommonOptions): Promise<RslibConfig>;
3
+ export declare function loadRslibConfig(options: CommonOptions): Promise<{
4
+ content: RslibConfig;
5
+ filePath: string;
6
+ }>;
@@ -0,0 +1,7 @@
1
+ export declare function watchFilesForRestart(files: string[], restart: () => Promise<void>): Promise<void>;
2
+ type Cleaner = () => Promise<unknown> | unknown;
3
+ /**
4
+ * Add a cleaner to handle side effects
5
+ */
6
+ export declare const onBeforeRestart: (cleaner: Cleaner) => void;
7
+ export {};
@@ -1,5 +1,5 @@
1
1
  import { type EnvironmentConfig, type RsbuildConfig } from '@rsbuild/core';
2
- import type { AutoExternal, BannerAndFooter, LibConfig, PkgJson, RsbuildConfigWithLibInfo, RslibConfig, RslibConfigAsyncFn, RslibConfigExport, RslibConfigSyncFn } from './types';
2
+ import type { AutoExternal, BannerAndFooter, LibConfig, PkgJson, RsbuildConfigEntry, RsbuildConfigWithLibInfo, RslibConfig, RslibConfigAsyncFn, RslibConfigExport, RslibConfigSyncFn } from './types';
3
3
  /**
4
4
  * This function helps you to autocomplete configuration types.
5
5
  * It accepts a Rslib config object, or a function that returns a config.
@@ -12,7 +12,10 @@ export declare function loadConfig({ cwd, path, envMode, }: {
12
12
  cwd?: string;
13
13
  path?: string;
14
14
  envMode?: string;
15
- }): Promise<RslibConfig>;
15
+ }): Promise<{
16
+ content: RslibConfig;
17
+ filePath: string;
18
+ }>;
16
19
  export declare const composeAutoExternalConfig: (options: {
17
20
  autoExternal: AutoExternal;
18
21
  pkgJson?: PkgJson;
@@ -23,6 +26,7 @@ export declare function composeBannerFooterConfig(banner: BannerAndFooter, foote
23
26
  export declare function composeDecoratorsConfig(compilerOptions?: Record<string, any>, version?: NonNullable<NonNullable<RsbuildConfig['source']>['decorators']>['version']): RsbuildConfig;
24
27
  export declare function createConstantRsbuildConfig(): Promise<RsbuildConfig>;
25
28
  export declare const composeModuleImportWarn: (request: string) => string;
29
+ export declare const appendEntryQuery: (entry: RsbuildConfigEntry) => RsbuildConfigEntry;
26
30
  export declare function composeCreateRsbuildConfig(rslibConfig: RslibConfig): Promise<RsbuildConfigWithLibInfo[]>;
27
31
  export declare function composeRsbuildEnvironments(rslibConfig: RslibConfig): Promise<Record<string, EnvironmentConfig>>;
28
32
  export declare const pruneEnvironments: (environments: Record<string, EnvironmentConfig>, libs?: string[]) => Record<string, EnvironmentConfig>;
@@ -9,6 +9,8 @@ export type RsbuildConfigWithLibInfo = {
9
9
  format: Format;
10
10
  config: RsbuildConfig;
11
11
  };
12
+ export type RsbuildConfigEntry = NonNullable<NonNullable<RsbuildConfig['source']>['entry']>;
13
+ export type RsbuildConfigEntryItem = RsbuildConfigEntry[string];
12
14
  export type RsbuildConfigOutputTarget = NonNullable<RsbuildConfig['output']>['target'];
13
15
  export type Syntax = EcmaScriptVersion | string[];
14
16
  export type Dts = (Pick<PluginDtsOptions, 'bundle' | 'distPath' | 'abortOnError' | 'build'> & {
@@ -15,4 +15,9 @@ export declare function pick<T, U extends keyof T>(obj: T, keys: ReadonlyArray<U
15
15
  export declare function omit<T extends object, U extends keyof T>(obj: T, keysObj: Record<U, boolean>): Omit<T, keyof U>;
16
16
  export declare function isPluginIncluded(pluginName: string, plugins?: RsbuildPlugins): boolean;
17
17
  export declare function checkMFPlugin(config: LibConfig): boolean;
18
+ export declare function debounce<T extends (...args: any[]) => void>(func: T, wait: number): (...args: Parameters<T>) => void;
19
+ /**
20
+ * Check if running in a TTY context
21
+ */
22
+ export declare const isTTY: (type?: "stdin" | "stdout") => boolean;
18
23
  export { color };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rslib/core",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "The Rsbuild-based library development tool.",
5
5
  "homepage": "https://lib.rsbuild.dev",
6
6
  "bugs": {
@@ -32,18 +32,19 @@
32
32
  "compiled"
33
33
  ],
34
34
  "dependencies": {
35
- "@rsbuild/core": "~1.1.4",
35
+ "@rsbuild/core": "~1.1.6",
36
36
  "tinyglobby": "^0.2.10",
37
- "rsbuild-plugin-dts": "0.1.0"
37
+ "rsbuild-plugin-dts": "0.1.1"
38
38
  },
39
39
  "devDependencies": {
40
40
  "@types/fs-extra": "^11.0.4",
41
+ "chokidar": "^4.0.1",
41
42
  "commander": "^12.1.0",
42
43
  "fs-extra": "^11.2.0",
43
44
  "memfs": "^4.14.0",
44
45
  "picocolors": "1.1.1",
45
46
  "prebundle": "1.2.5",
46
- "rslib": "npm:@rslib/core@0.0.18",
47
+ "rslib": "npm:@rslib/core@0.1.0",
47
48
  "rslog": "^1.2.3",
48
49
  "tsconfck": "3.1.4",
49
50
  "typescript": "^5.6.3",