This commit is contained in:
chrosey
2017-09-13 07:52:34 +02:00
parent a1f16c37f4
commit 2340b0226b
24621 changed files with 2912161 additions and 149 deletions
+51
View File
@@ -0,0 +1,51 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConstDependency = require("./dependencies/ConstDependency");
const ParserHelpers = require("./ParserHelpers");
const NullFactory = require("./NullFactory");
const REPLACEMENTS = {
__webpack_require__: "__webpack_require__", // eslint-disable-line camelcase
__webpack_public_path__: "__webpack_require__.p", // eslint-disable-line camelcase
__webpack_modules__: "__webpack_require__.m", // eslint-disable-line camelcase
__webpack_chunk_load__: "__webpack_require__.e", // eslint-disable-line camelcase
__non_webpack_require__: "require", // eslint-disable-line camelcase
__webpack_nonce__: "__webpack_require__.nc", // eslint-disable-line camelcase
"require.onError": "__webpack_require__.oe" // eslint-disable-line camelcase
};
const REPLACEMENT_TYPES = {
__webpack_public_path__: "string", // eslint-disable-line camelcase
__webpack_require__: "function", // eslint-disable-line camelcase
__webpack_modules__: "object", // eslint-disable-line camelcase
__webpack_chunk_load__: "function", // eslint-disable-line camelcase
__webpack_nonce__: "string" // eslint-disable-line camelcase
};
const IGNORES = [];
class APIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
IGNORES.forEach(key => {
parser.plugin(key, ParserHelpers.skipTraversal);
});
});
});
}
}
module.exports = APIPlugin;
+56
View File
@@ -0,0 +1,56 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConcatSource = require("webpack-sources").ConcatSource;
const Template = require("./Template");
class AmdMainTemplatePlugin {
constructor(name) {
this.name = name;
}
apply(compilation) {
const mainTemplate = compilation.mainTemplate;
compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
const externals = chunk.modules.filter((m) => m.external);
const externalsDepsArray = JSON.stringify(externals.map((m) =>
typeof m.request === "object" ? m.request.amd : m.request
));
const externalsArguments = externals.map((m) =>
Template.toIdentifier(`__WEBPACK_EXTERNAL_MODULE_${m.id}__`)
).join(", ");
if(this.name) {
const name = mainTemplate.applyPluginsWaterfall("asset-path", this.name, {
hash,
chunk
});
return new ConcatSource(
`define(${JSON.stringify(name)}, ${externalsDepsArray}, function(${externalsArguments}) { return `, source, "});"
);
} else if(externalsArguments) {
return new ConcatSource(`define(${externalsDepsArray}, function(${externalsArguments}) { return `, source, "});");
} else {
return new ConcatSource("define(function() { return ", source, "});");
}
});
mainTemplate.plugin("global-hash-paths", (paths) => {
if(this.name) paths.push(this.name);
return paths;
});
mainTemplate.plugin("hash", (hash) => {
hash.update("exports amd");
hash.update(this.name);
});
}
}
module.exports = AmdMainTemplatePlugin;
+53
View File
@@ -0,0 +1,53 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DependenciesBlock = require("./DependenciesBlock");
module.exports = class AsyncDependenciesBlock extends DependenciesBlock {
constructor(name, module, loc) {
super();
this.chunkName = name;
this.chunks = null;
this.module = module;
this.loc = loc;
}
get chunk() {
throw new Error("`chunk` was been renamed to `chunks` and is now an array");
}
set chunk(chunk) {
throw new Error("`chunk` was been renamed to `chunks` and is now an array");
}
updateHash(hash) {
hash.update(this.chunkName || "");
hash.update(this.chunks && this.chunks.map((chunk) => {
return typeof chunk.id === "number" ? chunk.id : "";
}).join(",") || "");
super.updateHash(hash);
}
disconnect() {
this.chunks = null;
super.disconnect();
}
unseal() {
this.chunks = null;
super.unseal();
}
sortItems() {
super.sortItems();
if(this.chunks) {
this.chunks.sort((a, b) => {
let i = 0;
while(true) { // eslint-disable-line no-constant-condition
if(!a.modules[i] && !b.modules[i]) return 0;
if(!a.modules[i]) return -1;
if(!b.modules[i]) return 1;
if(a.modules[i].id > b.modules[i].id) return 1;
if(a.modules[i].id < b.modules[i].id) return -1;
i++;
}
});
}
}
};
+36
View File
@@ -0,0 +1,36 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const async = require("async");
const PrefetchDependency = require("./dependencies/PrefetchDependency");
const NormalModule = require("./NormalModule");
class AutomaticPrefetchPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
const normalModuleFactory = params.normalModuleFactory;
compilation.dependencyFactories.set(PrefetchDependency, normalModuleFactory);
});
let lastModules = null;
compiler.plugin("after-compile", (compilation, callback) => {
lastModules = compilation.modules
.filter(m => m instanceof NormalModule)
.map(m => ({
context: m.context,
request: m.request
}));
callback();
});
compiler.plugin("make", (compilation, callback) => {
if(!lastModules) return callback();
async.forEach(lastModules, (m, callback) => {
compilation.prefetch(m.context || compiler.context, new PrefetchDependency(m.request), callback);
}, callback);
});
}
}
module.exports = AutomaticPrefetchPlugin;
+51
View File
@@ -0,0 +1,51 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConcatSource = require("webpack-sources").ConcatSource;
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
function wrapComment(str) {
if(!str.includes("\n")) return `/*! ${str} */`;
return `/*!\n * ${str.split("\n").join("\n * ")}\n */`;
}
class BannerPlugin {
constructor(options) {
if(arguments.length > 1)
throw new Error("BannerPlugin only takes one argument (pass an options object)");
if(typeof options === "string")
options = {
banner: options
};
this.options = options || {};
this.banner = this.options.raw ? options.banner : wrapComment(options.banner);
}
apply(compiler) {
const options = this.options;
const banner = this.banner;
compiler.plugin("compilation", (compilation) => {
compilation.plugin("optimize-chunk-assets", (chunks, callback) => {
chunks.forEach((chunk) => {
if(options.entryOnly && !chunk.isInitial()) return;
chunk.files
.filter(ModuleFilenameHelpers.matchObject.bind(undefined, options))
.forEach((file) =>
compilation.assets[file] = new ConcatSource(
banner, "\n", compilation.assets[file]
)
);
});
callback();
});
});
}
}
module.exports = BannerPlugin;
+181
View File
@@ -0,0 +1,181 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class BasicEvaluatedExpression {
constructor() {
this.range = null;
}
isNull() {
return !!this.null;
}
isString() {
return Object.prototype.hasOwnProperty.call(this, "string");
}
isNumber() {
return Object.prototype.hasOwnProperty.call(this, "number");
}
isBoolean() {
return Object.prototype.hasOwnProperty.call(this, "bool");
}
isRegExp() {
return Object.prototype.hasOwnProperty.call(this, "regExp");
}
isConditional() {
return Object.prototype.hasOwnProperty.call(this, "options");
}
isArray() {
return Object.prototype.hasOwnProperty.call(this, "items");
}
isConstArray() {
return Object.prototype.hasOwnProperty.call(this, "array");
}
isIdentifier() {
return Object.prototype.hasOwnProperty.call(this, "identifier");
}
isWrapped() {
return Object.prototype.hasOwnProperty.call(this, "prefix") || Object.prototype.hasOwnProperty.call(this, "postfix");
}
isTemplateString() {
return Object.prototype.hasOwnProperty.call(this, "quasis");
}
asBool() {
if(this.isBoolean()) return this.bool;
else if(this.isNull()) return false;
else if(this.isString()) return !!this.string;
else if(this.isNumber()) return !!this.number;
else if(this.isRegExp()) return true;
else if(this.isArray()) return true;
else if(this.isConstArray()) return true;
else if(this.isWrapped()) return this.prefix && this.prefix.asBool() || this.postfix && this.postfix.asBool() ? true : undefined;
else if(this.isTemplateString()) {
if(this.quasis.length === 1) return this.quasis[0].asBool();
for(let i = 0; i < this.quasis.length; i++) {
if(this.quasis[i].asBool()) return true;
}
// can't tell if string will be empty without executing
}
return undefined;
}
setString(str) {
if(str === null)
delete this.string;
else
this.string = str;
return this;
}
setNull() {
this.null = true;
return this;
}
setNumber(num) {
if(num === null)
delete this.number;
else
this.number = num;
return this;
}
setBoolean(bool) {
if(bool === null)
delete this.bool;
else
this.bool = bool;
return this;
}
setRegExp(regExp) {
if(regExp === null)
delete this.regExp;
else
this.regExp = regExp;
return this;
}
setIdentifier(identifier) {
if(identifier === null)
delete this.identifier;
else
this.identifier = identifier;
return this;
}
setWrapped(prefix, postfix) {
this.prefix = prefix;
this.postfix = postfix;
return this;
}
unsetWrapped() {
delete this.prefix;
delete this.postfix;
return this;
}
setOptions(options) {
if(options === null)
delete this.options;
else
this.options = options;
return this;
}
setItems(items) {
if(items === null)
delete this.items;
else
this.items = items;
return this;
}
setArray(array) {
if(array === null)
delete this.array;
else
this.array = array;
return this;
}
setTemplateString(quasis) {
if(quasis === null)
delete this.quasis;
else
this.quasis = quasis;
return this;
}
addOptions(options) {
if(!this.options) this.options = [];
options.forEach(item => {
this.options.push(item);
}, this);
return this;
}
setRange(range) {
this.range = range;
return this;
}
}
module.exports = BasicEvaluatedExpression;
+79
View File
@@ -0,0 +1,79 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const async = require("async");
class CachePlugin {
constructor(cache) {
this.cache = cache || {};
this.FS_ACCURENCY = 2000;
}
apply(compiler) {
if(Array.isArray(compiler.compilers)) {
compiler.compilers.forEach((c, idx) => {
c.apply(new CachePlugin(this.cache[idx] = this.cache[idx] || {}));
});
} else {
compiler.plugin("compilation", compilation => {
if(!compilation.notCacheable) {
compilation.cache = this.cache;
} else if(this.watching) {
compilation.warnings.push(
new Error(`CachePlugin - Cache cannot be used because of: ${compilation.notCacheable}`)
);
}
});
compiler.plugin("watch-run", (compiler, callback) => {
this.watching = true;
callback();
});
compiler.plugin("run", (compiler, callback) => {
if(!compiler._lastCompilationFileDependencies) return callback();
const fs = compiler.inputFileSystem;
const fileTs = compiler.fileTimestamps = {};
async.forEach(compiler._lastCompilationFileDependencies, (file, callback) => {
fs.stat(file, (err, stat) => {
if(err) {
if(err.code === "ENOENT") return callback();
return callback(err);
}
if(stat.mtime)
this.applyMtime(+stat.mtime);
fileTs[file] = +stat.mtime || Infinity;
callback();
});
}, err => {
if(err) return callback(err);
Object.keys(fileTs).forEach(key => {
fileTs[key] += this.FS_ACCURENCY;
});
callback();
});
});
compiler.plugin("after-compile", function(compilation, callback) {
compilation.compiler._lastCompilationFileDependencies = compilation.fileDependencies;
compilation.compiler._lastCompilationContextDependencies = compilation.contextDependencies;
callback();
});
}
}
/* istanbul ignore next */
applyMtime(mtime) {
if(this.FS_ACCURENCY > 1 && mtime % 2 !== 0)
this.FS_ACCURENCY = 1;
else if(this.FS_ACCURENCY > 10 && mtime % 20 !== 0)
this.FS_ACCURENCY = 10;
else if(this.FS_ACCURENCY > 100 && mtime % 200 !== 0)
this.FS_ACCURENCY = 100;
else if(this.FS_ACCURENCY > 1000 && mtime % 2000 !== 0)
this.FS_ACCURENCY = 1000;
}
}
module.exports = CachePlugin;
+46
View File
@@ -0,0 +1,46 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
module.exports = class CaseSensitiveModulesWarning extends Error {
constructor(modules) {
super();
this.name = "CaseSensitiveModulesWarning";
const sortedModules = this._sort(modules);
const modulesList = this._moduleMessages(sortedModules);
this.message = "There are multiple modules with names that only differ in casing.\n" +
"This can lead to unexpected behavior when compiling on a filesystem with other case-semantic.\n" +
`Use equal casing. Compare these module identifiers:\n${modulesList}`;
this.origin = this.module = sortedModules[0];
Error.captureStackTrace(this, CaseSensitiveModulesWarning);
}
_sort(modules) {
return modules.slice().sort((a, b) => {
a = a.identifier();
b = b.identifier();
/* istanbul ignore next */
if(a < b) return -1;
/* istanbul ignore next */
if(a > b) return 1;
/* istanbul ignore next */
return 0;
});
}
_moduleMessages(modules) {
return modules.map((m) => {
let message = `* ${m.identifier()}`;
const validReasons = m.reasons.filter((reason) => reason.module);
if(validReasons.length > 0) {
message += `\n Used by ${validReasons.length} module(s), i. e.`;
message += `\n ${validReasons[0].module.identifier()}`;
}
return message;
}).join("\n");
}
};
+396
View File
@@ -0,0 +1,396 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const compareLocations = require("./compareLocations");
let debugId = 1000;
const byId = (a, b) => {
if(a.id < b.id) return -1;
if(b.id < a.id) return 1;
return 0;
};
class Chunk {
constructor(name, module, loc) {
this.id = null;
this.ids = null;
this.debugId = debugId++;
this.name = name;
this.modules = [];
this.entrypoints = [];
this.chunks = [];
this.parents = [];
this.blocks = [];
this.origins = [];
this.files = [];
this.rendered = false;
if(module) {
this.origins.push({
module,
loc,
name
});
}
}
get entry() {
throw new Error("Chunk.entry was removed. Use hasRuntime()");
}
set entry(data) {
throw new Error("Chunk.entry was removed. Use hasRuntime()");
}
get initial() {
throw new Error("Chunk.initial was removed. Use isInitial()");
}
set initial(data) {
throw new Error("Chunk.initial was removed. Use isInitial()");
}
hasRuntime() {
if(this.entrypoints.length === 0) return false;
return this.entrypoints[0].chunks[0] === this;
}
isInitial() {
return this.entrypoints.length > 0;
}
hasEntryModule() {
return !!this.entryModule;
}
addToCollection(collection, item) {
if(item === this) {
return false;
}
if(collection.indexOf(item) > -1) {
return false;
}
collection.push(item);
return true;
}
addChunk(chunk) {
return this.addToCollection(this.chunks, chunk);
}
addParent(parentChunk) {
return this.addToCollection(this.parents, parentChunk);
}
addModule(module) {
return this.addToCollection(this.modules, module);
}
addBlock(block) {
return this.addToCollection(this.blocks, block);
}
removeModule(module) {
const idx = this.modules.indexOf(module);
if(idx >= 0) {
this.modules.splice(idx, 1);
module.removeChunk(this);
return true;
}
return false;
}
removeChunk(chunk) {
const idx = this.chunks.indexOf(chunk);
if(idx >= 0) {
this.chunks.splice(idx, 1);
chunk.removeParent(this);
return true;
}
return false;
}
removeParent(chunk) {
const idx = this.parents.indexOf(chunk);
if(idx >= 0) {
this.parents.splice(idx, 1);
chunk.removeChunk(this);
return true;
}
return false;
}
addOrigin(module, loc) {
this.origins.push({
module,
loc,
name: this.name
});
}
remove(reason) {
// cleanup modules
this.modules.slice().forEach(module => {
module.removeChunk(this);
});
// cleanup parents
this.parents.forEach(parentChunk => {
// remove this chunk from its parents
const idx = parentChunk.chunks.indexOf(this);
if(idx >= 0) {
parentChunk.chunks.splice(idx, 1);
}
// cleanup "sub chunks"
this.chunks.forEach(chunk => {
/**
* remove this chunk as "intermediary" and connect
* it "sub chunks" and parents directly
*/
// add parent to each "sub chunk"
chunk.addParent(parentChunk);
// add "sub chunk" to parent
parentChunk.addChunk(chunk);
});
});
/**
* we need to iterate again over the chunks
* to remove this from the chunks parents.
* This can not be done in the above loop
* as it is not garuanteed that `this.parents` contains anything.
*/
this.chunks.forEach(chunk => {
// remove this as parent of every "sub chunk"
const idx = chunk.parents.indexOf(this);
if(idx >= 0) {
chunk.parents.splice(idx, 1);
}
});
// cleanup blocks
this.blocks.forEach(block => {
const idx = block.chunks.indexOf(this);
if(idx >= 0) {
block.chunks.splice(idx, 1);
if(block.chunks.length === 0) {
block.chunks = null;
block.chunkReason = reason;
}
}
});
}
moveModule(module, otherChunk) {
module.removeChunk(this);
module.addChunk(otherChunk);
otherChunk.addModule(module);
module.rewriteChunkInReasons(this, [otherChunk]);
}
replaceChunk(oldChunk, newChunk) {
const idx = this.chunks.indexOf(oldChunk);
if(idx >= 0) {
this.chunks.splice(idx, 1);
}
if(this !== newChunk && newChunk.addParent(this)) {
this.addChunk(newChunk);
}
}
replaceParentChunk(oldParentChunk, newParentChunk) {
const idx = this.parents.indexOf(oldParentChunk);
if(idx >= 0) {
this.parents.splice(idx, 1);
}
if(this !== newParentChunk && newParentChunk.addChunk(this)) {
this.addParent(newParentChunk);
}
}
integrate(otherChunk, reason) {
if(!this.canBeIntegrated(otherChunk)) {
return false;
}
const otherChunkModules = otherChunk.modules.slice();
otherChunkModules.forEach(module => otherChunk.moveModule(module, this));
otherChunk.modules.length = 0;
otherChunk.parents.forEach(parentChunk => parentChunk.replaceChunk(otherChunk, this));
otherChunk.parents.length = 0;
otherChunk.chunks.forEach(chunk => chunk.replaceParentChunk(otherChunk, this));
otherChunk.chunks.length = 0;
otherChunk.blocks.forEach(b => {
b.chunks = b.chunks ? b.chunks.map(c => {
return c === otherChunk ? this : c;
}) : [this];
b.chunkReason = reason;
this.addBlock(b);
});
otherChunk.blocks.length = 0;
otherChunk.origins.forEach(origin => {
this.origins.push(origin);
});
this.origins.forEach(origin => {
if(!origin.reasons) {
origin.reasons = [reason];
} else if(origin.reasons[0] !== reason) {
origin.reasons.unshift(reason);
}
});
this.chunks = this.chunks.filter(chunk => {
return chunk !== otherChunk && chunk !== this;
});
this.parents = this.parents.filter(parentChunk => {
return parentChunk !== otherChunk && parentChunk !== this;
});
return true;
}
split(newChunk) {
this.blocks.forEach(block => {
newChunk.blocks.push(block);
block.chunks.push(newChunk);
});
this.chunks.forEach(chunk => {
newChunk.chunks.push(chunk);
chunk.parents.push(newChunk);
});
this.parents.forEach(parentChunk => {
parentChunk.chunks.push(newChunk);
newChunk.parents.push(parentChunk);
});
this.entrypoints.forEach(entrypoint => {
entrypoint.insertChunk(newChunk, this);
});
}
isEmpty() {
return this.modules.length === 0;
}
updateHash(hash) {
hash.update(`${this.id} `);
hash.update(this.ids ? this.ids.join(",") : "");
hash.update(`${this.name || ""} `);
this.modules.forEach(m => m.updateHash(hash));
}
canBeIntegrated(otherChunk) {
if(otherChunk.isInitial()) {
return false;
}
if(this.isInitial()) {
if(otherChunk.parents.length !== 1 || otherChunk.parents[0] !== this) {
return false;
}
}
return true;
}
addMultiplierAndOverhead(size, options) {
const overhead = typeof options.chunkOverhead === "number" ? options.chunkOverhead : 10000;
const multiplicator = this.isInitial() ? (options.entryChunkMultiplicator || 10) : 1;
return size * multiplicator + overhead;
}
modulesSize() {
let count = 0;
for(let i = 0; i < this.modules.length; i++) {
count += this.modules[i].size();
}
return count;
}
size(options) {
return this.addMultiplierAndOverhead(this.modulesSize(), options);
}
integratedSize(otherChunk, options) {
// Chunk if it's possible to integrate this chunk
if(!this.canBeIntegrated(otherChunk)) {
return false;
}
let integratedModulesSize = this.modulesSize();
// only count modules that do not exist in this chunk!
for(let i = 0; i < otherChunk.modules.length; i++) {
const otherModule = otherChunk.modules[i];
if(this.modules.indexOf(otherModule) === -1) {
integratedModulesSize += otherModule.size();
}
}
return this.addMultiplierAndOverhead(integratedModulesSize, options);
}
getChunkMaps(includeEntries, realHash) {
const chunksProcessed = [];
const chunkHashMap = {};
const chunkNameMap = {};
(function addChunk(chunk) {
if(chunksProcessed.indexOf(chunk) >= 0) return;
chunksProcessed.push(chunk);
if(!chunk.hasRuntime() || includeEntries) {
chunkHashMap[chunk.id] = realHash ? chunk.hash : chunk.renderedHash;
if(chunk.name)
chunkNameMap[chunk.id] = chunk.name;
}
chunk.chunks.forEach(addChunk);
}(this));
return {
hash: chunkHashMap,
name: chunkNameMap
};
}
sortItems() {
this.modules.sort(byId);
this.origins.sort((a, b) => {
const aIdent = a.module.identifier();
const bIdent = b.module.identifier();
if(aIdent < bIdent) return -1;
if(aIdent > bIdent) return 1;
return compareLocations(a.loc, b.loc);
});
this.origins.forEach(origin => {
if(origin.reasons)
origin.reasons.sort();
});
this.parents.sort(byId);
this.chunks.sort(byId);
}
toString() {
return `Chunk[${this.modules.join()}]`;
}
checkConstraints() {
const chunk = this;
chunk.chunks.forEach((child, idx) => {
if(chunk.chunks.indexOf(child) !== idx)
throw new Error(`checkConstraints: duplicate child in chunk ${chunk.debugId} ${child.debugId}`);
if(child.parents.indexOf(chunk) < 0)
throw new Error(`checkConstraints: child missing parent ${chunk.debugId} -> ${child.debugId}`);
});
chunk.parents.forEach((parentChunk, idx) => {
if(chunk.parents.indexOf(parentChunk) !== idx)
throw new Error(`checkConstraints: duplicate parent in chunk ${chunk.debugId} ${parentChunk.debugId}`);
if(parentChunk.chunks.indexOf(chunk) < 0)
throw new Error(`checkConstraints: parent missing child ${parentChunk.debugId} <- ${chunk.debugId}`);
});
}
}
module.exports = Chunk;
+22
View File
@@ -0,0 +1,22 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class ChunkRenderError extends Error {
constructor(chunk, file, error) {
super();
this.name = "ChunkRenderError";
this.error = error;
this.message = error.message;
this.details = error.stack;
this.file = file;
this.chunk = chunk;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = ChunkRenderError;
+36
View File
@@ -0,0 +1,36 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConcatSource = require("webpack-sources").ConcatSource;
const Template = require("./Template");
module.exports = class ChunkTemplate extends Template {
constructor(outputOptions) {
super(outputOptions);
}
render(chunk, moduleTemplate, dependencyTemplates) {
const modules = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates);
const core = this.applyPluginsWaterfall("modules", modules, chunk, moduleTemplate, dependencyTemplates);
let source = this.applyPluginsWaterfall("render", core, chunk, moduleTemplate, dependencyTemplates);
if(chunk.hasEntryModule()) {
source = this.applyPluginsWaterfall("render-with-entry", source, chunk);
}
chunk.rendered = true;
return new ConcatSource(source, ";");
}
updateHash(hash) {
hash.update("ChunkTemplate");
hash.update("2");
this.applyPlugins("hash", hash);
}
updateHashForChunk(hash, chunk) {
this.updateHash(hash);
this.applyPlugins("hash-for-chunk", hash, chunk);
}
};
+57
View File
@@ -0,0 +1,57 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConstDependency = require("./dependencies/ConstDependency");
const NullFactory = require("./NullFactory");
const jsonLoaderPath = require.resolve("json-loader");
const matchJson = /\.json$/i;
class CompatibilityPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
if(typeof parserOptions.browserify !== "undefined" && !parserOptions.browserify)
return;
parser.plugin("call require", (expr) => {
// support for browserify style require delegator: "require(o, !0)"
if(expr.arguments.length !== 2) return;
const second = parser.evaluateExpression(expr.arguments[1]);
if(!second.isBoolean()) return;
if(second.asBool() !== true) return;
const dep = new ConstDependency("require", expr.callee.range);
dep.loc = expr.loc;
if(parser.state.current.dependencies.length > 1) {
const last = parser.state.current.dependencies[parser.state.current.dependencies.length - 1];
if(last.critical && last.request === "." && last.userRequest === "." && last.recursive)
parser.state.current.dependencies.pop();
}
parser.state.current.addDependency(dep);
return true;
});
});
params.normalModuleFactory.plugin("after-resolve", (data, done) => {
// if this is a json file and there are no loaders active, we use the json-loader in order to avoid parse errors
// @see https://github.com/webpack/webpack/issues/3363
if(matchJson.test(data.request) && data.loaders.length === 0) {
data.loaders.push({
loader: jsonLoaderPath
});
}
done(null, data);
});
});
}
}
module.exports = CompatibilityPlugin;
+1247
View File
File diff suppressed because it is too large Load Diff
+499
View File
@@ -0,0 +1,499 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var path = require("path");
var Tapable = require("tapable");
var Compilation = require("./Compilation");
var NormalModuleFactory = require("./NormalModuleFactory");
var ContextModuleFactory = require("./ContextModuleFactory");
function Watching(compiler, watchOptions, handler) {
this.startTime = null;
this.invalid = false;
this.error = null;
this.stats = null;
this.handler = handler;
this.closed = false;
if(typeof watchOptions === "number") {
this.watchOptions = {
aggregateTimeout: watchOptions
};
} else if(watchOptions && typeof watchOptions === "object") {
this.watchOptions = Object.assign({}, watchOptions);
} else {
this.watchOptions = {};
}
this.watchOptions.aggregateTimeout = this.watchOptions.aggregateTimeout || 200;
this.compiler = compiler;
this.running = true;
this.compiler.readRecords(function(err) {
if(err) return this._done(err);
this._go();
}.bind(this));
}
Watching.prototype._go = function() {
var self = this;
self.startTime = new Date().getTime();
self.running = true;
self.invalid = false;
self.compiler.applyPluginsAsync("watch-run", self, function(err) {
if(err) return self._done(err);
self.compiler.compile(function onCompiled(err, compilation) {
if(err) return self._done(err);
if(self.invalid) return self._done();
if(self.compiler.applyPluginsBailResult("should-emit", compilation) === false) {
return self._done(null, compilation);
}
self.compiler.emitAssets(compilation, function(err) {
if(err) return self._done(err);
if(self.invalid) return self._done();
self.compiler.emitRecords(function(err) {
if(err) return self._done(err);
if(compilation.applyPluginsBailResult("need-additional-pass")) {
compilation.needAdditionalPass = true;
var stats = compilation.getStats();
stats.startTime = self.startTime;
stats.endTime = new Date().getTime();
self.compiler.applyPlugins("done", stats);
self.compiler.applyPluginsAsync("additional-pass", function(err) {
if(err) return self._done(err);
self.compiler.compile(onCompiled);
});
return;
}
return self._done(null, compilation);
});
});
});
});
};
Watching.prototype._done = function(err, compilation) {
this.running = false;
if(this.invalid) return this._go();
this.error = err || null;
this.stats = compilation ? compilation.getStats() : null;
if(this.stats) {
this.stats.startTime = this.startTime;
this.stats.endTime = new Date().getTime();
}
if(this.stats)
this.compiler.applyPlugins("done", this.stats);
else
this.compiler.applyPlugins("failed", this.error);
this.handler(this.error, this.stats);
if(!this.error && !this.closed)
this.watch(compilation.fileDependencies, compilation.contextDependencies, compilation.missingDependencies);
};
Watching.prototype.watch = function(files, dirs, missing) {
this.pausedWatcher = null;
this.watcher = this.compiler.watchFileSystem.watch(files, dirs, missing, this.startTime, this.watchOptions, function(err, filesModified, contextModified, missingModified, fileTimestamps, contextTimestamps) {
this.pausedWatcher = this.watcher;
this.watcher = null;
if(err) return this.handler(err);
this.compiler.fileTimestamps = fileTimestamps;
this.compiler.contextTimestamps = contextTimestamps;
this.invalidate();
}.bind(this), function(fileName, changeTime) {
this.compiler.applyPlugins("invalid", fileName, changeTime);
}.bind(this));
};
Watching.prototype.invalidate = function() {
if(this.watcher) {
this.pausedWatcher = this.watcher;
this.watcher.pause();
this.watcher = null;
}
if(this.running) {
this.invalid = true;
return false;
} else {
this._go();
}
};
Watching.prototype.close = function(callback) {
if(callback === undefined) callback = function() {};
this.closed = true;
if(this.watcher) {
this.watcher.close();
this.watcher = null;
}
if(this.pausedWatcher) {
this.pausedWatcher.close();
this.pausedWatcher = null;
}
if(this.running) {
this.invalid = true;
this._done = () => {
this.compiler.applyPlugins("watch-close");
callback();
};
} else {
this.compiler.applyPlugins("watch-close");
callback();
}
};
function Compiler() {
Tapable.call(this);
this.outputPath = "";
this.outputFileSystem = null;
this.inputFileSystem = null;
this.recordsInputPath = null;
this.recordsOutputPath = null;
this.records = {};
this.fileTimestamps = {};
this.contextTimestamps = {};
this.resolvers = {
normal: null,
loader: null,
context: null
};
var deprecationReported = false;
this.parser = {
plugin: function(hook, fn) {
if(!deprecationReported) {
console.warn("webpack: Using compiler.parser is deprecated.\n" +
"Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function(parser, options) { parser.plugin(/* ... */); });\n}); instead. " +
"It was called " + new Error().stack.split("\n")[2].trim() + ".");
deprecationReported = true;
}
this.plugin("compilation", function(compilation, data) {
data.normalModuleFactory.plugin("parser", function(parser) {
parser.plugin(hook, fn);
});
});
}.bind(this),
apply: function() {
var args = arguments;
if(!deprecationReported) {
console.warn("webpack: Using compiler.parser is deprecated.\n" +
"Use compiler.plugin(\"compilation\", function(compilation, data) {\n data.normalModuleFactory.plugin(\"parser\", function(parser, options) { parser.apply(/* ... */); });\n}); instead. " +
"It was called " + new Error().stack.split("\n")[2].trim() + ".");
deprecationReported = true;
}
this.plugin("compilation", function(compilation, data) {
data.normalModuleFactory.plugin("parser", function(parser) {
parser.apply.apply(parser, args);
});
});
}.bind(this)
};
this.options = {};
}
module.exports = Compiler;
Compiler.prototype = Object.create(Tapable.prototype);
Compiler.prototype.constructor = Compiler;
Compiler.Watching = Watching;
Compiler.prototype.watch = function(watchOptions, handler) {
this.fileTimestamps = {};
this.contextTimestamps = {};
var watching = new Watching(this, watchOptions, handler);
return watching;
};
Compiler.prototype.run = function(callback) {
var self = this;
var startTime = new Date().getTime();
self.applyPluginsAsync("before-run", self, function(err) {
if(err) return callback(err);
self.applyPluginsAsync("run", self, function(err) {
if(err) return callback(err);
self.readRecords(function(err) {
if(err) return callback(err);
self.compile(function onCompiled(err, compilation) {
if(err) return callback(err);
if(self.applyPluginsBailResult("should-emit", compilation) === false) {
var stats = compilation.getStats();
stats.startTime = startTime;
stats.endTime = new Date().getTime();
self.applyPlugins("done", stats);
return callback(null, stats);
}
self.emitAssets(compilation, function(err) {
if(err) return callback(err);
if(compilation.applyPluginsBailResult("need-additional-pass")) {
compilation.needAdditionalPass = true;
var stats = compilation.getStats();
stats.startTime = startTime;
stats.endTime = new Date().getTime();
self.applyPlugins("done", stats);
self.applyPluginsAsync("additional-pass", function(err) {
if(err) return callback(err);
self.compile(onCompiled);
});
return;
}
self.emitRecords(function(err) {
if(err) return callback(err);
var stats = compilation.getStats();
stats.startTime = startTime;
stats.endTime = new Date().getTime();
self.applyPlugins("done", stats);
return callback(null, stats);
});
});
});
});
});
});
};
Compiler.prototype.runAsChild = function(callback) {
this.compile(function(err, compilation) {
if(err) return callback(err);
this.parentCompilation.children.push(compilation);
Object.keys(compilation.assets).forEach(function(name) {
this.parentCompilation.assets[name] = compilation.assets[name];
}.bind(this));
var entries = Object.keys(compilation.entrypoints).map(function(name) {
return compilation.entrypoints[name].chunks;
}).reduce(function(array, chunks) {
return array.concat(chunks);
}, []);
return callback(null, entries, compilation);
}.bind(this));
};
Compiler.prototype.purgeInputFileSystem = function() {
if(this.inputFileSystem && this.inputFileSystem.purge)
this.inputFileSystem.purge();
};
Compiler.prototype.emitAssets = function(compilation, callback) {
var outputPath;
this.applyPluginsAsync("emit", compilation, function(err) {
if(err) return callback(err);
outputPath = compilation.getPath(this.outputPath);
this.outputFileSystem.mkdirp(outputPath, emitFiles.bind(this));
}.bind(this));
function emitFiles(err) {
if(err) return callback(err);
require("async").forEach(Object.keys(compilation.assets), function(file, callback) {
var targetFile = file;
var queryStringIdx = targetFile.indexOf("?");
if(queryStringIdx >= 0) {
targetFile = targetFile.substr(0, queryStringIdx);
}
if(targetFile.match(/\/|\\/)) {
var dir = path.dirname(targetFile);
this.outputFileSystem.mkdirp(this.outputFileSystem.join(outputPath, dir), writeOut.bind(this));
} else writeOut.call(this);
function writeOut(err) {
if(err) return callback(err);
var targetPath = this.outputFileSystem.join(outputPath, targetFile);
var source = compilation.assets[file];
if(source.existsAt === targetPath) {
source.emitted = false;
return callback();
}
var content = source.source();
if(!Buffer.isBuffer(content)) {
content = new Buffer(content, "utf8"); //eslint-disable-line
}
source.existsAt = targetPath;
source.emitted = true;
this.outputFileSystem.writeFile(targetPath, content, callback);
}
}.bind(this), function(err) {
if(err) return callback(err);
afterEmit.call(this);
}.bind(this));
}
function afterEmit() {
this.applyPluginsAsyncSeries1("after-emit", compilation, function(err) {
if(err) return callback(err);
return callback();
});
}
};
Compiler.prototype.emitRecords = function emitRecords(callback) {
if(!this.recordsOutputPath) return callback();
var idx1 = this.recordsOutputPath.lastIndexOf("/");
var idx2 = this.recordsOutputPath.lastIndexOf("\\");
var recordsOutputPathDirectory = null;
if(idx1 > idx2) recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx1);
if(idx1 < idx2) recordsOutputPathDirectory = this.recordsOutputPath.substr(0, idx2);
if(!recordsOutputPathDirectory) return writeFile.call(this);
this.outputFileSystem.mkdirp(recordsOutputPathDirectory, function(err) {
if(err) return callback(err);
writeFile.call(this);
}.bind(this));
function writeFile() {
this.outputFileSystem.writeFile(this.recordsOutputPath, JSON.stringify(this.records, undefined, 2), callback);
}
};
Compiler.prototype.readRecords = function readRecords(callback) {
var self = this;
if(!self.recordsInputPath) {
self.records = {};
return callback();
}
self.inputFileSystem.stat(self.recordsInputPath, function(err) {
// It doesn't exist
// We can ignore self.
if(err) return callback();
self.inputFileSystem.readFile(self.recordsInputPath, function(err, content) {
if(err) return callback(err);
try {
self.records = JSON.parse(content);
} catch(e) {
e.message = "Cannot parse records: " + e.message;
return callback(e);
}
return callback();
});
});
};
Compiler.prototype.createChildCompiler = function(compilation, compilerName, outputOptions, plugins) {
var childCompiler = new Compiler();
if(Array.isArray(plugins)) {
plugins.forEach(plugin => childCompiler.apply(plugin));
}
for(var name in this._plugins) {
if(["make", "compile", "emit", "after-emit", "invalid", "done", "this-compilation"].indexOf(name) < 0)
childCompiler._plugins[name] = this._plugins[name].slice();
}
childCompiler.name = compilerName;
childCompiler.outputPath = this.outputPath;
childCompiler.inputFileSystem = this.inputFileSystem;
childCompiler.outputFileSystem = null;
childCompiler.resolvers = this.resolvers;
childCompiler.fileTimestamps = this.fileTimestamps;
childCompiler.contextTimestamps = this.contextTimestamps;
if(!this.records[compilerName]) this.records[compilerName] = [];
this.records[compilerName].push(childCompiler.records = {});
childCompiler.options = Object.create(this.options);
childCompiler.options.output = Object.create(childCompiler.options.output);
for(name in outputOptions) {
childCompiler.options.output[name] = outputOptions[name];
}
childCompiler.parentCompilation = compilation;
return childCompiler;
};
Compiler.prototype.isChild = function() {
return !!this.parentCompilation;
};
Compiler.prototype.createCompilation = function() {
return new Compilation(this);
};
Compiler.prototype.newCompilation = function(params) {
var compilation = this.createCompilation();
compilation.fileTimestamps = this.fileTimestamps;
compilation.contextTimestamps = this.contextTimestamps;
compilation.name = this.name;
compilation.records = this.records;
compilation.compilationDependencies = params.compilationDependencies;
this.applyPlugins("this-compilation", compilation, params);
this.applyPlugins("compilation", compilation, params);
return compilation;
};
Compiler.prototype.createNormalModuleFactory = function() {
var normalModuleFactory = new NormalModuleFactory(this.options.context, this.resolvers, this.options.module || {});
this.applyPlugins("normal-module-factory", normalModuleFactory);
return normalModuleFactory;
};
Compiler.prototype.createContextModuleFactory = function() {
var contextModuleFactory = new ContextModuleFactory(this.resolvers, this.inputFileSystem);
this.applyPlugins("context-module-factory", contextModuleFactory);
return contextModuleFactory;
};
Compiler.prototype.newCompilationParams = function() {
var params = {
normalModuleFactory: this.createNormalModuleFactory(),
contextModuleFactory: this.createContextModuleFactory(),
compilationDependencies: []
};
return params;
};
Compiler.prototype.compile = function(callback) {
var self = this;
var params = self.newCompilationParams();
self.applyPluginsAsync("before-compile", params, function(err) {
if(err) return callback(err);
self.applyPlugins("compile", params);
var compilation = self.newCompilation(params);
self.applyPluginsParallel("make", compilation, function(err) {
if(err) return callback(err);
compilation.finish();
compilation.seal(function(err) {
if(err) return callback(err);
self.applyPluginsAsync("after-compile", compilation, function(err) {
if(err) return callback(err);
return callback(null, compilation);
});
});
});
});
};
+60
View File
@@ -0,0 +1,60 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConstDependency = require("./dependencies/ConstDependency");
const NullFactory = require("./NullFactory");
const ParserHelpers = require("./ParserHelpers");
const getQuery = (request) => {
const i = request.indexOf("?");
return request.indexOf("?") < 0 ? "" : request.substr(i);
};
class ConstPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", parser => {
parser.plugin("statement if", function(statement) {
const param = this.evaluateExpression(statement.test);
const bool = param.asBool();
if(typeof bool === "boolean") {
if(statement.test.type !== "Literal") {
const dep = new ConstDependency(`${bool}`, param.range);
dep.loc = statement.loc;
this.state.current.addDependency(dep);
}
return bool;
}
});
parser.plugin("expression ?:", function(expression) {
const param = this.evaluateExpression(expression.test);
const bool = param.asBool();
if(typeof bool === "boolean") {
if(expression.test.type !== "Literal") {
const dep = new ConstDependency(` ${bool}`, param.range);
dep.loc = expression.loc;
this.state.current.addDependency(dep);
}
return bool;
}
});
parser.plugin("evaluate Identifier __resourceQuery", function(expr) {
if(!this.state.module) return;
return ParserHelpers.evaluateToString(getQuery(this.state.module.resource))(expr);
});
parser.plugin("expression __resourceQuery", function() {
if(!this.state.module) return;
this.state.current.addVariable("__resourceQuery", JSON.stringify(getQuery(this.state.module.resource)));
return true;
});
});
});
}
}
module.exports = ConstPlugin;
+256
View File
@@ -0,0 +1,256 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const path = require("path");
const Module = require("./Module");
const OriginalSource = require("webpack-sources").OriginalSource;
const RawSource = require("webpack-sources").RawSource;
const AsyncDependenciesBlock = require("./AsyncDependenciesBlock");
class ContextModule extends Module {
constructor(resolveDependencies, context, recursive, regExp, addon, isAsync) {
super();
this.resolveDependencies = resolveDependencies;
this.context = context;
this.recursive = recursive;
this.regExp = regExp;
this.addon = addon;
this.async = !!isAsync;
this.cacheable = true;
this.contextDependencies = [context];
this.built = false;
}
prettyRegExp(regexString) {
// remove the "/" at the front and the beginning
// "/foo/" -> "foo"
return regexString.substring(1, regexString.length - 1);
}
contextify(context, request) {
return request.split("!").map(subrequest => {
let rp = path.relative(context, subrequest);
if(path.sep === "\\")
rp = rp.replace(/\\/g, "/");
if(rp.indexOf("../") !== 0)
rp = "./" + rp;
return rp;
}).join("!");
}
identifier() {
let identifier = this.context;
if(this.async)
identifier += " async";
if(!this.recursive)
identifier += " nonrecursive";
if(this.addon)
identifier += ` ${this.addon}`;
if(this.regExp)
identifier += ` ${this.regExp}`;
return identifier;
}
readableIdentifier(requestShortener) {
let identifier = requestShortener.shorten(this.context);
if(this.async)
identifier += " async";
if(!this.recursive)
identifier += " nonrecursive";
if(this.addon)
identifier += ` ${requestShortener.shorten(this.addon)}`;
if(this.regExp)
identifier += ` ${this.prettyRegExp(this.regExp + "")}`;
return identifier;
}
libIdent(options) {
let identifier = this.contextify(options.context, this.context);
if(this.async)
identifier += " async";
if(this.recursive)
identifier += " recursive";
if(this.addon)
identifier += ` ${this.contextify(options.context, this.addon)}`;
if(this.regExp)
identifier += ` ${this.prettyRegExp(this.regExp + "")}`;
return identifier;
}
needRebuild(fileTimestamps, contextTimestamps) {
const ts = contextTimestamps[this.context];
if(!ts) {
return true;
}
return ts >= this.builtTime;
}
unbuild() {
this.built = false;
super.unbuild();
}
build(options, compilation, resolver, fs, callback) {
this.built = true;
this.builtTime = new Date().getTime();
this.resolveDependencies(fs, this.context, this.recursive, this.regExp, (err, dependencies) => {
if(err) return callback(err);
if(!dependencies) {
this.dependencies = [];
callback();
return;
}
// enhance dependencies
dependencies.forEach(dep => {
dep.loc = dep.userRequest;
dep.request = this.addon + dep.request;
});
// if these we are not a async context
// add dependencies and continue
if(!this.async) {
this.dependencies = dependencies;
callback();
return;
}
// if we are async however create a new async dependency block
// and add that block to this context
dependencies.forEach(dep => {
const block = new AsyncDependenciesBlock(null, dep.module, dep.loc);
block.addDependency(dep);
this.addBlock(block);
});
callback();
});
}
getSourceWithDependencies(dependencies, id) {
// if we filter first we get a new array
// therefor we dont need to create a clone of dependencies explicitly
// therefore the order of this is !important!
const map = dependencies
.filter(dependency => dependency.module)
.sort((a, b) => {
if(a.userRequest === b.userRequest) {
return 0;
}
return a.userRequest < b.userRequest ? -1 : 1;
}).reduce(function(map, dep) {
map[dep.userRequest] = dep.module.id;
return map;
}, Object.create(null));
return `var map = ${JSON.stringify(map, null, "\t")};
function webpackContext(req) {
return __webpack_require__(webpackContextResolve(req));
};
function webpackContextResolve(req) {
var id = map[req];
if(!(id + 1)) // check for number or string
throw new Error("Cannot find module '" + req + "'.");
return id;
};
webpackContext.keys = function webpackContextKeys() {
return Object.keys(map);
};
webpackContext.resolve = webpackContextResolve;
module.exports = webpackContext;
webpackContext.id = ${JSON.stringify(id)};`;
}
getSourceWithBlocks(blocks, id) {
let hasMultipleOrNoChunks = false;
const map = blocks
.filter(block => block.dependencies[0].module)
.map((block) => ({
dependency: block.dependencies[0],
block: block,
userRequest: block.dependencies[0].userRequest
})).sort((a, b) => {
if(a.userRequest === b.userRequest) return 0;
return a.userRequest < b.userRequest ? -1 : 1;
}).reduce((map, item) => {
const chunks = item.block.chunks || [];
if(chunks.length !== 1) {
hasMultipleOrNoChunks = true;
}
map[item.userRequest] = [item.dependency.module.id]
.concat(chunks.map(chunk => chunk.id));
return map;
}, Object.create(null));
const requestPrefix = hasMultipleOrNoChunks ?
"Promise.all(ids.slice(1).map(__webpack_require__.e))" :
"__webpack_require__.e(ids[1])";
return `var map = ${JSON.stringify(map, null, "\t")};
function webpackAsyncContext(req) {
var ids = map[req];
if(!ids)
return Promise.reject(new Error("Cannot find module '" + req + "'."));
return ${requestPrefix}.then(function() {
return __webpack_require__(ids[0]);
});
};
webpackAsyncContext.keys = function webpackAsyncContextKeys() {
return Object.keys(map);
};
module.exports = webpackAsyncContext;
webpackAsyncContext.id = ${JSON.stringify(id)};`;
}
getSourceForEmptyContext(id) {
return `function webpackEmptyContext(req) {
throw new Error("Cannot find module '" + req + "'.");
}
webpackEmptyContext.keys = function() { return []; };
webpackEmptyContext.resolve = webpackEmptyContext;
module.exports = webpackEmptyContext;
webpackEmptyContext.id = ${JSON.stringify(id)};`;
}
getSourceString() {
if(this.dependencies && this.dependencies.length > 0) {
return this.getSourceWithDependencies(this.dependencies, this.id);
}
if(this.blocks && this.blocks.length > 0) {
return this.getSourceWithBlocks(this.blocks, this.id);
}
return this.getSourceForEmptyContext(this.id);
}
getSource(sourceString) {
if(this.useSourceMap) {
return new OriginalSource(sourceString, this.identifier());
}
return new RawSource(sourceString);
}
source() {
return this.getSource(
this.getSourceString()
);
}
size() {
// base penalty
const initialSize = 160;
// if we dont have dependencies we stop here.
return this.dependencies
.reduce((size, dependency) => size + 5 + dependency.userRequest.length, initialSize);
}
}
module.exports = ContextModule;
+159
View File
@@ -0,0 +1,159 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var async = require("async");
var path = require("path");
var Tapable = require("tapable");
var ContextModule = require("./ContextModule");
var ContextElementDependency = require("./dependencies/ContextElementDependency");
function ContextModuleFactory(resolvers) {
Tapable.call(this);
this.resolvers = resolvers;
}
module.exports = ContextModuleFactory;
ContextModuleFactory.prototype = Object.create(Tapable.prototype);
ContextModuleFactory.prototype.constructor = ContextModuleFactory;
ContextModuleFactory.prototype.create = function(data, callback) {
var module = this;
var context = data.context;
var dependencies = data.dependencies;
var dependency = dependencies[0];
this.applyPluginsAsyncWaterfall("before-resolve", {
context: context,
request: dependency.request,
recursive: dependency.recursive,
regExp: dependency.regExp,
async: dependency.async,
dependencies: dependencies
}, function(err, result) {
if(err) return callback(err);
// Ignored
if(!result) return callback();
var context = result.context;
var request = result.request;
var recursive = result.recursive;
var regExp = result.regExp;
var asyncContext = result.async;
var dependencies = result.dependencies;
var loaders, resource, loadersPrefix = "";
var idx = request.lastIndexOf("!");
if(idx >= 0) {
loaders = request.substr(0, idx + 1);
for(var i = 0; i < loaders.length && loaders[i] === "!"; i++) {
loadersPrefix += "!";
}
loaders = loaders.substr(i).replace(/!+$/, "").replace(/!!+/g, "!");
if(loaders === "") loaders = [];
else loaders = loaders.split("!");
resource = request.substr(idx + 1);
} else {
loaders = [];
resource = request;
}
var resolvers = module.resolvers;
async.parallel([
function(callback) {
resolvers.context.resolve({}, context, resource, function(err, result) {
if(err) return callback(err);
callback(null, result);
});
},
function(callback) {
async.map(loaders, function(loader, callback) {
resolvers.loader.resolve({}, context, loader, function(err, result) {
if(err) return callback(err);
callback(null, result);
});
}, callback);
}
], function(err, result) {
if(err) return callback(err);
module.applyPluginsAsyncWaterfall("after-resolve", {
loaders: loadersPrefix + result[1].join("!") + (result[1].length > 0 ? "!" : ""),
resource: result[0],
recursive: recursive,
regExp: regExp,
async: asyncContext,
dependencies: dependencies,
resolveDependencies: module.resolveDependencies.bind(module)
}, function(err, result) {
if(err) return callback(err);
// Ignored
if(!result) return callback();
return callback(null, new ContextModule(result.resolveDependencies, result.resource, result.recursive, result.regExp, result.loaders, result.async));
});
});
});
};
ContextModuleFactory.prototype.resolveDependencies = function resolveDependencies(fs, resource, recursive, regExp, callback) {
if(!regExp || !resource)
return callback(null, []);
(function addDirectory(directory, callback) {
fs.readdir(directory, function(err, files) {
if(err) return callback(err);
if(!files || files.length === 0) return callback(null, []);
async.map(files.filter(function(p) {
return p.indexOf(".") !== 0;
}), function(seqment, callback) {
var subResource = path.join(directory, seqment);
fs.stat(subResource, function(err, stat) {
if(err) return callback(err);
if(stat.isDirectory()) {
if(!recursive) return callback();
addDirectory.call(this, subResource, callback);
} else if(stat.isFile()) {
var obj = {
context: resource,
request: "." + subResource.substr(resource.length).replace(/\\/g, "/")
};
this.applyPluginsAsyncWaterfall("alternatives", [obj], function(err, alternatives) {
if(err) return callback(err);
alternatives = alternatives.filter(function(obj) {
return regExp.test(obj.request);
}).map(function(obj) {
var dep = new ContextElementDependency(obj.request);
dep.optional = true;
return dep;
});
callback(null, alternatives);
});
} else callback();
}.bind(this));
}.bind(this), function(err, result) {
if(err) return callback(err);
if(!result) return callback(null, []);
callback(null, result.filter(function(i) {
return !!i;
}).reduce(function(a, i) {
return a.concat(i);
}, []));
});
}.bind(this));
}.call(this, resource, callback));
};
+111
View File
@@ -0,0 +1,111 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const path = require("path");
const ContextElementDependency = require("./dependencies/ContextElementDependency");
class ContextReplacementPlugin {
constructor(resourceRegExp, newContentResource, newContentRecursive, newContentRegExp) {
this.resourceRegExp = resourceRegExp;
if(typeof newContentResource === "function") {
this.newContentCallback = newContentResource;
} else if(typeof newContentResource === "string" && typeof newContentRecursive === "object") {
this.newContentResource = newContentResource;
this.newContentCreateContextMap = (fs, callback) => {
callback(null, newContentRecursive);
};
} else if(typeof newContentResource === "string" && typeof newContentRecursive === "function") {
this.newContentResource = newContentResource;
this.newContentCreateContextMap = newContentRecursive;
} else {
if(typeof newContentResource !== "string") {
newContentRegExp = newContentRecursive;
newContentRecursive = newContentResource;
newContentResource = undefined;
}
if(typeof newContentRecursive !== "boolean") {
newContentRegExp = newContentRecursive;
newContentRecursive = undefined;
}
this.newContentResource = newContentResource;
this.newContentRecursive = newContentRecursive;
this.newContentRegExp = newContentRegExp;
}
}
apply(compiler) {
const resourceRegExp = this.resourceRegExp;
const newContentCallback = this.newContentCallback;
const newContentResource = this.newContentResource;
const newContentRecursive = this.newContentRecursive;
const newContentRegExp = this.newContentRegExp;
const newContentCreateContextMap = this.newContentCreateContextMap;
compiler.plugin("context-module-factory", (cmf) => {
cmf.plugin("before-resolve", (result, callback) => {
if(!result) return callback();
if(resourceRegExp.test(result.request)) {
if(typeof newContentResource !== "undefined")
result.request = newContentResource;
if(typeof newContentRecursive !== "undefined")
result.recursive = newContentRecursive;
if(typeof newContentRegExp !== "undefined")
result.regExp = newContentRegExp;
if(typeof newContentCallback === "function") {
newContentCallback(result);
} else {
result.dependencies.forEach((d) => {
if(d.critical)
d.critical = false;
});
}
}
return callback(null, result);
});
cmf.plugin("after-resolve", (result, callback) => {
if(!result) return callback();
if(resourceRegExp.test(result.resource)) {
if(typeof newContentResource !== "undefined")
result.resource = path.resolve(result.resource, newContentResource);
if(typeof newContentRecursive !== "undefined")
result.recursive = newContentRecursive;
if(typeof newContentRegExp !== "undefined")
result.regExp = newContentRegExp;
if(typeof newContentCreateContextMap === "function")
result.resolveDependencies = createResolveDependenciesFromContextMap(newContentCreateContextMap);
if(typeof newContentCallback === "function") {
const origResource = result.resource;
newContentCallback(result);
if(result.resource !== origResource) {
result.resource = path.resolve(origResource, result.resource);
}
} else {
result.dependencies.forEach((d) => {
if(d.critical)
d.critical = false;
});
}
}
return callback(null, result);
});
});
}
}
const createResolveDependenciesFromContextMap = (createContextMap) => {
return function resolveDependenciesFromContextMap(fs, resource, recursive, regExp, callback) {
createContextMap(fs, (err, map) => {
if(err) return callback(err);
const dependencies = Object.keys(map).map((key) => {
return new ContextElementDependency(map[key], key);
});
callback(null, dependencies);
});
};
};
module.exports = ContextReplacementPlugin;
+123
View File
@@ -0,0 +1,123 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConstDependency = require("./dependencies/ConstDependency");
const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
const ParserHelpers = require("./ParserHelpers");
const NullFactory = require("./NullFactory");
class DefinePlugin {
constructor(definitions) {
this.definitions = definitions;
}
apply(compiler) {
const definitions = this.definitions;
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", (parser) => {
(function walkDefinitions(definitions, prefix) {
Object.keys(definitions).forEach((key) => {
const code = definitions[key];
if(code && typeof code === "object" && !(code instanceof RegExp)) {
walkDefinitions(code, prefix + key + ".");
applyObjectDefine(prefix + key, code);
return;
}
applyDefineKey(prefix, key);
applyDefine(prefix + key, code);
});
}(definitions, ""));
function stringifyObj(obj) {
return "__webpack_require__.i({" + Object.keys(obj).map((key) => {
const code = obj[key];
return JSON.stringify(key) + ":" + toCode(code);
}).join(",") + "})";
}
function toCode(code) {
if(code === null) return "null";
else if(code === undefined) return "undefined";
else if(code instanceof RegExp && code.toString) return code.toString();
else if(typeof code === "function" && code.toString) return "(" + code.toString() + ")";
else if(typeof code === "object") return stringifyObj(code);
else return code + "";
}
function applyDefineKey(prefix, key) {
const splittedKey = key.split(".");
splittedKey.slice(1).forEach((_, i) => {
const fullKey = prefix + splittedKey.slice(0, i + 1).join(".");
parser.plugin("can-rename " + fullKey, ParserHelpers.approve);
});
}
function applyDefine(key, code) {
const isTypeof = /^typeof\s+/.test(key);
if(isTypeof) key = key.replace(/^typeof\s+/, "");
let recurse = false;
let recurseTypeof = false;
code = toCode(code);
if(!isTypeof) {
parser.plugin("can-rename " + key, ParserHelpers.approve);
parser.plugin("evaluate Identifier " + key, (expr) => {
/**
* this is needed in case there is a recursion in the DefinePlugin
* to prevent an endless recursion
* e.g.: new DefinePlugin({
* "a": "b",
* "b": "a"
* });
*/
if(recurse) return;
recurse = true;
const res = parser.evaluate(code);
recurse = false;
res.setRange(expr.range);
return res;
});
parser.plugin("expression " + key, ParserHelpers.toConstantDependency(code));
}
const typeofCode = isTypeof ? code : "typeof (" + code + ")";
parser.plugin("evaluate typeof " + key, (expr) => {
/**
* this is needed in case there is a recursion in the DefinePlugin
* to prevent an endless recursion
* e.g.: new DefinePlugin({
* "typeof a": "tyepof b",
* "typeof b": "typeof a"
* });
*/
if(recurseTypeof) return;
recurseTypeof = true;
const res = parser.evaluate(typeofCode);
recurseTypeof = false;
res.setRange(expr.range);
return res;
});
parser.plugin("typeof " + key, (expr) => {
const res = parser.evaluate(typeofCode);
if(!res.isString()) return;
return ParserHelpers.toConstantDependency(JSON.stringify(res.string)).bind(parser)(expr);
});
}
function applyObjectDefine(key, obj) {
const code = stringifyObj(obj);
parser.plugin("can-rename " + key, ParserHelpers.approve);
parser.plugin("evaluate Identifier " + key, (expr) => new BasicEvaluatedExpression().setRange(expr.range));
parser.plugin("evaluate typeof " + key, ParserHelpers.evaluateToString("object"));
parser.plugin("expression " + key, ParserHelpers.toConstantDependency(code));
parser.plugin("typeof " + key, ParserHelpers.toConstantDependency(JSON.stringify("object")));
}
});
});
}
}
module.exports = DefinePlugin;
+80
View File
@@ -0,0 +1,80 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var Module = require("./Module");
var OriginalSource = require("webpack-sources").OriginalSource;
var RawSource = require("webpack-sources").RawSource;
var WebpackMissingModule = require("./dependencies/WebpackMissingModule");
var DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
function DelegatedModule(sourceRequest, data, type, userRequest) {
Module.call(this);
this.sourceRequest = sourceRequest;
this.request = data.id;
this.meta = data.meta;
this.type = type;
this.userRequest = userRequest;
this.built = false;
this.delegateData = data;
}
module.exports = DelegatedModule;
DelegatedModule.prototype = Object.create(Module.prototype);
DelegatedModule.prototype.constructor = DelegatedModule;
DelegatedModule.prototype.delegated = true;
DelegatedModule.prototype.identifier = function() {
return "delegated " + JSON.stringify(this.request) + " from " + this.sourceRequest;
};
DelegatedModule.prototype.readableIdentifier = function() {
return "delegated " + this.userRequest + " from " + this.sourceRequest;
};
DelegatedModule.prototype.needRebuild = function() {
return false;
};
DelegatedModule.prototype.build = function(options, compilation, resolver, fs, callback) {
this.built = true;
this.builtTime = new Date().getTime();
this.usedExports = true;
this.providedExports = this.delegateData.exports || true;
this.dependencies.length = 0;
this.addDependency(new DelegatedSourceDependency(this.sourceRequest));
callback();
};
DelegatedModule.prototype.unbuild = function() {
this.built = false;
Module.prototype.unbuild.call(this);
};
DelegatedModule.prototype.source = function() {
var sourceModule = this.dependencies[0].module;
var str;
if(!sourceModule) {
str = WebpackMissingModule.moduleCode(this.sourceRequest);
} else {
str = "module.exports = (__webpack_require__(" + sourceModule.id + "))";
switch(this.type) {
case "require":
str += "(" + JSON.stringify(this.request) + ");";
break;
case "object":
str += "[" + JSON.stringify(this.request) + "];";
break;
}
}
if(this.useSourceMap) {
return new OriginalSource(str, this.identifier());
} else {
return new RawSource(str);
}
};
DelegatedModule.prototype.size = function() {
return 42;
};
+58
View File
@@ -0,0 +1,58 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DelegatedModule = require("./DelegatedModule");
// options.source
// options.type
// options.context
// options.scope
// options.content
class DelegatedModuleFactoryPlugin {
constructor(options) {
this.options = options;
options.type = options.type || "require";
options.extensions = options.extensions || ["", ".js"];
}
apply(normalModuleFactory) {
const scope = this.options.scope;
if(scope) {
normalModuleFactory.plugin("factory", factory => (data, callback) => {
const dependency = data.dependencies[0];
const request = dependency.request;
if(request && request.indexOf(scope + "/") === 0) {
const innerRequest = "." + request.substr(scope.length);
let resolved;
if(innerRequest in this.options.content) {
resolved = this.options.content[innerRequest];
return callback(null, new DelegatedModule(this.options.source, resolved, this.options.type, innerRequest));
}
for(let i = 0; i < this.options.extensions.length; i++) {
const requestPlusExt = innerRequest + this.options.extensions[i];
if(requestPlusExt in this.options.content) {
resolved = this.options.content[requestPlusExt];
return callback(null, new DelegatedModule(this.options.source, resolved, this.options.type, requestPlusExt));
}
}
}
return factory(data, callback);
});
} else {
normalModuleFactory.plugin("module", module => {
if(module.libIdent) {
const request = module.libIdent(this.options);
if(request && request in this.options.content) {
const resolved = this.options.content[request];
return new DelegatedModule(this.options.source, resolved, this.options.type, request);
}
}
return module;
});
}
}
}
module.exports = DelegatedModuleFactoryPlugin;
+27
View File
@@ -0,0 +1,27 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin");
const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
class DelegatedPlugin {
constructor(options) {
this.options = options;
}
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(DelegatedSourceDependency, params.normalModuleFactory);
});
compiler.plugin("compile", (params) => {
params.normalModuleFactory.apply(new DelegatedModuleFactoryPlugin(this.options));
});
}
}
module.exports = DelegatedPlugin;
+75
View File
@@ -0,0 +1,75 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var DependenciesBlockVariable = require("./DependenciesBlockVariable");
function DependenciesBlock() {
this.dependencies = [];
this.blocks = [];
this.variables = [];
}
module.exports = DependenciesBlock;
DependenciesBlock.prototype.addBlock = function(block) {
this.blocks.push(block);
block.parent = this;
};
DependenciesBlock.prototype.addVariable = function(name, expression, dependencies) {
for(var i = 0; i < this.variables.length; i++) {
var v = this.variables[i];
if(v.name === name && v.expression === expression) return;
}
this.variables.push(new DependenciesBlockVariable(name, expression, dependencies));
};
DependenciesBlock.prototype.addDependency = function(dependency) {
this.dependencies.push(dependency);
};
DependenciesBlock.prototype.updateHash = function(hash) {
this.dependencies.forEach(function(d) {
d.updateHash(hash);
});
this.blocks.forEach(function(b) {
b.updateHash(hash);
});
this.variables.forEach(function(v) {
v.updateHash(hash);
});
};
DependenciesBlock.prototype.disconnect = function() {
function disconnect(i) {
i.disconnect();
}
this.dependencies.forEach(disconnect);
this.blocks.forEach(disconnect);
this.variables.forEach(disconnect);
};
DependenciesBlock.prototype.unseal = function() {
function unseal(i) {
i.unseal();
}
this.blocks.forEach(unseal);
};
DependenciesBlock.prototype.hasDependencies = function(filter) {
if(filter) {
if(this.dependencies.some(filter)) return true;
} else {
if(this.dependencies.length > 0) return true;
}
return this.blocks.concat(this.variables).some(function(item) {
return item.hasDependencies(filter);
});
};
DependenciesBlock.prototype.sortItems = function() {
this.blocks.forEach(function(block) {
block.sortItems();
});
};
+51
View File
@@ -0,0 +1,51 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ReplaceSource = require("webpack-sources").ReplaceSource;
const RawSource = require("webpack-sources").RawSource;
class DependenciesBlockVariable {
constructor(name, expression, dependencies) {
this.name = name;
this.expression = expression;
this.dependencies = dependencies || [];
}
updateHash(hash) {
hash.update(this.name);
hash.update(this.expression);
this.dependencies.forEach(d => {
d.updateHash(hash);
});
}
expressionSource(dependencyTemplates, outputOptions, requestShortener) {
const source = new ReplaceSource(new RawSource(this.expression));
this.dependencies.forEach(dep => {
const template = dependencyTemplates.get(dep.constructor);
if(!template) throw new Error(`No template for dependency: ${dep.constructor.name}`);
template.apply(dep, source, outputOptions, requestShortener, dependencyTemplates);
});
return source;
}
disconnect() {
this.dependencies.forEach(d => {
d.disconnect();
});
}
hasDependencies(filter) {
if(filter) {
if(this.dependencies.some(filter)) return true;
} else {
if(this.dependencies.length > 0) return true;
}
return false;
}
}
module.exports = DependenciesBlockVariable;
+53
View File
@@ -0,0 +1,53 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const compareLocations = require("./compareLocations");
class Dependency {
constructor() {
this.module = null;
}
isEqualResource() {
return false;
}
// Returns the referenced module and export
getReference() {
if(!this.module) return null;
return {
module: this.module,
importedNames: true, // true: full object, false: only sideeffects/no export, array of strings: the exports with this names
};
}
// Returns the exported names
getExports() {
return null;
}
getWarnings() {
return null;
}
getErrors() {
return null;
}
updateHash(hash) {
hash.update((this.module && this.module.id) + "");
}
disconnect() {
this.module = null;
}
compare(a, b) {
return compareLocations(a.loc, b.loc);
}
}
Dependency.compare = (a, b) => compareLocations(a.loc, b.loc);
module.exports = Dependency;
+37
View File
@@ -0,0 +1,37 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DllEntryDependency = require("./dependencies/DllEntryDependency");
const SingleEntryDependency = require("./dependencies/SingleEntryDependency");
const DllModuleFactory = require("./DllModuleFactory");
class DllEntryPlugin {
constructor(context, entries, name) {
this.context = context;
this.entries = entries;
this.name = name;
}
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
const dllModuleFactory = new DllModuleFactory();
const normalModuleFactory = params.normalModuleFactory;
compilation.dependencyFactories.set(DllEntryDependency, dllModuleFactory);
compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory);
});
compiler.plugin("make", (compilation, callback) => {
compilation.addEntry(this.context, new DllEntryDependency(this.entries.map((e, idx) => {
const dep = new SingleEntryDependency(e);
dep.loc = `${this.name}:${idx}`;
return dep;
}), this.name), this.name, callback);
});
}
}
module.exports = DllEntryPlugin;
+58
View File
@@ -0,0 +1,58 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Module = require("./Module");
const RawSource = require("webpack-sources").RawSource;
class DllModule extends Module {
constructor(context, dependencies, name, type) {
super();
this.context = context;
this.dependencies = dependencies;
this.name = name;
this.built = false;
this.cacheable = true;
this.type = type;
}
identifier() {
return `dll ${this.name}`;
}
readableIdentifier() {
return `dll ${this.name}`;
}
disconnect() {
this.built = false;
super.disconnect();
}
build(options, compilation, resolver, fs, callback) {
this.built = true;
return callback();
}
source() {
return new RawSource("module.exports = __webpack_require__;");
}
needRebuild() {
return false;
}
size() {
return 12;
}
updateHash(hash) {
hash.update("dll module");
hash.update(this.name || "");
super.updateHash(hash);
}
}
module.exports = DllModule;
+20
View File
@@ -0,0 +1,20 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
var Tapable = require("tapable");
var DllModule = require("./DllModule");
class DllModuleFactory extends Tapable {
constructor() {
super();
}
create(data, callback) {
const dependency = data.dependencies[0];
callback(null, new DllModule(data.context, dependency.dependencies, dependency.name, dependency.type));
}
}
module.exports = DllModuleFactory;
+38
View File
@@ -0,0 +1,38 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DllEntryPlugin = require("./DllEntryPlugin");
const LibManifestPlugin = require("./LibManifestPlugin");
const FlagInitialModulesAsUsedPlugin = require("./FlagInitialModulesAsUsedPlugin");
class DllPlugin {
constructor(options) {
this.options = options;
}
apply(compiler) {
compiler.plugin("entry-option", (context, entry) => {
function itemToPlugin(item, name) {
if(Array.isArray(item))
return new DllEntryPlugin(context, item, name);
else
throw new Error("DllPlugin: supply an Array as entry");
}
if(typeof entry === "object" && !Array.isArray(entry)) {
Object.keys(entry).forEach(name => {
compiler.apply(itemToPlugin(entry[name], name));
});
} else {
compiler.apply(itemToPlugin(entry, "main"));
}
return true;
});
compiler.apply(new LibManifestPlugin(this.options));
compiler.apply(new FlagInitialModulesAsUsedPlugin());
}
}
module.exports = DllPlugin;
+59
View File
@@ -0,0 +1,59 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DelegatedSourceDependency = require("./dependencies/DelegatedSourceDependency");
const DelegatedModuleFactoryPlugin = require("./DelegatedModuleFactoryPlugin");
const ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin");
class DllReferencePlugin {
constructor(options) {
this.options = options;
}
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
const normalModuleFactory = params.normalModuleFactory;
compilation.dependencyFactories.set(DelegatedSourceDependency, normalModuleFactory);
});
compiler.plugin("before-compile", (params, callback) => {
const manifest = this.options.manifest;
if(typeof manifest === "string") {
params.compilationDependencies.push(manifest);
compiler.inputFileSystem.readFile(manifest, function(err, result) {
if(err) return callback(err);
params["dll reference " + manifest] = JSON.parse(result.toString("utf-8"));
return callback();
});
} else {
return callback();
}
});
compiler.plugin("compile", (params) => {
let manifest = this.options.manifest;
if(typeof manifest === "string") {
manifest = params["dll reference " + manifest];
}
const name = this.options.name || manifest.name;
const sourceType = this.options.sourceType || "var";
const externals = {};
const source = "dll-reference " + name;
externals[source] = name;
params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(sourceType, externals));
params.normalModuleFactory.apply(new DelegatedModuleFactoryPlugin({
source: source,
type: this.options.type,
scope: this.options.scope,
context: this.options.context || compiler.options.context,
content: this.options.content || manifest.content,
extensions: this.options.extensions
}));
});
}
}
module.exports = DllReferencePlugin;
+59
View File
@@ -0,0 +1,59 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Naoyuki Kanezawa @nkzawa
*/
"use strict";
const MultiEntryDependency = require("./dependencies/MultiEntryDependency");
const SingleEntryDependency = require("./dependencies/SingleEntryDependency");
const MultiModuleFactory = require("./MultiModuleFactory");
const MultiEntryPlugin = require("./MultiEntryPlugin");
const SingleEntryPlugin = require("./SingleEntryPlugin");
class DynamicEntryPlugin {
constructor(context, entry) {
this.context = context;
this.entry = entry;
}
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
const multiModuleFactory = new MultiModuleFactory();
const normalModuleFactory = params.normalModuleFactory;
compilation.dependencyFactories.set(MultiEntryDependency, multiModuleFactory);
compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory);
});
compiler.plugin("make", (compilation, callback) => {
const addEntry = (entry, name) => {
const dep = DynamicEntryPlugin.createDependency(entry, name);
return new Promise((resolve, reject) => {
compilation.addEntry(this.context, dep, name, (err) => {
if(err) return reject(err);
resolve();
});
});
};
Promise.resolve(this.entry()).then((entry) => {
if(typeof entry === "string" || Array.isArray(entry)) {
addEntry(entry, "main").then(() => callback(), callback);
} else if(typeof entry === "object") {
Promise.all(Object.keys(entry).map((name) => {
return addEntry(entry[name], name);
})).then(() => callback(), callback);
}
});
});
}
}
module.exports = DynamicEntryPlugin;
DynamicEntryPlugin.createDependency = function(entry, name) {
if(Array.isArray(entry))
return MultiEntryPlugin.createDependency(entry, name);
else
return SingleEntryPlugin.createDependency(entry, name);
};
+16
View File
@@ -0,0 +1,16 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
function EntryModuleNotFoundError(err) {
Error.call(this);
this.name = "EntryModuleNotFoundError";
this.message = "Entry module not found: " + err;
this.details = err.details;
this.error = err;
Error.captureStackTrace(this, EntryModuleNotFoundError);
}
module.exports = EntryModuleNotFoundError;
EntryModuleNotFoundError.prototype = Object.create(Error.prototype);
EntryModuleNotFoundError.prototype.constructor = EntryModuleNotFoundError;
+31
View File
@@ -0,0 +1,31 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const SingleEntryPlugin = require("./SingleEntryPlugin");
const MultiEntryPlugin = require("./MultiEntryPlugin");
const DynamicEntryPlugin = require("./DynamicEntryPlugin");
module.exports = class EntryOptionPlugin {
apply(compiler) {
compiler.plugin("entry-option", (context, entry) => {
function itemToPlugin(item, name) {
if(Array.isArray(item)) {
return new MultiEntryPlugin(context, item, name);
} else {
return new SingleEntryPlugin(context, item, name);
}
}
if(typeof entry === "string" || Array.isArray(entry)) {
compiler.apply(itemToPlugin(entry, "main"));
} else if(typeof entry === "object") {
Object.keys(entry).forEach(name => compiler.apply(itemToPlugin(entry[name], name)));
} else if(typeof entry === "function") {
compiler.apply(new DynamicEntryPlugin(context, entry));
}
return true;
});
}
};
+43
View File
@@ -0,0 +1,43 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class Entrypoint {
constructor(name) {
this.name = name;
this.chunks = [];
}
unshiftChunk(chunk) {
this.chunks.unshift(chunk);
chunk.entrypoints.push(this);
}
insertChunk(chunk, before) {
const idx = this.chunks.indexOf(before);
if(idx >= 0) {
this.chunks.splice(idx, 0, chunk);
} else {
throw new Error("before chunk not found");
}
chunk.entrypoints.push(this);
}
getFiles() {
const files = [];
for(let chunkIdx = 0; chunkIdx < this.chunks.length; chunkIdx++) {
for(let fileIdx = 0; fileIdx < this.chunks[chunkIdx].files.length; fileIdx++) {
if(files.indexOf(this.chunks[chunkIdx].files[fileIdx]) === -1) {
files.push(this.chunks[chunkIdx].files[fileIdx]);
}
}
}
return files;
}
}
module.exports = Entrypoint;
+50
View File
@@ -0,0 +1,50 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Authors Simen Brekken @simenbrekken, Einar Löve @einarlove
*/
"use strict";
const DefinePlugin = require("./DefinePlugin");
class EnvironmentPlugin {
constructor(keys) {
if(Array.isArray(keys)) {
this.keys = keys;
this.defaultValues = {};
} else if(keys && typeof keys === "object") {
this.keys = Object.keys(keys);
this.defaultValues = keys;
} else {
this.keys = Array.prototype.slice.call(arguments);
this.defaultValues = {};
}
}
apply(compiler) {
const definitions = this.keys.reduce((defs, key) => {
const value = process.env[key] !== undefined ? process.env[key] : this.defaultValues[key];
if(value === undefined) {
compiler.plugin("this-compilation", compilation => {
const error = new Error(
`EnvironmentPlugin - ${key} environment variable is undefined.\n\n` +
"You can pass an object with default values to suppress this warning.\n" +
"See https://webpack.js.org/plugins/environment-plugin for example."
);
error.name = "EnvVariableNotDefinedError";
compilation.warnings.push(error);
});
}
defs[`process.env.${key}`] = typeof value === "undefined" ? "undefined" : JSON.stringify(value);
return defs;
}, {});
compiler.apply(new DefinePlugin(definitions));
}
}
module.exports = EnvironmentPlugin;
+31
View File
@@ -0,0 +1,31 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const loaderFlag = "LOADER_EXECUTION";
exports.cutOffLoaderExecution = (stack) => {
stack = stack.split("\n");
for(let i = 0; i < stack.length; i++)
if(stack[i].indexOf(loaderFlag) >= 0)
stack.length = i;
return stack.join("\n");
};
exports.cutOffMessage = (stack, message) => {
const nextLine = stack.indexOf("\n");
if(nextLine === -1) {
return stack === message ? "" : stack;
} else {
const firstLine = stack.substr(0, nextLine);
return firstLine === message ? stack.substr(nextLine + 1) : stack;
}
};
exports.cleanUp = (stack, message) => {
stack = exports.cutOffLoaderExecution(stack);
stack = exports.cutOffMessage(stack, message);
return stack;
};
+22
View File
@@ -0,0 +1,22 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const EvalDevToolModuleTemplatePlugin = require("./EvalDevToolModuleTemplatePlugin");
class EvalDevToolModulePlugin {
constructor(sourceUrlComment, moduleFilenameTemplate) {
this.sourceUrlComment = sourceUrlComment;
this.moduleFilenameTemplate = moduleFilenameTemplate;
}
apply(compiler) {
compiler.plugin("compilation", (compilation) => {
compilation.moduleTemplate.apply(new EvalDevToolModuleTemplatePlugin(this.sourceUrlComment, this.moduleFilenameTemplate));
});
}
}
module.exports = EvalDevToolModulePlugin;
+33
View File
@@ -0,0 +1,33 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const RawSource = require("webpack-sources").RawSource;
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
class EvalDevToolModuleTemplatePlugin {
constructor(sourceUrlComment, moduleFilenameTemplate) {
this.sourceUrlComment = sourceUrlComment || "\n//# sourceURL=[url]";
this.moduleFilenameTemplate = moduleFilenameTemplate || "webpack:///[resourcePath]?[loaders]";
}
apply(moduleTemplate) {
moduleTemplate.plugin("module", (source, module) => {
const content = source.source();
const str = ModuleFilenameHelpers.createFilename(module, this.moduleFilenameTemplate, moduleTemplate.requestShortener);
const footer = ["\n",
ModuleFilenameHelpers.createFooter(module, moduleTemplate.requestShortener),
this.sourceUrlComment.replace(/\[url\]/g, encodeURI(str).replace(/%2F/g, "/").replace(/%20/g, "_").replace(/%5E/g, "^").replace(/%5C/g, "\\").replace(/^\//, ""))
].join("\n");
return new RawSource(`eval(${JSON.stringify(content + footer)});`);
});
moduleTemplate.plugin("hash", hash => {
hash.update("EvalDevToolModuleTemplatePlugin");
hash.update("2");
});
}
}
module.exports = EvalDevToolModuleTemplatePlugin;
+74
View File
@@ -0,0 +1,74 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const RawSource = require("webpack-sources").RawSource;
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
class EvalSourceMapDevToolModuleTemplatePlugin {
constructor(compilation, options) {
this.compilation = compilation;
this.sourceMapComment = options.append || "//# sourceMappingURL=[url]";
this.moduleFilenameTemplate = options.moduleFilenameTemplate || "webpack:///[resource-path]?[hash]";
this.options = options;
}
apply(moduleTemplate) {
const self = this;
const options = this.options;
moduleTemplate.plugin("module", function(source, module) {
if(source.__EvalSourceMapDevToolData)
return source.__EvalSourceMapDevToolData;
let sourceMap;
let content;
if(source.sourceAndMap) {
const sourceAndMap = source.sourceAndMap(options);
sourceMap = sourceAndMap.map;
content = sourceAndMap.source;
} else {
sourceMap = source.map(options);
content = source.source();
}
if(!sourceMap) {
return source;
}
// Clone (flat) the sourcemap to ensure that the mutations below do not persist.
sourceMap = Object.keys(sourceMap).reduce(function(obj, key) {
obj[key] = sourceMap[key];
return obj;
}, {});
const modules = sourceMap.sources.map(function(source) {
const module = self.compilation.findModule(source);
return module || source;
});
let moduleFilenames = modules.map(function(module) {
return ModuleFilenameHelpers.createFilename(module, self.moduleFilenameTemplate, this.requestShortener);
}, this);
moduleFilenames = ModuleFilenameHelpers.replaceDuplicates(moduleFilenames, function(filename, i, n) {
for(let j = 0; j < n; j++)
filename += "*";
return filename;
});
sourceMap.sources = moduleFilenames;
if(sourceMap.sourcesContent) {
sourceMap.sourcesContent = sourceMap.sourcesContent.map(function(content, i) {
return `${content}\n\n\n${ModuleFilenameHelpers.createFooter(modules[i], this.requestShortener)}`;
}, this);
}
sourceMap.sourceRoot = options.sourceRoot || "";
sourceMap.file = `${module.id}.js`;
const footer = self.sourceMapComment.replace(/\[url\]/g, `data:application/json;charset=utf-8;base64,${new Buffer(JSON.stringify(sourceMap), "utf8").toString("base64")}`); //eslint-disable-line
source.__EvalSourceMapDevToolData = new RawSource(`eval(${JSON.stringify(content + footer)});`);
return source.__EvalSourceMapDevToolData;
});
moduleTemplate.plugin("hash", function(hash) {
hash.update("eval-source-map");
hash.update("1");
});
}
}
module.exports = EvalSourceMapDevToolModuleTemplatePlugin;
+32
View File
@@ -0,0 +1,32 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const EvalSourceMapDevToolModuleTemplatePlugin = require("./EvalSourceMapDevToolModuleTemplatePlugin");
const SourceMapDevToolModuleOptionsPlugin = require("./SourceMapDevToolModuleOptionsPlugin");
class EvalSourceMapDevToolPlugin {
constructor(options) {
if(arguments.length > 1)
throw new Error("EvalSourceMapDevToolPlugin only takes one argument (pass an options object)");
if(typeof options === "string") {
options = {
append: options
};
}
if(!options) options = {};
this.options = options;
}
apply(compiler) {
const options = this.options;
compiler.plugin("compilation", (compilation) => {
new SourceMapDevToolModuleOptionsPlugin(options).apply(compilation);
compilation.moduleTemplate.apply(new EvalSourceMapDevToolModuleTemplatePlugin(compilation, options));
});
}
}
module.exports = EvalSourceMapDevToolPlugin;
+42
View File
@@ -0,0 +1,42 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConstDependency = require("./dependencies/ConstDependency");
const ParserHelpers = require("./ParserHelpers");
const NullFactory = require("./NullFactory");
const REPLACEMENTS = {
__webpack_hash__: "__webpack_require__.h" // eslint-disable-line camelcase
};
const REPLACEMENT_TYPES = {
__webpack_hash__: "string" // eslint-disable-line camelcase
};
class ExtendedAPIPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
compilation.mainTemplate.plugin("require-extensions", function(source, chunk, hash) {
const buf = [source];
buf.push("");
buf.push("// __webpack_hash__");
buf.push(`${this.requireFn}.h = ${JSON.stringify(hash)};`);
return this.asString(buf);
});
compilation.mainTemplate.plugin("global-hash", () => true);
params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
Object.keys(REPLACEMENTS).forEach(key => {
parser.plugin(`expression ${key}`, ParserHelpers.toConstantDependency(REPLACEMENTS[key]));
parser.plugin(`evaluate typeof ${key}`, ParserHelpers.evaluateToString(REPLACEMENT_TYPES[key]));
});
});
});
}
}
module.exports = ExtendedAPIPlugin;
+116
View File
@@ -0,0 +1,116 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Module = require("./Module");
const OriginalSource = require("webpack-sources").OriginalSource;
const RawSource = require("webpack-sources").RawSource;
const WebpackMissingModule = require("./dependencies/WebpackMissingModule");
const Template = require("./Template");
class ExternalModule extends Module {
constructor(request, type) {
super();
this.request = request;
this.type = type;
this.built = false;
this.external = true;
}
chunkCondition(chunk) {
return chunk.hasEntryModule();
}
identifier() {
return "external " + JSON.stringify(this.request);
}
readableIdentifier() {
return "external " + JSON.stringify(this.request);
}
needRebuild() {
return false;
}
build(options, compilation, resolver, fs, callback) {
this.builtTime = new Date().getTime();
callback();
}
getSourceForGlobalVariableExternal(variableName, type) {
if(!Array.isArray(variableName)) {
// make it an array as the look up works the same basically
variableName = [variableName];
}
// needed for e.g. window["some"]["thing"]
const objectLookup = variableName.map(r => `[${JSON.stringify(r)}]`).join("");
return `(function() { module.exports = ${type}${objectLookup}; }());`;
}
getSourceForCommonJsExternal(moduleAndSpecifiers) {
if(!Array.isArray(moduleAndSpecifiers)) {
return `module.exports = require(${JSON.stringify(moduleAndSpecifiers)});`;
}
const moduleName = moduleAndSpecifiers[0];
const objectLookup = moduleAndSpecifiers.slice(1).map(r => `[${JSON.stringify(r)}]`).join("");
return `module.exports = require(${moduleName})${objectLookup};`;
}
checkExternalVariable(variableToCheck, request) {
return `if(typeof ${variableToCheck} === 'undefined') {${WebpackMissingModule.moduleCode(request)}}\n`;
}
getSourceForAmdOrUmdExternal(id, optional, request) {
const externalVariable = Template.toIdentifier(`__WEBPACK_EXTERNAL_MODULE_${id}__`);
const missingModuleError = optional ? this.checkExternalVariable(externalVariable, request) : "";
return `${missingModuleError}module.exports = ${externalVariable};`;
}
getSourceForDefaultCase(optional, request) {
const missingModuleError = optional ? this.checkExternalVariable(request, request) : "";
return `${missingModuleError}module.exports = ${request};`;
}
getSourceString() {
const request = typeof this.request === "object" ? this.request[this.type] : this.request;
switch(this.type) {
case "this":
case "window":
case "global":
return this.getSourceForGlobalVariableExternal(request, this.type);
case "commonjs":
case "commonjs2":
return this.getSourceForCommonJsExternal(request);
case "amd":
case "umd":
case "umd2":
return this.getSourceForAmdOrUmdExternal(this.id, this.optional, request);
default:
return this.getSourceForDefaultCase(this.optional, request);
}
}
getSource(sourceString) {
if(this.useSourceMap) {
return new OriginalSource(sourceString, this.identifier());
}
return new RawSource(sourceString);
}
source() {
return this.getSource(
this.getSourceString()
);
}
size() {
return 42;
}
}
module.exports = ExternalModule;
+88
View File
@@ -0,0 +1,88 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var ExternalModule = require("./ExternalModule");
function ExternalModuleFactoryPlugin(type, externals) {
this.type = type;
this.externals = externals;
}
module.exports = ExternalModuleFactoryPlugin;
ExternalModuleFactoryPlugin.prototype.apply = function(normalModuleFactory) {
var globalType = this.type;
normalModuleFactory.plugin("factory", function(factory) {
return function(data, callback) {
var context = data.context;
var dependency = data.dependencies[0];
function handleExternal(value, type, callback) {
if(typeof type === "function") {
callback = type;
type = undefined;
}
if(value === false) return factory(data, callback);
if(value === true) value = dependency.request;
if(typeof type === "undefined" && /^[a-z0-9]+ /.test(value)) {
var idx = value.indexOf(" ");
type = value.substr(0, idx);
value = value.substr(idx + 1);
}
callback(null, new ExternalModule(value, type || globalType));
return true;
}
(function handleExternals(externals, callback) {
if(typeof externals === "string") {
if(externals === dependency.request) {
return handleExternal(dependency.request, callback);
}
} else if(Array.isArray(externals)) {
var i = 0;
(function next() {
var handleExternalsAndCallback = function handleExternalsAndCallback(err, module) {
if(err) return callback(err);
if(!module) {
if(async) {
async = false;
return;
}
return next();
}
callback(null, module);
};
do {
var async = true;
if(i >= externals.length) return callback();
handleExternals(externals[i++], handleExternalsAndCallback);
} while (!async); // eslint-disable-line keyword-spacing
async = false;
}());
return;
} else if(externals instanceof RegExp) {
if(externals.test(dependency.request)) {
return handleExternal(dependency.request, callback);
}
} else if(typeof externals === "function") {
externals.call(null, context, dependency.request, function(err, value, type) {
if(err) return callback(err);
if(typeof value !== "undefined") {
handleExternal(value, type, callback);
} else {
callback();
}
});
return;
} else if(typeof externals === "object" && Object.prototype.hasOwnProperty.call(externals, dependency.request)) {
return handleExternal(externals[dependency.request], callback);
}
callback();
}(this.externals, function(err, module) {
if(err) return callback(err);
if(!module) return handleExternal(false, callback);
return callback(null, module);
}));
}.bind(this);
}.bind(this));
};
+21
View File
@@ -0,0 +1,21 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
var ExternalModuleFactoryPlugin = require("./ExternalModuleFactoryPlugin");
class ExternalsPlugin {
constructor(type, externals) {
this.type = type;
this.externals = externals;
}
apply(compiler) {
compiler.plugin("compile", (params) => {
params.normalModuleFactory.apply(new ExternalModuleFactoryPlugin(this.type, this.externals));
});
}
}
module.exports = ExternalsPlugin;
+101
View File
@@ -0,0 +1,101 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class FlagDependencyExportsPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation) => {
compilation.plugin("finish-modules", (modules) => {
const dependencies = Object.create(null);
let module;
let moduleWithExports;
let moduleProvidedExports;
const queue = modules.filter((m) => !m.providedExports);
for(let i = 0; i < queue.length; i++) {
module = queue[i];
if(module.providedExports !== true) {
moduleWithExports = false;
moduleProvidedExports = Array.isArray(module.providedExports) ? new Set(module.providedExports) : new Set();
processDependenciesBlock(module);
if(!moduleWithExports) {
module.providedExports = true;
notifyDependencies();
} else if(module.providedExports !== true) {
module.providedExports = Array.from(moduleProvidedExports);
}
}
}
function processDependenciesBlock(depBlock) {
depBlock.dependencies.forEach((dep) => processDependency(dep));
depBlock.variables.forEach((variable) => {
variable.dependencies.forEach((dep) => processDependency(dep));
});
depBlock.blocks.forEach(processDependenciesBlock);
}
function processDependency(dep) {
const exportDesc = dep.getExports && dep.getExports();
if(!exportDesc) return;
moduleWithExports = true;
const exports = exportDesc.exports;
const exportDeps = exportDesc.dependencies;
if(exportDeps) {
exportDeps.forEach((dep) => {
const depIdent = dep.identifier();
// if this was not yet initialized
// initialize it as an array containing the module and stop
const array = dependencies[depIdent];
if(!array) {
dependencies[depIdent] = [module];
return;
}
// check if this module is known
// if not, add it to the dependencies for this identifier
if(array.indexOf(module) < 0)
array.push(module);
});
}
let changed = false;
if(module.providedExports !== true) {
if(exports === true) {
module.providedExports = true;
changed = true;
} else if(Array.isArray(exports)) {
changed = addToSet(moduleProvidedExports, exports);
}
}
if(changed) {
notifyDependencies();
}
}
function notifyDependencies() {
const deps = dependencies[module.identifier()];
if(deps) {
deps.forEach((dep) => queue.push(dep));
}
}
});
function addToSet(a, b) {
let changed = false;
b.forEach((item) => {
if(!a.has(item)) {
a.add(item);
changed = true;
}
});
return changed;
}
});
}
}
module.exports = FlagDependencyExportsPlugin;
+93
View File
@@ -0,0 +1,93 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
function FlagDependencyUsagePlugin() {
}
module.exports = FlagDependencyUsagePlugin;
FlagDependencyUsagePlugin.prototype.apply = function(compiler) {
compiler.plugin("compilation", function(compilation) {
compilation.plugin("optimize-modules-advanced", function(modules) {
modules.forEach(function(module) {
module.used = false;
});
var queue = [];
compilation.chunks.forEach(function(chunk) {
if(chunk.entryModule) {
processModule(chunk.entryModule, true);
}
});
while(queue.length) {
var queueItem = queue.pop();
processDependenciesBlock(queueItem[0], queueItem[1]);
}
function processModule(module, usedExports) {
module.used = true;
if(module.usedExports === true)
return;
else if(usedExports === true)
module.usedExports = true;
else if(Array.isArray(usedExports)) {
var old = module.usedExports ? module.usedExports.length : -1;
module.usedExports = addToSet(module.usedExports || [], usedExports);
if(module.usedExports.length === old)
return;
} else if(Array.isArray(module.usedExports))
return;
else
module.usedExports = false;
queue.push([module, module.usedExports]);
}
function processDependenciesBlock(depBlock, usedExports) {
depBlock.dependencies.forEach(function(dep) {
processDependency(dep, usedExports);
});
depBlock.variables.forEach(function(variable) {
variable.dependencies.forEach(function(dep) {
processDependency(dep, usedExports);
});
});
depBlock.blocks.forEach(function(block) {
queue.push([block, usedExports]);
});
}
function processDependency(dep, usedExports) {
var reference = dep.getReference && dep.getReference();
if(!reference) return;
var module = reference.module;
var importedNames = reference.importedNames;
var oldUsed = module.used;
var oldUsedExports = module.usedExports;
if(!oldUsed || (importedNames && (!oldUsedExports || !isSubset(oldUsedExports, importedNames)))) {
processModule(module, importedNames);
}
}
});
function addToSet(a, b) {
b.forEach(function(item) {
if(a.indexOf(item) < 0)
a.push(item);
});
return a;
}
function isSubset(biggerSet, subset) {
if(biggerSet === true) return true;
if(subset === true) return false;
return subset.every(function(item) {
return biggerSet.indexOf(item) >= 0;
});
}
});
};
+24
View File
@@ -0,0 +1,24 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class FlagInitialModulesAsUsedPlugin {
apply(compiler) {
compiler.plugin("compilation", (compilation) => {
compilation.plugin("after-optimize-chunks", (chunks) => {
chunks.forEach((chunk) => {
if(!chunk.isInitial()) {
return;
}
chunk.modules.forEach((module) => {
module.usedExports = true;
});
});
});
});
}
}
module.exports = FlagInitialModulesAsUsedPlugin;
+24
View File
@@ -0,0 +1,24 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const FunctionModuleTemplatePlugin = require("./FunctionModuleTemplatePlugin");
const RequestShortener = require("./RequestShortener");
class FunctionModulePlugin {
constructor(options, requestShortener) {
this.options = options;
this.requestShortener = requestShortener;
}
apply(compiler) {
compiler.plugin("compilation", (compilation) => {
compilation.moduleTemplate.requestShortener = this.requestShortener || new RequestShortener(compiler.context);
compilation.moduleTemplate.apply(new FunctionModuleTemplatePlugin());
});
}
}
module.exports = FunctionModulePlugin;
+51
View File
@@ -0,0 +1,51 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConcatSource = require("webpack-sources").ConcatSource;
class FunctionModuleTemplatePlugin {
apply(moduleTemplate) {
moduleTemplate.plugin("render", function(moduleSource, module) {
const source = new ConcatSource();
const defaultArguments = [module.moduleArgument || "module", module.exportsArgument || "exports"];
if((module.arguments && module.arguments.length !== 0) || module.hasDependencies(d => d.requireWebpackRequire !== false)) {
defaultArguments.push("__webpack_require__");
}
source.add("/***/ (function(" + defaultArguments.concat(module.arguments || []).join(", ") + ") {\n\n");
if(module.strict) source.add("\"use strict\";\n");
source.add(moduleSource);
source.add("\n\n/***/ })");
return source;
});
moduleTemplate.plugin("package", function(moduleSource, module) {
if(this.outputOptions.pathinfo) {
const source = new ConcatSource();
const req = module.readableIdentifier(this.requestShortener);
if(Array.isArray(module.providedExports))
source.add("/* exports provided: " + module.providedExports.join(", ") + " */\n");
else if(module.providedExports)
source.add("/* unknown exports provided */\n");
if(Array.isArray(module.usedExports))
source.add("/* exports used: " + module.usedExports.join(", ") + " */\n");
else if(module.usedExports)
source.add("/* all exports used */\n");
source.add("/*!****" + req.replace(/./g, "*") + "****!*\\\n");
source.add(" !*** " + req.replace(/\*\//g, "*_/") + " ***!\n");
source.add(" \\****" + req.replace(/./g, "*") + "****/\n");
source.add(moduleSource);
return source;
}
return moduleSource;
});
moduleTemplate.plugin("hash", function(hash) {
hash.update("FunctionModuleTemplatePlugin");
hash.update("2");
});
}
}
module.exports = FunctionModuleTemplatePlugin;
+42
View File
@@ -0,0 +1,42 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const createHash = require("crypto").createHash;
class HashedModuleIdsPlugin {
constructor(options) {
this.options = Object.assign({
hashFunction: "md5",
hashDigest: "base64",
hashDigestLength: 4
}, options);
}
apply(compiler) {
const options = this.options;
compiler.plugin("compilation", (compilation) => {
const usedIds = new Set();
compilation.plugin("before-module-ids", (modules) => {
modules.forEach((module) => {
if(module.id === null && module.libIdent) {
const id = module.libIdent({
context: this.options.context || compiler.options.context
});
const hash = createHash(options.hashFunction);
hash.update(id);
const hashId = hash.digest(options.hashDigest);
let len = options.hashDigestLength;
while(usedIds.has(hashId.substr(0, len)))
len++;
module.id = hashId.substr(0, len);
usedIds.add(module.id);
}
});
});
});
}
}
module.exports = HashedModuleIdsPlugin;
+585
View File
@@ -0,0 +1,585 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
/*global $hash$ installedModules $require$ hotDownloadManifest hotDownloadUpdateChunk hotDisposeChunk modules */
module.exports = function() {
var hotApplyOnUpdate = true;
var hotCurrentHash = $hash$; // eslint-disable-line no-unused-vars
var hotCurrentModuleData = {};
var hotMainModule = true; // eslint-disable-line no-unused-vars
var hotCurrentParents = []; // eslint-disable-line no-unused-vars
var hotCurrentParentsTemp = []; // eslint-disable-line no-unused-vars
function hotCreateRequire(moduleId) { // eslint-disable-line no-unused-vars
var me = installedModules[moduleId];
if(!me) return $require$;
var fn = function(request) {
if(me.hot.active) {
if(installedModules[request]) {
if(installedModules[request].parents.indexOf(moduleId) < 0)
installedModules[request].parents.push(moduleId);
} else hotCurrentParents = [moduleId];
if(me.children.indexOf(request) < 0)
me.children.push(request);
} else {
console.warn("[HMR] unexpected require(" + request + ") from disposed module " + moduleId);
hotCurrentParents = [];
}
hotMainModule = false;
return $require$(request);
};
var ObjectFactory = function ObjectFactory(name) {
return {
configurable: true,
enumerable: true,
get: function() {
return $require$[name];
},
set: function(value) {
$require$[name] = value;
}
};
};
for(var name in $require$) {
if(Object.prototype.hasOwnProperty.call($require$, name)) {
Object.defineProperty(fn, name, ObjectFactory(name));
}
}
Object.defineProperty(fn, "e", {
enumerable: true,
value: function(chunkId) {
if(hotStatus === "ready")
hotSetStatus("prepare");
hotChunksLoading++;
return $require$.e(chunkId).then(finishChunkLoading, function(err) {
finishChunkLoading();
throw err;
});
function finishChunkLoading() {
hotChunksLoading--;
if(hotStatus === "prepare") {
if(!hotWaitingFilesMap[chunkId]) {
hotEnsureUpdateChunk(chunkId);
}
if(hotChunksLoading === 0 && hotWaitingFiles === 0) {
hotUpdateDownloaded();
}
}
}
}
});
return fn;
}
function hotCreateModule(moduleId) { // eslint-disable-line no-unused-vars
var hot = {
// private stuff
_acceptedDependencies: {},
_declinedDependencies: {},
_selfAccepted: false,
_selfDeclined: false,
_disposeHandlers: [],
_main: hotMainModule,
// Module API
active: true,
accept: function(dep, callback) {
if(typeof dep === "undefined")
hot._selfAccepted = true;
else if(typeof dep === "function")
hot._selfAccepted = dep;
else if(typeof dep === "object")
for(var i = 0; i < dep.length; i++)
hot._acceptedDependencies[dep[i]] = callback || function() {};
else
hot._acceptedDependencies[dep] = callback || function() {};
},
decline: function(dep) {
if(typeof dep === "undefined")
hot._selfDeclined = true;
else if(typeof dep === "object")
for(var i = 0; i < dep.length; i++)
hot._declinedDependencies[dep[i]] = true;
else
hot._declinedDependencies[dep] = true;
},
dispose: function(callback) {
hot._disposeHandlers.push(callback);
},
addDisposeHandler: function(callback) {
hot._disposeHandlers.push(callback);
},
removeDisposeHandler: function(callback) {
var idx = hot._disposeHandlers.indexOf(callback);
if(idx >= 0) hot._disposeHandlers.splice(idx, 1);
},
// Management API
check: hotCheck,
apply: hotApply,
status: function(l) {
if(!l) return hotStatus;
hotStatusHandlers.push(l);
},
addStatusHandler: function(l) {
hotStatusHandlers.push(l);
},
removeStatusHandler: function(l) {
var idx = hotStatusHandlers.indexOf(l);
if(idx >= 0) hotStatusHandlers.splice(idx, 1);
},
//inherit from previous dispose call
data: hotCurrentModuleData[moduleId]
};
hotMainModule = true;
return hot;
}
var hotStatusHandlers = [];
var hotStatus = "idle";
function hotSetStatus(newStatus) {
hotStatus = newStatus;
for(var i = 0; i < hotStatusHandlers.length; i++)
hotStatusHandlers[i].call(null, newStatus);
}
// while downloading
var hotWaitingFiles = 0;
var hotChunksLoading = 0;
var hotWaitingFilesMap = {};
var hotRequestedFilesMap = {};
var hotAvailableFilesMap = {};
var hotDeferred;
// The update info
var hotUpdate, hotUpdateNewHash;
function toModuleId(id) {
var isNumber = (+id) + "" === id;
return isNumber ? +id : id;
}
function hotCheck(apply) {
if(hotStatus !== "idle") throw new Error("check() is only allowed in idle status");
hotApplyOnUpdate = apply;
hotSetStatus("check");
return hotDownloadManifest().then(function(update) {
if(!update) {
hotSetStatus("idle");
return null;
}
hotRequestedFilesMap = {};
hotWaitingFilesMap = {};
hotAvailableFilesMap = update.c;
hotUpdateNewHash = update.h;
hotSetStatus("prepare");
var promise = new Promise(function(resolve, reject) {
hotDeferred = {
resolve: resolve,
reject: reject
};
});
hotUpdate = {};
/*foreachInstalledChunks*/
{ // eslint-disable-line no-lone-blocks
/*globals chunkId */
hotEnsureUpdateChunk(chunkId);
}
if(hotStatus === "prepare" && hotChunksLoading === 0 && hotWaitingFiles === 0) {
hotUpdateDownloaded();
}
return promise;
});
}
function hotAddUpdateChunk(chunkId, moreModules) { // eslint-disable-line no-unused-vars
if(!hotAvailableFilesMap[chunkId] || !hotRequestedFilesMap[chunkId])
return;
hotRequestedFilesMap[chunkId] = false;
for(var moduleId in moreModules) {
if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {
hotUpdate[moduleId] = moreModules[moduleId];
}
}
if(--hotWaitingFiles === 0 && hotChunksLoading === 0) {
hotUpdateDownloaded();
}
}
function hotEnsureUpdateChunk(chunkId) {
if(!hotAvailableFilesMap[chunkId]) {
hotWaitingFilesMap[chunkId] = true;
} else {
hotRequestedFilesMap[chunkId] = true;
hotWaitingFiles++;
hotDownloadUpdateChunk(chunkId);
}
}
function hotUpdateDownloaded() {
hotSetStatus("ready");
var deferred = hotDeferred;
hotDeferred = null;
if(!deferred) return;
if(hotApplyOnUpdate) {
hotApply(hotApplyOnUpdate).then(function(result) {
deferred.resolve(result);
}, function(err) {
deferred.reject(err);
});
} else {
var outdatedModules = [];
for(var id in hotUpdate) {
if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) {
outdatedModules.push(toModuleId(id));
}
}
deferred.resolve(outdatedModules);
}
}
function hotApply(options) {
if(hotStatus !== "ready") throw new Error("apply() is only allowed in ready status");
options = options || {};
var cb;
var i;
var j;
var module;
var moduleId;
function getAffectedStuff(updateModuleId) {
var outdatedModules = [updateModuleId];
var outdatedDependencies = {};
var queue = outdatedModules.slice().map(function(id) {
return {
chain: [id],
id: id
};
});
while(queue.length > 0) {
var queueItem = queue.pop();
var moduleId = queueItem.id;
var chain = queueItem.chain;
module = installedModules[moduleId];
if(!module || module.hot._selfAccepted)
continue;
if(module.hot._selfDeclined) {
return {
type: "self-declined",
chain: chain,
moduleId: moduleId
};
}
if(module.hot._main) {
return {
type: "unaccepted",
chain: chain,
moduleId: moduleId
};
}
for(var i = 0; i < module.parents.length; i++) {
var parentId = module.parents[i];
var parent = installedModules[parentId];
if(!parent) continue;
if(parent.hot._declinedDependencies[moduleId]) {
return {
type: "declined",
chain: chain.concat([parentId]),
moduleId: moduleId,
parentId: parentId
};
}
if(outdatedModules.indexOf(parentId) >= 0) continue;
if(parent.hot._acceptedDependencies[moduleId]) {
if(!outdatedDependencies[parentId])
outdatedDependencies[parentId] = [];
addAllToSet(outdatedDependencies[parentId], [moduleId]);
continue;
}
delete outdatedDependencies[parentId];
outdatedModules.push(parentId);
queue.push({
chain: chain.concat([parentId]),
id: parentId
});
}
}
return {
type: "accepted",
moduleId: updateModuleId,
outdatedModules: outdatedModules,
outdatedDependencies: outdatedDependencies
};
}
function addAllToSet(a, b) {
for(var i = 0; i < b.length; i++) {
var item = b[i];
if(a.indexOf(item) < 0)
a.push(item);
}
}
// at begin all updates modules are outdated
// the "outdated" status can propagate to parents if they don't accept the children
var outdatedDependencies = {};
var outdatedModules = [];
var appliedUpdate = {};
var warnUnexpectedRequire = function warnUnexpectedRequire() {
console.warn("[HMR] unexpected require(" + result.moduleId + ") to disposed module");
};
for(var id in hotUpdate) {
if(Object.prototype.hasOwnProperty.call(hotUpdate, id)) {
moduleId = toModuleId(id);
var result;
if(hotUpdate[id]) {
result = getAffectedStuff(moduleId);
} else {
result = {
type: "disposed",
moduleId: id
};
}
var abortError = false;
var doApply = false;
var doDispose = false;
var chainInfo = "";
if(result.chain) {
chainInfo = "\nUpdate propagation: " + result.chain.join(" -> ");
}
switch(result.type) {
case "self-declined":
if(options.onDeclined)
options.onDeclined(result);
if(!options.ignoreDeclined)
abortError = new Error("Aborted because of self decline: " + result.moduleId + chainInfo);
break;
case "declined":
if(options.onDeclined)
options.onDeclined(result);
if(!options.ignoreDeclined)
abortError = new Error("Aborted because of declined dependency: " + result.moduleId + " in " + result.parentId + chainInfo);
break;
case "unaccepted":
if(options.onUnaccepted)
options.onUnaccepted(result);
if(!options.ignoreUnaccepted)
abortError = new Error("Aborted because " + moduleId + " is not accepted" + chainInfo);
break;
case "accepted":
if(options.onAccepted)
options.onAccepted(result);
doApply = true;
break;
case "disposed":
if(options.onDisposed)
options.onDisposed(result);
doDispose = true;
break;
default:
throw new Error("Unexception type " + result.type);
}
if(abortError) {
hotSetStatus("abort");
return Promise.reject(abortError);
}
if(doApply) {
appliedUpdate[moduleId] = hotUpdate[moduleId];
addAllToSet(outdatedModules, result.outdatedModules);
for(moduleId in result.outdatedDependencies) {
if(Object.prototype.hasOwnProperty.call(result.outdatedDependencies, moduleId)) {
if(!outdatedDependencies[moduleId])
outdatedDependencies[moduleId] = [];
addAllToSet(outdatedDependencies[moduleId], result.outdatedDependencies[moduleId]);
}
}
}
if(doDispose) {
addAllToSet(outdatedModules, [result.moduleId]);
appliedUpdate[moduleId] = warnUnexpectedRequire;
}
}
}
// Store self accepted outdated modules to require them later by the module system
var outdatedSelfAcceptedModules = [];
for(i = 0; i < outdatedModules.length; i++) {
moduleId = outdatedModules[i];
if(installedModules[moduleId] && installedModules[moduleId].hot._selfAccepted)
outdatedSelfAcceptedModules.push({
module: moduleId,
errorHandler: installedModules[moduleId].hot._selfAccepted
});
}
// Now in "dispose" phase
hotSetStatus("dispose");
Object.keys(hotAvailableFilesMap).forEach(function(chunkId) {
if(hotAvailableFilesMap[chunkId] === false) {
hotDisposeChunk(chunkId);
}
});
var idx;
var queue = outdatedModules.slice();
while(queue.length > 0) {
moduleId = queue.pop();
module = installedModules[moduleId];
if(!module) continue;
var data = {};
// Call dispose handlers
var disposeHandlers = module.hot._disposeHandlers;
for(j = 0; j < disposeHandlers.length; j++) {
cb = disposeHandlers[j];
cb(data);
}
hotCurrentModuleData[moduleId] = data;
// disable module (this disables requires from this module)
module.hot.active = false;
// remove module from cache
delete installedModules[moduleId];
// remove "parents" references from all children
for(j = 0; j < module.children.length; j++) {
var child = installedModules[module.children[j]];
if(!child) continue;
idx = child.parents.indexOf(moduleId);
if(idx >= 0) {
child.parents.splice(idx, 1);
}
}
}
// remove outdated dependency from module children
var dependency;
var moduleOutdatedDependencies;
for(moduleId in outdatedDependencies) {
if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) {
module = installedModules[moduleId];
if(module) {
moduleOutdatedDependencies = outdatedDependencies[moduleId];
for(j = 0; j < moduleOutdatedDependencies.length; j++) {
dependency = moduleOutdatedDependencies[j];
idx = module.children.indexOf(dependency);
if(idx >= 0) module.children.splice(idx, 1);
}
}
}
}
// Not in "apply" phase
hotSetStatus("apply");
hotCurrentHash = hotUpdateNewHash;
// insert new code
for(moduleId in appliedUpdate) {
if(Object.prototype.hasOwnProperty.call(appliedUpdate, moduleId)) {
modules[moduleId] = appliedUpdate[moduleId];
}
}
// call accept handlers
var error = null;
for(moduleId in outdatedDependencies) {
if(Object.prototype.hasOwnProperty.call(outdatedDependencies, moduleId)) {
module = installedModules[moduleId];
moduleOutdatedDependencies = outdatedDependencies[moduleId];
var callbacks = [];
for(i = 0; i < moduleOutdatedDependencies.length; i++) {
dependency = moduleOutdatedDependencies[i];
cb = module.hot._acceptedDependencies[dependency];
if(callbacks.indexOf(cb) >= 0) continue;
callbacks.push(cb);
}
for(i = 0; i < callbacks.length; i++) {
cb = callbacks[i];
try {
cb(moduleOutdatedDependencies);
} catch(err) {
if(options.onErrored) {
options.onErrored({
type: "accept-errored",
moduleId: moduleId,
dependencyId: moduleOutdatedDependencies[i],
error: err
});
}
if(!options.ignoreErrored) {
if(!error)
error = err;
}
}
}
}
}
// Load self accepted modules
for(i = 0; i < outdatedSelfAcceptedModules.length; i++) {
var item = outdatedSelfAcceptedModules[i];
moduleId = item.module;
hotCurrentParents = [moduleId];
try {
$require$(moduleId);
} catch(err) {
if(typeof item.errorHandler === "function") {
try {
item.errorHandler(err);
} catch(err2) {
if(options.onErrored) {
options.onErrored({
type: "self-accept-error-handler-errored",
moduleId: moduleId,
error: err2,
orginalError: err
});
}
if(!options.ignoreErrored) {
if(!error)
error = err2;
}
if(!error)
error = err;
}
} else {
if(options.onErrored) {
options.onErrored({
type: "self-accept-errored",
moduleId: moduleId,
error: err
});
}
if(!options.ignoreErrored) {
if(!error)
error = err;
}
}
}
}
// handle errors in accept handlers and self accepted module load
if(error) {
hotSetStatus("fail");
return Promise.reject(error);
}
hotSetStatus("idle");
return Promise.resolve(outdatedModules);
}
};
+261
View File
@@ -0,0 +1,261 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
var Template = require("./Template");
var ModuleHotAcceptDependency = require("./dependencies/ModuleHotAcceptDependency");
var ModuleHotDeclineDependency = require("./dependencies/ModuleHotDeclineDependency");
var RawSource = require("webpack-sources").RawSource;
var ConstDependency = require("./dependencies/ConstDependency");
var NullFactory = require("./NullFactory");
const ParserHelpers = require("./ParserHelpers");
function HotModuleReplacementPlugin(options) {
options = options || {};
this.multiStep = options.multiStep;
this.fullBuildTimeout = options.fullBuildTimeout || 200;
}
module.exports = HotModuleReplacementPlugin;
HotModuleReplacementPlugin.prototype.apply = function(compiler) {
var multiStep = this.multiStep;
var fullBuildTimeout = this.fullBuildTimeout;
var hotUpdateChunkFilename = compiler.options.output.hotUpdateChunkFilename;
var hotUpdateMainFilename = compiler.options.output.hotUpdateMainFilename;
compiler.plugin("compilation", function(compilation, params) {
var hotUpdateChunkTemplate = compilation.hotUpdateChunkTemplate;
if(!hotUpdateChunkTemplate) return;
var normalModuleFactory = params.normalModuleFactory;
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
compilation.dependencyFactories.set(ModuleHotAcceptDependency, normalModuleFactory);
compilation.dependencyTemplates.set(ModuleHotAcceptDependency, new ModuleHotAcceptDependency.Template());
compilation.dependencyFactories.set(ModuleHotDeclineDependency, normalModuleFactory);
compilation.dependencyTemplates.set(ModuleHotDeclineDependency, new ModuleHotDeclineDependency.Template());
compilation.plugin("record", function(compilation, records) {
if(records.hash === this.hash) return;
records.hash = compilation.hash;
records.moduleHashs = {};
this.modules.forEach(function(module) {
var identifier = module.identifier();
var hash = require("crypto").createHash("md5");
module.updateHash(hash);
records.moduleHashs[identifier] = hash.digest("hex");
});
records.chunkHashs = {};
this.chunks.forEach(function(chunk) {
records.chunkHashs[chunk.id] = chunk.hash;
});
records.chunkModuleIds = {};
this.chunks.forEach(function(chunk) {
records.chunkModuleIds[chunk.id] = chunk.modules.map(function(m) {
return m.id;
});
});
});
var initialPass = false;
var recompilation = false;
compilation.plugin("after-hash", function() {
var records = this.records;
if(!records) {
initialPass = true;
return;
}
if(!records.hash)
initialPass = true;
var preHash = records.preHash || "x";
var prepreHash = records.prepreHash || "x";
if(preHash === this.hash) {
recompilation = true;
this.modifyHash(prepreHash);
return;
}
records.prepreHash = records.hash || "x";
records.preHash = this.hash;
this.modifyHash(records.prepreHash);
});
compilation.plugin("should-generate-chunk-assets", function() {
if(multiStep && !recompilation && !initialPass)
return false;
});
compilation.plugin("need-additional-pass", function() {
if(multiStep && !recompilation && !initialPass)
return true;
});
compiler.plugin("additional-pass", function(callback) {
if(multiStep)
return setTimeout(callback, fullBuildTimeout);
return callback();
});
compilation.plugin("additional-chunk-assets", function() {
var records = this.records;
if(records.hash === this.hash) return;
if(!records.moduleHashs || !records.chunkHashs || !records.chunkModuleIds) return;
this.modules.forEach(function(module) {
var identifier = module.identifier();
var hash = require("crypto").createHash("md5");
module.updateHash(hash);
hash = hash.digest("hex");
module.hotUpdate = records.moduleHashs[identifier] !== hash;
});
var hotUpdateMainContent = {
h: this.hash,
c: {}
};
Object.keys(records.chunkHashs).forEach(function(chunkId) {
chunkId = +chunkId;
var currentChunk = this.chunks.filter(function(chunk) {
return chunk.id === chunkId;
})[0];
if(currentChunk) {
var newModules = currentChunk.modules.filter(function(module) {
return module.hotUpdate;
});
var allModules = {};
currentChunk.modules.forEach(function(module) {
allModules[module.id] = true;
});
var removedModules = records.chunkModuleIds[chunkId].filter(function(id) {
return !allModules[id];
});
if(newModules.length > 0 || removedModules.length > 0) {
var source = hotUpdateChunkTemplate.render(chunkId, newModules, removedModules, this.hash, this.moduleTemplate, this.dependencyTemplates);
var filename = this.getPath(hotUpdateChunkFilename, {
hash: records.hash,
chunk: currentChunk
});
this.additionalChunkAssets.push(filename);
this.assets[filename] = source;
hotUpdateMainContent.c[chunkId] = true;
currentChunk.files.push(filename);
this.applyPlugins("chunk-asset", currentChunk, filename);
}
} else {
hotUpdateMainContent.c[chunkId] = false;
}
}, this);
var source = new RawSource(JSON.stringify(hotUpdateMainContent));
var filename = this.getPath(hotUpdateMainFilename, {
hash: records.hash
});
this.assets[filename] = source;
});
compilation.mainTemplate.plugin("hash", function(hash) {
hash.update("HotMainTemplateDecorator");
});
compilation.mainTemplate.plugin("module-require", function(_, chunk, hash, varModuleId) {
return "hotCreateRequire(" + varModuleId + ")";
});
compilation.mainTemplate.plugin("require-extensions", function(source) {
var buf = [source];
buf.push("");
buf.push("// __webpack_hash__");
buf.push(this.requireFn + ".h = function() { return hotCurrentHash; };");
return this.asString(buf);
});
compilation.mainTemplate.plugin("bootstrap", function(source, chunk, hash) {
source = this.applyPluginsWaterfall("hot-bootstrap", source, chunk, hash);
return this.asString([
source,
"",
hotInitCode
.replace(/\$require\$/g, this.requireFn)
.replace(/\$hash\$/g, JSON.stringify(hash))
.replace(/\/\*foreachInstalledChunks\*\//g, chunk.chunks.length > 0 ? "for(var chunkId in installedChunks)" : "var chunkId = " + chunk.id + ";")
]);
});
compilation.mainTemplate.plugin("global-hash", function() {
return true;
});
compilation.mainTemplate.plugin("current-hash", function(_, length) {
if(isFinite(length))
return "hotCurrentHash.substr(0, " + length + ")";
else
return "hotCurrentHash";
});
compilation.mainTemplate.plugin("module-obj", function(source, chunk, hash, varModuleId) {
return this.asString([
source + ",",
"hot: hotCreateModule(" + varModuleId + "),",
"parents: (hotCurrentParentsTemp = hotCurrentParents, hotCurrentParents = [], hotCurrentParentsTemp),",
"children: []"
]);
});
params.normalModuleFactory.plugin("parser", function(parser, parserOptions) {
parser.plugin("expression __webpack_hash__", ParserHelpers.toConstantDependency("__webpack_require__.h()"));
parser.plugin("evaluate typeof __webpack_hash__", ParserHelpers.evaluateToString("string"));
parser.plugin("evaluate Identifier module.hot", function(expr) {
return ParserHelpers.evaluateToBoolean(!!this.state.compilation.hotUpdateChunkTemplate)(expr);
});
parser.plugin("call module.hot.accept", function(expr) {
if(!this.state.compilation.hotUpdateChunkTemplate) return false;
if(expr.arguments.length >= 1) {
var arg = this.evaluateExpression(expr.arguments[0]);
var params = [],
requests = [];
if(arg.isString()) {
params = [arg];
} else if(arg.isArray()) {
params = arg.items.filter(function(param) {
return param.isString();
});
}
if(params.length > 0) {
params.forEach(function(param, idx) {
var request = param.string;
var dep = new ModuleHotAcceptDependency(request, param.range);
dep.optional = true;
dep.loc = Object.create(expr.loc);
dep.loc.index = idx;
this.state.module.addDependency(dep);
requests.push(request);
}.bind(this));
if(expr.arguments.length > 1)
this.applyPluginsBailResult("hot accept callback", expr.arguments[1], requests);
else
this.applyPluginsBailResult("hot accept without callback", expr, requests);
}
}
});
parser.plugin("call module.hot.decline", function(expr) {
if(!this.state.compilation.hotUpdateChunkTemplate) return false;
if(expr.arguments.length === 1) {
var arg = this.evaluateExpression(expr.arguments[0]);
var params = [];
if(arg.isString()) {
params = [arg];
} else if(arg.isArray()) {
params = arg.items.filter(function(param) {
return param.isString();
});
}
params.forEach(function(param, idx) {
var dep = new ModuleHotDeclineDependency(param.string, param.range);
dep.optional = true;
dep.loc = Object.create(expr.loc);
dep.loc.index = idx;
this.state.module.addDependency(dep);
}.bind(this));
}
});
parser.plugin("expression module.hot", ParserHelpers.skipTraversal);
});
});
};
var hotInitCode = Template.getFunctionContent(require("./HotModuleReplacement.runtime.js"));
+30
View File
@@ -0,0 +1,30 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Template = require("./Template");
module.exports = class HotUpdateChunkTemplate extends Template {
constructor(outputOptions) {
super(outputOptions);
}
render(id, modules, removedModules, hash, moduleTemplate, dependencyTemplates) {
const modulesSource = this.renderChunkModules({
id: id,
modules: modules,
removedModules: removedModules
}, moduleTemplate, dependencyTemplates);
const core = this.applyPluginsWaterfall("modules", modulesSource, modules, removedModules, moduleTemplate, dependencyTemplates);
const source = this.applyPluginsWaterfall("render", core, modules, removedModules, hash, id, moduleTemplate, dependencyTemplates);
return source;
}
updateHash(hash) {
hash.update("HotUpdateChunkTemplate");
hash.update("1");
this.applyPlugins("hash", hash);
}
};
+38
View File
@@ -0,0 +1,38 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class IgnorePlugin {
constructor(resourceRegExp, contextRegExp) {
this.resourceRegExp = resourceRegExp;
this.contextRegExp = contextRegExp;
}
apply(compiler) {
const resourceRegExp = this.resourceRegExp;
const contextRegExp = this.contextRegExp;
compiler.plugin("normal-module-factory", (nmf) => {
nmf.plugin("before-resolve", (result, callback) => {
if(!result) return callback();
if(resourceRegExp.test(result.request) &&
(!contextRegExp || contextRegExp.test(result.context))) {
return callback();
}
return callback(null, result);
});
});
compiler.plugin("context-module-factory", (cmf) => {
cmf.plugin("before-resolve", (result, callback) => {
if(!result) return callback();
if(resourceRegExp.test(result.request)) {
return callback();
}
return callback(null, result);
});
});
}
}
module.exports = IgnorePlugin;
+31
View File
@@ -0,0 +1,31 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var ConcatSource = require("webpack-sources").ConcatSource;
function JsonpChunkTemplatePlugin() {}
module.exports = JsonpChunkTemplatePlugin;
JsonpChunkTemplatePlugin.prototype.apply = function(chunkTemplate) {
chunkTemplate.plugin("render", function(modules, chunk) {
var jsonpFunction = this.outputOptions.jsonpFunction;
var source = new ConcatSource();
source.add(jsonpFunction + "(" + JSON.stringify(chunk.ids) + ",");
source.add(modules);
var entries = [chunk.entryModule].filter(Boolean).map(function(m) {
return m.id;
});
if(entries.length > 0) {
source.add("," + JSON.stringify(entries));
}
source.add(")");
return source;
});
chunkTemplate.plugin("hash", function(hash) {
hash.update("JsonpChunkTemplatePlugin");
hash.update("3");
hash.update(this.outputOptions.jsonpFunction + "");
hash.update(this.outputOptions.library + "");
});
};
+37
View File
@@ -0,0 +1,37 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConcatSource = require("webpack-sources").ConcatSource;
class JsonpExportMainTemplatePlugin {
constructor(name) {
this.name = name;
}
apply(compilation) {
const mainTemplate = compilation.mainTemplate;
compilation.templatesPlugin("render-with-entry", (source, chunk, hash) => {
const name = mainTemplate.applyPluginsWaterfall("asset-path", this.name || "", {
hash: hash,
chunk: chunk
});
return new ConcatSource(`${name}(`, source, ");");
});
mainTemplate.plugin("global-hash-paths", paths => {
if(this.name) paths.push(this.name);
return paths;
});
mainTemplate.plugin("hash", hash => {
hash.update("jsonp export");
hash.update(`${this.name}`);
});
}
}
module.exports = JsonpExportMainTemplatePlugin;
+27
View File
@@ -0,0 +1,27 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConcatSource = require("webpack-sources").ConcatSource;
class JsonpHotUpdateChunkTemplatePlugin {
apply(hotUpdateChunkTemplate) {
hotUpdateChunkTemplate.plugin("render", function(modulesSource, modules, removedModules, hash, id) {
const source = new ConcatSource();
source.add(`${this.outputOptions.hotUpdateFunction}(${JSON.stringify(id)},`);
source.add(modulesSource);
source.add(")");
return source;
});
hotUpdateChunkTemplate.plugin("hash", function(hash) {
hash.update("JsonpHotUpdateChunkTemplatePlugin");
hash.update("3");
hash.update(`${this.outputOptions.hotUpdateFunction}`);
hash.update(`${this.outputOptions.library}`);
});
}
}
module.exports = JsonpHotUpdateChunkTemplatePlugin;
+58
View File
@@ -0,0 +1,58 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
/*globals hotAddUpdateChunk parentHotUpdateCallback document XMLHttpRequest $require$ $hotChunkFilename$ $hotMainFilename$ */
module.exports = function() {
function webpackHotUpdateCallback(chunkId, moreModules) { // eslint-disable-line no-unused-vars
hotAddUpdateChunk(chunkId, moreModules);
if(parentHotUpdateCallback) parentHotUpdateCallback(chunkId, moreModules);
} //$semicolon
function hotDownloadUpdateChunk(chunkId) { // eslint-disable-line no-unused-vars
var head = document.getElementsByTagName("head")[0];
var script = document.createElement("script");
script.type = "text/javascript";
script.charset = "utf-8";
script.src = $require$.p + $hotChunkFilename$;
head.appendChild(script);
}
function hotDownloadManifest() { // eslint-disable-line no-unused-vars
return new Promise(function(resolve, reject) {
if(typeof XMLHttpRequest === "undefined")
return reject(new Error("No browser support"));
try {
var request = new XMLHttpRequest();
var requestPath = $require$.p + $hotMainFilename$;
request.open("GET", requestPath, true);
request.timeout = 10000;
request.send(null);
} catch(err) {
return reject(err);
}
request.onreadystatechange = function() {
if(request.readyState !== 4) return;
if(request.status === 0) {
// timeout
reject(new Error("Manifest request to " + requestPath + " timed out."));
} else if(request.status === 404) {
// no update available
resolve();
} else if(request.status !== 200 && request.status !== 304) {
// other failure
reject(new Error("Manifest request to " + requestPath + " failed."));
} else {
// success
try {
var update = JSON.parse(request.responseText);
} catch(e) {
reject(e);
return;
}
resolve(update);
}
};
});
}
};
+208
View File
@@ -0,0 +1,208 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var Template = require("./Template");
function JsonpMainTemplatePlugin() {}
module.exports = JsonpMainTemplatePlugin;
JsonpMainTemplatePlugin.prototype.constructor = JsonpMainTemplatePlugin;
JsonpMainTemplatePlugin.prototype.apply = function(mainTemplate) {
mainTemplate.plugin("local-vars", function(source, chunk) {
if(chunk.chunks.length > 0) {
return this.asString([
source,
"",
"// objects to store loaded and loading chunks",
"var installedChunks = {",
this.indent(
chunk.ids.map(function(id) {
return id + ": 0";
}).join(",\n")
),
"};"
]);
}
return source;
});
mainTemplate.plugin("jsonp-script", function(_, chunk, hash) {
var chunkFilename = this.outputOptions.chunkFilename;
var chunkMaps = chunk.getChunkMaps();
var crossOriginLoading = this.outputOptions.crossOriginLoading;
var chunkLoadTimeout = this.outputOptions.chunkLoadTimeout || 120000;
return this.asString([
"var script = document.createElement('script');",
"script.type = 'text/javascript';",
"script.charset = 'utf-8';",
"script.async = true;",
"script.timeout = " + chunkLoadTimeout + ";",
crossOriginLoading ? "script.crossOrigin = '" + crossOriginLoading + "';" : "",
"if (" + this.requireFn + ".nc) {",
this.indent("script.setAttribute(\"nonce\", " + this.requireFn + ".nc);"),
"}",
"script.src = " + this.requireFn + ".p + " +
this.applyPluginsWaterfall("asset-path", JSON.stringify(chunkFilename), {
hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"",
hashWithLength: function(length) {
return "\" + " + this.renderCurrentHashCode(hash, length) + " + \"";
}.bind(this),
chunk: {
id: "\" + chunkId + \"",
hash: "\" + " + JSON.stringify(chunkMaps.hash) + "[chunkId] + \"",
hashWithLength: function(length) {
var shortChunkHashMap = {};
Object.keys(chunkMaps.hash).forEach(function(chunkId) {
if(typeof chunkMaps.hash[chunkId] === "string")
shortChunkHashMap[chunkId] = chunkMaps.hash[chunkId].substr(0, length);
});
return "\" + " + JSON.stringify(shortChunkHashMap) + "[chunkId] + \"";
},
name: "\" + (" + JSON.stringify(chunkMaps.name) + "[chunkId]||chunkId) + \""
}
}) + ";",
"var timeout = setTimeout(onScriptComplete, " + chunkLoadTimeout + ");",
"script.onerror = script.onload = onScriptComplete;",
"function onScriptComplete() {",
this.indent([
"// avoid mem leaks in IE.",
"script.onerror = script.onload = null;",
"clearTimeout(timeout);",
"var chunk = installedChunks[chunkId];",
"if(chunk !== 0) {",
this.indent([
"if(chunk) chunk[1](new Error('Loading chunk ' + chunkId + ' failed.'));",
"installedChunks[chunkId] = undefined;"
]),
"}"
]),
"};",
]);
});
mainTemplate.plugin("require-ensure", function(_, chunk, hash) {
return this.asString([
"if(installedChunks[chunkId] === 0)",
this.indent([
"return Promise.resolve();"
]),
"",
"// a Promise means \"currently loading\".",
"if(installedChunks[chunkId]) {",
this.indent([
"return installedChunks[chunkId][2];"
]),
"}",
"",
"// setup Promise in chunk cache",
"var promise = new Promise(function(resolve, reject) {",
this.indent([
"installedChunks[chunkId] = [resolve, reject];"
]),
"});",
"installedChunks[chunkId][2] = promise;",
"",
"// start chunk loading",
"var head = document.getElementsByTagName('head')[0];",
this.applyPluginsWaterfall("jsonp-script", "", chunk, hash),
"head.appendChild(script);",
"",
"return promise;"
]);
});
mainTemplate.plugin("require-extensions", function(source, chunk) {
if(chunk.chunks.length === 0) return source;
return this.asString([
source,
"",
"// on error function for async loading",
this.requireFn + ".oe = function(err) { console.error(err); throw err; };"
]);
});
mainTemplate.plugin("bootstrap", function(source, chunk, hash) {
if(chunk.chunks.length > 0) {
var jsonpFunction = this.outputOptions.jsonpFunction;
return this.asString([
source,
"",
"// install a JSONP callback for chunk loading",
"var parentJsonpFunction = window[" + JSON.stringify(jsonpFunction) + "];",
"window[" + JSON.stringify(jsonpFunction) + "] = function webpackJsonpCallback(chunkIds, moreModules, executeModules) {",
this.indent([
"// add \"moreModules\" to the modules object,",
"// then flag all \"chunkIds\" as loaded and fire callback",
"var moduleId, chunkId, i = 0, resolves = [], result;",
"for(;i < chunkIds.length; i++) {",
this.indent([
"chunkId = chunkIds[i];",
"if(installedChunks[chunkId])",
this.indent("resolves.push(installedChunks[chunkId][0]);"),
"installedChunks[chunkId] = 0;"
]),
"}",
"for(moduleId in moreModules) {",
this.indent([
"if(Object.prototype.hasOwnProperty.call(moreModules, moduleId)) {",
this.indent(this.renderAddModule(hash, chunk, "moduleId", "moreModules[moduleId]")),
"}"
]),
"}",
"if(parentJsonpFunction) parentJsonpFunction(chunkIds, moreModules, executeModules);",
"while(resolves.length)",
this.indent("resolves.shift()();"),
this.entryPointInChildren(chunk) ? [
"if(executeModules) {",
this.indent([
"for(i=0; i < executeModules.length; i++) {",
this.indent("result = " + this.requireFn + "(" + this.requireFn + ".s = executeModules[i]);"),
"}"
]),
"}",
"return result;",
] : ""
]),
"};"
]);
}
return source;
});
mainTemplate.plugin("hot-bootstrap", function(source, chunk, hash) {
var hotUpdateChunkFilename = this.outputOptions.hotUpdateChunkFilename;
var hotUpdateMainFilename = this.outputOptions.hotUpdateMainFilename;
var hotUpdateFunction = this.outputOptions.hotUpdateFunction;
var currentHotUpdateChunkFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateChunkFilename), {
hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"",
hashWithLength: function(length) {
return "\" + " + this.renderCurrentHashCode(hash, length) + " + \"";
}.bind(this),
chunk: {
id: "\" + chunkId + \""
}
});
var currentHotUpdateMainFilename = this.applyPluginsWaterfall("asset-path", JSON.stringify(hotUpdateMainFilename), {
hash: "\" + " + this.renderCurrentHashCode(hash) + " + \"",
hashWithLength: function(length) {
return "\" + " + this.renderCurrentHashCode(hash, length) + " + \"";
}.bind(this)
});
return source + "\n" +
"function hotDisposeChunk(chunkId) {\n" +
"\tdelete installedChunks[chunkId];\n" +
"}\n" +
"var parentHotUpdateCallback = this[" + JSON.stringify(hotUpdateFunction) + "];\n" +
"this[" + JSON.stringify(hotUpdateFunction) + "] = " + Template.getFunctionContent(require("./JsonpMainTemplate.runtime.js"))
.replace(/\/\/\$semicolon/g, ";")
.replace(/\$require\$/g, this.requireFn)
.replace(/\$hotMainFilename\$/g, currentHotUpdateMainFilename)
.replace(/\$hotChunkFilename\$/g, currentHotUpdateChunkFilename)
.replace(/\$hash\$/g, JSON.stringify(hash));
});
mainTemplate.plugin("hash", function(hash) {
hash.update("jsonp");
hash.update("4");
hash.update(this.outputOptions.filename + "");
hash.update(this.outputOptions.chunkFilename + "");
hash.update(this.outputOptions.jsonpFunction + "");
hash.update(this.outputOptions.hotUpdateFunction + "");
});
};
+21
View File
@@ -0,0 +1,21 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const JsonpMainTemplatePlugin = require("./JsonpMainTemplatePlugin");
const JsonpChunkTemplatePlugin = require("./JsonpChunkTemplatePlugin");
const JsonpHotUpdateChunkTemplatePlugin = require("./JsonpHotUpdateChunkTemplatePlugin");
class JsonpTemplatePlugin {
apply(compiler) {
compiler.plugin("this-compilation", (compilation) => {
compilation.mainTemplate.apply(new JsonpMainTemplatePlugin());
compilation.chunkTemplate.apply(new JsonpChunkTemplatePlugin());
compilation.hotUpdateChunkTemplate.apply(new JsonpHotUpdateChunkTemplatePlugin());
});
}
}
module.exports = JsonpTemplatePlugin;
+53
View File
@@ -0,0 +1,53 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var path = require("path");
var async = require("async");
function LibManifestPlugin(options) {
this.options = options;
}
module.exports = LibManifestPlugin;
LibManifestPlugin.prototype.apply = function(compiler) {
compiler.plugin("emit", function(compilation, callback) {
async.forEach(compilation.chunks, function(chunk, callback) {
if(!chunk.isInitial()) {
callback();
return;
}
var targetPath = compilation.getPath(this.options.path, {
hash: compilation.hash,
chunk: chunk
});
var name = this.options.name && compilation.getPath(this.options.name, {
hash: compilation.hash,
chunk: chunk
});
var manifest = {
name: name,
type: this.options.type,
content: chunk.modules.reduce(function(obj, module) {
if(module.libIdent) {
var ident = module.libIdent({
context: this.options.context || compiler.options.context
});
if(ident) {
obj[ident] = {
id: module.id,
meta: module.meta,
exports: Array.isArray(module.providedExports) ? module.providedExports : undefined
};
}
}
return obj;
}.bind(this), {})
};
var content = new Buffer(JSON.stringify(manifest, null, 2), "utf8"); //eslint-disable-line
compiler.outputFileSystem.mkdirp(path.dirname(targetPath), function(err) {
if(err) return callback(err);
compiler.outputFileSystem.writeFile(targetPath, content, callback);
});
}.bind(this), callback);
}.bind(this));
};
+87
View File
@@ -0,0 +1,87 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const SetVarMainTemplatePlugin = require("./SetVarMainTemplatePlugin");
function accessorToObjectAccess(accessor) {
return accessor.map((a) => {
return `[${JSON.stringify(a)}]`;
}).join("");
}
function accessorAccess(base, accessor, joinWith) {
accessor = [].concat(accessor);
return accessor.map((a, idx) => {
a = base ?
base + accessorToObjectAccess(accessor.slice(0, idx + 1)) :
accessor[0] + accessorToObjectAccess(accessor.slice(1, idx + 1));
if(idx === accessor.length - 1) return a;
if(idx === 0 && typeof base === "undefined") return `${a} = typeof ${a} === "object" ? ${a} : {}`;
return `${a} = ${a} || {}`;
}).join(joinWith || "; ");
}
class LibraryTemplatePlugin {
constructor(name, target, umdNamedDefine, auxiliaryComment) {
this.name = name;
this.target = target;
this.umdNamedDefine = umdNamedDefine;
this.auxiliaryComment = auxiliaryComment;
}
apply(compiler) {
compiler.plugin("this-compilation", (compilation) => {
switch(this.target) {
case "var":
compilation.apply(new SetVarMainTemplatePlugin(`var ${accessorAccess(false, this.name)}`));
break;
case "assign":
compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(undefined, this.name)));
break;
case "this":
case "window":
case "global":
if(this.name)
compilation.apply(new SetVarMainTemplatePlugin(accessorAccess(this.target, this.name)));
else
compilation.apply(new SetVarMainTemplatePlugin(this.target, true));
break;
case "commonjs":
if(this.name)
compilation.apply(new SetVarMainTemplatePlugin(accessorAccess("exports", this.name)));
else
compilation.apply(new SetVarMainTemplatePlugin("exports", true));
break;
case "commonjs2":
case "commonjs-module":
compilation.apply(new SetVarMainTemplatePlugin("module.exports"));
break;
case "amd":
var AmdMainTemplatePlugin = require("./AmdMainTemplatePlugin");
compilation.apply(new AmdMainTemplatePlugin(this.name));
break;
case "umd":
case "umd2":
var UmdMainTemplatePlugin = require("./UmdMainTemplatePlugin");
compilation.apply(new UmdMainTemplatePlugin(this.name, {
optionalAmdExternalAsGlobal: this.target === "umd2",
namedDefine: this.umdNamedDefine,
auxiliaryComment: this.auxiliaryComment
}));
break;
case "jsonp":
var JsonpExportMainTemplatePlugin = require("./JsonpExportMainTemplatePlugin");
compilation.apply(new JsonpExportMainTemplatePlugin(this.name));
break;
default:
throw new Error(`${this.target} is not a valid Library target`);
}
});
}
}
module.exports = LibraryTemplatePlugin;
+36
View File
@@ -0,0 +1,36 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ModuleFilenameHelpers = require("./ModuleFilenameHelpers");
class LoaderOptionsPlugin {
constructor(options) {
if(typeof options !== "object") options = {};
if(!options.test) options.test = {
test: () => true
};
this.options = options;
}
apply(compiler) {
const options = this.options;
compiler.plugin("compilation", (compilation) => {
compilation.plugin("normal-module-loader", (context, module) => {
const resource = module.resource;
if(!resource) return;
const i = resource.indexOf("?");
if(ModuleFilenameHelpers.matchObject(options, i < 0 ? resource : resource.substr(0, i))) {
const filterSet = new Set(["include", "exclude", "test"]);
Object.keys(options)
.filter((key) => !filterSet.has(key))
.forEach((key) => context[key] = options[key]);
}
});
});
}
}
module.exports = LoaderOptionsPlugin;
+19
View File
@@ -0,0 +1,19 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class LoaderTargetPlugin {
constructor(target) {
this.target = target;
}
apply(compiler) {
compiler.plugin("compilation", (compilation) => {
compilation.plugin("normal-module-loader", (loaderContext) => loaderContext.target = this.target);
});
}
}
module.exports = LoaderTargetPlugin;
+236
View File
@@ -0,0 +1,236 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ConcatSource = require("webpack-sources").ConcatSource;
const OriginalSource = require("webpack-sources").OriginalSource;
const PrefixSource = require("webpack-sources").PrefixSource;
const Template = require("./Template");
// require function shortcuts:
// __webpack_require__.s = the module id of the entry point
// __webpack_require__.c = the module cache
// __webpack_require__.m = the module functions
// __webpack_require__.p = the bundle public path
// __webpack_require__.i = the identity function used for harmony imports
// __webpack_require__.e = the chunk ensure function
// __webpack_require__.d = the exported propery define getter function
// __webpack_require__.o = Object.prototype.hasOwnProperty.call
// __webpack_require__.n = compatibility get default export
// __webpack_require__.h = the webpack hash
// __webpack_require__.oe = the uncatched error handler for the webpack runtime
// __webpack_require__.nc = the script nonce
module.exports = class MainTemplate extends Template {
constructor(outputOptions) {
super(outputOptions);
this.plugin("startup", (source, chunk, hash) => {
const buf = [];
if(chunk.entryModule) {
buf.push("// Load entry module and return exports");
buf.push("return " + this.renderRequireFunctionForModule(hash, chunk, JSON.stringify(chunk.entryModule.id)) +
"(" + this.requireFn + ".s = " + JSON.stringify(chunk.entryModule.id) + ");");
}
return this.asString(buf);
});
this.plugin("render", (bootstrapSource, chunk, hash, moduleTemplate, dependencyTemplates) => {
const source = new ConcatSource();
source.add("/******/ (function(modules) { // webpackBootstrap\n");
source.add(new PrefixSource("/******/", bootstrapSource));
source.add("/******/ })\n");
source.add("/************************************************************************/\n");
source.add("/******/ (");
const modules = this.renderChunkModules(chunk, moduleTemplate, dependencyTemplates, "/******/ ");
source.add(this.applyPluginsWaterfall("modules", modules, chunk, hash, moduleTemplate, dependencyTemplates));
source.add(")");
return source;
});
this.plugin("local-vars", (source, chunk, hash) => {
return this.asString([
source,
"// The module cache",
"var installedModules = {};"
]);
});
this.plugin("require", (source, chunk, hash) => {
return this.asString([
source,
"// Check if module is in cache",
"if(installedModules[moduleId])",
this.indent("return installedModules[moduleId].exports;"),
"",
"// Create a new module (and put it into the cache)",
"var module = installedModules[moduleId] = {",
this.indent(this.applyPluginsWaterfall("module-obj", "", chunk, hash, "moduleId")),
"};",
"",
this.asString(outputOptions.strictModuleExceptionHandling ? [
"// Execute the module function",
"var threw = true;",
"try {",
this.indent([
"modules[moduleId].call(module.exports, module, module.exports, " + this.renderRequireFunctionForModule(hash, chunk, "moduleId") + ");",
"threw = false;"
]),
"} finally {",
this.indent([
"if(threw) delete installedModules[moduleId];"
]),
"}"
] : [
"// Execute the module function",
"modules[moduleId].call(module.exports, module, module.exports, " + this.renderRequireFunctionForModule(hash, chunk, "moduleId") + ");",
]),
"",
"// Flag the module as loaded",
"module.l = true;",
"",
"// Return the exports of the module",
"return module.exports;"
]);
});
this.plugin("module-obj", (source, chunk, hash, varModuleId) => {
return this.asString([
"i: moduleId,",
"l: false,",
"exports: {}"
]);
});
this.plugin("require-extensions", (source, chunk, hash) => {
const buf = [];
if(chunk.chunks.length > 0) {
buf.push("// This file contains only the entry chunk.");
buf.push("// The chunk loading function for additional chunks");
buf.push(this.requireFn + ".e = function requireEnsure(chunkId) {");
buf.push(this.indent(this.applyPluginsWaterfall("require-ensure", "throw new Error('Not chunk loading available');", chunk, hash, "chunkId")));
buf.push("};");
}
buf.push("");
buf.push("// expose the modules object (__webpack_modules__)");
buf.push(this.requireFn + ".m = modules;");
buf.push("");
buf.push("// expose the module cache");
buf.push(this.requireFn + ".c = installedModules;");
buf.push("");
buf.push("// identity function for calling harmony imports with the correct context");
buf.push(this.requireFn + ".i = function(value) { return value; };");
buf.push("");
buf.push("// define getter function for harmony exports");
buf.push(this.requireFn + ".d = function(exports, name, getter) {");
buf.push(this.indent([
"if(!" + this.requireFn + ".o(exports, name)) {",
this.indent([
"Object.defineProperty(exports, name, {",
this.indent([
"configurable: false,",
"enumerable: true,",
"get: getter"
]),
"});"
]),
"}"
]));
buf.push("};");
buf.push("");
buf.push("// getDefaultExport function for compatibility with non-harmony modules");
buf.push(this.requireFn + ".n = function(module) {");
buf.push(this.indent([
"var getter = module && module.__esModule ?",
this.indent([
"function getDefault() { return module['default']; } :",
"function getModuleExports() { return module; };"
]),
this.requireFn + ".d(getter, 'a', getter);",
"return getter;"
]));
buf.push("};");
buf.push("");
buf.push("// Object.prototype.hasOwnProperty.call");
buf.push(this.requireFn + ".o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };");
const publicPath = this.getPublicPath({
hash: hash
});
buf.push("");
buf.push("// __webpack_public_path__");
buf.push(this.requireFn + ".p = " + JSON.stringify(publicPath) + ";");
return this.asString(buf);
});
this.requireFn = "__webpack_require__";
}
render(hash, chunk, moduleTemplate, dependencyTemplates) {
const buf = [];
buf.push(this.applyPluginsWaterfall("bootstrap", "", chunk, hash, moduleTemplate, dependencyTemplates));
buf.push(this.applyPluginsWaterfall("local-vars", "", chunk, hash));
buf.push("");
buf.push("// The require function");
buf.push("function " + this.requireFn + "(moduleId) {");
buf.push(this.indent(this.applyPluginsWaterfall("require", "", chunk, hash)));
buf.push("}");
buf.push("");
buf.push(this.asString(this.applyPluginsWaterfall("require-extensions", "", chunk, hash)));
buf.push("");
buf.push(this.asString(this.applyPluginsWaterfall("startup", "", chunk, hash)));
let source = this.applyPluginsWaterfall("render", new OriginalSource(this.prefix(buf, " \t") + "\n", "webpack/bootstrap " + hash), chunk, hash, moduleTemplate, dependencyTemplates);
if(chunk.hasEntryModule()) {
source = this.applyPluginsWaterfall("render-with-entry", source, chunk, hash);
}
if(!source) throw new Error("Compiler error: MainTemplate plugin 'render' should return something");
chunk.rendered = true;
return new ConcatSource(source, ";");
}
renderRequireFunctionForModule(hash, chunk, varModuleId) {
return this.applyPluginsWaterfall("module-require", this.requireFn, chunk, hash, varModuleId);
}
renderAddModule(hash, chunk, varModuleId, varModule) {
return this.applyPluginsWaterfall("add-module", "modules[" + varModuleId + "] = " + varModule + ";", chunk, hash, varModuleId, varModule);
}
renderCurrentHashCode(hash, length) {
length = length || Infinity;
return this.applyPluginsWaterfall("current-hash", JSON.stringify(hash.substr(0, length)), length);
}
entryPointInChildren(chunk) {
const checkChildren = (chunk, alreadyCheckedChunks) => {
return chunk.chunks.some((child) => {
if(alreadyCheckedChunks.indexOf(child) >= 0) return;
alreadyCheckedChunks.push(child);
return child.hasEntryModule() || checkChildren(child, alreadyCheckedChunks);
});
};
return checkChildren(chunk, []);
}
getPublicPath(options) {
return this.applyPluginsWaterfall("asset-path", this.outputOptions.publicPath || "", options);
}
updateHash(hash) {
hash.update("maintemplate");
hash.update("3");
hash.update(this.outputOptions.publicPath + "");
this.applyPlugins("hash", hash);
}
updateHashForChunk(hash, chunk) {
this.updateHash(hash);
this.applyPlugins("hash-for-chunk", hash, chunk);
}
useChunkHash(chunk) {
const paths = this.applyPluginsWaterfall("global-hash-paths", []);
return !this.applyPluginsBailResult("global-hash", chunk, paths);
}
};
+5
View File
@@ -0,0 +1,5 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
module.exports = require("memory-fs");
+190
View File
@@ -0,0 +1,190 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var DependenciesBlock = require("./DependenciesBlock");
var ModuleReason = require("./ModuleReason");
var Template = require("./Template");
var debugId = 1000;
function Module() {
DependenciesBlock.call(this);
this.context = null;
this.reasons = [];
this.debugId = debugId++;
this.lastId = -1;
this.id = null;
this.portableId = null;
this.index = null;
this.index2 = null;
this.depth = null;
this.used = null;
this.usedExports = null;
this.providedExports = null;
this.chunks = [];
this.warnings = [];
this.dependenciesWarnings = [];
this.errors = [];
this.dependenciesErrors = [];
this.strict = false;
this.meta = {};
}
module.exports = Module;
Module.prototype = Object.create(DependenciesBlock.prototype);
Module.prototype.constructor = Module;
Object.defineProperty(Module.prototype, "entry", {
configurable: false,
get: function() {
throw new Error("Module.entry was removed. Use Chunk.entryModule");
},
set: function() {
throw new Error("Module.entry was removed. Use Chunk.entryModule");
}
});
Module.prototype.disconnect = function() {
this.reasons.length = 0;
this.lastId = this.id;
this.id = null;
this.index = null;
this.index2 = null;
this.depth = null;
this.used = null;
this.usedExports = null;
this.providedExports = null;
this.chunks.length = 0;
DependenciesBlock.prototype.disconnect.call(this);
};
Module.prototype.unseal = function() {
this.lastId = this.id;
this.id = null;
this.index = null;
this.index2 = null;
this.depth = null;
this.chunks.length = 0;
DependenciesBlock.prototype.unseal.call(this);
};
Module.prototype.addChunk = function(chunk) {
var idx = this.chunks.indexOf(chunk);
if(idx < 0)
this.chunks.push(chunk);
};
Module.prototype.removeChunk = function(chunk) {
var idx = this.chunks.indexOf(chunk);
if(idx >= 0) {
this.chunks.splice(idx, 1);
chunk.removeModule(this);
return true;
}
return false;
};
Module.prototype.addReason = function(module, dependency) {
this.reasons.push(new ModuleReason(module, dependency));
};
Module.prototype.removeReason = function(module, dependency) {
for(var i = 0; i < this.reasons.length; i++) {
var r = this.reasons[i];
if(r.module === module && r.dependency === dependency) {
this.reasons.splice(i, 1);
return true;
}
}
return false;
};
Module.prototype.hasReasonForChunk = function(chunk) {
for(var i = 0; i < this.reasons.length; i++) {
var r = this.reasons[i];
if(r.chunks) {
if(r.chunks.indexOf(chunk) >= 0)
return true;
} else if(r.module.chunks.indexOf(chunk) >= 0)
return true;
}
return false;
};
function addToSet(set, items) {
items.forEach(function(item) {
if(set.indexOf(item) < 0)
set.push(item);
});
}
Module.prototype.rewriteChunkInReasons = function(oldChunk, newChunks) {
this.reasons.forEach(function(r) {
if(!r.chunks) {
if(r.module.chunks.indexOf(oldChunk) < 0)
return;
r.chunks = r.module.chunks;
}
r.chunks = r.chunks.reduce(function(arr, c) {
addToSet(arr, c !== oldChunk ? [c] : newChunks);
return arr;
}, []);
});
};
Module.prototype.isUsed = function(exportName) {
if(this.used === null) return exportName;
if(!exportName) return this.used ? true : false;
if(!this.used) return false;
if(!this.usedExports) return false;
if(this.usedExports === true) return exportName;
var idx = this.usedExports.indexOf(exportName);
if(idx < 0) return false;
if(this.isProvided(exportName))
return Template.numberToIdentifer(idx);
return exportName;
};
Module.prototype.isProvided = function(exportName) {
if(!Array.isArray(this.providedExports))
return null;
return this.providedExports.indexOf(exportName) >= 0;
};
Module.prototype.toString = function() {
return "Module[" + (this.id || this.debugId) + "]";
};
Module.prototype.needRebuild = function(fileTimestamps, contextTimestamps) {
return true;
};
Module.prototype.updateHash = function(hash) {
hash.update(this.id + "" + this.used);
hash.update(JSON.stringify(this.usedExports));
DependenciesBlock.prototype.updateHash.call(this, hash);
};
function byId(a, b) {
return a.id - b.id;
}
Module.prototype.sortItems = function() {
DependenciesBlock.prototype.sortItems.call(this);
this.chunks.sort(byId);
this.reasons.sort(function(a, b) {
return byId(a.module, b.module);
});
};
Module.prototype.unbuild = function() {
this.disconnect();
};
Module.prototype.identifier = null;
Module.prototype.readableIdentifier = null;
Module.prototype.build = null;
Module.prototype.source = null;
Module.prototype.size = null;
Module.prototype.nameForCondition = null;
+40
View File
@@ -0,0 +1,40 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const cutOffLoaderExecution = require("./ErrorHelpers").cutOffLoaderExecution;
class ModuleBuildError extends Error {
constructor(module, err) {
super();
this.name = "ModuleBuildError";
this.message = "Module build failed: ";
if(err !== null && typeof err === "object") {
if(typeof err.stack === "string" && err.stack) {
var stack = cutOffLoaderExecution(err.stack);
if(!err.hideStack) {
this.message += stack;
} else {
this.details = stack;
if(typeof err.message === "string" && err.message) {
this.message += err.message;
} else {
this.message += err;
}
}
} else if(typeof err.message === "string" && err.message) {
this.message += err.message;
} else {
this.message += err;
}
}
this.module = module;
this.error = err;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = ModuleBuildError;
+21
View File
@@ -0,0 +1,21 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const formatLocation = require("./formatLocation");
module.exports = class ModuleDependencyError extends Error {
constructor(module, err, loc) {
super();
this.name = "ModuleDependencyError";
this.message = `${formatLocation(loc)} ${err.message}`;
this.details = err.stack.split("\n").slice(1).join("\n");
this.origin = this.module = module;
this.error = err;
Error.captureStackTrace(this, this.constructor);
}
};
+21
View File
@@ -0,0 +1,21 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const formatLocation = require("./formatLocation");
module.exports = class ModuleDependencyWarning extends Error {
constructor(module, err, loc) {
super();
this.name = "ModuleDependencyWarning";
this.message = `${formatLocation(loc)} ${err.message}`;
this.details = err.stack.split("\n").slice(1).join("\n");
this.origin = this.module = module;
this.error = err;
Error.captureStackTrace(this, this.constructor);
}
};
+24
View File
@@ -0,0 +1,24 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const cleanUp = require("./ErrorHelpers").cleanUp;
class ModuleError extends Error {
constructor(module, err) {
super();
this.name = "ModuleError";
this.module = module;
this.message = err && typeof err === "object" && err.message ? err.message : err;
this.error = err;
this.details = err && typeof err === "object" && err.stack ? cleanUp(err.stack, this.message) : undefined;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = ModuleError;
+162
View File
@@ -0,0 +1,162 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var ModuleFilenameHelpers = exports;
ModuleFilenameHelpers.ALL_LOADERS_RESOURCE = "[all-loaders][resource]";
ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE = /\[all-?loaders\]\[resource\]/gi;
ModuleFilenameHelpers.LOADERS_RESOURCE = "[loaders][resource]";
ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE = /\[loaders\]\[resource\]/gi;
ModuleFilenameHelpers.RESOURCE = "[resource]";
ModuleFilenameHelpers.REGEXP_RESOURCE = /\[resource\]/gi;
ModuleFilenameHelpers.ABSOLUTE_RESOURCE_PATH = "[absolute-resource-path]";
ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH = /\[abs(olute)?-?resource-?path\]/gi;
ModuleFilenameHelpers.RESOURCE_PATH = "[resource-path]";
ModuleFilenameHelpers.REGEXP_RESOURCE_PATH = /\[resource-?path\]/gi;
ModuleFilenameHelpers.ALL_LOADERS = "[all-loaders]";
ModuleFilenameHelpers.REGEXP_ALL_LOADERS = /\[all-?loaders\]/gi;
ModuleFilenameHelpers.LOADERS = "[loaders]";
ModuleFilenameHelpers.REGEXP_LOADERS = /\[loaders\]/gi;
ModuleFilenameHelpers.QUERY = "[query]";
ModuleFilenameHelpers.REGEXP_QUERY = /\[query\]/gi;
ModuleFilenameHelpers.ID = "[id]";
ModuleFilenameHelpers.REGEXP_ID = /\[id\]/gi;
ModuleFilenameHelpers.HASH = "[hash]";
ModuleFilenameHelpers.REGEXP_HASH = /\[hash\]/gi;
function getAfter(str, token) {
var idx = str.indexOf(token);
return idx < 0 ? "" : str.substr(idx);
}
function getBefore(str, token) {
var idx = str.lastIndexOf(token);
return idx < 0 ? "" : str.substr(0, idx);
}
function getHash(str) {
var hash = require("crypto").createHash("md5");
hash.update(str);
return hash.digest("hex").substr(0, 4);
}
function asRegExp(test) {
if(typeof test === "string") test = new RegExp("^" + test.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"));
return test;
}
ModuleFilenameHelpers.createFilename = function createFilename(module, moduleFilenameTemplate, requestShortener) {
var absoluteResourcePath;
var hash;
var identifier;
var moduleId;
var shortIdentifier;
if(!module) module = "";
if(typeof module === "string") {
shortIdentifier = requestShortener.shorten(module);
identifier = shortIdentifier;
moduleId = "";
absoluteResourcePath = module.split("!").pop();
hash = getHash(identifier);
} else {
shortIdentifier = module.readableIdentifier(requestShortener);
identifier = requestShortener.shorten(module.identifier());
moduleId = module.id;
absoluteResourcePath = module.resourcePath || module.identifier().split("!").pop();
hash = getHash(identifier);
}
var resource = shortIdentifier.split("!").pop();
var loaders = getBefore(shortIdentifier, "!");
var allLoaders = getBefore(identifier, "!");
var query = getAfter(resource, "?");
var resourcePath = resource.substr(0, resource.length - query.length);
if(typeof moduleFilenameTemplate === "function") {
return moduleFilenameTemplate({
identifier: identifier,
shortIdentifier: shortIdentifier,
resource: resource,
resourcePath: resourcePath,
absoluteResourcePath: absoluteResourcePath,
allLoaders: allLoaders,
query: query,
moduleId: moduleId,
hash: hash
});
}
return moduleFilenameTemplate
.replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS_RESOURCE, identifier)
.replace(ModuleFilenameHelpers.REGEXP_LOADERS_RESOURCE, shortIdentifier)
.replace(ModuleFilenameHelpers.REGEXP_RESOURCE, resource)
.replace(ModuleFilenameHelpers.REGEXP_RESOURCE_PATH, resourcePath)
.replace(ModuleFilenameHelpers.REGEXP_ABSOLUTE_RESOURCE_PATH, absoluteResourcePath)
.replace(ModuleFilenameHelpers.REGEXP_ALL_LOADERS, allLoaders)
.replace(ModuleFilenameHelpers.REGEXP_LOADERS, loaders)
.replace(ModuleFilenameHelpers.REGEXP_QUERY, query)
.replace(ModuleFilenameHelpers.REGEXP_ID, moduleId)
.replace(ModuleFilenameHelpers.REGEXP_HASH, hash);
};
ModuleFilenameHelpers.createFooter = function createFooter(module, requestShortener) {
if(!module) module = "";
if(typeof module === "string") {
return [
"// WEBPACK FOOTER //",
"// " + requestShortener.shorten(module)
].join("\n");
} else {
return [
"//////////////////",
"// WEBPACK FOOTER",
"// " + module.readableIdentifier(requestShortener),
"// module id = " + module.id,
"// module chunks = " + module.chunks.map(function(c) {
return c.id;
}).join(" ")
].join("\n");
}
};
ModuleFilenameHelpers.replaceDuplicates = function replaceDuplicates(array, fn, comparator) {
var countMap = {};
var posMap = {};
array.forEach(function(item, idx) {
countMap[item] = (countMap[item] || []);
countMap[item].push(idx);
posMap[item] = 0;
});
if(comparator) {
Object.keys(countMap).forEach(function(item) {
countMap[item].sort(comparator);
});
}
return array.map(function(item, i) {
if(countMap[item].length > 1) {
if(comparator && countMap[item][0] === i)
return item;
return fn(item, i, posMap[item]++);
} else return item;
});
};
ModuleFilenameHelpers.matchPart = function matchPart(str, test) {
if(!test) return true;
test = asRegExp(test);
if(Array.isArray(test)) {
return test.map(asRegExp).filter(function(regExp) {
return regExp.test(str);
}).length > 0;
} else {
return test.test(str);
}
};
ModuleFilenameHelpers.matchObject = function matchObject(obj, str) {
if(obj.test)
if(!ModuleFilenameHelpers.matchPart(str, obj.test)) return false;
if(obj.include)
if(!ModuleFilenameHelpers.matchPart(str, obj.include)) return false;
if(obj.exclude)
if(ModuleFilenameHelpers.matchPart(str, obj.exclude)) return false;
return true;
};
+24
View File
@@ -0,0 +1,24 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class ModuleNotFoundError extends Error {
constructor(module, err, dependencies) {
super();
this.name = "ModuleNotFoundError";
this.message = "Module not found: " + err;
this.details = err.details;
this.missing = err.missing;
this.module = module;
this.origin = module;
this.dependencies = dependencies;
this.error = err;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = ModuleNotFoundError;
+32
View File
@@ -0,0 +1,32 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class ModuleParseError extends Error {
constructor(module, source, err) {
super();
this.name = "ModuleParseError";
this.message = "Module parse failed: " + module.request + " " + err.message;
this.message += "\nYou may need an appropriate loader to handle this file type.";
if(err.loc && typeof err.loc === "object" && typeof err.loc.line === "number") {
var lineNumber = err.loc.line;
if(/[\0\u0001\u0002\u0003\u0004\u0005\u0006\u0007]/.test(source)) { // binary file
this.message += "\n(Source code omitted for this binary file)";
} else {
source = source.split("\n");
this.message += "\n| " + source.slice(Math.max(0, lineNumber - 3), lineNumber + 2).join("\n| ");
}
} else {
this.message += "\n" + err.stack;
}
this.module = module;
this.error = err;
if(Error.hasOwnProperty("captureStackTrace")) {
Error.captureStackTrace(this, this.constructor);
}
}
}
module.exports = ModuleParseError;
+12
View File
@@ -0,0 +1,12 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
module.exports = class ModuleReason {
constructor(module, dependency) {
this.module = module;
this.dependency = dependency;
}
};
+23
View File
@@ -0,0 +1,23 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Template = require("./Template");
module.exports = class ModuleTemplate extends Template {
constructor(outputOptions) {
super(outputOptions);
}
render(module, dependencyTemplates, chunk) {
const moduleSource = module.source(dependencyTemplates, this.outputOptions, this.requestShortener);
const moduleSourcePostModule = this.applyPluginsWaterfall("module", moduleSource, module, chunk, dependencyTemplates);
const moduleSourcePostRender = this.applyPluginsWaterfall("render", moduleSourcePostModule, module, chunk, dependencyTemplates);
return this.applyPluginsWaterfall("package", moduleSourcePostRender, module, chunk, dependencyTemplates);
}
updateHash(hash) {
hash.update("1");
this.applyPlugins("hash", hash);
}
};
+24
View File
@@ -0,0 +1,24 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const cleanUp = require("./ErrorHelpers").cleanUp;
class ModuleWarning extends Error {
constructor(module, warning) {
super();
this.name = "ModuleWarning";
this.module = module;
this.message = warning && typeof warning === "object" && warning.message ? warning.message : warning;
this.warning = warning;
this.details = warning && typeof warning === "object" && warning.stack ? cleanUp(warning.stack, this.message) : undefined;
Error.captureStackTrace(this, this.constructor);
}
}
module.exports = ModuleWarning;
+21
View File
@@ -0,0 +1,21 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
module.exports = class MovedToPluginWarningPlugin {
constructor(optionName, pluginName) {
this.optionName = optionName;
this.pluginName = pluginName;
}
apply(compiler) {
const optionName = this.optionName;
const pluginName = this.pluginName;
compiler.plugin("compilation", (compilation) => {
compilation.warnings.push(new Error `webpack options:
DEPRECATED option ${optionName} will be moved to the ${pluginName}.
Use this instead.
For more info about the usage of the ${pluginName} see https://webpack.js.org/plugins/`);
});
}
};
+177
View File
@@ -0,0 +1,177 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var Tapable = require("tapable");
var async = require("async");
var MultiWatching = require("./MultiWatching");
var MultiStats = require("./MultiStats");
function MultiCompiler(compilers) {
Tapable.call(this);
if(!Array.isArray(compilers)) {
compilers = Object.keys(compilers).map(function(name) {
compilers[name].name = name;
return compilers[name];
});
}
this.compilers = compilers;
function delegateProperty(name) {
Object.defineProperty(this, name, {
configurable: false,
get: function() {
throw new Error("Cannot read " + name + " of a MultiCompiler");
},
set: function(value) {
this.compilers.forEach(function(compiler) {
compiler[name] = value;
});
}.bind(this)
});
}
delegateProperty.call(this, "outputFileSystem");
delegateProperty.call(this, "inputFileSystem");
Object.defineProperty(this, "outputPath", {
configurable: false,
get: function() {
var commonPath = compilers[0].outputPath;
for(var i = 1; i < compilers.length; i++) {
while(compilers[i].outputPath.indexOf(commonPath) !== 0 && /[\/\\]/.test(commonPath)) {
commonPath = commonPath.replace(/[\/\\][^\/\\]*$/, "");
}
}
if(!commonPath && compilers[0].outputPath[0] === "/") return "/";
return commonPath;
}
});
var doneCompilers = 0;
var compilerStats = [];
this.compilers.forEach(function(compiler, idx) {
var compilerDone = false;
compiler.plugin("done", function(stats) {
if(!compilerDone) {
compilerDone = true;
doneCompilers++;
}
compilerStats[idx] = stats;
if(doneCompilers === this.compilers.length) {
this.applyPlugins("done", new MultiStats(compilerStats));
}
}.bind(this));
compiler.plugin("invalid", function() {
if(compilerDone) {
compilerDone = false;
doneCompilers--;
}
this.applyPlugins("invalid");
}.bind(this));
}, this);
}
module.exports = MultiCompiler;
MultiCompiler.prototype = Object.create(Tapable.prototype);
MultiCompiler.prototype.constructor = MultiCompiler;
function runWithDependencies(compilers, fn, callback) {
var fulfilledNames = {};
var remainingCompilers = compilers;
function isDependencyFulfilled(d) {
return fulfilledNames[d];
}
function getReadyCompilers() {
var readyCompilers = [];
var list = remainingCompilers;
remainingCompilers = [];
for(var i = 0; i < list.length; i++) {
var c = list[i];
var ready = !c.dependencies || c.dependencies.every(isDependencyFulfilled);
if(ready)
readyCompilers.push(c);
else
remainingCompilers.push(c);
}
return readyCompilers;
}
function runCompilers(callback) {
if(remainingCompilers.length === 0) return callback();
async.map(getReadyCompilers(), function(compiler, callback) {
fn(compiler, function(err) {
if(err) return callback(err);
fulfilledNames[compiler.name] = true;
runCompilers(callback);
});
}, callback);
}
runCompilers(callback);
}
MultiCompiler.prototype.watch = function(watchOptions, handler) {
var watchings = [];
var allStats = this.compilers.map(function() {
return null;
});
var compilerStatus = this.compilers.map(function() {
return false;
});
runWithDependencies(this.compilers, function(compiler, callback) {
var compilerIdx = this.compilers.indexOf(compiler);
var firstRun = true;
var watching = compiler.watch(watchOptions, function(err, stats) {
if(err)
handler(err);
if(stats) {
allStats[compilerIdx] = stats;
compilerStatus[compilerIdx] = "new";
if(compilerStatus.every(Boolean)) {
var freshStats = allStats.filter(function(s, idx) {
return compilerStatus[idx] === "new";
});
compilerStatus.fill(true);
var multiStats = new MultiStats(freshStats);
handler(null, multiStats);
}
}
if(firstRun && !err) {
firstRun = false;
callback();
}
});
watchings.push(watching);
}.bind(this), function() {
// ignore
});
return new MultiWatching(watchings, this);
};
MultiCompiler.prototype.run = function(callback) {
var allStats = this.compilers.map(function() {
return null;
});
runWithDependencies(this.compilers, function(compiler, callback) {
var compilerIdx = this.compilers.indexOf(compiler);
compiler.run(function(err, stats) {
if(err) return callback(err);
allStats[compilerIdx] = stats;
callback();
});
}.bind(this), function(err) {
if(err) return callback(err);
callback(null, new MultiStats(allStats));
});
};
MultiCompiler.prototype.purgeInputFileSystem = function() {
this.compilers.forEach(function(compiler) {
if(compiler.inputFileSystem && compiler.inputFileSystem.purge)
compiler.inputFileSystem.purge();
});
};
+39
View File
@@ -0,0 +1,39 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const MultiEntryDependency = require("./dependencies/MultiEntryDependency");
const SingleEntryDependency = require("./dependencies/SingleEntryDependency");
const MultiModuleFactory = require("./MultiModuleFactory");
module.exports = class MultiEntryPlugin {
constructor(context, entries, name) {
this.context = context;
this.entries = entries;
this.name = name;
}
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
const multiModuleFactory = new MultiModuleFactory();
const normalModuleFactory = params.normalModuleFactory;
compilation.dependencyFactories.set(MultiEntryDependency, multiModuleFactory);
compilation.dependencyFactories.set(SingleEntryDependency, normalModuleFactory);
});
compiler.plugin("make", (compilation, callback) => {
const dep = MultiEntryPlugin.createDependency(this.entries, this.name);
compilation.addEntry(this.context, dep, this.name, callback);
});
}
static createDependency(entries, name) {
return new MultiEntryDependency(entries.map((e, idx) => {
const dep = new SingleEntryDependency(e);
dep.loc = name + ":" + (100000 + idx);
return dep;
}), name);
}
};
+75
View File
@@ -0,0 +1,75 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Module = require("./Module");
const RawSource = require("webpack-sources").RawSource;
class MultiModule extends Module {
constructor(context, dependencies, name) {
super();
this.context = context;
this.dependencies = dependencies;
this.name = name;
this.built = false;
this.cacheable = true;
}
identifier() {
return `multi ${this.dependencies.map((d) => d.request).join(" ")}`;
}
readableIdentifier(requestShortener) {
return `multi ${this.dependencies.map((d) => requestShortener.shorten(d.request)).join(" ")}`;
}
disconnect() {
this.built = false;
super.disconnect();
}
build(options, compilation, resolver, fs, callback) {
this.built = true;
return callback();
}
needRebuild() {
return false;
}
size() {
return 16 + this.dependencies.length * 12;
}
updateHash(hash) {
hash.update("multi module");
hash.update(this.name || "");
super.updateHash(hash);
}
source(dependencyTemplates, outputOptions) {
const str = [];
this.dependencies.forEach(function(dep, idx) {
if(dep.module) {
if(idx === this.dependencies.length - 1)
str.push("module.exports = ");
str.push("__webpack_require__(");
if(outputOptions.pathinfo)
str.push(`/*! ${dep.request} */`);
str.push(`${JSON.stringify(dep.module.id)}`);
str.push(")");
} else {
str.push("(function webpackMissingModule() { throw new Error(");
str.push(JSON.stringify(`Cannot find module "${dep.request}"`));
str.push("); }())");
}
str.push(";\n");
}, this);
return new RawSource(str.join(""));
}
}
module.exports = MultiModule;
+19
View File
@@ -0,0 +1,19 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Tapable = require("tapable");
const MultiModule = require("./MultiModule");
module.exports = class MultiModuleFactory extends Tapable {
constructor() {
super();
}
create(data, callback) {
const dependency = data.dependencies[0];
callback(null, new MultiModule(data.context, dependency.dependencies, dependency.name));
}
};
+79
View File
@@ -0,0 +1,79 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const Stats = require("./Stats");
const optionOrFallback = (optionValue, fallbackValue) => optionValue !== undefined ? optionValue : fallbackValue;
class MultiStats {
constructor(stats) {
this.stats = stats;
this.hash = stats.map((stat) => stat.hash).join("");
}
hasErrors() {
return this.stats.map((stat) => stat.hasErrors()).reduce((a, b) => a || b, false);
}
hasWarnings() {
return this.stats.map((stat) => stat.hasWarnings()).reduce((a, b) => a || b, false);
}
toJson(options, forToString) {
if(typeof options === "boolean" || typeof options === "string") {
options = Stats.presetToOptions(options);
} else if(!options) {
options = {};
}
const jsons = this.stats.map((stat, idx) => {
const childOptions = Stats.getChildOptions(options, idx);
const obj = stat.toJson(childOptions, forToString);
obj.name = stat.compilation && stat.compilation.name;
return obj;
});
const showVersion = typeof options.version === "undefined" ? jsons.every(j => j.version) : options.version !== false;
const showHash = typeof options.hash === "undefined" ? jsons.every(j => j.hash) : options.hash !== false;
jsons.forEach(j => {
if(showVersion)
delete j.version;
});
const obj = {
errors: jsons.reduce((arr, j) => {
return arr.concat(j.errors.map((msg) => {
return `(${j.name}) ${msg}`;
}));
}, []),
warnings: jsons.reduce((arr, j) => {
return arr.concat(j.warnings.map((msg) => {
return `(${j.name}) ${msg}`;
}));
}, [])
};
if(showVersion)
obj.version = require("../package.json").version;
if(showHash)
obj.hash = this.hash;
if(options.children !== false)
obj.children = jsons;
return obj;
}
toString(options) {
if(typeof options === "boolean" || typeof options === "string") {
options = Stats.presetToOptions(options);
} else if(!options) {
options = {};
}
const useColors = optionOrFallback(options.colors, false);
const obj = this.toJson(options, true);
return Stats.jsonToString(obj, useColors);
}
}
module.exports = MultiStats;
+32
View File
@@ -0,0 +1,32 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const async = require("async");
class MultiWatching {
constructor(watchings, compiler) {
this.watchings = watchings;
this.compiler = compiler;
}
invalidate() {
this.watchings.forEach((watching) => watching.invalidate());
}
close(callback) {
if(callback === undefined) callback = () => { /*do nothing*/ };
async.forEach(this.watchings, (watching, finishedCallback) => {
watching.close(finishedCallback);
}, err => {
this.compiler.applyPlugins("watch-close");
callback(err);
});
}
}
module.exports = MultiWatching;
+27
View File
@@ -0,0 +1,27 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class NamedModulesPlugin {
constructor(options) {
this.options = options || {};
}
apply(compiler) {
compiler.plugin("compilation", (compilation) => {
compilation.plugin("before-module-ids", (modules) => {
modules.forEach((module) => {
if(module.id === null && module.libIdent) {
module.id = module.libIdent({
context: this.options.context || compiler.options.context
});
}
});
});
});
}
}
module.exports = NamedModulesPlugin;
+15
View File
@@ -0,0 +1,15 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class NewWatchingPlugin {
apply(compiler) {
compiler.plugin("compilation", function(compilation) {
compilation.warnings.push(new Error("The 'NewWatchingPlugin' is no longer necessary (now default)"));
});
}
}
module.exports = NewWatchingPlugin;
+22
View File
@@ -0,0 +1,22 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class NoEmitOnErrorsPlugin {
apply(compiler) {
compiler.plugin("should-emit", (compilation) => {
if(compilation.errors.length > 0)
return false;
});
compiler.plugin("compilation", (compilation) => {
compilation.plugin("should-record", () => {
if(compilation.errors.length > 0)
return false;
});
});
}
}
module.exports = NoEmitOnErrorsPlugin;
+29
View File
@@ -0,0 +1,29 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
let deprecationReported = false;
class NoErrorsPlugin {
apply(compiler) {
compiler.plugin("should-emit", (compilation) => {
if(!deprecationReported) {
compilation.warnings.push("webpack: Using NoErrorsPlugin is deprecated.\n" +
"Use NoEmitOnErrorsPlugin instead.\n");
deprecationReported = true;
}
if(compilation.errors.length > 0)
return false;
});
compiler.plugin("compilation", (compilation) => {
compilation.plugin("should-record", () => {
if(compilation.errors.length > 0)
return false;
});
});
}
}
module.exports = NoErrorsPlugin;
+96
View File
@@ -0,0 +1,96 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var path = require("path");
var ParserHelpers = require("./ParserHelpers");
var ConstDependency = require("./dependencies/ConstDependency");
var NullFactory = require("./NullFactory");
function NodeStuffPlugin(options) {
this.options = options;
}
module.exports = NodeStuffPlugin;
NodeStuffPlugin.prototype.apply = function(compiler) {
var options = this.options;
compiler.plugin("compilation", function(compilation, params) {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", function(parser, parserOptions) {
if(parserOptions.node === false)
return;
var localOptions = options;
if(parserOptions.node)
localOptions = Object.assign({}, localOptions, parserOptions.node);
function setConstant(expressionName, value) {
parser.plugin("expression " + expressionName, function() {
this.state.current.addVariable(expressionName, JSON.stringify(value));
return true;
});
}
function setModuleConstant(expressionName, fn) {
parser.plugin("expression " + expressionName, function() {
this.state.current.addVariable(expressionName, JSON.stringify(fn(this.state.module)));
return true;
});
}
var context = compiler.context;
if(localOptions.__filename === "mock") {
setConstant("__filename", "/index.js");
} else if(localOptions.__filename) {
setModuleConstant("__filename", function(module) {
return path.relative(context, module.resource);
});
}
parser.plugin("evaluate Identifier __filename", function(expr) {
if(!this.state.module) return;
var resource = this.state.module.resource;
var i = resource.indexOf("?");
return ParserHelpers.evaluateToString(i < 0 ? resource : resource.substr(0, i))(expr);
});
if(localOptions.__dirname === "mock") {
setConstant("__dirname", "/");
} else if(localOptions.__dirname) {
setModuleConstant("__dirname", function(module) {
return path.relative(context, module.context);
});
}
parser.plugin("evaluate Identifier __dirname", function(expr) {
if(!this.state.module) return;
return ParserHelpers.evaluateToString(this.state.module.context)(expr);
});
parser.plugin("expression require.main", ParserHelpers.toConstantDependency("__webpack_require__.c[__webpack_require__.s]"));
parser.plugin(
"expression require.extensions",
ParserHelpers.expressionIsUnsupported("require.extensions is not supported by webpack. Use a loader instead.")
);
parser.plugin("expression module.loaded", ParserHelpers.toConstantDependency("module.l"));
parser.plugin("expression module.id", ParserHelpers.toConstantDependency("module.i"));
parser.plugin("expression module.exports", function() {
var module = this.state.module;
var isHarmony = module.meta && module.meta.harmonyModule;
if(!isHarmony)
return true;
});
parser.plugin("evaluate Identifier module.hot", ParserHelpers.evaluateToBoolean(false));
parser.plugin("expression module", function() {
var module = this.state.module;
var isHarmony = module.meta && module.meta.harmonyModule;
var moduleJsPath = path.join(__dirname, "..", "buildin", isHarmony ? "harmony-module.js" : "module.js");
if(module.context) {
moduleJsPath = path.relative(this.state.module.context, moduleJsPath);
if(!/^[A-Z]:/i.test(moduleJsPath)) {
moduleJsPath = "./" + moduleJsPath.replace(/\\/g, "/");
}
}
return ParserHelpers.addParsedVariableToModule(this, "module", "require(" + JSON.stringify(moduleJsPath) + ")(module)");
});
});
});
};
+520
View File
@@ -0,0 +1,520 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const path = require("path");
const NativeModule = require("module");
const crypto = require("crypto");
const SourceMapSource = require("webpack-sources").SourceMapSource;
const OriginalSource = require("webpack-sources").OriginalSource;
const RawSource = require("webpack-sources").RawSource;
const ReplaceSource = require("webpack-sources").ReplaceSource;
const CachedSource = require("webpack-sources").CachedSource;
const LineToLineMappedSource = require("webpack-sources").LineToLineMappedSource;
const Module = require("./Module");
const ModuleParseError = require("./ModuleParseError");
const ModuleBuildError = require("./ModuleBuildError");
const ModuleError = require("./ModuleError");
const ModuleWarning = require("./ModuleWarning");
const runLoaders = require("loader-runner").runLoaders;
const getContext = require("loader-runner").getContext;
function asString(buf) {
if(Buffer.isBuffer(buf)) {
return buf.toString("utf-8");
}
return buf;
}
function contextify(context, request) {
return request.split("!").map(function(r) {
let rp = path.relative(context, r);
if(path.sep === "\\")
rp = rp.replace(/\\/g, "/");
if(rp.indexOf("../") !== 0)
rp = "./" + rp;
return rp;
}).join("!");
}
class NonErrorEmittedError extends Error {
constructor(error) {
super();
this.name = "NonErrorEmittedError";
this.message = "(Emitted value instead of an instance of Error) " + error;
Error.captureStackTrace(this, this.constructor);
}
}
class NormalModule extends Module {
constructor(request, userRequest, rawRequest, loaders, resource, parser) {
super();
this.request = request;
this.userRequest = userRequest;
this.rawRequest = rawRequest;
this.parser = parser;
this.resource = resource;
this.context = getContext(resource);
this.loaders = loaders;
this.fileDependencies = [];
this.contextDependencies = [];
this.warnings = [];
this.errors = [];
this.error = null;
this._source = null;
this.assets = {};
this.built = false;
this._cachedSource = null;
}
identifier() {
return this.request;
}
readableIdentifier(requestShortener) {
return requestShortener.shorten(this.userRequest);
}
libIdent(options) {
return contextify(options.context, this.userRequest);
}
nameForCondition() {
const idx = this.resource.indexOf("?");
if(idx >= 0) return this.resource.substr(0, idx);
return this.resource;
}
createSourceForAsset(name, content, sourceMap) {
if(!sourceMap) {
return new RawSource(content);
}
if(typeof sourceMap === "string") {
return new OriginalSource(content, sourceMap);
}
return new SourceMapSource(content, name, sourceMap);
}
createLoaderContext(resolver, options, compilation, fs) {
const loaderContext = {
version: 2,
emitWarning: (warning) => {
if(!(warning instanceof Error))
warning = new NonErrorEmittedError(warning);
this.warnings.push(new ModuleWarning(this, warning));
},
emitError: (error) => {
if(!(error instanceof Error))
error = new NonErrorEmittedError(error);
this.errors.push(new ModuleError(this, error));
},
exec: (code, filename) => {
const module = new NativeModule(filename, this);
module.paths = NativeModule._nodeModulePaths(this.context);
module.filename = filename;
module._compile(code, filename);
return module.exports;
},
resolve(context, request, callback) {
resolver.resolve({}, context, request, callback);
},
resolveSync(context, request) {
return resolver.resolveSync({}, context, request);
},
emitFile: (name, content, sourceMap) => {
this.assets[name] = this.createSourceForAsset(name, content, sourceMap);
},
options: options,
webpack: true,
sourceMap: !!this.useSourceMap,
_module: this,
_compilation: compilation,
_compiler: compilation.compiler,
fs: fs,
};
compilation.applyPlugins("normal-module-loader", loaderContext, this);
if(options.loader)
Object.assign(loaderContext, options.loader);
return loaderContext;
}
createSource(source, resourceBuffer, sourceMap) {
// if there is no identifier return raw source
if(!this.identifier) {
return new RawSource(source);
}
// from here on we assume we have an identifier
const identifier = this.identifier();
if(this.lineToLine && resourceBuffer) {
return new LineToLineMappedSource(
source, identifier, asString(resourceBuffer));
}
if(this.useSourceMap && sourceMap) {
return new SourceMapSource(source, identifier, sourceMap);
}
return new OriginalSource(source, identifier);
}
doBuild(options, compilation, resolver, fs, callback) {
this.cacheable = false;
const loaderContext = this.createLoaderContext(resolver, options, compilation, fs);
runLoaders({
resource: this.resource,
loaders: this.loaders,
context: loaderContext,
readResource: fs.readFile.bind(fs)
}, (err, result) => {
if(result) {
this.cacheable = result.cacheable;
this.fileDependencies = result.fileDependencies;
this.contextDependencies = result.contextDependencies;
}
if(err) {
const error = new ModuleBuildError(this, err);
return callback(error);
}
const resourceBuffer = result.resourceBuffer;
const source = result.result[0];
const sourceMap = result.result[1];
if(!Buffer.isBuffer(source) && typeof source !== "string") {
const error = new ModuleBuildError(this, new Error("Final loader didn't return a Buffer or String"));
return callback(error);
}
this._source = this.createSource(asString(source), resourceBuffer, sourceMap);
return callback();
});
}
disconnect() {
this.built = false;
super.disconnect();
}
markModuleAsErrored(error) {
this.meta = null;
this.error = error;
this.errors.push(this.error);
this._source = new RawSource("throw new Error(" + JSON.stringify(this.error.message) + ");");
}
applyNoParseRule(rule, content) {
// must start with "rule" if rule is a string
if(typeof rule === "string") {
return content.indexOf(rule) === 0;
}
// we assume rule is a regexp
return rule.test(content);
}
// check if module should not be parsed
// returns "true" if the module should !not! be parsed
// returns "false" if the module !must! be parsed
shouldPreventParsing(noParseRule, request) {
// if no noParseRule exists, return false
// the module !must! be parsed.
if(!noParseRule) {
return false;
}
// we only have one rule to check
if(!Array.isArray(noParseRule)) {
// returns "true" if the module is !not! to be parsed
return this.applyNoParseRule(noParseRule, request);
}
for(let i = 0; i < noParseRule.length; i++) {
const rule = noParseRule[i];
// early exit on first truthy match
// this module is !not! to be parsed
if(this.applyNoParseRule(rule, request)) {
return true;
}
}
// no match found, so this module !should! be parsed
return false;
}
build(options, compilation, resolver, fs, callback) {
this.buildTimestamp = new Date().getTime();
this.built = true;
this._source = null;
this.error = null;
this.errors.length = 0;
this.warnings.length = 0;
this.meta = {};
return this.doBuild(options, compilation, resolver, fs, (err) => {
this.dependencies.length = 0;
this.variables.length = 0;
this.blocks.length = 0;
this._cachedSource = null;
// if we have an error mark module as failed and exit
if(err) {
this.markModuleAsErrored(err);
return callback();
}
// check if this module should !not! be parsed.
// if so, exit here;
const noParseRule = options.module && options.module.noParse;
if(this.shouldPreventParsing(noParseRule, this.request)) {
return callback();
}
try {
this.parser.parse(this._source.source(), {
current: this,
module: this,
compilation: compilation,
options: options
});
} catch(e) {
const source = this._source.source();
const error = new ModuleParseError(this, source, e);
this.markModuleAsErrored(error);
return callback();
}
return callback();
});
}
getHashDigest() {
const hash = crypto.createHash("md5");
this.updateHash(hash);
return hash.digest("hex");
}
sourceDependency(dependency, dependencyTemplates, source, outputOptions, requestShortener) {
const template = dependencyTemplates.get(dependency.constructor);
if(!template) throw new Error("No template for dependency: " + dependency.constructor.name);
template.apply(dependency, source, outputOptions, requestShortener, dependencyTemplates);
}
sourceVariables(variable, availableVars, dependencyTemplates, outputOptions, requestShortener) {
const name = variable.name;
const expr = variable.expressionSource(dependencyTemplates, outputOptions, requestShortener);
if(availableVars.some(v => v.name === name && v.expression.source() === expr.source())) {
return;
}
return {
name: name,
expression: expr
};
}
/*
* creates the start part of a IIFE around the module to inject a variable name
* (function(...){ <- this part
* }.call(...))
*/
variableInjectionFunctionWrapperStartCode(varNames) {
const args = varNames.join(", ");
return `/* WEBPACK VAR INJECTION */(function(${args}) {`;
}
contextArgument(block) {
if(this === block) {
return this.exportsArgument || "exports";
}
return "this";
}
/*
* creates the end part of a IIFE around the module to inject a variable name
* (function(...){
* }.call(...)) <- this part
*/
variableInjectionFunctionWrapperEndCode(varExpressions, block) {
const firstParam = this.contextArgument(block);
const furtherParams = varExpressions.map(e => e.source()).join(", ");
return `}.call(${firstParam}, ${furtherParams}))`;
}
splitVariablesInUniqueNamedChunks(vars) {
const startState = [
[]
];
return vars.reduce((chunks, variable) => {
const current = chunks[chunks.length - 1];
// check if variable with same name exists already
// if so create a new chunk of variables.
const variableNameAlreadyExists = current.some(v => v.name === variable.name);
if(variableNameAlreadyExists) {
// start new chunk with current variable
chunks.push([variable]);
} else {
// else add it to current chunk
current.push(variable);
}
return chunks;
}, startState);
}
sourceBlock(block, availableVars, dependencyTemplates, source, outputOptions, requestShortener) {
block.dependencies.forEach((dependency) => this.sourceDependency(
dependency, dependencyTemplates, source, outputOptions, requestShortener));
/**
* Get the variables of all blocks that we need to inject.
* These will contain the variable name and its expression.
* The name will be added as a paramter in a IIFE the expression as its value.
*/
const vars = block.variables.map((variable) => this.sourceVariables(
variable, availableVars, dependencyTemplates, outputOptions, requestShortener))
.filter(Boolean);
/**
* if we actually have variables
* this is important as how #splitVariablesInUniqueNamedChunks works
* it will always return an array in an array which would lead to a IIFE wrapper around
* a module if we do this with an empty vars array.
*/
if(vars.length > 0) {
/**
* Split all variables up into chunks of unique names.
* e.g. imagine you have the following variable names that need to be injected:
* [foo, bar, baz, foo, some, more]
* we can not inject "foo" twice, therefore we just make two IIFEs like so:
* (function(foo, bar, baz){
* (function(foo, some, more){
* ...
* }(...));
* }(...));
*
* "splitVariablesInUniqueNamedChunks" splits the variables shown above up to this:
* [[foo, bar, baz], [foo, some, more]]
*/
const injectionVariableChunks = this.splitVariablesInUniqueNamedChunks(vars);
// create all the beginnings of IIFEs
const functionWrapperStarts = injectionVariableChunks.map((variableChunk) => variableChunk.map(variable => variable.name))
.map(names => this.variableInjectionFunctionWrapperStartCode(names));
// and all the ends
const functionWrapperEnds = injectionVariableChunks.map((variableChunk) => variableChunk.map(variable => variable.expression))
.map(expressions => this.variableInjectionFunctionWrapperEndCode(expressions, block));
// join them to one big string
const varStartCode = functionWrapperStarts.join("");
// reverse the ends first before joining them, as the last added must be the inner most
const varEndCode = functionWrapperEnds.reverse().join("");
// if we have anything, add it to the source
if(varStartCode && varEndCode) {
const start = block.range ? block.range[0] : -10;
const end = block.range ? block.range[1] : (this._source.size() + 1);
source.insert(start + 0.5, varStartCode);
source.insert(end + 0.5, "\n/* WEBPACK VAR INJECTION */" + varEndCode);
}
}
block.blocks.forEach((block) => this.sourceBlock(
block, availableVars.concat(vars), dependencyTemplates, source, outputOptions, requestShortener));
}
source(dependencyTemplates, outputOptions, requestShortener) {
const hashDigest = this.getHashDigest();
if(this._cachedSource && this._cachedSource.hash === hashDigest) {
return this._cachedSource.source;
}
if(!this._source) {
return new RawSource("throw new Error('No source available');");
}
const source = new ReplaceSource(this._source);
this._cachedSource = {
source: source,
hash: hashDigest
};
this.sourceBlock(this, [], dependencyTemplates, source, outputOptions, requestShortener);
return new CachedSource(source);
}
getHighestTimestamp(keys, timestampsByKey) {
let highestTimestamp = 0;
for(let i = 0; i < keys.length; i++) {
const key = keys[i];
const timestamp = timestampsByKey[key];
// if there is no timestamp yet, early return with Infinity
if(!timestamp) return Infinity;
highestTimestamp = Math.max(highestTimestamp, timestamp);
}
return highestTimestamp;
}
needRebuild(fileTimestamps, contextTimestamps) {
const highestFileDepTimestamp = this.getHighestTimestamp(
this.fileDependencies, fileTimestamps);
// if the hightest is Infinity, we need a rebuild
// exit early here.
if(highestFileDepTimestamp === Infinity) {
return true;
}
const highestContextDepTimestamp = this.getHighestTimestamp(
this.contextDependencies, contextTimestamps);
// Again if the hightest is Infinity, we need a rebuild
// exit early here.
if(highestContextDepTimestamp === Infinity) {
return true;
}
// else take the highest of file and context timestamps and compare
// to last build timestamp
return Math.max(highestContextDepTimestamp, highestFileDepTimestamp) >= this.buildTimestamp;
}
size() {
return this._source ? this._source.size() : -1;
}
updateHashWithSource(hash) {
if(!this._source) {
hash.update("null");
return;
}
hash.update("source");
this._source.updateHash(hash);
}
updateHashWithMeta(hash) {
hash.update("meta");
hash.update(JSON.stringify(this.meta));
}
updateHash(hash) {
this.updateHashWithSource(hash);
this.updateHashWithMeta(hash);
super.updateHash(hash);
}
}
module.exports = NormalModule;
+300
View File
@@ -0,0 +1,300 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
var async = require("async");
var Tapable = require("tapable");
var NormalModule = require("./NormalModule");
var RawModule = require("./RawModule");
var Parser = require("./Parser");
var RuleSet = require("./RuleSet");
function loaderToIdent(data) {
if(!data.options)
return data.loader;
if(typeof data.options === "string")
return data.loader + "?" + data.options;
if(typeof data.options !== "object")
throw new Error("loader options must be string or object");
if(data.ident)
return data.loader + "??" + data.ident;
return data.loader + "?" + JSON.stringify(data.options);
}
function identToLoaderRequest(resultString) {
var idx = resultString.indexOf("?");
var options;
if(idx >= 0) {
options = resultString.substr(idx + 1);
resultString = resultString.substr(0, idx);
return {
loader: resultString,
options: options
};
} else {
return {
loader: resultString
};
}
}
function NormalModuleFactory(context, resolvers, options) {
Tapable.call(this);
this.resolvers = resolvers;
this.ruleSet = new RuleSet(options.rules || options.loaders);
this.cachePredicate = typeof options.unsafeCache === "function" ? options.unsafeCache : Boolean.bind(null, options.unsafeCache);
this.context = context || "";
this.parserCache = {};
this.plugin("factory", function() {
var _this = this;
return function(result, callback) {
var resolver = _this.applyPluginsWaterfall0("resolver", null);
// Ignored
if(!resolver) return callback();
resolver(result, function onDoneResolving(err, data) {
if(err) return callback(err);
// Ignored
if(!data) return callback();
// direct module
if(typeof data.source === "function")
return callback(null, data);
_this.applyPluginsAsyncWaterfall("after-resolve", data, function(err, result) {
if(err) return callback(err);
// Ignored
if(!result) return callback();
var createdModule = _this.applyPluginsBailResult("create-module", result);
if(!createdModule) {
if(!result.request) {
return callback(new Error("Empty dependency (no request)"));
}
createdModule = new NormalModule(
result.request,
result.userRequest,
result.rawRequest,
result.loaders,
result.resource,
result.parser
);
}
createdModule = _this.applyPluginsWaterfall0("module", createdModule);
return callback(null, createdModule);
});
});
};
});
this.plugin("resolver", function() {
var _this = this;
return function(data, callback) {
var contextInfo = data.contextInfo;
var context = data.context;
var request = data.request;
var resolveContextInfo = {};
var noAutoLoaders = /^-?!/.test(request);
var noPrePostAutoLoaders = /^!!/.test(request);
var noPostAutoLoaders = /^-!/.test(request);
var elements = request.replace(/^-?!+/, "").replace(/!!+/g, "!").split("!");
var resource = elements.pop();
elements = elements.map(identToLoaderRequest);
async.parallel([
function(callback) {
_this.resolveRequestArray(resolveContextInfo, context, elements, _this.resolvers.loader, callback);
},
function(callback) {
if(resource === "" || resource[0] === "?")
return callback(null, {
resource: resource
});
_this.resolvers.normal.resolve(resolveContextInfo, context, resource, function(err, resource, resourceResolveData) {
if(err) return callback(err);
callback(null, {
resourceResolveData: resourceResolveData,
resource: resource,
});
});
}
], function(err, results) {
if(err) return callback(err);
var loaders = results[0];
var resourceResolveData = results[1].resourceResolveData;
resource = results[1].resource;
// translate option idents
try {
loaders.forEach(function(item) {
if(typeof item.options === "string" && /^\?/.test(item.options)) {
item.options = _this.ruleSet.findOptionsByIdent(item.options.substr(1));
}
});
} catch(e) {
return callback(e);
}
if(resource === false)
return callback(null,
new RawModule("/* (ignored) */",
"ignored " + context + " " + request,
request + " (ignored)")); // ignored
var userRequest = loaders.map(loaderToIdent).concat([resource]).join("!");
var resourcePath = resource;
var resourceQuery = "";
var queryIndex = resourcePath.indexOf("?");
if(queryIndex >= 0) {
resourceQuery = resourcePath.substr(queryIndex);
resourcePath = resourcePath.substr(0, queryIndex);
}
var result = _this.ruleSet.exec({
resource: resourcePath,
resourceQuery: resourceQuery,
issuer: contextInfo.issuer,
compiler: contextInfo.compiler
});
var settings = {};
var useLoadersPost = [];
var useLoaders = [];
var useLoadersPre = [];
result.forEach(function(r) {
if(r.type === "use") {
if(r.enforce === "post" && !noPostAutoLoaders && !noPrePostAutoLoaders)
useLoadersPost.push(r.value);
else if(r.enforce === "pre" && !noPrePostAutoLoaders)
useLoadersPre.push(r.value);
else if(!r.enforce && !noAutoLoaders && !noPrePostAutoLoaders)
useLoaders.push(r.value);
} else {
settings[r.type] = r.value;
}
});
async.parallel([
_this.resolveRequestArray.bind(_this, resolveContextInfo, _this.context, useLoadersPost, _this.resolvers.loader),
_this.resolveRequestArray.bind(_this, resolveContextInfo, _this.context, useLoaders, _this.resolvers.loader),
_this.resolveRequestArray.bind(_this, resolveContextInfo, _this.context, useLoadersPre, _this.resolvers.loader)
], function(err, results) {
if(err) return callback(err);
loaders = results[0].concat(loaders).concat(results[1]).concat(results[2]);
process.nextTick(onDoneResolving);
});
function onDoneResolving() {
callback(null, {
context: context,
request: loaders.map(loaderToIdent).concat([resource]).join("!"),
dependencies: data.dependencies,
userRequest: userRequest,
rawRequest: request,
loaders: loaders,
resource: resource,
resourceResolveData: resourceResolveData,
parser: _this.getParser(settings.parser)
});
}
});
};
});
}
module.exports = NormalModuleFactory;
NormalModuleFactory.prototype = Object.create(Tapable.prototype);
NormalModuleFactory.prototype.constructor = NormalModuleFactory;
NormalModuleFactory.prototype.create = function(data, callback) {
var _this = this;
var dependencies = data.dependencies;
var cacheEntry = dependencies[0].__NormalModuleFactoryCache;
if(cacheEntry) return callback(null, cacheEntry);
var context = data.context || this.context;
var request = dependencies[0].request;
var contextInfo = data.contextInfo || {};
_this.applyPluginsAsyncWaterfall("before-resolve", {
contextInfo: contextInfo,
context: context,
request: request,
dependencies: dependencies
}, function(err, result) {
if(err) return callback(err);
// Ignored
if(!result) return callback();
var factory = _this.applyPluginsWaterfall0("factory", null);
// Ignored
if(!factory) return callback();
factory(result, function(err, module) {
if(err) return callback(err);
if(module && _this.cachePredicate(module)) {
dependencies.forEach(function(d) {
d.__NormalModuleFactoryCache = module;
});
}
callback(null, module);
});
});
};
NormalModuleFactory.prototype.resolveRequestArray = function resolveRequestArray(contextInfo, context, array, resolver, callback) {
if(array.length === 0) return callback(null, []);
async.map(array, function(item, callback) {
resolver.resolve(contextInfo, context, item.loader, function(err, result) {
if(err && /^[^/]*$/.test(item.loader) && !/-loader$/.test(item.loader)) {
return resolver.resolve(contextInfo, context, item.loader + "-loader", function(err2) {
if(!err2) {
err.message = err.message + "\n" +
"BREAKING CHANGE: It's no longer allowed to omit the '-loader' suffix when using loaders.\n" +
" You need to specify '" + item.loader + "-loader' instead of '" + item.loader + "',\n" +
" see https://webpack.js.org/guides/migrating/#automatic-loader-module-name-extension-removed";
}
callback(err);
});
}
if(err) return callback(err);
var optionsOnly = item.options ? {
options: item.options
} : undefined;
return callback(null, Object.assign({}, item, identToLoaderRequest(result), optionsOnly));
});
}, callback);
};
NormalModuleFactory.prototype.getParser = function getParser(parserOptions) {
var ident = "null";
if(parserOptions) {
if(parserOptions.ident)
ident = parserOptions.ident;
else
ident = JSON.stringify(parserOptions);
}
var parser = this.parserCache[ident];
if(parser)
return parser;
return this.parserCache[ident] = this.createParser(parserOptions);
};
NormalModuleFactory.prototype.createParser = function createParser(parserOptions) {
var parser = new Parser();
this.applyPlugins2("parser", parser, parserOptions || {});
return parser;
};
+45
View File
@@ -0,0 +1,45 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const path = require("path");
class NormalModuleReplacementPlugin {
constructor(resourceRegExp, newResource) {
this.resourceRegExp = resourceRegExp;
this.newResource = newResource;
}
apply(compiler) {
const resourceRegExp = this.resourceRegExp;
const newResource = this.newResource;
compiler.plugin("normal-module-factory", (nmf) => {
nmf.plugin("before-resolve", (result, callback) => {
if(!result) return callback();
if(resourceRegExp.test(result.request)) {
if(typeof newResource === "function") {
newResource(result);
} else {
result.request = newResource;
}
}
return callback(null, result);
});
nmf.plugin("after-resolve", (result, callback) => {
if(!result) return callback();
if(resourceRegExp.test(result.resource)) {
if(typeof newResource === "function") {
newResource(result);
} else {
result.resource = path.resolve(path.dirname(result.resource), newResource);
}
}
return callback(null, result);
});
});
}
}
module.exports = NormalModuleReplacementPlugin;
+12
View File
@@ -0,0 +1,12 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class NullFactory {
create(data, callback) {
return callback();
}
}
module.exports = NullFactory;
+10
View File
@@ -0,0 +1,10 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class OptionsApply {
process(options, compiler) {}
}
module.exports = OptionsApply;
+71
View File
@@ -0,0 +1,71 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
function getProperty(obj, name) {
name = name.split(".");
for(var i = 0; i < name.length - 1; i++) {
obj = obj[name[i]];
if(typeof obj !== "object" || !obj) return;
}
return obj[name.pop()];
}
function setProperty(obj, name, value) {
name = name.split(".");
for(var i = 0; i < name.length - 1; i++) {
if(typeof obj[name[i]] !== "object" && typeof obj[name[i]] !== "undefined") return;
if(!obj[name[i]]) obj[name[i]] = {};
obj = obj[name[i]];
}
obj[name.pop()] = value;
}
class OptionsDefaulter {
constructor() {
this.defaults = {};
this.config = {};
}
process(options) {
for(let name in this.defaults) {
switch(this.config[name]) {
case undefined:
if(getProperty(options, name) === undefined)
setProperty(options, name, this.defaults[name]);
break;
case "call":
setProperty(options, name, this.defaults[name].call(this, getProperty(options, name), options), options);
break;
case "make":
if(getProperty(options, name) === undefined)
setProperty(options, name, this.defaults[name].call(this, options), options);
break;
case "append":
{
let oldValue = getProperty(options, name);
if(!Array.isArray(oldValue)) oldValue = [];
oldValue.push.apply(oldValue, this.defaults[name]);
setProperty(options, name, oldValue);
break;
}
default:
throw new Error("OptionsDefaulter cannot process " + this.config[name]);
}
}
}
set(name, config, def) {
if(arguments.length === 3) {
this.defaults[name] = def;
this.config[name] = config;
} else {
this.defaults[name] = config;
delete this.config[name];
}
}
}
module.exports = OptionsDefaulter;
+1214
View File
File diff suppressed because it is too large Load Diff
+76
View File
@@ -0,0 +1,76 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const path = require("path");
const BasicEvaluatedExpression = require("./BasicEvaluatedExpression");
const ConstDependency = require("./dependencies/ConstDependency");
const UnsupportedFeatureWarning = require("./UnsupportedFeatureWarning");
const ParserHelpers = exports;
ParserHelpers.addParsedVariableToModule = function(parser, name, expression) {
if(!parser.state.current.addVariable) return false;
var deps = [];
parser.parse(expression, {
current: {
addDependency: function(dep) {
dep.userRequest = name;
deps.push(dep);
}
},
module: parser.state.module
});
parser.state.current.addVariable(name, expression, deps);
return true;
};
ParserHelpers.requireFileAsExpression = function(context, pathToModule) {
var moduleJsPath = path.relative(context, pathToModule);
if(!/^[A-Z]:/i.test(moduleJsPath)) {
moduleJsPath = "./" + moduleJsPath.replace(/\\/g, "/");
}
return "require(" + JSON.stringify(moduleJsPath) + ")";
};
ParserHelpers.toConstantDependency = function(value) {
return function constDependency(expr) {
var dep = new ConstDependency(value, expr.range);
dep.loc = expr.loc;
this.state.current.addDependency(dep);
return true;
};
};
ParserHelpers.evaluateToString = function(value) {
return function stringExpression(expr) {
return new BasicEvaluatedExpression().setString(value).setRange(expr.range);
};
};
ParserHelpers.evaluateToBoolean = function(value) {
return function booleanExpression(expr) {
return new BasicEvaluatedExpression().setBoolean(value).setRange(expr.range);
};
};
ParserHelpers.expressionIsUnsupported = function(message) {
return function unsupportedExpression(expr) {
var dep = new ConstDependency("(void 0)", expr.range);
dep.loc = expr.loc;
this.state.current.addDependency(dep);
if(!this.state.module) return;
this.state.module.warnings.push(new UnsupportedFeatureWarning(this.state.module, message));
return true;
};
};
ParserHelpers.skipTraversal = function skipTraversal() {
return true;
};
ParserHelpers.approve = function approve() {
return true;
};
+31
View File
@@ -0,0 +1,31 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const PrefetchDependency = require("./dependencies/PrefetchDependency");
class PrefetchPlugin {
constructor(context, request) {
if(!request) {
this.request = context;
} else {
this.context = context;
this.request = request;
}
}
apply(compiler) {
compiler.plugin("compilation", (compilation, params) => {
const normalModuleFactory = params.normalModuleFactory;
compilation.dependencyFactories.set(PrefetchDependency, normalModuleFactory);
});
compiler.plugin("make", (compilation, callback) => {
compilation.prefetch(this.context || compiler.context, new PrefetchDependency(this.request), callback);
});
}
}
module.exports = PrefetchPlugin;
+190
View File
@@ -0,0 +1,190 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
class ProgressPlugin {
constructor(options) {
if(typeof options === "function") {
options = {
handler: options
};
}
options = options || {};
this.profile = options.profile;
this.handler = options.handler;
}
apply(compiler) {
const handler = this.handler || defaultHandler;
const profile = this.profile;
if(compiler.compilers) {
const states = new Array(compiler.compilers.length);
compiler.compilers.forEach(function(compiler, idx) {
compiler.apply(new ProgressPlugin(function(p, msg) {
states[idx] = Array.prototype.slice.apply(arguments);
handler.apply(null, [
states.map(state => state && state[0] || 0).reduce((a, b) => a + b) / states.length,
`[${idx}] ${msg}`
].concat(Array.prototype.slice.call(arguments, 2)));
}));
});
} else {
let lastModulesCount = 0;
let moduleCount = 500;
let doneModules = 0;
const activeModules = [];
const update = function update(module) {
handler(
0.1 + (doneModules / Math.max(lastModulesCount, moduleCount)) * 0.6,
"building modules",
`${doneModules}/${moduleCount} modules`,
`${activeModules.length} active`,
activeModules[activeModules.length - 1]
);
};
const moduleDone = function moduleDone(module) {
doneModules++;
const ident = module.identifier();
if(ident) {
const idx = activeModules.indexOf(ident);
if(idx >= 0) activeModules.splice(idx, 1);
}
update();
};
compiler.plugin("compilation", function(compilation) {
if(compilation.compiler.isChild()) return;
lastModulesCount = moduleCount;
moduleCount = 0;
doneModules = 0;
handler(0, "compiling");
compilation.plugin("build-module", function(module) {
moduleCount++;
const ident = module.identifier();
if(ident) {
activeModules.push(ident);
}
update();
});
compilation.plugin("failed-module", moduleDone);
compilation.plugin("succeed-module", moduleDone);
const syncHooks = {
"seal": [0.71, "sealing"],
"optimize": [0.72, "optimizing"],
"optimize-modules-basic": [0.73, "basic module optimization"],
"optimize-modules": [0.74, "module optimization"],
"optimize-modules-advanced": [0.75, "advanced module optimization"],
"optimize-chunks-basic": [0.76, "basic chunk optimization"],
"optimize-chunks": [0.77, "chunk optimization"],
"optimize-chunks-advanced": [0.78, "advanced chunk optimization"],
// optimize-tree
"revive-modules": [0.80, "module reviving"],
"optimize-module-order": [0.81, "module order optimization"],
"optimize-module-ids": [0.82, "module id optimization"],
"revive-chunks": [0.83, "chunk reviving"],
"optimize-chunk-order": [0.84, "chunk order optimization"],
"optimize-chunk-ids": [0.85, "chunk id optimization"],
"before-hash": [0.86, "hashing"],
"before-module-assets": [0.87, "module assets processing"],
"before-chunk-assets": [0.88, "chunk assets processing"],
"additional-chunk-assets": [0.89, "additional chunk assets processing"],
"record": [0.90, "recording"]
};
Object.keys(syncHooks).forEach(name => {
let pass = 0;
const settings = syncHooks[name];
compilation.plugin(name, () => {
if(pass++ > 0)
handler(settings[0], settings[1], `pass ${pass}`);
else
handler(settings[0], settings[1]);
});
});
compilation.plugin("optimize-tree", (chunks, modules, callback) => {
handler(0.79, "module and chunk tree optimization");
callback();
});
compilation.plugin("additional-assets", callback => {
handler(0.91, "additional asset processing");
callback();
});
compilation.plugin("optimize-chunk-assets", (chunks, callback) => {
handler(0.92, "chunk asset optimization");
callback();
});
compilation.plugin("optimize-assets", (assets, callback) => {
handler(0.94, "asset optimization");
callback();
});
});
compiler.plugin("emit", (compilation, callback) => {
handler(0.95, "emitting");
callback();
});
compiler.plugin("done", () => {
handler(1, "");
});
}
let lineCaretPosition = 0,
lastState, lastStateTime;
function defaultHandler(percentage, msg) {
let state = msg;
const details = Array.prototype.slice.call(arguments, 2);
if(percentage < 1) {
percentage = Math.floor(percentage * 100);
msg = `${percentage}% ${msg}`;
if(percentage < 100) {
msg = ` ${msg}`;
}
if(percentage < 10) {
msg = ` ${msg}`;
}
details.forEach(detail => {
if(!detail) return;
if(detail.length > 40) {
detail = `...${detail.substr(detail.length - 37)}`;
}
msg += ` ${detail}`;
});
}
if(profile) {
state = state.replace(/^\d+\/\d+\s+/, "");
if(percentage === 0) {
lastState = null;
lastStateTime = +new Date();
} else if(state !== lastState || percentage === 1) {
const now = +new Date();
if(lastState) {
const stateMsg = `${now - lastStateTime}ms ${lastState}`;
goToLineStart(stateMsg);
process.stderr.write(stateMsg + "\n");
lineCaretPosition = 0;
}
lastState = state;
lastStateTime = now;
}
}
goToLineStart(msg);
process.stderr.write(msg);
}
function goToLineStart(nextMessage) {
let str = "";
for(; lineCaretPosition > nextMessage.length; lineCaretPosition--) {
str += "\b \b";
}
for(var i = 0; i < lineCaretPosition; i++) {
str += "\b";
}
lineCaretPosition = nextMessage.length;
if(str) process.stderr.write(str);
}
}
}
module.exports = ProgressPlugin;
+55
View File
@@ -0,0 +1,55 @@
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ParserHelpers = require("./ParserHelpers");
const ConstDependency = require("./dependencies/ConstDependency");
const NullFactory = require("./NullFactory");
class ProvidePlugin {
constructor(definitions) {
this.definitions = definitions;
}
apply(compiler) {
const definitions = this.definitions;
compiler.plugin("compilation", (compilation, params) => {
compilation.dependencyFactories.set(ConstDependency, new NullFactory());
compilation.dependencyTemplates.set(ConstDependency, new ConstDependency.Template());
params.normalModuleFactory.plugin("parser", (parser, parserOptions) => {
Object.keys(definitions).forEach(name => {
var request = [].concat(definitions[name]);
var splittedName = name.split(".");
if(splittedName.length > 0) {
splittedName.slice(1).forEach((_, i) => {
const name = splittedName.slice(0, i + 1).join(".");
parser.plugin(`can-rename ${name}`, ParserHelpers.approve);
});
}
parser.plugin(`expression ${name}`, function(expr) {
let nameIdentifier = name;
const scopedName = name.indexOf(".") >= 0;
let expression = `require(${JSON.stringify(request[0])})`;
if(scopedName) {
nameIdentifier = `__webpack_provided_${name.replace(/\./g, "_dot_")}`;
}
if(request.length > 1) {
expression += request.slice(1).map(r => `[${JSON.stringify(r)}]`).join("");
}
if(!ParserHelpers.addParsedVariableToModule(this, nameIdentifier, expression)) {
return false;
}
if(scopedName) {
ParserHelpers.toConstantDependency(nameIdentifier).bind(this)(expr);
}
return true;
});
});
});
});
}
}
module.exports = ProvidePlugin;

Some files were not shown because too many files have changed in this diff Show More