diff --git a/crates/node_binding/binding.d.ts b/crates/node_binding/binding.d.ts index bb6d35b6e9c..8784603778d 100644 --- a/crates/node_binding/binding.d.ts +++ b/crates/node_binding/binding.d.ts @@ -501,7 +501,6 @@ export interface JsStatsChunkGroupAsset { export interface JsStatsError { message: string - formatted: string moduleIdentifier?: string moduleName?: string moduleId?: string @@ -573,7 +572,6 @@ export interface JsStatsOptimizationBailout { export interface JsStatsWarning { message: string - formatted: string moduleIdentifier?: string moduleName?: string moduleId?: string diff --git a/crates/rspack_binding_values/src/stats.rs b/crates/rspack_binding_values/src/stats.rs index 5e5a678490d..2071ee7dae2 100644 --- a/crates/rspack_binding_values/src/stats.rs +++ b/crates/rspack_binding_values/src/stats.rs @@ -14,7 +14,6 @@ use super::{JsCompilation, ToJsCompatSource}; #[derive(Debug)] pub struct JsStatsError { pub message: String, - pub formatted: String, pub module_identifier: Option, pub module_name: Option, pub module_id: Option, @@ -24,7 +23,6 @@ impl From for JsStatsError { fn from(stats: rspack_core::StatsError) -> Self { Self { message: stats.message, - formatted: stats.formatted, module_identifier: stats.module_identifier, module_name: stats.module_name, module_id: stats.module_id, @@ -35,7 +33,6 @@ impl From for JsStatsError { #[napi(object)] pub struct JsStatsWarning { pub message: String, - pub formatted: String, pub module_identifier: Option, pub module_name: Option, pub module_id: Option, @@ -45,7 +42,6 @@ impl From for JsStatsWarning { fn from(stats: rspack_core::StatsWarning) -> Self { Self { message: stats.message, - formatted: stats.formatted, module_identifier: stats.module_identifier, module_name: stats.module_name, module_id: stats.module_id, diff --git a/crates/rspack_core/src/stats.rs b/crates/rspack_core/src/stats.rs index 5c2c51f06e9..400506b1a3a 100644 --- a/crates/rspack_core/src/stats.rs +++ b/crates/rspack_core/src/stats.rs @@ -339,9 +339,6 @@ impl Stats<'_> { message: diagnostic_displayer .emit_diagnostic(d) .expect("should print diagnostics"), - formatted: diagnostic_displayer - .emit_diagnostic(d) - .expect("should print diagnostics"), module_identifier: module_identifier.map(|i| i.to_string()), module_name, module_id: module_id.flatten(), @@ -369,9 +366,6 @@ impl Stats<'_> { message: diagnostic_displayer .emit_diagnostic(d) .expect("should print diagnostics"), - formatted: diagnostic_displayer - .emit_diagnostic(d) - .expect("should print diagnostics"), module_identifier: module_identifier.map(|i| i.to_string()), module_name, module_id: module_id.flatten(), @@ -703,7 +697,6 @@ fn get_stats_module_name_and_id( #[derive(Debug)] pub struct StatsError { pub message: String, - pub formatted: String, pub module_identifier: Option, pub module_name: Option, pub module_id: Option, @@ -712,7 +705,6 @@ pub struct StatsError { #[derive(Debug)] pub struct StatsWarning { pub message: String, - pub formatted: String, pub module_identifier: Option, pub module_name: Option, pub module_id: Option, diff --git a/packages/rspack-test-tools/tests/errorCases/error-map.js b/packages/rspack-test-tools/tests/errorCases/error-map.js index bae713d499a..aab080b11fa 100644 --- a/packages/rspack-test-tools/tests/errorCases/error-map.js +++ b/packages/rspack-test-tools/tests/errorCases/error-map.js @@ -23,7 +23,6 @@ module.exports = { expect(errors).toMatchInlineSnapshot(` Array [ Object { - "formatted": " × Resolve error: Can't resolve './answer' in 'packages/rspack-test-tools/tests/fixtures/errors/resolve-fail-esm'\\n ╭────\\n 1 │ import { answer } from './answer';\\n · ──────────\\n ╰────\\n help: Did you mean './answer.js'?\\n \\n The request './answer' failed to resolve only because it was resolved as fully specified,\\n probably because the origin is strict EcmaScript Module,\\n e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '\\"type\\": \\"module\\"'.\\n \\n The extension in the request is mandatory for it to be fully specified.\\n Add the extension to the request.\\n", "index": 0, "message": " × Resolve error: Can't resolve './answer' in 'packages/rspack-test-tools/tests/fixtures/errors/resolve-fail-esm'\\n ╭────\\n 1 │ import { answer } from './answer';\\n · ──────────\\n ╰────\\n help: Did you mean './answer.js'?\\n \\n The request './answer' failed to resolve only because it was resolved as fully specified,\\n probably because the origin is strict EcmaScript Module,\\n e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '\\"type\\": \\"module\\"'.\\n \\n The extension in the request is mandatory for it to be fully specified.\\n Add the extension to the request.\\n", "moduleId": "./resolve-fail-esm/index.js", diff --git a/packages/rspack-test-tools/tests/errorCases/error-test-push.js b/packages/rspack-test-tools/tests/errorCases/error-test-push.js index 8675f18ac20..9fa7c69fb58 100644 --- a/packages/rspack-test-tools/tests/errorCases/error-test-push.js +++ b/packages/rspack-test-tools/tests/errorCases/error-test-push.js @@ -18,11 +18,9 @@ module.exports = { Object { "errors": Array [ Object { - "formatted": " × test push\\n", "message": " × test push\\n", }, Object { - "formatted": " × Resolve error: Can't resolve './answer' in 'packages/rspack-test-tools/tests/fixtures/errors/resolve-fail-esm'\\n ╭────\\n 1 │ import { answer } from './answer';\\n · ──────────\\n ╰────\\n help: Did you mean './answer.js'?\\n \\n The request './answer' failed to resolve only because it was resolved as fully specified,\\n probably because the origin is strict EcmaScript Module,\\n e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '\\"type\\": \\"module\\"'.\\n \\n The extension in the request is mandatory for it to be fully specified.\\n Add the extension to the request.\\n", "message": " × Resolve error: Can't resolve './answer' in 'packages/rspack-test-tools/tests/fixtures/errors/resolve-fail-esm'\\n ╭────\\n 1 │ import { answer } from './answer';\\n · ──────────\\n ╰────\\n help: Did you mean './answer.js'?\\n \\n The request './answer' failed to resolve only because it was resolved as fully specified,\\n probably because the origin is strict EcmaScript Module,\\n e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '\\"type\\": \\"module\\"'.\\n \\n The extension in the request is mandatory for it to be fully specified.\\n Add the extension to the request.\\n", "moduleId": "./resolve-fail-esm/index.js", "moduleIdentifier": "javascript/esm|packages/rspack-test-tools/tests/fixtures/errors/resolve-fail-esm/index.js", diff --git a/packages/rspack-test-tools/tests/errorCases/error-test-shift.js b/packages/rspack-test-tools/tests/errorCases/error-test-shift.js index 13d8caa0c71..c985435585b 100644 --- a/packages/rspack-test-tools/tests/errorCases/error-test-shift.js +++ b/packages/rspack-test-tools/tests/errorCases/error-test-shift.js @@ -22,7 +22,6 @@ module.exports = { Object { "errors": Array [ Object { - "formatted": " × test unshift\\n", "message": " × test unshift\\n", }, ], diff --git a/packages/rspack-test-tools/tests/errorCases/error-test-splice-1.js b/packages/rspack-test-tools/tests/errorCases/error-test-splice-1.js index 27769318b47..abf90bb2866 100644 --- a/packages/rspack-test-tools/tests/errorCases/error-test-splice-1.js +++ b/packages/rspack-test-tools/tests/errorCases/error-test-splice-1.js @@ -18,7 +18,6 @@ module.exports = { Object { "errors": Array [ Object { - "formatted": " × test splice\\n", "message": " × test splice\\n", }, ], diff --git a/packages/rspack-test-tools/tests/errorCases/error-test-splice-2.js b/packages/rspack-test-tools/tests/errorCases/error-test-splice-2.js index 172ef138b13..5dfa9d2c273 100644 --- a/packages/rspack-test-tools/tests/errorCases/error-test-splice-2.js +++ b/packages/rspack-test-tools/tests/errorCases/error-test-splice-2.js @@ -18,11 +18,9 @@ module.exports = { Object { "errors": Array [ Object { - "formatted": " × test splice\\n", "message": " × test splice\\n", }, Object { - "formatted": " × Resolve error: Can't resolve './answer' in 'packages/rspack-test-tools/tests/fixtures/errors/resolve-fail-esm'\\n ╭────\\n 1 │ import { answer } from './answer';\\n · ──────────\\n ╰────\\n help: Did you mean './answer.js'?\\n \\n The request './answer' failed to resolve only because it was resolved as fully specified,\\n probably because the origin is strict EcmaScript Module,\\n e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '\\"type\\": \\"module\\"'.\\n \\n The extension in the request is mandatory for it to be fully specified.\\n Add the extension to the request.\\n", "message": " × Resolve error: Can't resolve './answer' in 'packages/rspack-test-tools/tests/fixtures/errors/resolve-fail-esm'\\n ╭────\\n 1 │ import { answer } from './answer';\\n · ──────────\\n ╰────\\n help: Did you mean './answer.js'?\\n \\n The request './answer' failed to resolve only because it was resolved as fully specified,\\n probably because the origin is strict EcmaScript Module,\\n e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '\\"type\\": \\"module\\"'.\\n \\n The extension in the request is mandatory for it to be fully specified.\\n Add the extension to the request.\\n", "moduleId": "./resolve-fail-esm/index.js", "moduleIdentifier": "javascript/esm|packages/rspack-test-tools/tests/fixtures/errors/resolve-fail-esm/index.js", diff --git a/packages/rspack-test-tools/tests/errorCases/resolve-fail-esm.js b/packages/rspack-test-tools/tests/errorCases/resolve-fail-esm.js index 417d37a3036..e9732f71ee2 100644 --- a/packages/rspack-test-tools/tests/errorCases/resolve-fail-esm.js +++ b/packages/rspack-test-tools/tests/errorCases/resolve-fail-esm.js @@ -11,7 +11,6 @@ module.exports = { Object { "errors": Array [ Object { - "formatted": " × Resolve error: Can't resolve './answer' in 'packages/rspack-test-tools/tests/fixtures/errors/resolve-fail-esm'\\n ╭────\\n 1 │ import { answer } from './answer';\\n · ──────────\\n ╰────\\n help: Did you mean './answer.js'?\\n \\n The request './answer' failed to resolve only because it was resolved as fully specified,\\n probably because the origin is strict EcmaScript Module,\\n e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '\\"type\\": \\"module\\"'.\\n \\n The extension in the request is mandatory for it to be fully specified.\\n Add the extension to the request.\\n", "message": " × Resolve error: Can't resolve './answer' in 'packages/rspack-test-tools/tests/fixtures/errors/resolve-fail-esm'\\n ╭────\\n 1 │ import { answer } from './answer';\\n · ──────────\\n ╰────\\n help: Did you mean './answer.js'?\\n \\n The request './answer' failed to resolve only because it was resolved as fully specified,\\n probably because the origin is strict EcmaScript Module,\\n e. g. a module with javascript mimetype, a '*.mjs' file, or a '*.js' file where the package.json contains '\\"type\\": \\"module\\"'.\\n \\n The extension in the request is mandatory for it to be fully specified.\\n Add the extension to the request.\\n", "moduleId": "./resolve-fail-esm/index.js", "moduleIdentifier": "javascript/esm|packages/rspack-test-tools/tests/fixtures/errors/resolve-fail-esm/index.js", diff --git a/packages/rspack-test-tools/tests/errorCases/warning-map.js b/packages/rspack-test-tools/tests/errorCases/warning-map.js index b5fdaccdadc..0049c9b0046 100644 --- a/packages/rspack-test-tools/tests/errorCases/warning-map.js +++ b/packages/rspack-test-tools/tests/errorCases/warning-map.js @@ -23,7 +23,6 @@ module.exports = { expect(warnings).toMatchInlineSnapshot(` Array [ Object { - "formatted": " ⚠ Module parse warning:\\n ╰─▶ ⚠ Module parse failed: require.main.require() is not supported by Rspack.\\n ╭────\\n 1 │ require.main.require('./file');\\n · ──────────────────────────────\\n ╰────\\n \\n", "index": 0, "message": " ⚠ Module parse warning:\\n ╰─▶ ⚠ Module parse failed: require.main.require() is not supported by Rspack.\\n ╭────\\n 1 │ require.main.require('./file');\\n · ──────────────────────────────\\n ╰────\\n \\n", "moduleId": "./require.main.require.js", diff --git a/packages/rspack-test-tools/tests/errorCases/warning-test-push.js b/packages/rspack-test-tools/tests/errorCases/warning-test-push.js index 4c0c5b655cf..3f62d546e1b 100644 --- a/packages/rspack-test-tools/tests/errorCases/warning-test-push.js +++ b/packages/rspack-test-tools/tests/errorCases/warning-test-push.js @@ -19,11 +19,9 @@ module.exports = { "errors": Array [], "warnings": Array [ Object { - "formatted": " ⚠ Error: test push\\n │ at packages/rspack-test-tools/tests/errorCases/warning-test-push.js:10:33\\n │ at Hook.eval [as callAsync] (eval at create (node_modules/tapable/lib/HookCodeFactory.js:33:10), :9:1)\\n │ at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (node_modules/tapable/lib/Hook.js:18:14)\\n │ at packages/rspack/dist/Compiler.js:466:41\\n │ at packages/rspack/dist/Compiler.js:533:65\\n", "message": " ⚠ Error: test push\\n │ at packages/rspack-test-tools/tests/errorCases/warning-test-push.js:10:33\\n │ at Hook.eval [as callAsync] (eval at create (node_modules/tapable/lib/HookCodeFactory.js:33:10), :9:1)\\n │ at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (node_modules/tapable/lib/Hook.js:18:14)\\n │ at packages/rspack/dist/Compiler.js:466:41\\n │ at packages/rspack/dist/Compiler.js:533:65\\n", }, Object { - "formatted": " ⚠ Module parse warning:\\n ╰─▶ ⚠ Module parse failed: require.main.require() is not supported by Rspack.\\n ╭────\\n 1 │ require.main.require('./file');\\n · ──────────────────────────────\\n ╰────\\n \\n", "message": " ⚠ Module parse warning:\\n ╰─▶ ⚠ Module parse failed: require.main.require() is not supported by Rspack.\\n ╭────\\n 1 │ require.main.require('./file');\\n · ──────────────────────────────\\n ╰────\\n \\n", "moduleId": "./require.main.require.js", "moduleIdentifier": "packages/rspack-test-tools/tests/fixtures/errors/require.main.require.js", diff --git a/packages/rspack-test-tools/tests/errorCases/warning-test-shift.js b/packages/rspack-test-tools/tests/errorCases/warning-test-shift.js index 13469964ac8..64eff878a9a 100644 --- a/packages/rspack-test-tools/tests/errorCases/warning-test-shift.js +++ b/packages/rspack-test-tools/tests/errorCases/warning-test-shift.js @@ -23,7 +23,6 @@ module.exports = { "errors": Array [], "warnings": Array [ Object { - "formatted": " ⚠ Error: test unshift\\n │ at packages/rspack-test-tools/tests/errorCases/warning-test-shift.js:13:37\\n │ at Hook.eval [as callAsync] (eval at create (node_modules/tapable/lib/HookCodeFactory.js:33:10), :9:1)\\n │ at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (node_modules/tapable/lib/Hook.js:18:14)\\n │ at packages/rspack/dist/Compiler.js:466:41\\n │ at packages/rspack/dist/Compiler.js:533:65\\n", "message": " ⚠ Error: test unshift\\n │ at packages/rspack-test-tools/tests/errorCases/warning-test-shift.js:13:37\\n │ at Hook.eval [as callAsync] (eval at create (node_modules/tapable/lib/HookCodeFactory.js:33:10), :9:1)\\n │ at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (node_modules/tapable/lib/Hook.js:18:14)\\n │ at packages/rspack/dist/Compiler.js:466:41\\n │ at packages/rspack/dist/Compiler.js:533:65\\n", }, ], diff --git a/packages/rspack-test-tools/tests/errorCases/warning-test-splice-1.js b/packages/rspack-test-tools/tests/errorCases/warning-test-splice-1.js index 78ce130bbbf..01291fdd17a 100644 --- a/packages/rspack-test-tools/tests/errorCases/warning-test-splice-1.js +++ b/packages/rspack-test-tools/tests/errorCases/warning-test-splice-1.js @@ -19,7 +19,6 @@ module.exports = { "errors": Array [], "warnings": Array [ Object { - "formatted": " ⚠ Error: test splice\\n │ at packages/rspack-test-tools/tests/errorCases/warning-test-splice-1.js:10:41\\n │ at Hook.eval [as callAsync] (eval at create (node_modules/tapable/lib/HookCodeFactory.js:33:10), :9:1)\\n │ at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (node_modules/tapable/lib/Hook.js:18:14)\\n │ at packages/rspack/dist/Compiler.js:466:41\\n │ at packages/rspack/dist/Compiler.js:533:65\\n", "message": " ⚠ Error: test splice\\n │ at packages/rspack-test-tools/tests/errorCases/warning-test-splice-1.js:10:41\\n │ at Hook.eval [as callAsync] (eval at create (node_modules/tapable/lib/HookCodeFactory.js:33:10), :9:1)\\n │ at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (node_modules/tapable/lib/Hook.js:18:14)\\n │ at packages/rspack/dist/Compiler.js:466:41\\n │ at packages/rspack/dist/Compiler.js:533:65\\n", }, ], diff --git a/packages/rspack-test-tools/tests/errorCases/warning-test-splice-2.js b/packages/rspack-test-tools/tests/errorCases/warning-test-splice-2.js index 3e9eed58e77..3599acd99b1 100644 --- a/packages/rspack-test-tools/tests/errorCases/warning-test-splice-2.js +++ b/packages/rspack-test-tools/tests/errorCases/warning-test-splice-2.js @@ -19,11 +19,9 @@ module.exports = { "errors": Array [], "warnings": Array [ Object { - "formatted": " ⚠ Error: test splice\\n │ at packages/rspack-test-tools/tests/errorCases/warning-test-splice-2.js:10:41\\n │ at Hook.eval [as callAsync] (eval at create (node_modules/tapable/lib/HookCodeFactory.js:33:10), :9:1)\\n │ at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (node_modules/tapable/lib/Hook.js:18:14)\\n │ at packages/rspack/dist/Compiler.js:466:41\\n │ at packages/rspack/dist/Compiler.js:533:65\\n", "message": " ⚠ Error: test splice\\n │ at packages/rspack-test-tools/tests/errorCases/warning-test-splice-2.js:10:41\\n │ at Hook.eval [as callAsync] (eval at create (node_modules/tapable/lib/HookCodeFactory.js:33:10), :9:1)\\n │ at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (node_modules/tapable/lib/Hook.js:18:14)\\n │ at packages/rspack/dist/Compiler.js:466:41\\n │ at packages/rspack/dist/Compiler.js:533:65\\n", }, Object { - "formatted": " ⚠ Module parse warning:\\n ╰─▶ ⚠ Module parse failed: require.main.require() is not supported by Rspack.\\n ╭────\\n 1 │ require.main.require('./file');\\n · ──────────────────────────────\\n ╰────\\n \\n", "message": " ⚠ Module parse warning:\\n ╰─▶ ⚠ Module parse failed: require.main.require() is not supported by Rspack.\\n ╭────\\n 1 │ require.main.require('./file');\\n · ──────────────────────────────\\n ╰────\\n \\n", "moduleId": "./require.main.require.js", "moduleIdentifier": "packages/rspack-test-tools/tests/fixtures/errors/require.main.require.js", diff --git a/packages/rspack/etc/api.md b/packages/rspack/etc/api.md index ecfb427ec69..5e0d2845148 100644 --- a/packages/rspack/etc/api.md +++ b/packages/rspack/etc/api.md @@ -35,7 +35,6 @@ import { JsModule } from '@rspack/binding'; import { JsPathData } from '@rspack/binding'; import type { JsRuntimeModule } from '@rspack/binding'; import { JsStats } from '@rspack/binding'; -import type { JsStatsChunk } from '@rspack/binding'; import { JsStatsError } from '@rspack/binding'; import { JsStatsWarning } from '@rspack/binding'; import { libCacheFacade } from './lib/CacheFacade'; @@ -957,21 +956,19 @@ export class Compilation { // @internal __internal__deleteAssetSource(filename: string): void; // @internal - __internal__findJsModule(identifier: string, modules: Map): JsModule | undefined; - // @internal __internal__getAssetFilenames(): string[]; // @internal __internal__getAssetSource(filename: string): Source | void; // @internal - __internal__getAssociatedModules(chunk: JsStatsChunk): any[] | undefined; - // @internal __internal__getChunks(): Chunk[]; // @internal __internal__getModules(): JsModule[]; // @internal __internal__hasAsset(name: string): boolean; - // (undocumented) - __internal__pushNativeDiagnostics(diagnostics: ExternalObject): void; + // @internal + __internal__pushDiagnostic(severity: "error" | "warning", title: string, message: string): void; + // @internal + __internal__pushNativeDiagnostics(diagnostics: ExternalObject<"Diagnostic[]">): void; // @internal __internal__setAssetSource(filename: string, source: Source): void; // (undocumented) @@ -1022,7 +1019,7 @@ export class Compilation { endTime?: number; get entrypoints(): ReadonlyMap; // (undocumented) - get errors(): any; + get errors(): JsStatsError[]; // (undocumented) fileDependencies: { [Symbol.iterator](): Generator; @@ -1037,12 +1034,12 @@ export class Compilation { // (undocumented) get fullHash(): string | null; // (undocumented) - getAsset(name: string): Asset | void; + getAsset(name: string): Readonly | void; // (undocumented) getAssetPath(filename: Filename, data?: PathData): string; // (undocumented) getAssetPathWithInfo(filename: Filename, data?: PathData): PathWithInfo; - getAssets(): Readonly[]; + getAssets(): ReadonlyArray; // (undocumented) getCache(name: string): libCacheFacade; // (undocumented) @@ -1140,8 +1137,6 @@ export class Compilation { // (undocumented) static PROCESS_ASSETS_STAGE_SUMMARIZE: number; // (undocumented) - pushDiagnostic(severity: "error" | "warning", title: string, message: string): void; - // (undocumented) rebuildModule(m: Module, f: (err: Error, m: Module) => void): void; // (undocumented) _rebuildModuleCaller: MergeCaller<[string, (err: Error, m: Module) => void]>; diff --git a/packages/rspack/src/Compilation.ts b/packages/rspack/src/Compilation.ts index 7e2d3350cca..cbf7faf09ea 100644 --- a/packages/rspack/src/Compilation.ts +++ b/packages/rspack/src/Compilation.ts @@ -13,15 +13,14 @@ import { Source } from "webpack-sources"; import type { ExternalObject, JsAssetInfo, - JsChunk, JsCompatSource, JsCompilation, JsModule, JsRuntimeModule, - JsStatsChunk, JsStatsError, JsPathData, - JsStatsWarning + JsStatsWarning, + JsDiagnostic } from "@rspack/binding"; import { @@ -35,7 +34,6 @@ import { import * as liteTapable from "./lite-tapable"; import { ContextModuleFactory } from "./ContextModuleFactory"; import ResolverFactory = require("./ResolverFactory"); -import { ChunkGroup } from "./ChunkGroup"; import { Compiler } from "./Compiler"; import ErrorHelpers from "./ErrorHelpers"; import { LogType, Logger } from "./logging/Logger"; @@ -49,8 +47,8 @@ import { } from "./Stats"; import { StatsFactory } from "./stats/StatsFactory"; import { StatsPrinter } from "./stats/StatsPrinter"; -import { concatErrorMsgAndStack, isJsStatsError, toJsAssetInfo } from "./util"; -import { createRawFromSource, createSourceFromRaw } from "./util/createSource"; +import { concatErrorMsgAndStack, toJsAssetInfo } from "./util"; +import { JsSource } from "./util/source"; import { createFakeCompilationDependencies } from "./util/fake"; import MergeCaller from "./util/MergeCaller"; import { memoizeValue } from "./util/memoize"; @@ -104,6 +102,7 @@ type CreateStatsOptionsContext = KnownCreateStatsOptionsContext & export class Compilation { #inner: JsCompilation; + #cachedAssets: Record; hooks: { processAssets: liteTapable.AsyncSeriesHook; @@ -134,17 +133,18 @@ export class Compilation { runtimeModule: liteTapable.SyncHook<[JsRuntimeModule, Chunk], void>; afterSeal: liteTapable.AsyncSeriesHook<[], void>; }; - options: RspackOptionsNormalized; - outputOptions: OutputNormalized; + name?: string; + startTime?: number; + endTime?: number; compiler: Compiler; + resolverFactory: ResolverFactory; inputFileSystem: any; + options: RspackOptionsNormalized; + outputOptions: OutputNormalized; logging: Map; - name?: string; - childrenCounters: Record = {}; - startTime?: number; - endTime?: number; - children: Compilation[] = []; + childrenCounters: Record; + children: Compilation[]; chunkGraph: ChunkGraph; fileSystemInfo = { createSnapshot() { @@ -154,14 +154,12 @@ export class Compilation { }; constructor(compiler: Compiler, inner: JsCompilation) { - this.name = undefined; - this.startTime = undefined; - this.endTime = undefined; + this.#inner = inner; + this.#cachedAssets = this.#createCachedAssets(); const processAssetsHook = new liteTapable.AsyncSeriesHook([ "assets" ]); - const createProcessAssetsHook = ( name: string, stage: number, @@ -246,9 +244,9 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si this.options = compiler.options; this.outputOptions = compiler.options.output; this.logging = new Map(); + this.childrenCounters = {}; + this.children = []; this.chunkGraph = new ChunkGraph(this); - this.#inner = inner; - // Cache the current NormalModuleHooks } get currentNormalModuleHooks() { @@ -265,10 +263,55 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si /** * Get a map of all assets. - * - * Source: [assets](https://github.com/webpack/webpack/blob/9fcaa243573005d6fdece9a3f8d89a0e8b399613/lib/Compilation.js#L1008-L1009) */ get assets(): Record { + return this.#cachedAssets; + } + + /** + * Get a map of all entrypoints. + */ + get entrypoints(): ReadonlyMap { + return new Map( + Object.entries(this.#inner.entrypoints).map(([n, e]) => [ + n, + Entrypoint.__from_binding(e, this.#inner) + ]) + ); + } + + get modules() { + return memoizeValue(() => { + return this.__internal__getModules().map(item => + Module.__from_binding(item) + ); + }); + } + + // FIXME: Webpack returns a `Set` + get chunks() { + return memoizeValue(() => { + return this.__internal__getChunks(); + }); + } + + /** + * Get the named chunks. + * + * Note: This is a proxy for webpack internal API, only method `get` is supported now. + */ + get namedChunks(): Map> { + return { + get: (property: unknown) => { + if (typeof property === "string") { + const chunk = this.#inner.getNamedChunk(property) || undefined; + return chunk && Chunk.__from_binding(chunk, this.#inner); + } + } + } as Map>; + } + + #createCachedAssets() { return new Proxy( {}, { @@ -277,14 +320,14 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si return this.__internal__getAssetSource(property); } }, - set: (target, p, newValue, receiver) => { + set: (_, p, newValue) => { if (typeof p === "string") { this.__internal__setAssetSource(p, newValue); return true; } return false; }, - deleteProperty: (target, p) => { + deleteProperty: (_, p) => { if (typeof p === "string") { this.__internal__deleteAssetSource(p); return true; @@ -312,18 +355,6 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si ); } - /** - * Get a map of all entrypoints. - */ - get entrypoints(): ReadonlyMap { - return new Map( - Object.entries(this.#inner.entrypoints).map(([n, e]) => [ - n, - Entrypoint.__from_binding(e, this.#inner) - ]) - ); - } - getCache(name: string) { return this.compiler.getCache(name); } @@ -445,9 +476,6 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si /** * Update an existing asset. Trying to update an asset that doesn't exist will throw an error. * - * See: [Compilation.updateAsset](https://webpack.js.org/api/compilation-object/#updateasset) - * Source: [updateAsset](https://github.com/webpack/webpack/blob/9fcaa243573005d6fdece9a3f8d89a0e8b399613/lib/Compilation.js#L4320) - * * FIXME: *AssetInfo* may be undefined in update fn for webpack impl, but still not implemented in rspack */ updateAsset( @@ -465,12 +493,12 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si compatNewSourceOrFunction = function newSourceFunction( source: JsCompatSource ) { - return createRawFromSource( - newSourceOrFunction(createSourceFromRaw(source)) + return JsSource.__to_binding( + newSourceOrFunction(JsSource.__from_binding(source)) ); }; } else { - compatNewSourceOrFunction = createRawFromSource(newSourceOrFunction); + compatNewSourceOrFunction = JsSource.__to_binding(newSourceOrFunction); } this.#inner.updateAsset( @@ -487,9 +515,6 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si /** * Emit an not existing asset. Trying to emit an asset that already exists will throw an error. * - * See: [Compilation.emitAsset](https://webpack.js.org/api/compilation-object/#emitasset) - * Source: [emitAsset](https://github.com/webpack/webpack/blob/9fcaa243573005d6fdece9a3f8d89a0e8b399613/lib/Compilation.js#L4239) - * * @param file - file name * @param source - asset source * @param assetInfo - extra asset information @@ -497,7 +522,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si emitAsset(filename: string, source: Source, assetInfo?: AssetInfo) { this.#inner.emitAsset( filename, - createRawFromSource(source), + JsSource.__to_binding(source), toJsAssetInfo(assetInfo) ); } @@ -512,11 +537,8 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si /** * Get an array of Asset - * - * See: [Compilation.getAssets](https://webpack.js.org/api/compilation-object/#getassets) - * Source: [getAssets](https://github.com/webpack/webpack/blob/9fcaa243573005d6fdece9a3f8d89a0e8b399613/lib/Compilation.js#L4448) */ - getAssets(): Readonly[] { + getAssets(): ReadonlyArray { const assets = this.#inner.getAssets(); return assets.map(asset => { @@ -526,7 +548,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si }); } - getAsset(name: string): Asset | void { + getAsset(name: string): Readonly | void { const asset = this.#inner.getAsset(name); if (!asset) { return; @@ -536,7 +558,12 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si }) as Asset; } - pushDiagnostic( + /** + * Note: This is not a webpack public API, maybe removed in future. + * + * @internal + */ + __internal__pushDiagnostic( severity: "error" | "warning", title: string, message: string @@ -544,14 +571,21 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si this.#inner.pushDiagnostic(severity, title, message); } - __internal__pushNativeDiagnostics(diagnostics: ExternalObject) { + /** + * Note: This is not a webpack public API, maybe removed in future. + * + * @internal + */ + __internal__pushNativeDiagnostics( + diagnostics: ExternalObject<"Diagnostic[]"> + ) { this.#inner.pushNativeDiagnostics(diagnostics); } - get errors() { + get errors(): JsStatsError[] { const inner = this.#inner; type ErrorType = Error | JsStatsError | string; - const errors = inner.getStats().getErrors() as any; + const errors = inner.getStats().getErrors(); const proxyMethod = [ { method: "push", @@ -562,21 +596,11 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si ) { for (let i = 0; i < errs.length; i++) { const error = errs[i]; - if (isJsStatsError(error)) { - inner.pushDiagnostic( - "error", - "Error", - concatErrorMsgAndStack(error) - ); - } else if (typeof error === "string") { - inner.pushDiagnostic("error", "Error", error); - } else { - inner.pushDiagnostic( - "error", - error.name, - concatErrorMsgAndStack(error) - ); - } + inner.pushDiagnostic( + "error", + error instanceof Error ? error.name : "Error", + concatErrorMsgAndStack(error) + ); } return Reflect.apply(target, thisArg, errs); } @@ -606,25 +630,11 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si errs: ErrorType[] ) { const errList = errs.map(error => { - if (isJsStatsError(error)) { - return { - severity: "error" as const, - title: "Error", - message: concatErrorMsgAndStack(error) - }; - } else if (typeof error === "string") { - return { - severity: "error" as const, - title: "Error", - message: error - }; - } else { - return { - severity: "error" as const, - title: error.name, - message: concatErrorMsgAndStack(error) - }; - } + return { + severity: "error", + title: error instanceof Error ? error.name : "Error", + message: concatErrorMsgAndStack(error) + } satisfies JsDiagnostic; }); inner.spliceDiagnostic(0, 0, errList); return Reflect.apply(target, thisArg, errs); @@ -638,25 +648,11 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si [startIdx, delCount, ...errors]: [number, number, ...ErrorType[]] ) { const errList = errors.map(error => { - if (isJsStatsError(error)) { - return { - severity: "error" as const, - title: "Error", - message: concatErrorMsgAndStack(error) - }; - } else if (typeof error === "string") { - return { - severity: "error" as const, - title: "Error", - message: error - }; - } else { - return { - severity: "error" as const, - title: error.name, - message: concatErrorMsgAndStack(error) - }; - } + return { + severity: "error", + title: error instanceof Error ? error.name : "Error", + message: concatErrorMsgAndStack(error) + } satisfies JsDiagnostic; }); inner.spliceDiagnostic(startIdx, startIdx + delCount, errList); return Reflect.apply(target, thisArg, [ @@ -676,7 +672,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si return errors; } - get warnings() { + get warnings(): JsStatsWarning[] { const inner = this.#inner; type WarnType = Error | JsStatsWarning; const processWarningsHook = this.hooks.processWarnings; @@ -694,7 +690,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si const warn = warns[i]; inner.pushDiagnostic( "warning", - isJsStatsError(warn) ? "Warning" : warn.name, + warn instanceof Error ? warn.name : "Warning", concatErrorMsgAndStack(warn) ); } @@ -728,10 +724,10 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si warns = processWarningsHook.call(warns as any); const warnList = warns.map(warn => { return { - severity: "warning" as const, - title: isJsStatsError(warn) ? "Warning" : warn.name, + severity: "warning", + title: warn instanceof Error ? warn.name : "Warning", message: concatErrorMsgAndStack(warn) - }; + } satisfies JsDiagnostic; }); inner.spliceDiagnostic(0, 0, warnList); return Reflect.apply(target, thisArg, warns); @@ -747,10 +743,10 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si warns = processWarningsHook.call(warns as any); const warnList = warns.map(warn => { return { - severity: "warning" as const, - title: isJsStatsError(warn) ? "Warning" : warn.name, + severity: "warning", + title: warn instanceof Error ? warn.name : "Warning", message: concatErrorMsgAndStack(warn) - }; + } satisfies JsDiagnostic; }); inner.spliceDiagnostic(startIdx, startIdx + delCount, warnList); return Reflect.apply(target, thisArg, [ @@ -915,107 +911,6 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si d => this.#inner.addBuildDependencies(d) ); - get modules() { - return memoizeValue(() => { - return this.__internal__getModules().map(item => - Module.__from_binding(item) - ); - }); - } - - // FIXME: This is not aligned with Webpack. - get chunks() { - return memoizeValue(() => { - return this.__internal__getChunks(); - }); - } - - /** - * Get the named chunks. - * - * Note: This is a proxy for webpack internal API, only method `get` is supported now. - */ - get namedChunks(): Map> { - return { - get: (property: unknown) => { - if (typeof property === "string") { - const chunk = this.#inner.getNamedChunk(property); - return chunk && Chunk.__from_binding(chunk, this.#inner); - } - } - } as Map>; - } - - /** - * Get the associated `modules` of an given chunk. - * - * Note: This is not a webpack public API, maybe removed in future. - * - * @internal - */ - __internal__getAssociatedModules(chunk: JsStatsChunk): any[] | undefined { - const modules = this.__internal__getModules(); - const moduleMap: Map = new Map(); - for (const module of modules) { - moduleMap.set(module.moduleIdentifier, module); - } - return chunk.modules?.flatMap(chunkModule => { - const jsModule = this.__internal__findJsModule( - chunkModule.issuer ?? chunkModule.identifier, - moduleMap - ); - return { - ...jsModule - // dependencies: chunkModule.reasons?.flatMap(jsReason => { - // let jsOriginModule = this.__internal__findJsModule( - // jsReason.moduleIdentifier ?? "", - // moduleMap - // ); - // return { - // ...jsReason, - // originModule: jsOriginModule - // }; - // }) - }; - }); - } - - /** - * Find a modules in an array. - * - * Note: This is not a webpack public API, maybe removed in future. - * - * @internal - */ - __internal__findJsModule( - identifier: string, - modules: Map - ): JsModule | undefined { - return modules.get(identifier); - } - - /** - * - * Note: This is not a webpack public API, maybe removed in future. - * - * @internal - */ - __internal__getModules(): JsModule[] { - return this.#inner.getModules(); - } - - /** - * - * Note: This is not a webpack public API, maybe removed in future. - * - * @internal - */ - __internal__getChunks(): Chunk[] { - return this.#inner - .getChunks() - .map(c => Chunk.__from_binding(c, this.#inner)); - } - getStats() { return new Stats(this); } @@ -1054,6 +949,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si }, 10 ); + rebuildModule(m: Module, f: (err: Error, m: Module) => void) { this._rebuildModuleCaller.push([m.identifier(), f]); } @@ -1070,7 +966,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si if (!rawSource) { return; } - return createSourceFromRaw(rawSource); + return JsSource.__from_binding(rawSource); } /** @@ -1081,7 +977,7 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si * @internal */ __internal__setAssetSource(filename: string, source: Source) { - this.#inner.setAssetSource(filename, createRawFromSource(source)); + this.#inner.setAssetSource(filename, JsSource.__to_binding(source)); } /** @@ -1117,6 +1013,26 @@ BREAKING CHANGE: Asset processing hooks in Compilation has been merged into a si return this.#inner.hasAsset(name); } + /** + * Note: This is not a webpack public API, maybe removed in future. + * + * @internal + */ + __internal__getModules(): JsModule[] { + return this.#inner.getModules(); + } + + /** + * Note: This is not a webpack public API, maybe removed in future. + * + * @internal + */ + __internal__getChunks(): Chunk[] { + return this.#inner + .getChunks() + .map(c => Chunk.__from_binding(c, this.#inner)); + } + __internal_getInner() { return this.#inner; } diff --git a/packages/rspack/src/Module.ts b/packages/rspack/src/Module.ts index 303eee73fc8..67b05badd7b 100644 --- a/packages/rspack/src/Module.ts +++ b/packages/rspack/src/Module.ts @@ -5,7 +5,7 @@ import { JsModule } from "@rspack/binding"; import { Source } from "webpack-sources"; -import { createSourceFromRaw } from "./util/createSource"; +import { JsSource } from "./util/source"; export type ResourceData = { resource: string; @@ -69,7 +69,9 @@ export class Module { get originalSource(): Source | null { if (this._originalSource) return this._originalSource; if (this.#inner.originalSource) { - this._originalSource = createSourceFromRaw(this.#inner.originalSource); + this._originalSource = JsSource.__from_binding( + this.#inner.originalSource + ); return this._originalSource; } else { return null; diff --git a/packages/rspack/src/loader-runner/index.ts b/packages/rspack/src/loader-runner/index.ts index 3edf00fc0f4..d1b6e59b651 100644 --- a/packages/rspack/src/loader-runner/index.ts +++ b/packages/rspack/src/loader-runner/index.ts @@ -470,7 +470,7 @@ export async function runLoaders( const title = "Module Error"; const message = error instanceof Error ? concatErrorMsgAndStack(error) : error; - compiler._lastCompilation!.pushDiagnostic( + compiler._lastCompilation!.__internal__pushDiagnostic( "error", title, `${message}\n(from: ${stringifyLoaderObject( @@ -482,7 +482,7 @@ export async function runLoaders( const title = "Module Warning"; const message = warning instanceof Error ? concatErrorMsgAndStack(warning) : warning; - compiler._lastCompilation!.pushDiagnostic( + compiler._lastCompilation!.__internal__pushDiagnostic( "warning", title, `${message}\n(from: ${stringifyLoaderObject( diff --git a/packages/rspack/src/util/createSource.ts b/packages/rspack/src/util/createSource.ts deleted file mode 100644 index 07900b54d1a..00000000000 --- a/packages/rspack/src/util/createSource.ts +++ /dev/null @@ -1,77 +0,0 @@ -import type { JsCompatSource } from "@rspack/binding"; - -import { RawSource, CompatSource, Source } from "webpack-sources"; -import { isNil } from "./index"; - -function createSourceFromRaw(source: JsCompatSource): Source { - if (source.isRaw) { - return new RawSource( - // @ts-expect-error: webpack-sources can accept buffer as source, see: https://github.com/webpack/webpack-sources/blob/9f98066311d53a153fdc7c633422a1d086528027/lib/RawSource.js#L12 - source.isBuffer ? source.source : source.source.toString("utf-8") - ); - } - - if (!source.map) { - return new RawSource(source.source.toString("utf-8")); - } - - return new CompatSource({ - source() { - return source.source.toString("utf-8"); - }, - buffer() { - return source.source; - }, - map(_) { - if (source.map) { - return JSON.parse(source.map.toString("utf-8")); - } - - return null; - } - }); -} - -function createRawFromSource(source: Source): JsCompatSource { - const sourceSource = source.source(); - const isBuffer = Buffer.isBuffer(sourceSource); - - if (source instanceof RawSource) { - return { - source: source.buffer(), - isRaw: true, - isBuffer - }; - } - - const buffer = - source.buffer?.() ?? - (isBuffer - ? sourceSource - : sourceSource instanceof ArrayBuffer - ? arrayBufferToBuffer(sourceSource) - : Buffer.from(sourceSource)); - const map = JSON.stringify( - source.map?.({ - columns: true - }) - ); - - return { - source: buffer, - map: isNil(map) ? map : Buffer.from(map), - isRaw: false, - isBuffer - }; -} - -function arrayBufferToBuffer(ab: ArrayBuffer) { - const buf = Buffer.alloc(ab.byteLength); - const view = new Uint8Array(ab); - for (let i = 0; i < buf.length; ++i) { - buf[i] = view[i]; - } - return buf; -} - -export { createSourceFromRaw, createRawFromSource }; diff --git a/packages/rspack/src/util/index.ts b/packages/rspack/src/util/index.ts index eb709ae1fa5..5883eaf099d 100644 --- a/packages/rspack/src/util/index.ts +++ b/packages/rspack/src/util/index.ts @@ -70,17 +70,16 @@ export function isJsStatsError(err: any): err is JsStatsError { return !(err instanceof Error) && err.formatted; } -export function concatErrorMsgAndStack(err: Error | JsStatsError): string { - // deduplicate the error if message is already shown in the stack - //@ts-ignore - const stackStartPrefix = err.name ? `${err.name}: ` : "Error: "; - return isJsStatsError(err) - ? err.formatted - : err.stack - ? err.stack.startsWith(`${stackStartPrefix}${err.message}`) - ? `${err.stack}` - : `${err.message}\n${err.stack}` - : `${err.message}`; +export function concatErrorMsgAndStack( + err: Error | JsStatsError | string +): string { + if (typeof err === "string") { + return err; + } + if ("stack" in err) { + return err.stack || err.message; + } + return err.message; } export function indent(str: string, prefix: string) { diff --git a/packages/rspack/src/util/source.ts b/packages/rspack/src/util/source.ts new file mode 100644 index 00000000000..0b596f6abba --- /dev/null +++ b/packages/rspack/src/util/source.ts @@ -0,0 +1,79 @@ +import type { JsCompatSource } from "@rspack/binding"; + +import { RawSource, CompatSource, Source } from "webpack-sources"; +import { isNil } from "./index"; + +class JsSource extends Source { + static __from_binding(source: JsCompatSource): Source { + if (source.isRaw) { + return new RawSource( + // @ts-expect-error: webpack-sources can accept buffer as source, see: https://github.com/webpack/webpack-sources/blob/9f98066311d53a153fdc7c633422a1d086528027/lib/RawSource.js#L12 + source.isBuffer ? source.source : source.source.toString("utf-8") + ); + } + + if (!source.map) { + return new RawSource(source.source.toString("utf-8")); + } + + return new CompatSource({ + source() { + return source.source.toString("utf-8"); + }, + buffer() { + return source.source; + }, + map(_) { + if (source.map) { + return JSON.parse(source.map.toString("utf-8")); + } + + return null; + } + }); + } + + static __to_binding(source: Source) { + const sourceSource = source.source(); + const isBuffer = Buffer.isBuffer(sourceSource); + + if (source instanceof RawSource) { + return { + source: source.buffer(), + isRaw: true, + isBuffer + }; + } + + const buffer = + source.buffer?.() ?? + (isBuffer + ? sourceSource + : sourceSource instanceof ArrayBuffer + ? arrayBufferToBuffer(sourceSource) + : Buffer.from(sourceSource)); + const map = JSON.stringify( + source.map?.({ + columns: true + }) + ); + + return { + source: buffer, + map: isNil(map) ? map : Buffer.from(map), + isRaw: false, + isBuffer + }; + } +} + +function arrayBufferToBuffer(ab: ArrayBuffer) { + const buf = Buffer.alloc(ab.byteLength); + const view = new Uint8Array(ab); + for (let i = 0; i < buf.length; ++i) { + buf[i] = view[i]; + } + return buf; +} + +export { JsSource };