@rsdoctor/webpack-plugin 0.0.2-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-present Bytedance, Inc. and its affiliates.
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 all
13
+ 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 THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,15 @@
1
+ # Rsdoctor
2
+
3
+ Rsdoctor is a tool for diagnosing and analyzing the build process and build artifacts to help developers quickly identify and solve problems.
4
+
5
+ It also supports Webpack and Rspack builders, as well as various build frameworks, such as Rsbuild.
6
+
7
+ ## Documentation
8
+
9
+ ## Contributing
10
+
11
+ Please read the [Contributing Guide](https://github.com/web-infra-dev/rsdoctor/blob/main/CONTRIBUTING.md).
12
+
13
+ ## License
14
+
15
+ Rsdoctor is [MIT licensed](https://github.com/web-infra-dev/rsdoctor/blob/main/LICENSE).
@@ -0,0 +1,6 @@
1
+ import type { Tap } from 'tapable';
2
+ export declare const pluginTapName = "DoctorWebpackPlugin";
3
+ export declare const pluginTapPostOptions: Tap;
4
+ export declare const pluginTapPreOptions: Tap;
5
+ export declare const internalPluginTapPreOptions: (namespace: string) => Tap;
6
+ export declare const internalPluginTapPostOptions: (namespace: string) => Tap;
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var constants_exports = {};
20
+ __export(constants_exports, {
21
+ internalPluginTapPostOptions: () => internalPluginTapPostOptions,
22
+ internalPluginTapPreOptions: () => internalPluginTapPreOptions,
23
+ pluginTapName: () => pluginTapName,
24
+ pluginTapPostOptions: () => pluginTapPostOptions,
25
+ pluginTapPreOptions: () => pluginTapPreOptions
26
+ });
27
+ module.exports = __toCommonJS(constants_exports);
28
+ const pluginTapName = "DoctorWebpackPlugin";
29
+ const pluginTapPostOptions = {
30
+ name: pluginTapName,
31
+ stage: 999
32
+ };
33
+ const pluginTapPreOptions = {
34
+ name: pluginTapName,
35
+ stage: -999
36
+ };
37
+ const internalPluginTapPreOptions = (namespace) => ({
38
+ name: `${pluginTapName}:${namespace}`,
39
+ stage: -998
40
+ });
41
+ const internalPluginTapPostOptions = (namespace) => ({
42
+ name: `${pluginTapName}:${namespace}`,
43
+ stage: 1e3
44
+ });
45
+ // Annotate the CommonJS export names for ESM import in node:
46
+ 0 && (module.exports = {
47
+ internalPluginTapPostOptions,
48
+ internalPluginTapPreOptions,
49
+ pluginTapName,
50
+ pluginTapPostOptions,
51
+ pluginTapPreOptions
52
+ });
@@ -0,0 +1,4 @@
1
+ export * from './plugin';
2
+ export * from './multiple';
3
+ export * from './plugins/bundle';
4
+ export { defineRule, LinterType } from '@rsdoctor/core/rules';
package/dist/index.js ADDED
@@ -0,0 +1,37 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __reExport = (target, mod, secondTarget) => (__copyProps(target, mod, "default"), secondTarget && __copyProps(secondTarget, mod, "default"));
19
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var src_exports = {};
21
+ __export(src_exports, {
22
+ LinterType: () => import_rules.LinterType,
23
+ defineRule: () => import_rules.defineRule
24
+ });
25
+ module.exports = __toCommonJS(src_exports);
26
+ __reExport(src_exports, require("./plugin"), module.exports);
27
+ __reExport(src_exports, require("./multiple"), module.exports);
28
+ __reExport(src_exports, require("./plugins/bundle"), module.exports);
29
+ var import_rules = require("@rsdoctor/core/rules");
30
+ // Annotate the CommonJS export names for ESM import in node:
31
+ 0 && (module.exports = {
32
+ LinterType,
33
+ defineRule,
34
+ ...require("./plugin"),
35
+ ...require("./multiple"),
36
+ ...require("./plugins/bundle")
37
+ });
@@ -0,0 +1,7 @@
1
+ import { Linter } from '@rsdoctor/types';
2
+ import type { DoctorWebpackMultiplePluginOptions } from '@rsdoctor/core';
3
+ import { RsdoctorWebpackPlugin } from './plugin';
4
+ export declare class RsdoctorWebpackMultiplePlugin<Rules extends Linter.ExtendRuleData[]> extends RsdoctorWebpackPlugin<Rules> {
5
+ private controller;
6
+ constructor(options?: DoctorWebpackMultiplePluginOptions<Rules>);
7
+ }
@@ -0,0 +1,52 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var multiple_exports = {};
20
+ __export(multiple_exports, {
21
+ RsdoctorWebpackMultiplePlugin: () => RsdoctorWebpackMultiplePlugin
22
+ });
23
+ module.exports = __toCommonJS(multiple_exports);
24
+ var import_sdk = require("@rsdoctor/sdk");
25
+ var import_plugin = require("./plugin");
26
+ let globalController;
27
+ class RsdoctorWebpackMultiplePlugin extends import_plugin.RsdoctorWebpackPlugin {
28
+ constructor(options = {}) {
29
+ const controller = (() => {
30
+ if (globalController) {
31
+ return globalController;
32
+ }
33
+ const controller2 = new import_sdk.DoctorSDKController();
34
+ globalController = controller2;
35
+ return controller2;
36
+ })();
37
+ const instance = controller.createSlave({
38
+ name: options.name || "Builder",
39
+ stage: options.stage,
40
+ extraConfig: { disableTOSUpload: options.disableTOSUpload || false }
41
+ });
42
+ super({
43
+ ...options,
44
+ sdkInstance: instance
45
+ });
46
+ this.controller = controller;
47
+ }
48
+ }
49
+ // Annotate the CommonJS export names for ESM import in node:
50
+ 0 && (module.exports = {
51
+ RsdoctorWebpackMultiplePlugin
52
+ });
@@ -0,0 +1,38 @@
1
+ import type { DoctorPluginInstance, DoctorPluginOptionsNormalized, DoctorWebpackPluginOptions } from '@rsdoctor/core/types';
2
+ import { ChunkGraph, ModuleGraph } from '@rsdoctor/graph';
3
+ import { DoctorWebpackSDK } from '@rsdoctor/sdk';
4
+ import { Linter } from '@rsdoctor/types';
5
+ import { Compiler, StatsCompilation } from 'webpack';
6
+ export declare class RsdoctorWebpackPlugin<Rules extends Linter.ExtendRuleData[]> implements DoctorPluginInstance<Compiler, Rules> {
7
+ readonly name = "DoctorWebpackPlugin";
8
+ readonly options: DoctorPluginOptionsNormalized<Rules>;
9
+ readonly sdk: DoctorWebpackSDK;
10
+ modulesGraph: ModuleGraph;
11
+ private outsideInstance;
12
+ _bootstrapTask: Promise<unknown>;
13
+ protected browserIsOpened: boolean;
14
+ chunkGraph: ChunkGraph;
15
+ constructor(options?: DoctorWebpackPluginOptions<Rules>);
16
+ apply(compiler: unknown): unknown;
17
+ afterPlugins: (compiler: Compiler) => void;
18
+ beforeRun: (compiler: Compiler) => Promise<void>;
19
+ private _modulesGraphApplied;
20
+ /**
21
+ * @description Generate ModuleGraph and ChunkGraph from stats and webpack module apis;
22
+ * @param {Compiler} compiler
23
+ * @return {*}
24
+ * @memberof DoctorWebpackPlugin
25
+ */
26
+ ensureModulesChunksGraphApplied(compiler: Compiler): void;
27
+ done: () => Promise<void>;
28
+ /**
29
+ * @protected
30
+ * @description This function to get module parsed code and size;
31
+ * @param {Compiler} compiler
32
+ * @param {StatsCompilation} stats
33
+ * @param {ModuleGraph} moduleGraph
34
+ * @return {*}
35
+ * @memberof DoctorWebpackPlugin
36
+ */
37
+ protected getModulesInfosByStats(compiler: Compiler, stats: StatsCompilation, moduleGraph: ModuleGraph): Promise<void>;
38
+ }
package/dist/plugin.js ADDED
@@ -0,0 +1,252 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var plugin_exports = {};
30
+ __export(plugin_exports, {
31
+ RsdoctorWebpackPlugin: () => RsdoctorWebpackPlugin
32
+ });
33
+ module.exports = __toCommonJS(plugin_exports);
34
+ var import_build_utils = require("@rsdoctor/core/build-utils");
35
+ var import_common_utils = require("@rsdoctor/core/common-utils");
36
+ var import_plugins = require("@rsdoctor/core/plugins");
37
+ var import_graph = require("@rsdoctor/graph");
38
+ var import_sdk = require("@rsdoctor/sdk");
39
+ var import_types = require("@rsdoctor/types");
40
+ var import_build = require("@rsdoctor/utils/build");
41
+ var import_logger = require("@rsdoctor/utils/logger");
42
+ var import_fs_extra = __toESM(require("fs-extra"));
43
+ var import_lodash = require("lodash");
44
+ var import_path = __toESM(require("path"));
45
+ var import_constants = require("./constants");
46
+ var import_bundle = require("./plugins/bundle");
47
+ var import_resolver = require("./plugins/resolver");
48
+ var import_rules = require("./plugins/rules");
49
+ class RsdoctorWebpackPlugin {
50
+ constructor(options) {
51
+ this.name = import_constants.pluginTapName;
52
+ this.outsideInstance = false;
53
+ this.browserIsOpened = false;
54
+ this.afterPlugins = (compiler) => {
55
+ if (compiler.isChild())
56
+ return;
57
+ const { plugins, infrastructureLogging, ...rest } = compiler.options;
58
+ const _rest = (0, import_lodash.cloneDeep)(rest);
59
+ (0, import_plugins.makeRulesSerializable)(_rest.module.defaultRules);
60
+ (0, import_plugins.makeRulesSerializable)(_rest.module.rules);
61
+ const configuration = {
62
+ ..._rest,
63
+ plugins: plugins.map((e) => e?.constructor.name)
64
+ };
65
+ this.sdk.reportConfiguration({
66
+ name: "webpack",
67
+ version: compiler.webpack?.version || "unknown",
68
+ config: configuration
69
+ });
70
+ this.sdk.setOutputDir(
71
+ import_path.default.resolve(compiler.outputPath, `./${import_types.Constants.DoctorOutputFolder}`)
72
+ );
73
+ if (configuration.name) {
74
+ this.sdk.setName(configuration.name);
75
+ }
76
+ };
77
+ this.beforeRun = async (compiler) => {
78
+ if (compiler.isChild())
79
+ return;
80
+ await this._bootstrapTask.then(() => {
81
+ if (!this.options.disableClientServer && !this.browserIsOpened) {
82
+ this.browserIsOpened = true;
83
+ this.sdk.server.openClientPage();
84
+ }
85
+ });
86
+ };
87
+ this._modulesGraphApplied = false;
88
+ this.done = async () => {
89
+ try {
90
+ this.sdk.server.broadcast();
91
+ (0, import_logger.debug)(import_build.Process.getMemoryUsageMessage, "[Before Write Manifest]");
92
+ await this.sdk.writeStore();
93
+ (0, import_logger.debug)(import_build.Process.getMemoryUsageMessage, "[After Write Manifest]");
94
+ if (this.options.disableClientServer) {
95
+ await this.sdk.dispose();
96
+ (0, import_logger.debug)(import_build.Process.getMemoryUsageMessage, "[After SDK Dispose]");
97
+ }
98
+ } catch (e) {
99
+ }
100
+ };
101
+ this.options = (0, import_plugins.normalizeUserConfig)(options);
102
+ this.sdk = this.options.sdkInstance ?? new import_sdk.DoctorWebpackSDK({
103
+ name: import_constants.pluginTapName,
104
+ root: process.cwd(),
105
+ type: this.options.reportCodeType,
106
+ config: { disableTOSUpload: this.options.disableTOSUpload }
107
+ });
108
+ this.outsideInstance = Boolean(this.options.sdkInstance);
109
+ this.modulesGraph = new import_graph.ModuleGraph();
110
+ this.chunkGraph = new import_graph.ChunkGraph();
111
+ }
112
+ apply(compiler) {
113
+ if (!this._bootstrapTask) {
114
+ this._bootstrapTask = this.sdk.bootstrap();
115
+ }
116
+ if (!this.outsideInstance) {
117
+ (0, import_plugins.setSDK)(this.sdk);
118
+ }
119
+ new import_plugins.InternalSummaryPlugin(this).apply(compiler);
120
+ if (this.options.features.loader) {
121
+ new import_plugins.InternalLoaderPlugin(this).apply(compiler);
122
+ }
123
+ if (this.options.features.resolver) {
124
+ new import_resolver.InternalResolverPlugin(this).apply(compiler);
125
+ }
126
+ if (this.options.features.plugins) {
127
+ new import_plugins.InternalPluginsPlugin(this).apply(compiler);
128
+ }
129
+ if (this.options.features.bundle) {
130
+ new import_bundle.InternalBundlePlugin(this).apply(compiler);
131
+ }
132
+ new import_plugins.InternalErrorReporterPlugin(this).apply(compiler);
133
+ new import_rules.InternalRulesPlugin(this).apply(compiler);
134
+ new import_plugins.InternalProgressPlugin(this).apply(compiler);
135
+ compiler.hooks.afterPlugins.tap(import_constants.pluginTapPostOptions, this.afterPlugins);
136
+ compiler.hooks.watchRun.tapPromise(import_constants.pluginTapPostOptions, this.beforeRun);
137
+ compiler.hooks.beforeRun.tapPromise(import_constants.pluginTapPostOptions, this.beforeRun);
138
+ compiler.hooks.done.tapPromise(
139
+ {
140
+ ...import_constants.pluginTapPostOptions,
141
+ stage: import_constants.pluginTapPostOptions.stage + 100
142
+ },
143
+ this.done.bind(this)
144
+ );
145
+ }
146
+ /**
147
+ * @description Generate ModuleGraph and ChunkGraph from stats and webpack module apis;
148
+ * @param {Compiler} compiler
149
+ * @return {*}
150
+ * @memberof DoctorWebpackPlugin
151
+ */
152
+ ensureModulesChunksGraphApplied(compiler) {
153
+ if (this._modulesGraphApplied)
154
+ return;
155
+ this._modulesGraphApplied = true;
156
+ const context = {
157
+ astCache: /* @__PURE__ */ new Map(),
158
+ packagePathMap: /* @__PURE__ */ new Map(),
159
+ getSourceMap: (file) => {
160
+ return this.sdk.getSourceMap(file);
161
+ }
162
+ };
163
+ compiler.hooks.normalModuleFactory.tap(
164
+ (0, import_constants.internalPluginTapPostOptions)("moduleGraph"),
165
+ (factory) => {
166
+ const record = (parser) => {
167
+ parser.hooks.program.tap(import_constants.pluginTapPreOptions, (ast) => {
168
+ context.astCache.set(parser.state.current, ast);
169
+ });
170
+ };
171
+ factory.hooks.parser.for("javascript/auto").tap(import_constants.pluginTapPostOptions, record);
172
+ factory.hooks.parser.for("javascript/dynamic").tap(import_constants.pluginTapPostOptions, record);
173
+ factory.hooks.parser.for("javascript/esm").tap(import_constants.pluginTapPostOptions, record);
174
+ }
175
+ );
176
+ compiler.hooks.done.tapPromise(
177
+ (0, import_constants.internalPluginTapPreOptions)("moduleGraph"),
178
+ async (stats) => {
179
+ const statsJson = stats.toJson();
180
+ (0, import_logger.debug)(import_build.Process.getMemoryUsageMessage, "[Before Generate ModuleGraph]");
181
+ this.chunkGraph = import_build_utils.Chunks.chunkTransform(/* @__PURE__ */ new Map(), statsJson);
182
+ this.modulesGraph = await import_build_utils.ModuleGraph.getModuleGraphByStats(
183
+ stats.compilation,
184
+ statsJson,
185
+ process.cwd(),
186
+ this.chunkGraph,
187
+ this.options.features,
188
+ context
189
+ );
190
+ (0, import_logger.debug)(import_build.Process.getMemoryUsageMessage, "[After Generate ModuleGraph]");
191
+ if (this.options.features.treeShaking) {
192
+ this.modulesGraph = import_build_utils.ModuleGraph.appendTreeShaking(
193
+ this.modulesGraph,
194
+ stats.compilation
195
+ );
196
+ this.sdk.addClientRoutes([
197
+ import_types.Manifest.DoctorManifestClientRoutes.TreeShaking
198
+ ]);
199
+ (0, import_logger.debug)(
200
+ import_build.Process.getMemoryUsageMessage,
201
+ "[After AppendTreeShaking to ModuleGraph]"
202
+ );
203
+ }
204
+ await this.getModulesInfosByStats(
205
+ compiler,
206
+ statsJson,
207
+ this.modulesGraph
208
+ );
209
+ (0, import_logger.debug)(import_build.Process.getMemoryUsageMessage, "[After Transform ModuleGraph]");
210
+ this.modulesGraph && await this.sdk.reportModuleGraph(this.modulesGraph);
211
+ await this.sdk.reportChunkGraph(this.chunkGraph);
212
+ const reportFilePath = await import_build_utils.Chunks.generateTileGraph(
213
+ statsJson,
214
+ {
215
+ reportFilename: import_build_utils.Chunks.TileGraphReportName,
216
+ reportTitle: "bundle-analyzer"
217
+ },
218
+ compiler.outputPath
219
+ );
220
+ reportFilePath && await this.sdk.reportTileHtml(
221
+ import_fs_extra.default.readFileSync(reportFilePath, "utf-8")
222
+ );
223
+ }
224
+ );
225
+ }
226
+ /**
227
+ * @protected
228
+ * @description This function to get module parsed code and size;
229
+ * @param {Compiler} compiler
230
+ * @param {StatsCompilation} stats
231
+ * @param {ModuleGraph} moduleGraph
232
+ * @return {*}
233
+ * @memberof DoctorWebpackPlugin
234
+ */
235
+ async getModulesInfosByStats(compiler, stats, moduleGraph) {
236
+ if (!moduleGraph) {
237
+ return;
238
+ }
239
+ try {
240
+ const parsedModulesData = await import_build_utils.Chunks.getAssetsModulesData(
241
+ stats,
242
+ compiler.outputPath
243
+ ) || {};
244
+ import_common_utils.Chunks.transformAssetsModulesData(parsedModulesData, moduleGraph);
245
+ } catch (e) {
246
+ }
247
+ }
248
+ }
249
+ // Annotate the CommonJS export names for ESM import in node:
250
+ 0 && (module.exports = {
251
+ RsdoctorWebpackPlugin
252
+ });
@@ -0,0 +1,14 @@
1
+ import { InternalBasePlugin } from '@rsdoctor/core/plugins';
2
+ import type { Compilation, Compiler } from 'webpack';
3
+ export declare class InternalBundlePlugin<T extends Compiler> extends InternalBasePlugin<T> {
4
+ readonly name = "bundle";
5
+ map: Map<string, {
6
+ content: string;
7
+ }>;
8
+ apply(compiler: T): void;
9
+ ensureAssetContent(name: string): {
10
+ content: string;
11
+ };
12
+ thisCompilation: (compilation: Compilation) => void;
13
+ done: () => Promise<void>;
14
+ }
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var bundle_exports = {};
20
+ __export(bundle_exports, {
21
+ InternalBundlePlugin: () => InternalBundlePlugin
22
+ });
23
+ module.exports = __toCommonJS(bundle_exports);
24
+ var import_common_utils = require("@rsdoctor/core/common-utils");
25
+ var import_plugins = require("@rsdoctor/core/plugins");
26
+ var import_types = require("@rsdoctor/types");
27
+ class InternalBundlePlugin extends import_plugins.InternalBasePlugin {
28
+ constructor() {
29
+ super(...arguments);
30
+ this.name = "bundle";
31
+ this.map = /* @__PURE__ */ new Map();
32
+ this.thisCompilation = (compilation) => {
33
+ if (compilation.hooks.processAssets && compilation.hooks.afterOptimizeAssets) {
34
+ compilation.hooks.afterOptimizeAssets.tap(
35
+ this.tapPostOptions,
36
+ (assets) => {
37
+ Object.keys(assets).forEach((file) => {
38
+ const v = this.ensureAssetContent(file);
39
+ v.content = assets[file].source().toString();
40
+ });
41
+ }
42
+ );
43
+ } else {
44
+ compilation.hooks.afterOptimizeChunkAssets.tap(
45
+ this.tapPostOptions,
46
+ (chunks) => {
47
+ [...chunks].reduce((t, chunk) => t.concat([...chunk.files]), []).forEach((file) => {
48
+ const v = this.ensureAssetContent(file);
49
+ v.content = compilation.assets[file].source().toString();
50
+ });
51
+ }
52
+ );
53
+ }
54
+ };
55
+ this.done = async () => {
56
+ import_common_utils.Chunks.assetsContents(this.map, this.scheduler.chunkGraph);
57
+ this.sdk.addClientRoutes([
58
+ import_types.Manifest.DoctorManifestClientRoutes.ModuleGraph,
59
+ import_types.Manifest.DoctorManifestClientRoutes.BundleSize
60
+ ]);
61
+ };
62
+ }
63
+ apply(compiler) {
64
+ this.scheduler.ensureModulesChunksGraphApplied(compiler);
65
+ compiler.hooks.compilation.tap(this.tapPostOptions, this.thisCompilation);
66
+ compiler.hooks.done.tapPromise(this.tapPreOptions, this.done.bind(this));
67
+ }
68
+ ensureAssetContent(name) {
69
+ const asset = this.map.get(name);
70
+ if (asset)
71
+ return asset;
72
+ const v = { content: "" };
73
+ this.map.set(name, v);
74
+ return v;
75
+ }
76
+ }
77
+ // Annotate the CommonJS export names for ESM import in node:
78
+ 0 && (module.exports = {
79
+ InternalBundlePlugin
80
+ });
@@ -0,0 +1,37 @@
1
+ import { InternalBasePlugin } from '@rsdoctor/core/plugins';
2
+ import { DoctorWebpackSDK } from '@rsdoctor/sdk';
3
+ import { SDK } from '@rsdoctor/types';
4
+ import type { Compiler, ResolvePluginInstance, Resolver } from 'webpack';
5
+ interface DoctorResolverPluginOptions {}
6
+ interface ResolveRequestContext {
7
+ issuer: string;
8
+ }
9
+ interface ResolveRequestWithContext {
10
+ [key: string]: unknown;
11
+ context: ResolveRequestContext;
12
+ }
13
+ export declare class DoctorResolverPlugin implements ResolvePluginInstance {
14
+ protected options: DoctorResolverPluginOptions;
15
+ protected sdk: DoctorWebpackSDK;
16
+ protected tapOptions: {
17
+ name: string;
18
+ };
19
+ protected contextMap: Map<string, [number, [number, number]]>;
20
+ constructor(options: DoctorResolverPluginOptions, sdk: DoctorWebpackSDK);
21
+ protected getResolverData(context: ResolveRequestContext, params: {
22
+ request: string;
23
+ query?: string;
24
+ result?: string;
25
+ error?: Error;
26
+ stacks?: SDK.ResolveStackData[];
27
+ }): SDK.PathResolverData | undefined;
28
+ protected getResolveStackData(request: ResolveRequestWithContext, path: string, name?: string): SDK.ResolveStackData;
29
+ protected getResolveRequest(request: string | undefined, ctx?: Parameters<Resolver['resolve']>[3]): string;
30
+ apply(resolver: Resolver): void;
31
+ }
32
+ export declare class InternalResolverPlugin extends InternalBasePlugin<Compiler> {
33
+ readonly name = "resolver";
34
+ apply(compiler: Compiler): void;
35
+ afterPlugins: (compiler: Compiler) => void;
36
+ }
37
+ export {};
@@ -0,0 +1,177 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+ var resolver_exports = {};
30
+ __export(resolver_exports, {
31
+ DoctorResolverPlugin: () => DoctorResolverPlugin,
32
+ InternalResolverPlugin: () => InternalResolverPlugin
33
+ });
34
+ module.exports = __toCommonJS(resolver_exports);
35
+ var import_plugins = require("@rsdoctor/core/plugins");
36
+ var import_types = require("@rsdoctor/types");
37
+ var import_common = require("@rsdoctor/utils/common");
38
+ var import_path = __toESM(require("path"));
39
+ class DoctorResolverPlugin {
40
+ constructor(options, sdk) {
41
+ this.options = options;
42
+ this.sdk = sdk;
43
+ this.tapOptions = {
44
+ name: "DoctorResolverPlugin"
45
+ };
46
+ this.contextMap = /* @__PURE__ */ new Map();
47
+ }
48
+ getResolverData(context, params) {
49
+ const ctx = this.contextMap.get(context.issuer);
50
+ if (!ctx)
51
+ return;
52
+ const { request, query, result, error, stacks } = params;
53
+ const [start, startHRTime] = ctx;
54
+ const data = {
55
+ isEntry: Boolean(context.issuer),
56
+ issuerPath: context.issuer || "",
57
+ request,
58
+ startAt: start,
59
+ endAt: import_common.Time.getCurrentTimestamp(start, startHRTime),
60
+ pid: process.pid,
61
+ ppid: process.ppid
62
+ };
63
+ if (query) {
64
+ data.query = query;
65
+ }
66
+ if (result) {
67
+ data.result = result;
68
+ }
69
+ if (error) {
70
+ data.error = error;
71
+ data.stacks = stacks || [];
72
+ }
73
+ return data;
74
+ }
75
+ getResolveStackData(request, path2, name = "anonymous") {
76
+ const data = {
77
+ name,
78
+ // issuerPath: request.context.issuer,
79
+ path: path2
80
+ };
81
+ const keys = [
82
+ "request",
83
+ "query",
84
+ "fragment",
85
+ "file",
86
+ "module",
87
+ "directory",
88
+ "internal"
89
+ ];
90
+ keys.forEach((key) => {
91
+ if (request[key]) {
92
+ data[key] = request[key];
93
+ }
94
+ });
95
+ return data;
96
+ }
97
+ getResolveRequest(request, ctx) {
98
+ if (request)
99
+ return request;
100
+ if (ctx && ctx.stack) {
101
+ const [target] = [...ctx.stack].map((e) => e.split(" ").map((e2) => e2.trim())).filter((e) => e.length > 2);
102
+ if (target) {
103
+ return target[target.length - 1];
104
+ }
105
+ }
106
+ return "";
107
+ }
108
+ apply(resolver) {
109
+ resolver.hooks.result.tap(this.tapOptions, (request, rsctx) => {
110
+ const { context } = request;
111
+ const ctx = this.contextMap.get(context.issuer);
112
+ if (ctx) {
113
+ const data = this.getResolverData(context, {
114
+ request: this.getResolveRequest(request.request, rsctx),
115
+ query: request.query,
116
+ result: request.path
117
+ });
118
+ data && this.sdk.reportResolver([data]);
119
+ }
120
+ });
121
+ resolver.hooks.noResolve.tap(this.tapOptions, (request, error) => {
122
+ const { context } = request;
123
+ if (context.issuer) {
124
+ const resolvedPaths = new Set(
125
+ error.details.split("\n").map((e) => e.trim().split(" ")[0]).filter((e) => import_path.default.isAbsolute(e))
126
+ );
127
+ if (resolvedPaths.size) {
128
+ if (this.contextMap.has(context.issuer)) {
129
+ const stacks = [...resolvedPaths].map(
130
+ (e) => this.getResolveStackData(
131
+ request,
132
+ e,
133
+ "noResolve"
134
+ )
135
+ );
136
+ const data = this.getResolverData(context, {
137
+ request: this.getResolveRequest(request.request),
138
+ query: request.query,
139
+ error,
140
+ stacks
141
+ });
142
+ data && this.sdk.reportResolver([data]);
143
+ }
144
+ }
145
+ }
146
+ });
147
+ resolver.hooks.resolveStep.tap(this.tapOptions, (_, request) => {
148
+ const { context } = request;
149
+ if (context.issuer && !this.contextMap.has(context.issuer)) {
150
+ this.contextMap.set(context.issuer, [Date.now(), process.hrtime()]);
151
+ }
152
+ });
153
+ }
154
+ }
155
+ class InternalResolverPlugin extends import_plugins.InternalBasePlugin {
156
+ constructor() {
157
+ super(...arguments);
158
+ this.name = "resolver";
159
+ this.afterPlugins = (compiler) => {
160
+ if (compiler.isChild())
161
+ return;
162
+ compiler.options.resolve.plugins = (compiler.options.resolve.plugins ?? []).concat(new DoctorResolverPlugin({}, this.sdk));
163
+ this.sdk.addClientRoutes([
164
+ import_types.Manifest.DoctorManifestClientRoutes.ModuleResolve
165
+ ]);
166
+ };
167
+ }
168
+ apply(compiler) {
169
+ this.scheduler.ensureModulesChunksGraphApplied(compiler);
170
+ compiler.hooks.afterPlugins.tap(this.tapPostOptions, this.afterPlugins);
171
+ }
172
+ }
173
+ // Annotate the CommonJS export names for ESM import in node:
174
+ 0 && (module.exports = {
175
+ DoctorResolverPlugin,
176
+ InternalResolverPlugin
177
+ });
@@ -0,0 +1,8 @@
1
+ import { InternalBasePlugin } from '@rsdoctor/core/plugins';
2
+ import type { Compilation, Compiler, Stats } from 'webpack';
3
+ export declare class InternalRulesPlugin extends InternalBasePlugin<Compiler> {
4
+ readonly name = "rules";
5
+ apply(compiler: Compiler): void;
6
+ done: (stats: Stats) => Promise<void>;
7
+ protected lint(compilation: Compilation): Promise<void>;
8
+ }
@@ -0,0 +1,85 @@
1
+ "use strict";
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __export = (target, all) => {
7
+ for (var name in all)
8
+ __defProp(target, name, { get: all[name], enumerable: true });
9
+ };
10
+ var __copyProps = (to, from, except, desc) => {
11
+ if (from && typeof from === "object" || typeof from === "function") {
12
+ for (let key of __getOwnPropNames(from))
13
+ if (!__hasOwnProp.call(to, key) && key !== except)
14
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
15
+ }
16
+ return to;
17
+ };
18
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
19
+ var rules_exports = {};
20
+ __export(rules_exports, {
21
+ InternalRulesPlugin: () => InternalRulesPlugin
22
+ });
23
+ module.exports = __toCommonJS(rules_exports);
24
+ var import_plugins = require("@rsdoctor/core/plugins");
25
+ var import_rules = require("@rsdoctor/core/rules");
26
+ var import_error = require("@rsdoctor/utils/error");
27
+ var import_lodash = require("lodash");
28
+ class InternalRulesPlugin extends import_plugins.InternalBasePlugin {
29
+ constructor() {
30
+ super(...arguments);
31
+ this.name = "rules";
32
+ this.done = async (stats) => {
33
+ await this.lint(stats.compilation);
34
+ };
35
+ }
36
+ apply(compiler) {
37
+ compiler.hooks.done.tapPromise(this.tapPreOptions, this.done);
38
+ }
39
+ async lint(compilation) {
40
+ const options = this.options ?? {};
41
+ const linter = new import_rules.Linter(options.linter);
42
+ const result = await linter.validate(this.sdk.getRuleContext({}));
43
+ const validateErrors = result.errors.map(
44
+ (err) => import_error.DevToolError.from(err, {
45
+ detail: err.detail,
46
+ controller: {
47
+ noColor: true
48
+ }
49
+ })
50
+ );
51
+ const errors = validateErrors.filter((item) => item.level === "Error");
52
+ const warnings = validateErrors.filter((item) => item.level === "Warn");
53
+ const toWebpackError = (err) => err.toError();
54
+ result.replace.forEach((item) => {
55
+ if ((0, import_lodash.isArray)(compilation.errors) && compilation.errors.includes(item)) {
56
+ (0, import_lodash.pull)(compilation.errors, item);
57
+ }
58
+ if ((0, import_lodash.isArray)(compilation.warnings) && compilation.warnings.includes(item)) {
59
+ (0, import_lodash.pull)(compilation.warnings, item);
60
+ }
61
+ });
62
+ if ((0, import_lodash.isArray)(compilation.errors)) {
63
+ errors.forEach((err) => {
64
+ compilation.warnings.push(toWebpackError(err));
65
+ });
66
+ }
67
+ if ((0, import_lodash.isArray)(compilation.warnings)) {
68
+ warnings.forEach((err) => {
69
+ compilation.warnings.push(toWebpackError(err));
70
+ });
71
+ }
72
+ this.sdk.reportError(validateErrors);
73
+ await linter.afterValidate({
74
+ data: this.sdk.getRuleContext({}),
75
+ validateResult: result,
76
+ hooks: {
77
+ afterSaveManifest: this.sdk.hooks.afterSaveManifest
78
+ }
79
+ });
80
+ }
81
+ }
82
+ // Annotate the CommonJS export names for ESM import in node:
83
+ 0 && (module.exports = {
84
+ InternalRulesPlugin
85
+ });
package/package.json ADDED
@@ -0,0 +1,45 @@
1
+ {
2
+ "name": "@rsdoctor/webpack-plugin",
3
+ "version": "0.0.2-beta.0",
4
+ "repository": {
5
+ "type": "git",
6
+ "url": "https://github.com/web-infra-dev/rsdoctor",
7
+ "directory": "packages/webpack-plugin"
8
+ },
9
+ "license": "MIT",
10
+ "main": "dist/index.js",
11
+ "types": "dist/index.d.ts",
12
+ "files": [
13
+ "dist"
14
+ ],
15
+ "dependencies": {
16
+ "fs-extra": "^11.1.1",
17
+ "lodash": "^4.17.21",
18
+ "webpack": "^5.89.0",
19
+ "@rsdoctor/core": "0.0.2-beta.0",
20
+ "@rsdoctor/sdk": "0.0.2-beta.0",
21
+ "@rsdoctor/graph": "0.0.2-beta.0",
22
+ "@rsdoctor/utils": "0.0.2-beta.0"
23
+ },
24
+ "devDependencies": {
25
+ "@types/fs-extra": "^11.0.2",
26
+ "@types/lodash": "^4.14.200",
27
+ "@types/node": "^16",
28
+ "@types/tapable": "2.2.2",
29
+ "@types/webpack": "5.28.0",
30
+ "tslib": "2.4.1",
31
+ "typescript": "^5.2.2",
32
+ "@rsdoctor/types": "0.0.2-beta.0"
33
+ },
34
+ "publishConfig": {
35
+ "access": "public",
36
+ "provenance": true,
37
+ "registry": "https://registry.npmjs.org/"
38
+ },
39
+ "scripts": {
40
+ "dev": "npm run start",
41
+ "build": "modern build",
42
+ "start": "modern build -w",
43
+ "test": "vitest run"
44
+ }
45
+ }