@lynx-js/rspeedy 0.8.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.
Files changed (127) hide show
  1. package/CHANGELOG.md +208 -0
  2. package/LICENSE +202 -0
  3. package/README.md +32 -0
  4. package/bin/rspeedy.js +33 -0
  5. package/client/hmr/WebSocketClient.js +65 -0
  6. package/client.d.ts +5 -0
  7. package/lib/api.d.ts +46 -0
  8. package/lib/api.js +2 -0
  9. package/lib/cli/build.d.ts +4 -0
  10. package/lib/cli/build.js +32 -0
  11. package/lib/cli/commands.d.ts +5 -0
  12. package/lib/cli/commands.js +45 -0
  13. package/lib/cli/dev.d.ts +4 -0
  14. package/lib/cli/dev.js +75 -0
  15. package/lib/cli/exit.d.ts +1 -0
  16. package/lib/cli/exit.js +51 -0
  17. package/lib/cli/inspect.d.ts +8 -0
  18. package/lib/cli/inspect.js +30 -0
  19. package/lib/cli/main.d.ts +1 -0
  20. package/lib/cli/main.js +39 -0
  21. package/lib/cli/preview.d.ts +4 -0
  22. package/lib/cli/preview.js +31 -0
  23. package/lib/cli/start.d.ts +6 -0
  24. package/lib/cli/start.js +88 -0
  25. package/lib/config/defaults.d.ts +2 -0
  26. package/lib/config/defaults.js +32 -0
  27. package/lib/config/defineConfig.d.ts +22 -0
  28. package/lib/config/defineConfig.js +24 -0
  29. package/lib/config/dev/client.d.ts +15 -0
  30. package/lib/config/dev/client.js +2 -0
  31. package/lib/config/dev/index.d.ts +133 -0
  32. package/lib/config/dev/index.js +2 -0
  33. package/lib/config/index.d.ts +172 -0
  34. package/lib/config/index.js +2 -0
  35. package/lib/config/loadConfig.d.ts +50 -0
  36. package/lib/config/loadConfig.js +98 -0
  37. package/lib/config/output/css-modules.d.ts +84 -0
  38. package/lib/config/output/css-modules.js +2 -0
  39. package/lib/config/output/dist-path.d.ts +68 -0
  40. package/lib/config/output/dist-path.js +2 -0
  41. package/lib/config/output/filename.d.ts +167 -0
  42. package/lib/config/output/filename.js +2 -0
  43. package/lib/config/output/index.d.ts +320 -0
  44. package/lib/config/output/index.js +2 -0
  45. package/lib/config/output/minify.d.ts +80 -0
  46. package/lib/config/output/minify.js +2 -0
  47. package/lib/config/output/source-map.d.ts +68 -0
  48. package/lib/config/output/source-map.js +2 -0
  49. package/lib/config/performance/chunk-split.d.ts +192 -0
  50. package/lib/config/performance/chunk-split.js +2 -0
  51. package/lib/config/performance/index.d.ts +50 -0
  52. package/lib/config/performance/index.js +2 -0
  53. package/lib/config/rsbuild/entry.d.ts +3 -0
  54. package/lib/config/rsbuild/entry.js +31 -0
  55. package/lib/config/rsbuild/index.d.ts +4 -0
  56. package/lib/config/rsbuild/index.js +70 -0
  57. package/lib/config/server/index.d.ts +47 -0
  58. package/lib/config/server/index.js +2 -0
  59. package/lib/config/source/decorators.d.ts +43 -0
  60. package/lib/config/source/decorators.js +2 -0
  61. package/lib/config/source/entry.d.ts +84 -0
  62. package/lib/config/source/entry.js +2 -0
  63. package/lib/config/source/index.d.ts +474 -0
  64. package/lib/config/source/index.js +2 -0
  65. package/lib/config/source/transformImport.d.ts +106 -0
  66. package/lib/config/source/transformImport.js +2 -0
  67. package/lib/config/tools/css-extract.d.ts +72 -0
  68. package/lib/config/tools/css-extract.js +2 -0
  69. package/lib/config/tools/css-loader.d.ts +130 -0
  70. package/lib/config/tools/css-loader.js +2 -0
  71. package/lib/config/tools/index.d.ts +170 -0
  72. package/lib/config/tools/index.js +2 -0
  73. package/lib/config/validate.d.ts +4 -0
  74. package/lib/config/validate.js +28962 -0
  75. package/lib/create-rspeedy.d.ts +45 -0
  76. package/lib/create-rspeedy.js +48 -0
  77. package/lib/debug.d.ts +3 -0
  78. package/lib/debug.js +25 -0
  79. package/lib/index.d.ts +45 -0
  80. package/lib/index.js +10 -0
  81. package/lib/plugins/api.plugin.d.ts +3 -0
  82. package/lib/plugins/api.plugin.js +25 -0
  83. package/lib/plugins/chunkLoading.plugin.d.ts +2 -0
  84. package/lib/plugins/chunkLoading.plugin.js +30 -0
  85. package/lib/plugins/dev.plugin.d.ts +5 -0
  86. package/lib/plugins/dev.plugin.js +130 -0
  87. package/lib/plugins/index.d.ts +3 -0
  88. package/lib/plugins/index.js +49 -0
  89. package/lib/plugins/inspect.plugin.d.ts +4 -0
  90. package/lib/plugins/inspect.plugin.js +39 -0
  91. package/lib/plugins/minify.plugin.d.ts +3 -0
  92. package/lib/plugins/minify.plugin.js +89 -0
  93. package/lib/plugins/optimization.plugin.d.ts +2 -0
  94. package/lib/plugins/optimization.plugin.js +31 -0
  95. package/lib/plugins/output.plugin.d.ts +3 -0
  96. package/lib/plugins/output.plugin.js +34 -0
  97. package/lib/plugins/resolve.plugin.d.ts +2 -0
  98. package/lib/plugins/resolve.plugin.js +38 -0
  99. package/lib/plugins/rsdoctor.plugin.d.ts +3 -0
  100. package/lib/plugins/rsdoctor.plugin.js +41 -0
  101. package/lib/plugins/sourcemap.plugin.d.ts +2 -0
  102. package/lib/plugins/sourcemap.plugin.js +84 -0
  103. package/lib/plugins/stats.plugin.d.ts +2 -0
  104. package/lib/plugins/stats.plugin.js +20 -0
  105. package/lib/plugins/swc.plugin.d.ts +2 -0
  106. package/lib/plugins/swc.plugin.js +21 -0
  107. package/lib/plugins/target.plugin.d.ts +2 -0
  108. package/lib/plugins/target.plugin.js +12 -0
  109. package/lib/utils/getESVersionTarget.d.ts +1 -0
  110. package/lib/utils/getESVersionTarget.js +7 -0
  111. package/lib/utils/is-ci.d.ts +1 -0
  112. package/lib/utils/is-ci.js +7 -0
  113. package/lib/version.d.ts +4 -0
  114. package/lib/version.js +15 -0
  115. package/lib/webpack/CompilationIdPlugin.d.ts +4 -0
  116. package/lib/webpack/CompilationIdPlugin.js +20 -0
  117. package/lib/webpack/EvalSourceMapDevToolPlugin.d.ts +9 -0
  118. package/lib/webpack/EvalSourceMapDevToolPlugin.js +15 -0
  119. package/lib/webpack/ProvidePlugin.d.ts +9 -0
  120. package/lib/webpack/ProvidePlugin.js +15 -0
  121. package/lib/webpack/SourceMapDevToolPlugin.d.ts +9 -0
  122. package/lib/webpack/SourceMapDevToolPlugin.js +15 -0
  123. package/package.json +83 -0
  124. package/register/data.d.ts +9 -0
  125. package/register/hooks.js +146 -0
  126. package/register/index.d.ts +4 -0
  127. package/register/index.js +47 -0
@@ -0,0 +1,45 @@
1
+ import { version } from '../version.js';
2
+ function applyCommonOptions(command) {
3
+ command
4
+ .option('-c --config <config>', 'specify the configuration file, can be a relative or absolute path');
5
+ }
6
+ export function apply(program) {
7
+ // TODO(cli): support custom cwd
8
+ const cwd = process.cwd();
9
+ program
10
+ .name('rspeedy')
11
+ .usage('<command> [options]')
12
+ .version(version)
13
+ .option('--unmanaged', 'Force to use the unmanaged version of Rspeedy, instead of the locally installed.')
14
+ .showHelpAfterError(true)
15
+ .showSuggestionAfterError(true)
16
+ .exitOverride(); // Avoid calling `process.exit` by commander
17
+ const buildCommand = program.command('build');
18
+ buildCommand
19
+ .description('Build the project in production mode')
20
+ .action((buildOptions) => import('./build.js').then(({ build }) => build.call(buildCommand, cwd, buildOptions)));
21
+ const devCommand = program.command('dev');
22
+ devCommand
23
+ .description('Run the dev server and watch for source file changes while serving.')
24
+ .action((devOptions) => import('./dev.js').then(({ dev }) => dev.call(devCommand, cwd, devOptions)));
25
+ const inspectCommand = program.command('inspect');
26
+ inspectCommand
27
+ .description('View the Rsbuild config and Rspack config of the project.')
28
+ .option('--mode <mode>', 'specify the mode of Rsbuild', 'development')
29
+ .option('--output <output>', 'specify inspect content output path')
30
+ .option('--verbose', 'show full function definitions in output')
31
+ .action((inspectOptions) => import('./inspect.js').then(({ inspect }) => inspect.call(inspectCommand, cwd, inspectOptions)));
32
+ const previewCommand = program.command('preview');
33
+ previewCommand
34
+ .description('Preview the production build outputs locally.')
35
+ .action((previewOptions) => import('./preview.js').then(({ preview }) => preview.call(previewCommand, cwd, previewOptions)));
36
+ const commonCommands = [
37
+ devCommand,
38
+ buildCommand,
39
+ inspectCommand,
40
+ previewCommand,
41
+ ];
42
+ commonCommands.forEach((command) => applyCommonOptions(command));
43
+ return program;
44
+ }
45
+ //# sourceMappingURL=commands.js.map
@@ -0,0 +1,4 @@
1
+ import type { Command } from 'commander';
2
+ import type { CommonOptions } from './commands.js';
3
+ export type DevOptions = CommonOptions;
4
+ export declare function dev(this: Command, cwd: string, devOptions: DevOptions): Promise<void>;
package/lib/cli/dev.js ADDED
@@ -0,0 +1,75 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import path from 'node:path';
5
+ import { logger } from '@rsbuild/core';
6
+ import color from 'picocolors';
7
+ import { loadConfig, resolveConfigPath } from '../config/loadConfig.js';
8
+ import { createRspeedy } from '../create-rspeedy.js';
9
+ import { exit } from './exit.js';
10
+ export async function dev(cwd, devOptions) {
11
+ let onBeforeRestart = [];
12
+ try {
13
+ const configPath = resolveConfigPath(cwd, devOptions.config);
14
+ const { content: rspeedyConfig } = await loadConfig({
15
+ cwd,
16
+ configPath,
17
+ });
18
+ const watchedFiles = [configPath];
19
+ if (Array.isArray(rspeedyConfig.dev?.watchFiles)) {
20
+ watchedFiles.push(...rspeedyConfig.dev.watchFiles
21
+ .filter(item => item.type === 'reload-server')
22
+ .flatMap(item => item.paths));
23
+ }
24
+ else if (rspeedyConfig.dev?.watchFiles?.type === 'reload-server') {
25
+ const { paths } = rspeedyConfig.dev.watchFiles;
26
+ watchedFiles.push(...Array.isArray(paths) ? paths : [paths]);
27
+ }
28
+ await watchFiles(watchedFiles.map(filePath => path.isAbsolute(filePath) ? filePath : path.join(cwd, filePath)), async (filename) => {
29
+ logger.info(`Restart because ${color.yellow(filename)} is changed.\n`);
30
+ const cleanup = onBeforeRestart.map(f => f());
31
+ onBeforeRestart = [];
32
+ await Promise.all(cleanup);
33
+ await dev.call(this, cwd, devOptions);
34
+ });
35
+ const rspeedy = await createRspeedy({ cwd, rspeedyConfig });
36
+ const server = await rspeedy.createDevServer();
37
+ const { server: { close } } = await server.listen();
38
+ onBeforeRestart.push(close);
39
+ }
40
+ catch (error) {
41
+ logger.error(error);
42
+ exit(1);
43
+ }
44
+ }
45
+ async function watchFiles(files, callback) {
46
+ const chokidar = await import('chokidar');
47
+ const watcher = chokidar.default.watch(files, {
48
+ // do not trigger add for initial files
49
+ ignoreInitial: true,
50
+ // If watching fails due to read permissions, the errors will be suppressed silently.
51
+ ignorePermissionErrors: true,
52
+ });
53
+ const cb = debounce((event, filePath) => {
54
+ const startTime = Date.now();
55
+ void watcher.close().then(() => callback(filePath, startTime, event));
56
+ },
57
+ // set 300ms debounce to avoid restart frequently
58
+ 300);
59
+ watcher.once('add', cb.bind(null, 'add'));
60
+ watcher.once('change', cb.bind(null, 'change'));
61
+ watcher.once('unlink', cb.bind(null, 'unlink'));
62
+ }
63
+ // biome-ignore lint/suspicious/noExplicitAny: Make TS happy
64
+ function debounce(func, wait) {
65
+ let timeoutId = null;
66
+ return (...args) => {
67
+ if (timeoutId !== null) {
68
+ clearTimeout(timeoutId);
69
+ }
70
+ timeoutId = setTimeout(() => {
71
+ func(...args);
72
+ }, wait);
73
+ };
74
+ }
75
+ //# sourceMappingURL=dev.js.map
@@ -0,0 +1 @@
1
+ export declare const exit: (signal?: number | undefined) => void;
@@ -0,0 +1,51 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import { logger } from '@rsbuild/core';
5
+ import { asyncExitHook, gracefulExit } from 'exit-hook';
6
+ import color from 'picocolors';
7
+ import { debug } from '../debug.js';
8
+ const start = Date.now();
9
+ const exitPromises = [];
10
+ const unsubscribe = asyncExitHook(onExit, { wait: 1000 });
11
+ // eslint-disable-next-line @typescript-eslint/no-misused-promises
12
+ process.on('unhandledRejection', async (reason) => {
13
+ logger.error('Unhandled Rejection with reason:', reason instanceof Error ? reason : new Error(JSON.stringify(reason)));
14
+ // Here we do not directly use `gracefulExit` since it will wait until
15
+ // the compilation finished.
16
+ unsubscribe();
17
+ await onExit(1);
18
+ // eslint-disable-next-line n/no-process-exit
19
+ process.exit(1);
20
+ });
21
+ let interrupted = false;
22
+ process.on('SIGINT', () => {
23
+ if (interrupted) {
24
+ logger.info(`Force exiting Rspeedy.`);
25
+ // The `exit` is not complete, yet.
26
+ // But the `Ctrl + C` has been pressed again, we make a force exit here.
27
+ // eslint-disable-next-line n/no-process-exit
28
+ return process.exit(/** 128 + 2(kill) */ 130);
29
+ }
30
+ interrupted = true;
31
+ logger.info(`Gracefully shutting down. Please wait... (Press ${color.cyan('Ctrl+C')} again to force exit)`);
32
+ // Graceful exit with code 130
33
+ // see: https://nodejs.org/docs/latest/api/process.html#signal-events
34
+ exit(/** 128 + 2(kill) */ 130);
35
+ });
36
+ let previousSignal = null;
37
+ export const exit = (signal = 0) => {
38
+ if (previousSignal !== null) {
39
+ debug(`graceful exit called multiple times, current: ${signal}, previous: ${previousSignal}`);
40
+ }
41
+ previousSignal = signal;
42
+ debug(`graceful exit process with signal: ${signal}`);
43
+ gracefulExit(signal);
44
+ };
45
+ async function onExit(signal) {
46
+ const duration = Date.now() - start;
47
+ debug(`exit hook fired with signal: ${signal}, duration: ${duration}`);
48
+ debug(`awaiting exit promises(length: ${exitPromises.length})...`);
49
+ await Promise.allSettled(exitPromises);
50
+ }
51
+ //# sourceMappingURL=exit.js.map
@@ -0,0 +1,8 @@
1
+ import type { Command } from 'commander';
2
+ import type { CommonOptions } from './commands.js';
3
+ export interface InspectOptions extends CommonOptions {
4
+ mode?: 'production' | 'development' | undefined;
5
+ verbose?: boolean | undefined;
6
+ output?: string | undefined;
7
+ }
8
+ export declare function inspect(this: Command, cwd: string, inspectOptions: InspectOptions): Promise<void>;
@@ -0,0 +1,30 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import { logger } from '@rsbuild/core';
5
+ import { exit } from './exit.js';
6
+ import { loadConfig } from '../config/loadConfig.js';
7
+ import { createRspeedy } from '../create-rspeedy.js';
8
+ export async function inspect(cwd, inspectOptions) {
9
+ try {
10
+ const { content: rspeedyConfig } = await loadConfig({
11
+ cwd,
12
+ configPath: inspectOptions.config,
13
+ });
14
+ const rspeedy = await createRspeedy({ cwd, rspeedyConfig });
15
+ await rspeedy.inspectConfig({
16
+ mode: inspectOptions.mode
17
+ ?? process.env['NODE_ENV']
18
+ ?? 'development',
19
+ verbose: inspectOptions.verbose ?? false,
20
+ outputPath: inspectOptions.output,
21
+ writeToDisk: true,
22
+ });
23
+ return exit();
24
+ }
25
+ catch (error) {
26
+ logger.error(error);
27
+ logger.error();
28
+ }
29
+ }
30
+ //# sourceMappingURL=inspect.js.map
@@ -0,0 +1 @@
1
+ export declare function main(argv: string[]): Promise<void>;
@@ -0,0 +1,39 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import { logger } from '@rsbuild/core';
5
+ import { exit } from './exit.js';
6
+ import { debug } from '../debug.js';
7
+ function initNodeEnv(argv) {
8
+ if (!process.env['NODE_ENV']) {
9
+ const NODE_ENV = (argv.includes('dev') || argv.includes('preview'))
10
+ ? 'development'
11
+ : 'production';
12
+ process.env['NODE_ENV'] = NODE_ENV;
13
+ debug(`No NODE_ENV found, set to ${NODE_ENV}`);
14
+ }
15
+ }
16
+ export async function main(argv) {
17
+ initNodeEnv(argv);
18
+ // If not called through a package manager,
19
+ // output a blank line to keep the greet log nice.
20
+ const { npm_execpath } = process.env;
21
+ if (!npm_execpath || npm_execpath.includes('npm-cli.js')
22
+ || npm_execpath.includes('npx-cli.js')) {
23
+ // biome-ignore lint/suspicious/noConsoleLog: <explanation>
24
+ console.log();
25
+ }
26
+ const { version, rsbuildVersion, rspackVersion } = await import('../version.js');
27
+ logger.greet(` Rspeedy v${version} (Rsbuild v${rsbuildVersion}, Rspack v${rspackVersion})\n`);
28
+ try {
29
+ const [{ Command }, { apply },] = await Promise.all([
30
+ import('commander'),
31
+ import('./commands.js'),
32
+ ]);
33
+ apply(new Command('rspeedy')).parse(argv);
34
+ }
35
+ catch {
36
+ return exit(1);
37
+ }
38
+ }
39
+ //# sourceMappingURL=main.js.map
@@ -0,0 +1,4 @@
1
+ import type { Command } from 'commander';
2
+ import type { CommonOptions } from './commands.js';
3
+ export type PreviewOptions = CommonOptions;
4
+ export declare function preview(this: Command, cwd: string, options: PreviewOptions): Promise<void>;
@@ -0,0 +1,31 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import fs from 'node:fs';
5
+ import { logger } from '@rsbuild/core';
6
+ import color from 'picocolors';
7
+ import { exit } from './exit.js';
8
+ import { loadConfig } from '../config/loadConfig.js';
9
+ import { createRspeedy } from '../create-rspeedy.js';
10
+ export async function preview(cwd, options) {
11
+ try {
12
+ const { content: rspeedyConfig } = await loadConfig({
13
+ cwd,
14
+ configPath: options.config,
15
+ });
16
+ const rspeedy = await createRspeedy({ cwd, rspeedyConfig });
17
+ await rspeedy.initConfigs();
18
+ const { distPath } = rspeedy.context;
19
+ if (!fs.existsSync(distPath)) {
20
+ throw new Error(`The output directory ${color.yellow(distPath)} does not exist, please build the project before previewing.`);
21
+ }
22
+ await rspeedy.preview();
23
+ }
24
+ catch (error) {
25
+ logger.error('Failed to start preview server.');
26
+ logger.error(error);
27
+ exit(1);
28
+ return;
29
+ }
30
+ }
31
+ //# sourceMappingURL=preview.js.map
@@ -0,0 +1,6 @@
1
+ /**
2
+ * When rspeedy is invoked via the shell path, we examine the project's package.json dependencies and try to load
3
+ * the locally installed version of rspeedy. This avoids accidentally building using the wrong version of rspeedy.
4
+ * Use "rspeedy --unmanaged" to bypass this feature.
5
+ */
6
+ export declare function tryStartLocalRspeedy(root?: string): false | Promise<void>;
@@ -0,0 +1,88 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
5
+ // See LICENSE in the project root for license information.
6
+ import * as fs from 'node:fs';
7
+ import * as path from 'node:path';
8
+ import { pathToFileURL } from 'node:url';
9
+ import { logger } from '@rsbuild/core';
10
+ import { debug } from '../debug.js';
11
+ var Constants;
12
+ (function (Constants) {
13
+ Constants["rspeedyPackageName"] = "@lynx-js/rspeedy";
14
+ Constants["unmanagedParameterLongName"] = "--unmanaged";
15
+ })(Constants || (Constants = {}));
16
+ // Excerpted from PackageJsonLookup.tryGetPackageFolderFor()
17
+ function tryGetPackageFolderFor(resolvedFileOrFolderPath) {
18
+ // Is resolvedFileOrFolderPath itself a folder with a package.json file? If so, return it.
19
+ if (fs.existsSync(path.join(resolvedFileOrFolderPath, 'package.json'))) {
20
+ return resolvedFileOrFolderPath;
21
+ }
22
+ // Otherwise go up one level
23
+ const parentFolder = path.dirname(resolvedFileOrFolderPath);
24
+ if (!parentFolder || parentFolder === resolvedFileOrFolderPath) {
25
+ // We reached the root directory without finding a package.json file,
26
+ // so cache the negative result
27
+ return undefined; // no match
28
+ }
29
+ // Recurse upwards
30
+ return tryGetPackageFolderFor(parentFolder);
31
+ }
32
+ /**
33
+ * When rspeedy is invoked via the shell path, we examine the project's package.json dependencies and try to load
34
+ * the locally installed version of rspeedy. This avoids accidentally building using the wrong version of rspeedy.
35
+ * Use "rspeedy --unmanaged" to bypass this feature.
36
+ */
37
+ export function tryStartLocalRspeedy(root = process.cwd()) {
38
+ if (process.argv.includes(Constants.unmanagedParameterLongName)) {
39
+ logger.info(`Bypassing the Rspeedy version selector because ${JSON.stringify(Constants.unmanagedParameterLongName)} was specified.`);
40
+ logger.info();
41
+ return false;
42
+ }
43
+ // The unmanaged flag could be undiscoverable if it's not in their locally installed version
44
+ debug(`Searching for a locally installed version of Rspeedy. Use the ${JSON.stringify(Constants.unmanagedParameterLongName)} flag if you want to avoid this.`);
45
+ // Find the package.json file that governs the current folder location
46
+ const projectFolder = tryGetPackageFolderFor(root);
47
+ if (projectFolder) {
48
+ debug(`found project at ${projectFolder}`);
49
+ let rspeedyEntryPoint;
50
+ let packageJson;
51
+ try {
52
+ const packageJsonPath = path.join(projectFolder, 'package.json');
53
+ const packageJsonContent = fs.readFileSync(packageJsonPath).toString();
54
+ try {
55
+ packageJson = JSON.parse(packageJsonContent);
56
+ }
57
+ catch (error) {
58
+ throw new Error(`Error parsing ${packageJsonPath}:${error.message}`);
59
+ }
60
+ // Does package.json have a dependency on Rspeedy?
61
+ if (!(packageJson.dependencies?.[Constants.rspeedyPackageName])
62
+ && !(packageJson.devDependencies?.[Constants.rspeedyPackageName])) {
63
+ // No explicit dependency on rspeedy
64
+ debug('The project does not have a dependency on Rspeedy');
65
+ return false;
66
+ }
67
+ // To avoid a loading the "resolve" NPM package, let's assume that the rspeedy dependency must be
68
+ // installed as "<projectFolder>/node_modules/@lynx-js/rspeedy".
69
+ const rspeedyFolder = path.join(projectFolder, 'node_modules', ...Constants.rspeedyPackageName.split('/'));
70
+ rspeedyEntryPoint = path.join(rspeedyFolder, 'lib', 'cli', 'main.js');
71
+ if (!fs.existsSync(rspeedyEntryPoint)) {
72
+ debug(`Unable to find rspeedy entry point: ${rspeedyEntryPoint}, using the unmanaged version.`);
73
+ return false;
74
+ }
75
+ }
76
+ catch (error) {
77
+ throw new Error(`Error probing for local rspeedy version: ${error.message}`);
78
+ }
79
+ debug(`found rspeedy entry point at ${rspeedyEntryPoint}`);
80
+ // We found and successfully invoked the local rspeedy
81
+ // Note that we are using `pathToFileURL` since absolute paths must be valid file:// URLs on Windows.
82
+ return import(pathToFileURL(rspeedyEntryPoint).toString()).then(({ main }) => main(process.argv));
83
+ }
84
+ debug(`no project folder found from ${process.cwd()}`);
85
+ // We couldn't find the package folder
86
+ return false;
87
+ }
88
+ //# sourceMappingURL=start.js.map
@@ -0,0 +1,2 @@
1
+ import type { Config } from './index.js';
2
+ export declare function applyDefaultRspeedyConfig(config: Config): Config;
@@ -0,0 +1,32 @@
1
+ // Copyright 2024 The Lynx Authors. All rights reserved.
2
+ // Licensed under the Apache License Version 2.0 that can be found in the
3
+ // LICENSE file in the root directory of this source tree.
4
+ import { mergeRsbuildConfig } from '@rsbuild/core';
5
+ export function applyDefaultRspeedyConfig(config) {
6
+ const ret = mergeRsbuildConfig(config, {
7
+ output: {
8
+ // We are applying the default filename to the config
9
+ // since some plugin(e.g.: `@lynx-js/qrcode-rsbuild-plugin`) will read
10
+ // from the `output.filename.bundle` field.
11
+ filename: getFilename(config.output?.filename),
12
+ },
13
+ });
14
+ return ret;
15
+ }
16
+ const DEFAULT_FILENAME = '[name].[platform].bundle';
17
+ function getFilename(filename) {
18
+ if (typeof filename === 'string') {
19
+ return {
20
+ bundle: filename,
21
+ template: filename,
22
+ };
23
+ }
24
+ const finalFilename = filename?.bundle
25
+ ?? filename?.template
26
+ ?? DEFAULT_FILENAME;
27
+ return {
28
+ bundle: finalFilename,
29
+ template: finalFilename,
30
+ };
31
+ }
32
+ //# sourceMappingURL=defaults.js.map
@@ -0,0 +1,22 @@
1
+ import type { Config } from './index.js';
2
+ /**
3
+ * The `defineConfig` method is a helper function used to get TypeScript intellisense.
4
+ *
5
+ * @param config - The config of Rspeedy.
6
+ * @returns - The identical config as the input config.
7
+ *
8
+ * @example
9
+ *
10
+ * Use `defineConfig` in `lynx.config.ts`:
11
+ *
12
+ * ```ts
13
+ * //@ts-check
14
+ * import { defineConfig } from '@lynx-js/rspeedy'
15
+ * export default defineConfig({
16
+ * // autocompletion works here!
17
+ * })
18
+ * ```
19
+ *
20
+ * @public
21
+ */
22
+ export declare function defineConfig(config: Config): Config;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * The `defineConfig` method is a helper function used to get TypeScript intellisense.
3
+ *
4
+ * @param config - The config of Rspeedy.
5
+ * @returns - The identical config as the input config.
6
+ *
7
+ * @example
8
+ *
9
+ * Use `defineConfig` in `lynx.config.ts`:
10
+ *
11
+ * ```ts
12
+ * //@ts-check
13
+ * import { defineConfig } from '@lynx-js/rspeedy'
14
+ * export default defineConfig({
15
+ * // autocompletion works here!
16
+ * })
17
+ * ```
18
+ *
19
+ * @public
20
+ */
21
+ export function defineConfig(config) {
22
+ return config;
23
+ }
24
+ //# sourceMappingURL=defineConfig.js.map
@@ -0,0 +1,15 @@
1
+ /**
2
+ * {@inheritdoc Dev.client}
3
+ *
4
+ * @public
5
+ */
6
+ export interface Client {
7
+ /**
8
+ * The path to websocket.
9
+ *
10
+ * @remarks
11
+ *
12
+ * Defaults to `require.resolve('@lynx-js/websocket')`
13
+ */
14
+ websocketTransport?: string | undefined;
15
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1,133 @@
1
+ import type { WatchFiles } from '@rsbuild/core';
2
+ import type { Client } from './client.js';
3
+ /**
4
+ * {@inheritdoc Config.dev}
5
+ * @public
6
+ */
7
+ export interface Dev {
8
+ /**
9
+ * The {@link Dev.assetPrefix} is used to set the URL prefix for static assets during development.
10
+ * @remarks
11
+ *
12
+ * The functionality of {@link Dev.assetPrefix} is basically the same as the {@link https://www.rspack.dev/config/output#outputpublicpath | output.publicPath}
13
+ * config in Rspack. With the following differences:
14
+ *
15
+ * - `dev.assetPrefix` only takes effect during development.
16
+ *
17
+ * - `dev.assetPrefix` automatically appends a trailing `/` by default.
18
+ *
19
+ * - The value of `dev.assetPrefix` is written to the `process.env.ASSET_PREFIX` environment variable.
20
+ *
21
+ * @example
22
+ *
23
+ * If `dev.assetPrefix` is set to true, the URL prefix will be `http://<host>:<port>/`:
24
+ *
25
+ * ```js
26
+ * import { defineConfig } from '@lynx-js/rspeedy'
27
+ * export default defineConfig({
28
+ * dev: {
29
+ * assetPrefix: true,
30
+ * },
31
+ * })
32
+ * ```
33
+ *
34
+ * @example
35
+ *
36
+ * If `dev.assetPrefix` is set to a string, the value will be used as a prefix and automatically appended to the static resource URL.
37
+ *
38
+ * ```js
39
+ * import { defineConfig } from '@lynx-js/rspeedy'
40
+ * export default defineConfig({
41
+ * dev: {
42
+ * assetPrefix: 'https://example.com/assets/',
43
+ * },
44
+ * })
45
+ * ```
46
+ *
47
+ * @example
48
+ *
49
+ * The port number that Rspeedy server listens on may change. For example, if the port is in use, Rspeedy will automatically increment the port number until it finds an available port.
50
+ *
51
+ * To avoid `dev.assetPrefix` becoming invalid due to port changes, you can use one of the following methods:
52
+ *
53
+ * - Enable `server.strictPort`.
54
+ *
55
+ * - Use the `<port>` placeholder to refer to the current port number. Rspeedy will replace the placeholder with the actual port number it is listening on.
56
+ *
57
+ * ```js
58
+ * import { defineConfig } from '@lynx-js/rspeedy'
59
+ * export default defineConfig({
60
+ * dev: {
61
+ * assetPrefix: 'https://example.com:<port>/assets/',
62
+ * },
63
+ * })
64
+ * ```
65
+ */
66
+ assetPrefix?: string | boolean | undefined;
67
+ /**
68
+ * Configuration of the development client.
69
+ */
70
+ client?: Client | undefined;
71
+ /**
72
+ * Watch specified files and directories for changes. When a file change is detected, it can trigger a page reload or restart the dev server.
73
+ *
74
+ * @example
75
+ *
76
+ * - Specify the files and directories watched for changes.
77
+ *
78
+ * ```js
79
+ * import { defineConfig } from '@lynx-js/rspeedy'
80
+ *
81
+ * export default defineConfig({
82
+ * dev: {
83
+ * watchFiles: {
84
+ * paths: ['src/**', 'public/**'],
85
+ * },
86
+ * },
87
+ * })
88
+ * ```
89
+ *
90
+ * @example
91
+ *
92
+ * - Use {@link https://github.com/paulmillr/chokidar#api | chokidar} options for watching.
93
+ *
94
+ * ```js
95
+ * import { defineConfig } from '@lynx-js/rspeedy'
96
+ *
97
+ * export default defineConfig({
98
+ * dev: {
99
+ * watchFiles: {
100
+ * paths: ['src/**', 'public/**'],
101
+ * options: { usePolling: false },
102
+ * },
103
+ * },
104
+ * })
105
+ * ```
106
+ */
107
+ watchFiles?: WatchFiles | WatchFiles[] | undefined;
108
+ /**
109
+ * Used to control whether the build artifacts of the development environment are written to the disk.
110
+ *
111
+ * @remarks
112
+ *
113
+ * This is bypassed to {@link https://github.com/webpack/webpack-dev-middleware?tab=readme-ov-file#writetodisk | `webpack-dev-middleware`}.
114
+ *
115
+ * Setting `writeToDisk: true` won't change the behavior of the `webpack-dev-middleware`, and bundle files accessed through the browser will still be served from memory.
116
+ *
117
+ * This option also accepts a `Function` value, which can be used to filter which files are written to disk.
118
+ *
119
+ * The function follows the same premise as `Array#filter` in which a return value of `false` will not write the file, and a return value of `true` will write the file to disk.
120
+ *
121
+ * @example
122
+ * ```js
123
+ * // lynx.config.ts
124
+ * import { defineConfig } from '@lynx-js/rspeedy'
125
+ * export default defineConfig({
126
+ * dev: {
127
+ * writeToDisk: (filePath) => /superman\.css$/.test(filePath),
128
+ * },
129
+ * })
130
+ * ```
131
+ */
132
+ writeToDisk?: boolean | ((filename: string) => boolean) | undefined;
133
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.js.map