Projekt

Obecné

Profil

Stáhnout (12.3 KB) Statistiky
| Větev: | Revize:
1
"use strict";
2

    
3
Object.defineProperty(exports, "__esModule", {
4
  value: true
5
});
6
exports.default = void 0;
7

    
8
var _crypto = _interopRequireDefault(require("crypto"));
9

    
10
var _path = _interopRequireDefault(require("path"));
11

    
12
var _sourceMap = require("source-map");
13

    
14
var _webpackSources = require("webpack-sources");
15

    
16
var _RequestShortener = _interopRequireDefault(require("webpack/lib/RequestShortener"));
17

    
18
var _ModuleFilenameHelpers = _interopRequireDefault(require("webpack/lib/ModuleFilenameHelpers"));
19

    
20
var _schemaUtils = _interopRequireDefault(require("schema-utils"));
21

    
22
var _serializeJavascript = _interopRequireDefault(require("serialize-javascript"));
23

    
24
var _package = _interopRequireDefault(require("terser/package.json"));
25

    
26
var _options = _interopRequireDefault(require("./options.json"));
27

    
28
var _TaskRunner = _interopRequireDefault(require("./TaskRunner"));
29

    
30
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
31

    
32
function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
33

    
34
function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
35

    
36
function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
37

    
38
const warningRegex = /\[.+:([0-9]+),([0-9]+)\]/;
39

    
40
class TerserPlugin {
41
  constructor(options = {}) {
42
    (0, _schemaUtils.default)(_options.default, options, 'Terser Plugin');
43
    const {
44
      minify,
45
      terserOptions = {},
46
      test = /\.m?js(\?.*)?$/i,
47
      chunkFilter = () => true,
48
      warningsFilter = () => true,
49
      extractComments = false,
50
      sourceMap = false,
51
      cache = false,
52
      cacheKeys = defaultCacheKeys => defaultCacheKeys,
53
      parallel = false,
54
      include,
55
      exclude
56
    } = options;
57
    this.options = {
58
      test,
59
      chunkFilter,
60
      warningsFilter,
61
      extractComments,
62
      sourceMap,
63
      cache,
64
      cacheKeys,
65
      parallel,
66
      include,
67
      exclude,
68
      minify,
69
      terserOptions: _objectSpread({
70
        output: {
71
          comments: extractComments ? false : /^\**!|@preserve|@license|@cc_on/i
72
        }
73
      }, terserOptions)
74
    };
75
  }
76

    
77
  static isSourceMap(input) {
78
    // All required options for `new SourceMapConsumer(...options)`
79
    // https://github.com/mozilla/source-map#new-sourcemapconsumerrawsourcemap
80
    return Boolean(input && input.version && input.sources && Array.isArray(input.sources) && typeof input.mappings === 'string');
81
  }
82

    
83
  static buildSourceMap(inputSourceMap) {
84
    if (!inputSourceMap || !TerserPlugin.isSourceMap(inputSourceMap)) {
85
      return null;
86
    }
87

    
88
    return new _sourceMap.SourceMapConsumer(inputSourceMap);
89
  }
90

    
91
  static buildError(err, file, sourceMap, requestShortener) {
92
    // Handling error which should have line, col, filename and message
93
    if (err.line) {
94
      const original = sourceMap && sourceMap.originalPositionFor({
95
        line: err.line,
96
        column: err.col
97
      });
98

    
99
      if (original && original.source && requestShortener) {
100
        return new Error(`${file} from Terser\n${err.message} [${requestShortener.shorten(original.source)}:${original.line},${original.column}][${file}:${err.line},${err.col}]`);
101
      }
102

    
103
      return new Error(`${file} from Terser\n${err.message} [${file}:${err.line},${err.col}]`);
104
    } else if (err.stack) {
105
      return new Error(`${file} from Terser\n${err.stack}`);
106
    }
107

    
108
    return new Error(`${file} from Terser\n${err.message}`);
109
  }
110

    
111
  static buildWarning(warning, file, sourceMap, requestShortener, warningsFilter) {
112
    let warningMessage = warning;
113
    let locationMessage = '';
114
    let source = null;
115

    
116
    if (sourceMap) {
117
      const match = warningRegex.exec(warning);
118

    
119
      if (match) {
120
        const line = +match[1];
121
        const column = +match[2];
122
        const original = sourceMap.originalPositionFor({
123
          line,
124
          column
125
        });
126

    
127
        if (original && original.source && original.source !== file && requestShortener) {
128
          ({
129
            source
130
          } = original);
131
          warningMessage = `${warningMessage.replace(warningRegex, '')}`;
132
          locationMessage = `[${requestShortener.shorten(original.source)}:${original.line},${original.column}]`;
133
        }
134
      }
135
    }
136

    
137
    if (warningsFilter && !warningsFilter(warning, source)) {
138
      return null;
139
    }
140

    
141
    return `Terser Plugin: ${warningMessage}${locationMessage}`;
142
  }
143

    
144
  apply(compiler) {
145
    const buildModuleFn = moduleArg => {
146
      // to get detailed location info about errors
147
      moduleArg.useSourceMap = true;
148
    };
149

    
150
    const optimizeFn = (compilation, chunks, callback) => {
151
      const taskRunner = new _TaskRunner.default({
152
        cache: this.options.cache,
153
        parallel: this.options.parallel
154
      });
155
      const processedAssets = new WeakSet();
156
      const tasks = [];
157
      const {
158
        chunkFilter
159
      } = this.options;
160
      Array.from(chunks).filter(chunk => chunkFilter && chunkFilter(chunk)).reduce((acc, chunk) => acc.concat(chunk.files || []), []).concat(compilation.additionalChunkAssets || []).filter(_ModuleFilenameHelpers.default.matchObject.bind(null, this.options)).forEach(file => {
161
        let inputSourceMap;
162
        const asset = compilation.assets[file];
163

    
164
        if (processedAssets.has(asset)) {
165
          return;
166
        }
167

    
168
        try {
169
          let input;
170

    
171
          if (this.options.sourceMap && asset.sourceAndMap) {
172
            const {
173
              source,
174
              map
175
            } = asset.sourceAndMap();
176
            input = source;
177

    
178
            if (TerserPlugin.isSourceMap(map)) {
179
              inputSourceMap = map;
180
            } else {
181
              inputSourceMap = map;
182
              compilation.warnings.push(new Error(`${file} contains invalid source map`));
183
            }
184
          } else {
185
            input = asset.source();
186
            inputSourceMap = null;
187
          } // Handling comment extraction
188

    
189

    
190
          let commentsFile = false;
191

    
192
          if (this.options.extractComments) {
193
            commentsFile = this.options.extractComments.filename || `${file}.LICENSE`;
194

    
195
            if (typeof commentsFile === 'function') {
196
              commentsFile = commentsFile(file);
197
            }
198
          }
199

    
200
          const task = {
201
            file,
202
            input,
203
            inputSourceMap,
204
            commentsFile,
205
            extractComments: this.options.extractComments,
206
            terserOptions: this.options.terserOptions,
207
            minify: this.options.minify
208
          };
209

    
210
          if (this.options.cache) {
211
            const defaultCacheKeys = {
212
              terser: _package.default.version,
213
              node_version: process.version,
214
              // eslint-disable-next-line global-require
215
              'terser-webpack-plugin': require('../package.json').version,
216
              'terser-webpack-plugin-options': this.options,
217
              hash: _crypto.default.createHash('md4').update(input).digest('hex')
218
            };
219
            task.cacheKeys = this.options.cacheKeys(defaultCacheKeys, file);
220
          }
221

    
222
          tasks.push(task);
223
        } catch (error) {
224
          compilation.errors.push(TerserPlugin.buildError(error, file, TerserPlugin.buildSourceMap(inputSourceMap), new _RequestShortener.default(compiler.context)));
225
        }
226
      });
227
      taskRunner.run(tasks, (tasksError, results) => {
228
        if (tasksError) {
229
          compilation.errors.push(tasksError);
230
          return;
231
        }
232

    
233
        results.forEach((data, index) => {
234
          const {
235
            file,
236
            input,
237
            inputSourceMap,
238
            commentsFile
239
          } = tasks[index];
240
          const {
241
            error,
242
            map,
243
            code,
244
            warnings
245
          } = data;
246
          let {
247
            extractedComments
248
          } = data;
249
          let sourceMap = null;
250

    
251
          if (error || warnings && warnings.length > 0) {
252
            sourceMap = TerserPlugin.buildSourceMap(inputSourceMap);
253
          } // Handling results
254
          // Error case: add errors, and go to next file
255

    
256

    
257
          if (error) {
258
            compilation.errors.push(TerserPlugin.buildError(error, file, sourceMap, new _RequestShortener.default(compiler.context)));
259
            return;
260
          }
261

    
262
          let outputSource;
263

    
264
          if (map) {
265
            outputSource = new _webpackSources.SourceMapSource(code, file, JSON.parse(map), input, inputSourceMap, true);
266
          } else {
267
            outputSource = new _webpackSources.RawSource(code);
268
          } // Write extracted comments to commentsFile
269

    
270

    
271
          if (commentsFile && extractedComments && extractedComments.length > 0) {
272
            if (commentsFile in compilation.assets) {
273
              const commentsFileSource = compilation.assets[commentsFile].source();
274
              extractedComments = extractedComments.filter(comment => !commentsFileSource.includes(comment));
275
            }
276

    
277
            if (extractedComments.length > 0) {
278
              // Add a banner to the original file
279
              if (this.options.extractComments.banner !== false) {
280
                let banner = this.options.extractComments.banner || `For license information please see ${_path.default.posix.basename(commentsFile)}`;
281

    
282
                if (typeof banner === 'function') {
283
                  banner = banner(commentsFile);
284
                }
285

    
286
                if (banner) {
287
                  outputSource = new _webpackSources.ConcatSource(`/*! ${banner} */\n`, outputSource);
288
                }
289
              }
290

    
291
              const commentsSource = new _webpackSources.RawSource(`${extractedComments.join('\n\n')}\n`);
292

    
293
              if (commentsFile in compilation.assets) {
294
                // commentsFile already exists, append new comments...
295
                if (compilation.assets[commentsFile] instanceof _webpackSources.ConcatSource) {
296
                  compilation.assets[commentsFile].add('\n');
297
                  compilation.assets[commentsFile].add(commentsSource);
298
                } else {
299
                  compilation.assets[commentsFile] = new _webpackSources.ConcatSource(compilation.assets[commentsFile], '\n', commentsSource);
300
                }
301
              } else {
302
                compilation.assets[commentsFile] = commentsSource;
303
              }
304
            }
305
          } // Updating assets
306

    
307

    
308
          processedAssets.add(compilation.assets[file] = outputSource); // Handling warnings
309

    
310
          if (warnings && warnings.length > 0) {
311
            warnings.forEach(warning => {
312
              const builtWarning = TerserPlugin.buildWarning(warning, file, sourceMap, new _RequestShortener.default(compiler.context), this.options.warningsFilter);
313

    
314
              if (builtWarning) {
315
                compilation.warnings.push(builtWarning);
316
              }
317
            });
318
          }
319
        });
320
        taskRunner.exit();
321
        callback();
322
      });
323
    };
324

    
325
    const plugin = {
326
      name: this.constructor.name
327
    };
328
    compiler.hooks.compilation.tap(plugin, compilation => {
329
      if (this.options.sourceMap) {
330
        compilation.hooks.buildModule.tap(plugin, buildModuleFn);
331
      }
332

    
333
      const {
334
        mainTemplate,
335
        chunkTemplate
336
      } = compilation; // Regenerate `contenthash` for minified assets
337

    
338
      for (const template of [mainTemplate, chunkTemplate]) {
339
        template.hooks.hashForChunk.tap(plugin, hash => {
340
          const data = (0, _serializeJavascript.default)({
341
            terser: _package.default.version,
342
            terserOptions: this.options.terserOptions
343
          });
344
          hash.update('TerserPlugin');
345
          hash.update(data);
346
        });
347
      }
348

    
349
      compilation.hooks.optimizeChunkAssets.tapAsync(plugin, optimizeFn.bind(this, compilation));
350
    });
351
  }
352

    
353
}
354

    
355
var _default = TerserPlugin;
356
exports.default = _default;
(3-3/6)