@rushstack/heft-webpack5-plugin 0.6.0-rc.2 → 0.6.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.
@@ -1,366 +0,0 @@
1
- "use strict";
2
- // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license.
3
- // See LICENSE in the project root for license information.
4
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
5
- if (k2 === undefined) k2 = k;
6
- var desc = Object.getOwnPropertyDescriptor(m, k);
7
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
8
- desc = { enumerable: true, get: function() { return m[k]; } };
9
- }
10
- Object.defineProperty(o, k2, desc);
11
- }) : (function(o, m, k, k2) {
12
- if (k2 === undefined) k2 = k;
13
- o[k2] = m[k];
14
- }));
15
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
16
- Object.defineProperty(o, "default", { enumerable: true, value: v });
17
- }) : function(o, v) {
18
- o["default"] = v;
19
- });
20
- var __importStar = (this && this.__importStar) || function (mod) {
21
- if (mod && mod.__esModule) return mod;
22
- var result = {};
23
- if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
24
- __setModuleDefault(result, mod);
25
- return result;
26
- };
27
- Object.defineProperty(exports, "__esModule", { value: true });
28
- exports.PLUGIN_NAME = void 0;
29
- const tapable_1 = require("tapable");
30
- const debug_certificate_manager_1 = require("@rushstack/debug-certificate-manager");
31
- const node_core_library_1 = require("@rushstack/node-core-library");
32
- const WebpackConfigurationLoader_1 = require("./WebpackConfigurationLoader");
33
- /**
34
- * @public
35
- */
36
- exports.PLUGIN_NAME = 'webpack5-plugin';
37
- const SERVE_PARAMETER_LONG_NAME = '--serve';
38
- const WEBPACK_PACKAGE_NAME = 'webpack';
39
- const WEBPACK_DEV_SERVER_PACKAGE_NAME = 'webpack-dev-server';
40
- const WEBPACK_DEV_SERVER_ENV_VAR_NAME = 'WEBPACK_DEV_SERVER';
41
- const WEBPACK_DEV_MIDDLEWARE_PACKAGE_NAME = 'webpack-dev-middleware';
42
- const UNINITIALIZED = 'UNINITIALIZED';
43
- /**
44
- * @internal
45
- */
46
- class Webpack5Plugin {
47
- constructor() {
48
- this._isServeMode = false;
49
- this._webpackConfiguration = UNINITIALIZED;
50
- }
51
- get accessor() {
52
- if (!this._accessor) {
53
- this._accessor = {
54
- hooks: {
55
- onLoadConfiguration: new tapable_1.AsyncSeriesBailHook(),
56
- onConfigure: new tapable_1.AsyncSeriesHook(['webpackConfiguration']),
57
- onAfterConfigure: new tapable_1.AsyncParallelHook(['webpackConfiguration']),
58
- onEmitStats: new tapable_1.AsyncParallelHook(['webpackStats'])
59
- },
60
- parameters: {
61
- isServeMode: this._isServeMode
62
- }
63
- };
64
- }
65
- return this._accessor;
66
- }
67
- apply(taskSession, heftConfiguration, options) {
68
- this._isServeMode = taskSession.parameters.getFlagParameter(SERVE_PARAMETER_LONG_NAME).value;
69
- if (!taskSession.parameters.watch && this._isServeMode) {
70
- throw new Error(`The ${JSON.stringify(SERVE_PARAMETER_LONG_NAME)} parameter is only available when running in watch mode.`);
71
- }
72
- taskSession.hooks.run.tapPromise(exports.PLUGIN_NAME, async (runOptions) => {
73
- await this._runWebpackAsync(taskSession, heftConfiguration, options);
74
- });
75
- taskSession.hooks.runIncremental.tapPromise(exports.PLUGIN_NAME, async (runOptions) => {
76
- await this._runWebpackWatchAsync(taskSession, heftConfiguration, options);
77
- });
78
- }
79
- async _getWebpackConfigurationAsync(taskSession, heftConfiguration, options) {
80
- if (this._webpackConfiguration === UNINITIALIZED) {
81
- // Obtain the webpack configuration by calling into the hook. If undefined
82
- // is returned, load the default Webpack configuration.
83
- taskSession.logger.terminal.writeVerboseLine('Attempting to load Webpack configuration via external plugins');
84
- let webpackConfiguration = await this.accessor.hooks.onLoadConfiguration.promise();
85
- if (webpackConfiguration === undefined) {
86
- taskSession.logger.terminal.writeVerboseLine('Attempt to load the default Webpack configuration');
87
- const configurationLoader = new WebpackConfigurationLoader_1.WebpackConfigurationLoader(taskSession.logger, taskSession.parameters.production, taskSession.parameters.watch && this._isServeMode);
88
- webpackConfiguration = await configurationLoader.tryLoadWebpackConfigurationAsync(Object.assign(Object.assign({}, options), { taskSession,
89
- heftConfiguration, loadWebpackAsyncFn: this._loadWebpackAsync.bind(this) }));
90
- }
91
- if (webpackConfiguration === false) {
92
- taskSession.logger.terminal.writeLine('Webpack disabled by external plugin');
93
- this._webpackConfiguration = undefined;
94
- }
95
- else if (webpackConfiguration === undefined ||
96
- (Array.isArray(webpackConfiguration) && webpackConfiguration.length === 0)) {
97
- taskSession.logger.terminal.writeLine('No Webpack configuration found');
98
- this._webpackConfiguration = undefined;
99
- }
100
- else {
101
- if (this.accessor.hooks.onConfigure.isUsed()) {
102
- // Allow for plugins to customise the configuration
103
- await this.accessor.hooks.onConfigure.promise(webpackConfiguration);
104
- }
105
- if (this.accessor.hooks.onAfterConfigure.isUsed()) {
106
- // Provide the finalized configuration
107
- await this.accessor.hooks.onAfterConfigure.promise(webpackConfiguration);
108
- }
109
- this._webpackConfiguration = webpackConfiguration;
110
- }
111
- }
112
- return this._webpackConfiguration;
113
- }
114
- async _loadWebpackAsync() {
115
- if (!this._webpack) {
116
- // Allow this to fail if webpack is not installed
117
- this._webpack = await Promise.resolve().then(() => __importStar(require(WEBPACK_PACKAGE_NAME)));
118
- }
119
- return this._webpack;
120
- }
121
- async _getWebpackCompilerAsync(taskSession, webpackConfiguration) {
122
- if (!this._webpackCompiler) {
123
- const webpack = await this._loadWebpackAsync();
124
- taskSession.logger.terminal.writeLine(`Using Webpack version ${webpack.version}`);
125
- this._webpackCompiler = Array.isArray(webpackConfiguration)
126
- ? webpack.default(webpackConfiguration) /* (webpack.Compilation[]) => MultiCompiler */
127
- : webpack.default(webpackConfiguration); /* (webpack.Compilation) => Compiler */
128
- }
129
- return this._webpackCompiler;
130
- }
131
- async _runWebpackAsync(taskSession, heftConfiguration, options) {
132
- this._validateEnvironmentVariable(taskSession);
133
- if (taskSession.parameters.watch || this._isServeMode) {
134
- // Should never happen, but just in case
135
- throw new node_core_library_1.InternalError('Cannot run Webpack in compilation mode when watch mode is enabled');
136
- }
137
- // Load the config and compiler, and return if there is no config found
138
- const webpackConfiguration = await this._getWebpackConfigurationAsync(taskSession, heftConfiguration, options);
139
- if (!webpackConfiguration) {
140
- return;
141
- }
142
- const compiler = await this._getWebpackCompilerAsync(taskSession, webpackConfiguration);
143
- taskSession.logger.terminal.writeLine('Running Webpack compilation');
144
- // Run the webpack compiler
145
- let stats;
146
- try {
147
- stats = await node_core_library_1.LegacyAdapters.convertCallbackToPromise(compiler.run.bind(compiler));
148
- await node_core_library_1.LegacyAdapters.convertCallbackToPromise(compiler.close.bind(compiler));
149
- }
150
- catch (e) {
151
- taskSession.logger.emitError(e);
152
- }
153
- // Emit the errors from the stats object, if present
154
- if (stats) {
155
- this._emitErrors(taskSession.logger, stats, heftConfiguration.buildFolderPath);
156
- if (this.accessor.hooks.onEmitStats.isUsed()) {
157
- await this.accessor.hooks.onEmitStats.promise(stats);
158
- }
159
- }
160
- }
161
- async _runWebpackWatchAsync(taskSession, heftConfiguration, options) {
162
- var _a, _b;
163
- // Save a handle to the original promise, since the this-scoped promise will be replaced whenever
164
- // the compilation completes.
165
- let webpackCompilationDonePromise = this._webpackCompilationDonePromise;
166
- if (!this._webpackWatchers) {
167
- this._validateEnvironmentVariable(taskSession);
168
- if (!taskSession.parameters.watch) {
169
- // Should never happen, but just in case
170
- throw new node_core_library_1.InternalError('Cannot run Webpack in watch mode when compilation mode is enabled');
171
- }
172
- // Load the config and compiler, and return if there is no config found
173
- const webpackConfiguration = await this._getWebpackConfigurationAsync(taskSession, heftConfiguration, options);
174
- if (!webpackConfiguration) {
175
- return;
176
- }
177
- // Get the compiler which will be used for both serve and watch mode
178
- const compiler = await this._getWebpackCompilerAsync(taskSession, webpackConfiguration);
179
- // Set up the hook to detect when the watcher completes the watcher compilation. We will also log out
180
- // errors from the compilation if present from the output stats object.
181
- this._webpackCompilationDonePromise = new Promise((resolve) => {
182
- this._webpackCompilationDonePromiseResolveFn = resolve;
183
- });
184
- webpackCompilationDonePromise = this._webpackCompilationDonePromise;
185
- compiler.hooks.done.tap(exports.PLUGIN_NAME, (stats) => {
186
- this._webpackCompilationDonePromiseResolveFn();
187
- this._webpackCompilationDonePromise = new Promise((resolve) => {
188
- this._webpackCompilationDonePromiseResolveFn = resolve;
189
- });
190
- if (stats) {
191
- this._emitErrors(taskSession.logger, stats, heftConfiguration.buildFolderPath);
192
- }
193
- });
194
- // Determine how we will run the compiler. When serving, we will run the compiler
195
- // via the webpack-dev-server. Otherwise, we will run the compiler directly.
196
- if (this._isServeMode) {
197
- const defaultDevServerOptions = {
198
- host: 'localhost',
199
- devMiddleware: {
200
- publicPath: '/',
201
- stats: {
202
- cached: false,
203
- cachedAssets: false,
204
- colors: heftConfiguration.terminalProvider.supportsColor
205
- }
206
- },
207
- client: {
208
- logging: 'info',
209
- webSocketURL: {
210
- port: 8080
211
- }
212
- },
213
- port: 8080,
214
- onListening: (server) => {
215
- var _a;
216
- const addressInfo = (_a = server.server) === null || _a === void 0 ? void 0 : _a.address();
217
- if (addressInfo) {
218
- const address = typeof addressInfo === 'string' ? addressInfo : `${addressInfo.address}:${addressInfo.port}`;
219
- taskSession.logger.terminal.writeLine(`Started Webpack Dev Server at https://${address}`);
220
- }
221
- }
222
- };
223
- // Obtain the devServerOptions from the webpack configuration, and combine with the default options
224
- let devServerOptions;
225
- if (Array.isArray(webpackConfiguration)) {
226
- const filteredDevServerOptions = webpackConfiguration
227
- .map((configuration) => configuration.devServer)
228
- .filter((devServer) => !!devServer);
229
- if (filteredDevServerOptions.length > 1) {
230
- taskSession.logger.emitWarning(new Error(`Detected multiple webpack devServer configurations, using the first one.`));
231
- }
232
- devServerOptions = Object.assign(Object.assign({}, defaultDevServerOptions), filteredDevServerOptions[0]);
233
- }
234
- else {
235
- devServerOptions = Object.assign(Object.assign({}, defaultDevServerOptions), webpackConfiguration.devServer);
236
- }
237
- // Add the certificate and key to the devServerOptions if these fields don't already have values
238
- if (!devServerOptions.server) {
239
- const certificateManager = new debug_certificate_manager_1.CertificateManager();
240
- const certificate = await certificateManager.ensureCertificateAsync(true, taskSession.logger.terminal);
241
- // Update the web socket URL to use the hostname provided by the certificate
242
- const clientConfiguration = devServerOptions.client;
243
- const hostname = (_a = certificate.subjectAltNames) === null || _a === void 0 ? void 0 : _a[0];
244
- if (hostname && typeof clientConfiguration === 'object') {
245
- const { webSocketURL } = clientConfiguration;
246
- if (typeof webSocketURL === 'object') {
247
- clientConfiguration.webSocketURL = Object.assign(Object.assign({}, webSocketURL), { hostname });
248
- }
249
- }
250
- devServerOptions = Object.assign(Object.assign({}, devServerOptions), { server: {
251
- type: 'https',
252
- options: {
253
- minVersion: 'TLSv1.3',
254
- key: certificate.pemKey,
255
- cert: certificate.pemCertificate,
256
- ca: certificate.pemCaCertificate
257
- }
258
- } });
259
- }
260
- // Since the webpack-dev-server does not return infrastructure errors via a callback like
261
- // compiler.watch(...), we will need to intercept them and log them ourselves.
262
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
263
- compiler.hooks.infrastructureLog.tap(exports.PLUGIN_NAME, (name, type, args) => {
264
- if (name === WEBPACK_DEV_MIDDLEWARE_PACKAGE_NAME && type === 'error') {
265
- const error = args[0];
266
- if (error) {
267
- taskSession.logger.emitError(error);
268
- }
269
- }
270
- return true;
271
- });
272
- // The webpack-dev-server package has a design flaw, where merely loading its package will set the
273
- // WEBPACK_DEV_SERVER environment variable -- even if no APIs are accessed. This environment variable
274
- // causes incorrect behavior if Heft is not running in serve mode. Thus, we need to be careful to call
275
- // require() only if Heft is in serve mode.
276
- taskSession.logger.terminal.writeLine('Starting webpack-dev-server');
277
- const WebpackDevServer = (await Promise.resolve().then(() => __importStar(require(WEBPACK_DEV_SERVER_PACKAGE_NAME))))
278
- .default;
279
- const webpackDevServer = new WebpackDevServer(devServerOptions, compiler);
280
- await webpackDevServer.start();
281
- }
282
- else {
283
- // Create the watcher. Compilation will start immediately after invoking watch().
284
- taskSession.logger.terminal.writeLine('Starting Webpack watcher');
285
- compiler.watch({}, (error) => {
286
- if (error) {
287
- taskSession.logger.emitError(error);
288
- }
289
- });
290
- }
291
- // Store the watchers to be used for suspend/resume
292
- this._webpackWatchers = ((_b = compiler.compilers) !== null && _b !== void 0 ? _b : [compiler]).map((compiler) => compiler.watching);
293
- }
294
- // Resume the compilation, wait for the compilation to complete, then suspend the watchers until the
295
- // next iteration. Even if there are no changes, the promise should resolve since resuming from a
296
- // suspended state invalidates the state of the watcher.
297
- taskSession.logger.terminal.writeLine('Running incremental Webpack compilation');
298
- for (const watcher of this._webpackWatchers) {
299
- watcher.resume();
300
- }
301
- await webpackCompilationDonePromise;
302
- for (const watcher of this._webpackWatchers) {
303
- watcher.suspend();
304
- }
305
- }
306
- _validateEnvironmentVariable(taskSession) {
307
- if (!this._isServeMode && process.env[WEBPACK_DEV_SERVER_ENV_VAR_NAME]) {
308
- taskSession.logger.emitWarning(new Error(`The "${WEBPACK_DEV_SERVER_ENV_VAR_NAME}" environment variable is set, ` +
309
- 'which will cause problems when webpack is not running in serve mode. ' +
310
- `(Did a dependency inadvertently load the "${WEBPACK_DEV_SERVER_PACKAGE_NAME}" package?)`));
311
- }
312
- }
313
- _emitErrors(logger, stats, buildFolderPath) {
314
- if (stats.hasErrors() || stats.hasWarnings()) {
315
- const serializedStats = stats.toJson('errors-warnings');
316
- if (serializedStats.warnings) {
317
- for (const warning of serializedStats.warnings) {
318
- logger.emitWarning(this._normalizeError(buildFolderPath, warning));
319
- }
320
- }
321
- if (serializedStats.errors) {
322
- for (const error of serializedStats.errors) {
323
- logger.emitError(this._normalizeError(buildFolderPath, error));
324
- }
325
- }
326
- }
327
- }
328
- _normalizeError(buildFolderPath, error) {
329
- if (error instanceof Error) {
330
- return error;
331
- }
332
- else if (error.moduleIdentifier) {
333
- let lineNumber;
334
- let columnNumber;
335
- if (error.loc) {
336
- // Format of "<line>:<columnStart>-<columnEnd>"
337
- // https://webpack.js.org/api/stats/#errors-and-warnings
338
- const [lineNumberRaw, columnRangeRaw] = error.loc.split(':');
339
- const [startColumnRaw] = columnRangeRaw.split('-');
340
- if (lineNumberRaw) {
341
- lineNumber = parseInt(lineNumberRaw, 10);
342
- if (isNaN(lineNumber)) {
343
- lineNumber = undefined;
344
- }
345
- }
346
- if (startColumnRaw) {
347
- columnNumber = parseInt(startColumnRaw, 10);
348
- if (isNaN(columnNumber)) {
349
- columnNumber = undefined;
350
- }
351
- }
352
- }
353
- return new node_core_library_1.FileError(error.message, {
354
- absolutePath: error.moduleIdentifier,
355
- projectFolder: buildFolderPath,
356
- line: lineNumber,
357
- column: columnNumber
358
- });
359
- }
360
- else {
361
- return new Error(error.message);
362
- }
363
- }
364
- }
365
- exports.default = Webpack5Plugin;
366
- //# sourceMappingURL=Webpack5Plugin.js.map
@@ -1 +0,0 @@
1
- {"version":3,"file":"Webpack5Plugin.js","sourceRoot":"","sources":["../src/Webpack5Plugin.ts"],"names":[],"mappings":";AAAA,4FAA4F;AAC5F,2DAA2D;;;;;;;;;;;;;;;;;;;;;;;;;;AAK3D,qCAAkF;AAClF,oFAA6F;AAC7F,oEAAwF;AAWxF,6EAA0E;AAU1E;;GAEG;AACU,QAAA,WAAW,GAAsB,iBAAiB,CAAC;AAChE,MAAM,yBAAyB,GAAc,SAAS,CAAC;AACvD,MAAM,oBAAoB,GAAc,SAAS,CAAC;AAClD,MAAM,+BAA+B,GAAyB,oBAAoB,CAAC;AACnF,MAAM,+BAA+B,GAAyB,oBAAoB,CAAC;AACnF,MAAM,mCAAmC,GAA6B,wBAAwB,CAAC;AAC/F,MAAM,aAAa,GAAoB,eAAe,CAAC;AAEvD;;GAEG;AACH,MAAqB,cAAc;IAAnC;QAEU,iBAAY,GAAY,KAAK,CAAC;QAG9B,0BAAqB,GAA6D,aAAa,CAAC;IA8Z1G,C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ft Corporation. All rights reserved. Licensed under the MIT license.\n// See LICENSE in the project root for license information.\n\nimport type { AddressInfo } from 'net';\nimport type * as TWebpack from 'webpack';\nimport type TWebpackDevServer from 'webpack-dev-server';\nimport { AsyncParallelHook, AsyncSeriesBailHook, AsyncSeriesHook } from 'tapable';\nimport { CertificateManager, type ICertificate } from '@rushstack/debug-certificate-manager';\nimport { FileError, InternalError, LegacyAdapters } from '@rushstack/node-core-library';\nimport type {\n HeftConfiguration,\n IHeftTaskSession,\n IHeftTaskPlugin,\n IHeftTaskRunHookOptions,\n IScopedLogger,\n IHeftTaskRunIncrementalHookOptions\n} from '@rushstack/heft';\n\nimport type { IWebpackConfiguration, IWebpackPluginAccessor } from './shared';\nimport { WebpackConfigurationLoader } from './WebpackConfigurationLoader';\n\ntype ExtendedCompiler = TWebpack.Compiler & { watching: TWebpack.Watching };\ntype ExtendedMultiCompiler = TWebpack.MultiCompiler & { compilers: ExtendedCompiler[] };\n\nexport interface IWebpackPluginOptions {\n devConfigurationPath: string | undefined;\n configurationPath: string | undefined;\n}\n\n/**\n * @public\n */\nexport const PLUGIN_NAME: 'webpack5-plugin' = 'webpack5-plugin';\nconst SERVE_PARAMETER_LONG_NAME: '--serve' = '--serve';\nconst WEBPACK_PACKAGE_NAME: 'webpack' = 'webpack';\nconst WEBPACK_DEV_SERVER_PACKAGE_NAME: 'webpack-dev-server' = 'webpack-dev-server';\nconst WEBPACK_DEV_SERVER_ENV_VAR_NAME: 'WEBPACK_DEV_SERVER' = 'WEBPACK_DEV_SERVER';\nconst WEBPACK_DEV_MIDDLEWARE_PACKAGE_NAME: 'webpack-dev-middleware' = 'webpack-dev-middleware';\nconst UNINITIALIZED: 'UNINITIALIZED' = 'UNINITIALIZED';\n\n/**\n * @internal\n */\nexport default class Webpack5Plugin implements IHeftTaskPlugin<IWebpackPluginOptions> {\n private _accessor: IWebpackPluginAccessor | undefined;\n private _isServeMode: boolean = false;\n private _webpack: typeof TWebpack | undefined;\n private _webpackCompiler: ExtendedCompiler | ExtendedMultiCompiler | undefined;\n private _webpackConfiguration: IWebpackConfiguration | undefined | typeof UNINITIALIZED = UNINITIALIZED;\n private _webpackWatchers: TWebpack.Watching[] | undefined;\n private _webpackCompilationDonePromise: Promise<void> | undefined;\n private _webpackCompilationDonePromiseResolveFn: (() => void) | undefined;\n\n public get accessor(): IWebpackPluginAccessor {\n if (!this._accessor) {\n this._accessor = {\n hooks: {\n onLoadConfiguration: new AsyncSeriesBailHook(),\n onConfigure: new AsyncSeriesHook(['webpackConfiguration']),\n onAfterConfigure: new AsyncParallelHook(['webpackConfiguration']),\n onEmitStats: new AsyncParallelHook(['webpackStats'])\n },\n parameters: {\n isServeMode: this._isServeMode\n }\n };\n }\n return this._accessor;\n }\n\n public apply(\n taskSession: IHeftTaskSession,\n heftConfiguration: HeftConfiguration,\n options: IWebpackPluginOptions\n ): void {\n this._isServeMode = taskSession.parameters.getFlagParameter(SERVE_PARAMETER_LONG_NAME).value;\n if (!taskSession.parameters.watch && this._isServeMode) {\n throw new Error(\n `The ${JSON.stringify(\n SERVE_PARAMETER_LONG_NAME\n )} parameter is only available when running in watch mode.`\n );\n }\n\n taskSession.hooks.run.tapPromise(PLUGIN_NAME, async (runOptions: IHeftTaskRunHookOptions) => {\n await this._runWebpackAsync(taskSession, heftConfiguration, options);\n });\n\n taskSession.hooks.runIncremental.tapPromise(\n PLUGIN_NAME,\n async (runOptions: IHeftTaskRunIncrementalHookOptions) => {\n await this._runWebpackWatchAsync(taskSession, heftConfiguration, options);\n }\n );\n }\n\n private async _getWebpackConfigurationAsync(\n taskSession: IHeftTaskSession,\n heftConfiguration: HeftConfiguration,\n options: IWebpackPluginOptions\n ): Promise<IWebpackConfiguration | undefined> {\n if (this._webpackConfiguration === UNINITIALIZED) {\n // Obtain the webpack configuration by calling into the hook. If undefined\n // is returned, load the default Webpack configuration.\n taskSession.logger.terminal.writeVerboseLine(\n 'Attempting to load Webpack configuration via external plugins'\n );\n let webpackConfiguration: IWebpackConfiguration | false | undefined =\n await this.accessor.hooks.onLoadConfiguration.promise();\n if (webpackConfiguration === undefined) {\n taskSession.logger.terminal.writeVerboseLine('Attempt to load the default Webpack configuration');\n const configurationLoader: WebpackConfigurationLoader = new WebpackConfigurationLoader(\n taskSession.logger,\n taskSession.parameters.production,\n taskSession.parameters.watch && this._isServeMode\n );\n webpackConfiguration = await configurationLoader.tryLoadWebpackConfigurationAsync({\n ...options,\n taskSession,\n heftConfiguration,\n loadWebpackAsyncFn: this._loadWebpackAsync.bind(this)\n });\n }\n\n if (webpackConfiguration === false) {\n taskSession.logger.terminal.writeLine('Webpack disabled by external plugin');\n this._webpackConfiguration = undefined;\n } else if (\n webpackConfiguration === undefined ||\n (Array.isArray(webpackConfiguration) && webpackConfiguration.length === 0)\n ) {\n taskSession.logger.terminal.writeLine('No Webpack configuration found');\n this._webpackConfiguration = undefined;\n } else {\n if (this.accessor.hooks.onConfigure.isUsed()) {\n // Allow for plugins to customise the configuration\n await this.accessor.hooks.onConfigure.promise(webpackConfiguration);\n }\n if (this.accessor.hooks.onAfterConfigure.isUsed()) {\n // Provide the finalized configuration\n await this.accessor.hooks.onAfterConfigure.promise(webpackConfiguration);\n }\n this._webpackConfiguration = webpackConfiguration;\n }\n }\n return this._webpackConfiguration;\n }\n\n private async _loadWebpackAsync(): Promise<typeof TWebpack> {\n if (!this._webpack) {\n // Allow this to fail if webpack is not installed\n this._webpack = await import(WEBPACK_PACKAGE_NAME);\n }\n return this._webpack!;\n }\n\n private async _getWebpackCompilerAsync(\n taskSession: IHeftTaskSession,\n webpackConfiguration: IWebpackConfiguration\n ): Promise<ExtendedCompiler | ExtendedMultiCompiler> {\n if (!this._webpackCompiler) {\n const webpack: typeof TWebpack = await this._loadWebpackAsync();\n taskSession.logger.terminal.writeLine(`Using Webpack version ${webpack.version}`);\n this._webpackCompiler = Array.isArray(webpackConfiguration)\n ? webpack.default(webpackConfiguration) /* (webpack.Compilation[]) => MultiCompiler */\n : webpack.default(webpackConfiguration); /* (webpack.Compilation) => Compiler */\n }\n return this._webpackCompiler;\n }\n\n private async _runWebpackAsync(\n taskSession: IHeftTaskSession,\n heftConfiguration: HeftConfiguration,\n options: IWebpackPluginOptions\n ): Promise<void> {\n this._validateEnvironmentVariable(taskSession);\n if (taskSession.parameters.watch || this._isServeMode) {\n // Should never happen, but just in case\n throw new InternalError('Cannot run Webpack in compilation mode when watch mode is enabled');\n }\n\n // Load the config and compiler, and return if there is no config found\n const webpackConfiguration: IWebpackConfiguration | undefined = await this._getWebpackConfigurationAsync(\n taskSession,\n heftConfiguration,\n options\n );\n if (!webpackConfiguration) {\n return;\n }\n const compiler: ExtendedCompiler | ExtendedMultiCompiler = await this._getWebpackCompilerAsync(\n taskSession,\n webpackConfiguration\n );\n taskSession.logger.terminal.writeLine('Running Webpack compilation');\n\n // Run the webpack compiler\n let stats: TWebpack.Stats | TWebpack.MultiStats | undefined;\n try {\n stats = await LegacyAdapters.convertCallbackToPromise(\n (compiler as ExtendedCompiler).run.bind(compiler)\n );\n await LegacyAdapters.convertCallbackToPromise(compiler.close.bind(compiler));\n } catch (e) {\n taskSession.logger.emitError(e as Error);\n }\n\n // Emit the errors from the stats object, if present\n if (stats) {\n this._emitErrors(taskSession.logger, stats, heftConfiguration.buildFolderPath);\n if (this.accessor.hooks.onEmitStats.isUsed()) {\n await this.accessor.hooks.onEmitStats.promise(stats);\n }\n }\n }\n\n private async _runWebpackWatchAsync(\n taskSession: IHeftTaskSession,\n heftConfiguration: HeftConfiguration,\n options: IWebpackPluginOptions\n ): Promise<void> {\n // Save a handle to the original promise, since the this-scoped promise will be replaced whenever\n // the compilation completes.\n let webpackCompilationDonePromise: Promise<void> | undefined = this._webpackCompilationDonePromise;\n\n if (!this._webpackWatchers) {\n this._validateEnvironmentVariable(taskSession);\n if (!taskSession.parameters.watch) {\n // Should never happen, but just in case\n throw new InternalError('Cannot run Webpack in watch mode when compilation mode is enabled');\n }\n\n // Load the config and compiler, and return if there is no config found\n const webpackConfiguration: IWebpackConfiguration | undefined =\n await this._getWebpackConfigurationAsync(taskSession, heftConfiguration, options);\n if (!webpackConfiguration) {\n return;\n }\n\n // Get the compiler which will be used for both serve and watch mode\n const compiler: ExtendedCompiler | ExtendedMultiCompiler = await this._getWebpackCompilerAsync(\n taskSession,\n webpackConfiguration\n );\n\n // Set up the hook to detect when the watcher completes the watcher compilation. We will also log out\n // errors from the compilation if present from the output stats object.\n this._webpackCompilationDonePromise = new Promise((resolve: () => void) => {\n this._webpackCompilationDonePromiseResolveFn = resolve;\n });\n webpackCompilationDonePromise = this._webpackCompilationDonePromise;\n compiler.hooks.done.tap(PLUGIN_NAME, (stats?: TWebpack.Stats | TWebpack.MultiStats) => {\n this._webpackCompilationDonePromiseResolveFn!();\n this._webpackCompilationDonePromise = new Promise((resolve: () => void) => {\n this._webpackCompilationDonePromiseResolveFn = resolve;\n });\n if (stats) {\n this._emitErrors(taskSession.logger, stats, heftConfiguration.buildFolderPath);\n }\n });\n\n // Determine how we will run the compiler. When serving, we will run the compiler\n // via the webpack-dev-server. Otherwise, we will run the compiler directly.\n if (this._isServeMode) {\n const defaultDevServerOptions: TWebpackDevServer.Configuration = {\n host: 'localhost',\n devMiddleware: {\n publicPath: '/',\n stats: {\n cached: false,\n cachedAssets: false,\n colors: heftConfiguration.terminalProvider.supportsColor\n }\n },\n client: {\n logging: 'info',\n webSocketURL: {\n port: 8080\n }\n },\n port: 8080,\n onListening: (server: TWebpackDevServer) => {\n const addressInfo: AddressInfo | string | undefined = server.server?.address() as AddressInfo;\n if (addressInfo) {\n const address: string =\n typeof addressInfo === 'string' ? addressInfo : `${addressInfo.address}:${addressInfo.port}`;\n taskSession.logger.terminal.writeLine(`Started Webpack Dev Server at https://${address}`);\n }\n }\n };\n\n // Obtain the devServerOptions from the webpack configuration, and combine with the default options\n let devServerOptions: TWebpackDevServer.Configuration;\n if (Array.isArray(webpackConfiguration)) {\n const filteredDevServerOptions: TWebpackDevServer.Configuration[] = webpackConfiguration\n .map((configuration) => configuration.devServer)\n .filter((devServer): devServer is TWebpackDevServer.Configuration => !!devServer);\n if (filteredDevServerOptions.length > 1) {\n taskSession.logger.emitWarning(\n new Error(`Detected multiple webpack devServer configurations, using the first one.`)\n );\n }\n devServerOptions = { ...defaultDevServerOptions, ...filteredDevServerOptions[0] };\n } else {\n devServerOptions = { ...defaultDevServerOptions, ...webpackConfiguration.devServer };\n }\n\n // Add the certificate and key to the devServerOptions if these fields don't already have values\n if (!devServerOptions.server) {\n const certificateManager: CertificateManager = new CertificateManager();\n const certificate: ICertificate = await certificateManager.ensureCertificateAsync(\n true,\n taskSession.logger.terminal\n );\n\n // Update the web socket URL to use the hostname provided by the certificate\n const clientConfiguration: TWebpackDevServer.Configuration['client'] = devServerOptions.client;\n const hostname: string | undefined = certificate.subjectAltNames?.[0];\n if (hostname && typeof clientConfiguration === 'object') {\n const { webSocketURL } = clientConfiguration;\n if (typeof webSocketURL === 'object') {\n clientConfiguration.webSocketURL = {\n ...webSocketURL,\n hostname\n };\n }\n }\n\n devServerOptions = {\n ...devServerOptions,\n server: {\n type: 'https',\n options: {\n minVersion: 'TLSv1.3',\n key: certificate.pemKey,\n cert: certificate.pemCertificate,\n ca: certificate.pemCaCertificate\n }\n }\n };\n }\n\n // Since the webpack-dev-server does not return infrastructure errors via a callback like\n // compiler.watch(...), we will need to intercept them and log them ourselves.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n compiler.hooks.infrastructureLog.tap(PLUGIN_NAME, (name: string, type: string, args: any[]) => {\n if (name === WEBPACK_DEV_MIDDLEWARE_PACKAGE_NAME && type === 'error') {\n const error: Error | undefined = args[0];\n if (error) {\n taskSession.logger.emitError(error);\n }\n }\n return true;\n });\n\n // The webpack-dev-server package has a design flaw, where merely loading its package will set the\n // WEBPACK_DEV_SERVER environment variable -- even if no APIs are accessed. This environment variable\n // causes incorrect behavior if Heft is not running in serve mode. Thus, we need to be careful to call\n // require() only if Heft is in serve mode.\n taskSession.logger.terminal.writeLine('Starting webpack-dev-server');\n const WebpackDevServer: typeof TWebpackDevServer = (await import(WEBPACK_DEV_SERVER_PACKAGE_NAME))\n .default;\n const webpackDevServer: TWebpackDevServer = new WebpackDevServer(devServerOptions, compiler);\n await webpackDevServer.start();\n } else {\n // Create the watcher. Compilation will start immediately after invoking watch().\n taskSession.logger.terminal.writeLine('Starting Webpack watcher');\n compiler.watch({}, (error?: Error | null) => {\n if (error) {\n taskSession.logger.emitError(error);\n }\n });\n }\n\n // Store the watchers to be used for suspend/resume\n this._webpackWatchers = (\n (compiler as ExtendedMultiCompiler).compilers ?? [compiler as ExtendedCompiler]\n ).map((compiler: ExtendedCompiler) => compiler.watching);\n }\n\n // Resume the compilation, wait for the compilation to complete, then suspend the watchers until the\n // next iteration. Even if there are no changes, the promise should resolve since resuming from a\n // suspended state invalidates the state of the watcher.\n taskSession.logger.terminal.writeLine('Running incremental Webpack compilation');\n for (const watcher of this._webpackWatchers) {\n watcher.resume();\n }\n await webpackCompilationDonePromise;\n for (const watcher of this._webpackWatchers) {\n watcher.suspend();\n }\n }\n\n private _validateEnvironmentVariable(taskSession: IHeftTaskSession): void {\n if (!this._isServeMode && process.env[WEBPACK_DEV_SERVER_ENV_VAR_NAME]) {\n taskSession.logger.emitWarning(\n new Error(\n `The \"${WEBPACK_DEV_SERVER_ENV_VAR_NAME}\" environment variable is set, ` +\n 'which will cause problems when webpack is not running in serve mode. ' +\n `(Did a dependency inadvertently load the \"${WEBPACK_DEV_SERVER_PACKAGE_NAME}\" package?)`\n )\n );\n }\n }\n\n private _emitErrors(\n logger: IScopedLogger,\n stats: TWebpack.Stats | TWebpack.MultiStats,\n buildFolderPath: string\n ): void {\n if (stats.hasErrors() || stats.hasWarnings()) {\n const serializedStats: TWebpack.StatsCompilation = stats.toJson('errors-warnings');\n\n if (serializedStats.warnings) {\n for (const warning of serializedStats.warnings) {\n logger.emitWarning(this._normalizeError(buildFolderPath, warning));\n }\n }\n\n if (serializedStats.errors) {\n for (const error of serializedStats.errors) {\n logger.emitError(this._normalizeError(buildFolderPath, error));\n }\n }\n }\n }\n\n private _normalizeError(buildFolderPath: string, error: TWebpack.StatsError): Error {\n if (error instanceof Error) {\n return error;\n } else if (error.moduleIdentifier) {\n let lineNumber: number | undefined;\n let columnNumber: number | undefined;\n if (error.loc) {\n // Format of \"<line>:<columnStart>-<columnEnd>\"\n // https://webpack.js.org/api/stats/#errors-and-warnings\n const [lineNumberRaw, columnRangeRaw] = error.loc.split(':');\n const [startColumnRaw] = columnRangeRaw.split('-');\n if (lineNumberRaw) {\n lineNumber = parseInt(lineNumberRaw, 10);\n if (isNaN(lineNumber)) {\n lineNumber = undefined;\n }\n }\n if (startColumnRaw) {\n columnNumber = parseInt(startColumnRaw, 10);\n if (isNaN(columnNumber)) {\n columnNumber = undefined;\n }\n }\n }\n\n return new FileError(error.message, {\n absolutePath: error.moduleIdentifier,\n projectFolder: buildFolderPath,\n line: lineNumber,\n column: columnNumber\n });\n } else {\n return new Error(error.message);\n }\n }\n}\n"]}
@@ -1,25 +0,0 @@
1
- {
2
- "$schema": "http://json-schema.org/draft-04/schema#",
3
- "title": "Webpack 5 Plugin Configuration",
4
- "description": "Defines options for Webpack 5 plugin execution.",
5
- "type": "object",
6
-
7
- "additionalProperties": false,
8
-
9
- "properties": {
10
- "$schema": {
11
- "description": "Part of the JSON Schema standard, this optional keyword declares the URL of the schema that the file conforms to. Editors may download the schema and use it to perform syntax highlighting.",
12
- "type": "string"
13
- },
14
-
15
- "devConfigurationPath": {
16
- "description": "Specifies a relative path to the Webpack dev configuration, which is used in \"serve\" mode. The default value is \"./webpack.dev.config.js\".",
17
- "type": "string"
18
- },
19
-
20
- "configurationPath": {
21
- "description": "Specifies a relative path to the Webpack configuration. The default value is \"./webpack.config.js\".",
22
- "type": "string"
23
- }
24
- }
25
- }