This commit is contained in:
darenhsu
2022-07-17 13:16:16 +08:00
parent 84759556ff
commit befd344ab0
28070 changed files with 4008428 additions and 1 deletions
+3
View File
@@ -0,0 +1,3 @@
module.exports = function Object_values(obj) {
return Object.keys(obj).map(key => [key, obj[key]]);
};
+3
View File
@@ -0,0 +1,3 @@
module.exports = function Object_values(obj) {
return Object.keys(obj).map(key => obj[key]);
};
+29
View File
@@ -0,0 +1,29 @@
// Perform a set of tasks in array quickly. Sometimes testing much better for
// large sets of work instead of individual promises.
const bulkFsTask = (array, each) =>
new Promise((resolve, reject) => {
let ops = 0;
const out = [];
array.forEach((item, i) => {
out[i] = each(item, (back, callback) => {
ops++;
return (err, value) => {
try {
out[i] = back(err, value, out[i]);
} catch (e) {
return reject(e);
}
ops--;
if (ops === 0) {
resolve(out);
}
};
});
});
if (ops === 0) {
resolve(out);
}
});
module.exports = bulkFsTask;
+89
View File
@@ -0,0 +1,89 @@
const fs = require('graceful-fs');
const path = require('path');
const logMessages = require('./log-messages');
exports.cachePrefix = cachePrefix;
const NS = fs.realpathSync(path.dirname(__dirname));
const cachePrefixNS = `${NS}/cachePrefix`;
function cachePrefix(compilation) {
if (typeof compilation[cachePrefixNS] === 'undefined') {
let prefix = '';
let nextCompilation = compilation;
while (nextCompilation.compiler.parentCompilation) {
const parentCompilation = nextCompilation.compiler.parentCompilation;
if (!nextCompilation.cache) {
logMessages.childCompilerWithoutCache(compilation);
prefix = null;
break;
}
const cache = nextCompilation.cache;
let parentCache = parentCompilation.cache;
if (cache === parentCache) {
nextCompilation = parentCompilation;
continue;
}
let cacheKey;
for (var key in parentCache) {
if (key && parentCache[key] === cache) {
cacheKey = key;
break;
}
}
// webpack 3 adds the children member containing compiler names paired
// with arrays of compilation caches, one for each compilation sharing the
// same name.
if (!cacheKey && parentCache.children) {
parentCache = parentCache.children;
for (var key in parentCache) {
if (key && parentCache[key]) {
for (const index in parentCache[key]) {
if (parentCache[key][index] === cache) {
cacheKey = `${key}.${index}`;
break;
}
if (
parentCache[key][index] &&
typeof parentCache[key][index] === 'object'
) {
for (const subkey in parentCache[key][index]) {
if (parentCache[key][index][subkey] === cache) {
cacheKey = `${key}.${index}.${subkey}`;
break;
}
}
}
}
}
}
}
if (!cacheKey) {
logMessages.childCompilerUnnamedCache(compilation);
prefix = null;
break;
} else {
prefix = cacheKey + prefix;
}
nextCompilation = parentCompilation;
}
compilation[cachePrefixNS] =
prefix !== null
? require('crypto')
.createHash('md5')
.update(prefix)
.digest('base64')
: null;
}
return compilation[cachePrefixNS];
}
+248
View File
@@ -0,0 +1,248 @@
const cachePrefix = require('.').cachePrefix;
const LoggerFactory = require('../loggerFactory');
exports.moduleFreezeError = (compilation, module, e) => {
const loggerSerial = LoggerFactory.getLogger(compilation).from('serial');
const compilerName = compilation.compiler.name;
const compilerContext = compilation.compiler.options.context;
const identifierPrefix = cachePrefix(compilation);
const moduleIdentifier = module.identifier();
const shortener = new (require('webpack/lib/RequestShortener'))(
compilerContext,
);
const moduleReadable = module.readableIdentifier(shortener);
loggerSerial.error(
{
id: 'serialization--error-freezing-module',
identifierPrefix,
compilerName,
moduleIdentifier,
moduleReadable,
error: e,
errorMessage: e.message,
errorStack: e.stack,
},
`Unable to freeze module "${moduleReadable}${
compilerName ? `" in compilation "${compilerName}` : ''
}". An error occured serializing it into a string: ${e.message}`,
);
};
exports.cacheNoParity = (compiler, { parityRoot }) => {
const loggerSerial = new LoggerFactory(compiler).create().from('serial');
loggerSerial.error(
{
id: 'serialzation--cache-incomplete',
parityRoot,
},
[
`Previous cache did not complete parity check. ${parityRoot.reason}`,
'Resetting cache.',
].join('\n'),
);
};
exports.serialBadCache = (compiler, error) => {
const loggerSerial = new LoggerFactory(compiler).create().from('serial');
loggerSerial.error(
{
id: 'serialzation--bad-cache',
},
['Cache is corrupted.', error.stack || error.message || error].join('\n'),
);
};
const logCore = compiler => new LoggerFactory(compiler).create().from('core');
exports.configHashSetButNotUsed = (compiler, { cacheDirectory }) => {
const loggerCore = logCore(compiler);
loggerCore.error(
{
id: 'confighash--directory-no-confighash',
cacheDirectory: cacheDirectory,
},
'HardSourceWebpackPlugin cannot use [confighash] in cacheDirectory ' +
'without configHash option being set and returning a non-falsy value.',
);
};
exports.configHashFirstBuild = (compiler, { cacheDirPath, configHash }) => {
const loggerCore = logCore(compiler);
loggerCore.log(
{
id: 'confighash--new',
cacheDirPath,
configHash,
},
`HardSourceWebpackPlugin is writing to a new confighash path for the first time: ${cacheDirPath}`,
);
};
exports.configHashBuildWith = (compiler, { cacheDirPath, configHash }) => {
const loggerCore = logCore(compiler);
loggerCore.log(
{
id: 'confighash--reused',
cacheDirPath,
configHash,
},
`HardSourceWebpackPlugin is reading from and writing to a confighash path: ${cacheDirPath}`,
);
};
exports.deleteOldCaches = (compiler, { newTotalSize, oldTotalSize }) => {
const loggerCore = logCore(compiler);
const sizeMB = Math.ceil(newTotalSize / 1024 / 1024);
const deletedSizeMB = Math.ceil(oldTotalSize / 1024 / 1024);
loggerCore.log(
{
id: 'caches--delete-old',
size: newTotalSize,
sizeMB,
deletedSize: oldTotalSize,
deletedSizeMB,
},
`HardSourceWebpackPlugin is using ${sizeMB} MB of disk space after deleting ${deletedSizeMB} MB.`,
);
};
exports.keepCaches = (compiler, { totalSize }) => {
const loggerCore = logCore(compiler);
const sizeMB = Math.ceil(totalSize / 1024 / 1024);
loggerCore.log(
{
id: 'caches--keep',
size: totalSize,
sizeMB,
},
`HardSourceWebpackPlugin is using ${sizeMB} MB of disk space.`,
);
};
exports.environmentInputs = (compiler, { inputs }) => {
const loggerCore = logCore(compiler);
loggerCore.log(
{
id: 'environment--inputs',
inputs,
},
`Tracking environment changes with ${inputs.join(', ')}.`,
);
};
exports.configHashChanged = compiler => {
const loggerCore = logCore(compiler);
loggerCore.warn(
{
id: 'environment--config-changed',
},
'Environment has changed (configuration was changed).\n' +
'HardSourceWebpackPlugin will reset the cache and store a fresh one.',
);
};
exports.environmentHashChanged = compiler => {
const loggerCore = logCore(compiler);
loggerCore.warn(
{
id: 'environment--changed',
},
'Environment has changed (node_modules was updated).\n' +
'HardSourceWebpackPlugin will reset the cache and store a fresh one.',
);
};
exports.hardSourceVersionChanged = compiler => {
const loggerCore = logCore(compiler);
loggerCore.warn(
{
id: 'environment--hardsource-changed',
},
'Installed HardSource version does not match the saved ' +
'cache.\nHardSourceWebpackPlugin will reset the cache and store ' +
'a fresh one.',
);
};
exports.childCompilerWithoutCache = compilation => {
var loggerUtil = LoggerFactory.getLogger(compilation).from('util');
loggerUtil.error(
{
id: 'childcompiler--no-cache',
compilerName: compilation.compiler.name,
},
[
`A child compiler (${compilation.compiler.name}) does not`,
"have a memory cache. Enable a memory cache with webpack's",
'`cache` configuration option. HardSourceWebpackPlugin will be',
'disabled for this child compiler until then.',
].join('\n'),
);
};
exports.childCompilerUnnamedCache = compilation => {
var loggerUtil = LoggerFactory.getLogger(compilation).from('util');
loggerUtil.error(
{
id: 'childcompiler--unnamed-cache',
compilerName: compilation.compiler.name,
},
[
`A child compiler (${compilation.compiler.name}) has a`,
'memory cache but its cache name is unknown.',
'HardSourceWebpackPlugin will be disabled for this child',
'compiler.',
].join('\n'),
);
};
const logParallel = compiler =>
new LoggerFactory(compiler).create().from('parallel');
exports.parallelStartWorkers = (compiler, options) => {
const loggerParallel = logParallel(compiler);
loggerParallel.log(
{
id: 'parallel--start-workers',
numWorkers: options.numWorkers,
},
[`Start ${options.numWorkers} module workers.`].join('\n'),
);
};
exports.parallelConfigMismatch = (compiler, options) => {
const loggerParallel = logParallel(compiler);
loggerParallel.error(
{
id: 'parallel--config-mismatch',
ourHash: options.ourHash,
theirHash: options.theirHash,
},
[
`Child process's configuration does not match parent `,
`configuration. Unable to parallelize webpack.`,
].join('\n'),
);
};
exports.parallelErrorSendingJob = (compiler, error) => {
const loggerParallel = logParallel(compiler);
loggerParallel.error(
{
id: 'parallel--error-sending-job',
error,
},
`Failed to send parallel module work. ${error.stack}`,
);
};
exports.parallelRequireWebpack4 = compiler => {
const loggerParallel = logParallel(compiler);
loggerParallel.error(
{
id: 'parallel--webpack-4',
},
`Parallel Module Plugin requires webpack 4.`,
);
};
+194
View File
@@ -0,0 +1,194 @@
const parseJson = require('parse-json');
const { cachePrefix } = require('.');
class ParityRoot {
constructor() {
this.children = [];
}
add(name) {
const bits = new ParityCache(name);
this.children.push(bits);
return bits;
}
verify() {
const firstChild = this.children[0];
if (!this.children.some(child => child.root)) {
return true;
}
for (const child of this.children) {
if (!child.verify()) {
this.reason = {
cache: child,
cacheName: child.name,
cacheReason: child.reason,
message: `Cache ${child.name} is not complete. ${
child.reason.message
}`,
};
return false;
}
if (child !== firstChild && child.root.token !== firstChild.root.token) {
this.reason = {
firstCache: firstChild,
firstCacheName: firstChild.name,
firstCacheReason: firstChild.reason,
secondCache: child,
secondCacheName: child.name,
secondCacheReason: child.reason,
message: `Cache ${firstChild.name} and ${child.name} disagree.`,
};
return false;
}
}
return true;
}
}
class ParityCache {
constructor(name) {
this.name = name;
this.root = null;
this.bits = {};
this.reason = null;
}
add(_token) {
const token = ParityToken.fromJson(_token);
if (token.isRoot) {
this.root = token;
}
this.bits[token.id] = token;
}
verify() {
if (this.root === null) {
this.reason = {
message: 'Root compilation not found.',
};
return false;
}
for (const id of this.root.ids) {
if (typeof this.bits[id] === 'undefined') {
this.reason = {
message: `Compilation '${id}' not found.`,
};
return false;
} else if (this.root.token !== this.bits[id].token) {
this.reason = {
message: `Root and '${id}' compilation disagree.`,
};
return false;
}
}
return true;
}
}
const createParityToken = (id, ids = null) => {
const token = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c =>
c === 'x'
? ((Math.random() * 16) | 0).toString(16)
: (((Math.random() * 4) | 0) + 8).toString(16),
);
return new ParityToken(id, token, ids);
};
class ParityToken {
constructor(id, token, ids = null) {
this.id = id;
this.token = token;
this.isRoot = ids !== null;
this.ids = ids;
}
static fromCompilation(compilation) {
let parentCompilation = compilation;
while (parentCompilation.compiler.parentCompilation) {
parentCompilation = parentCompilation.compiler.parentCompilation;
}
if (!parentCompilation.__hardSource_parityToken) {
parentCompilation.__hardSource_parityToken = createParityToken(
cachePrefix(parentCompilation),
[],
);
}
if (compilation !== parentCompilation) {
return parentCompilation.__hardSource_parityToken.createChild(
cachePrefix(compilation),
);
}
return parentCompilation.__hardSource_parityToken;
}
static fromJson(json) {
return new ParityToken(json.id, json.token, json.ids);
}
createChild(id) {
this.ids.push(id);
return new ParityToken(id, this.token);
}
toJSON() {
return {
type: 'CacheParityToken',
id: this.id,
ids: this.ids,
token: this.token,
};
}
}
const parseIfString = item => {
if (typeof item === 'string') {
return parseJson(item);
}
return item;
};
const parityCacheFromCache = (name, parityRoot, cache) => {
const parityCache = parityRoot.add(name);
if (cache.__hardSource_parityToken_root) {
const rootCompilation = parseIfString(cache.__hardSource_parityToken_root);
parityCache.add(rootCompilation);
rootCompilation.ids.forEach(id => {
if (cache[`__hardSource_parityToken_${id}`]) {
parityCache.add(parseIfString(cache[`__hardSource_parityToken_${id}`]));
}
});
}
};
const pushParityWriteOps = (compilation, ops) => {
if (compilation.compiler.parentCompilation) {
ops.push({
key: `__hardSource_parityToken_${cachePrefix(compilation)}`,
value: JSON.stringify(ParityToken.fromCompilation(compilation)),
});
} else {
ops.push({
key: `__hardSource_parityToken_root`,
value: JSON.stringify(ParityToken.fromCompilation(compilation)),
});
}
};
module.exports = {
ParityRoot,
ParityCache,
ParityToken,
parityCacheFromCache,
pushParityWriteOps,
};
+247
View File
@@ -0,0 +1,247 @@
let hookTypes;
const callStyles = {
sync: 'applyPlugins',
syncWaterfall: 'applyPluginsWaterfall',
syncBail: 'applyPluginsBailResult',
sync_map: 'applyPlugins',
asyncWaterfall: 'applyPluginsAsyncWaterfall',
asyncParallel: 'applyPluginsParallel',
asyncSerial: 'applyPluginsAsync',
};
const camelToDash = camel =>
camel.replace(/_/g, '--').replace(/[A-Z]/g, c => `-${c.toLowerCase()}`);
const knownPluginRegistrations = {
Compilation: {
needAdditionalPass: ['sync', []],
succeedModule: ['sync', ['module']],
buildModule: ['sync', ['module']],
seal: ['sync', []],
},
Compiler: {
afterCompile: ['asyncSerial', ['compilation']],
afterEnvironment: ['sync', []],
afterPlugins: ['sync', []],
afterResolvers: ['sync', []],
compilation: ['sync', ['compilation', 'params']],
emit: ['asyncSerial', ['compilation']],
make: ['asyncParallel', ['compilation']],
watchRun: ['asyncSerial', ['watcher']],
run: ['asyncSerial', ['compiler']],
},
NormalModuleFactory: {
createModule: ['syncBail', ['data']],
parser: ['sync_map', ['parser', 'parserOptions']],
resolver: ['syncWaterfall', ['nextResolver']],
},
ContextModuleFactory: {
afterResolve: ['asyncWaterfall', ['data']],
},
};
exports.register = (tapable, name, style, args) => {
if (tapable.hooks) {
if (!hookTypes) {
const Tapable = require('tapable');
hookTypes = {
sync: Tapable.SyncHook,
syncWaterfall: Tapable.SyncWaterfallHook,
syncBail: Tapable.SyncBailHook,
asyncWaterfall: Tapable.AsyncWaterfallHook,
asyncParallel: Tapable.AsyncParallelHook,
asyncSerial: Tapable.AsyncSeriesHook,
asyncSeries: Tapable.AsyncSeriesHook,
};
}
if (!tapable.hooks[name]) {
tapable.hooks[name] = new hookTypes[style](args);
}
} else {
if (!tapable.__hardSource_hooks) {
tapable.__hardSource_hooks = {};
}
if (!tapable.__hardSource_hooks[name]) {
tapable.__hardSource_hooks[name] = {
name,
dashName: camelToDash(name),
style,
args,
async: style.startsWith('async'),
map: style.endsWith('_map'),
};
}
if (!tapable.__hardSource_proxy) {
tapable.__hardSource_proxy = {};
}
if (!tapable.__hardSource_proxy[name]) {
if (tapable.__hardSource_hooks[name].map) {
const _forCache = {};
tapable.__hardSource_proxy[name] = {
_forCache,
for: key => {
let hook = _forCache[key];
if (hook) {
return hook;
}
_forCache[key] = {
tap: (...args) => exports.tapFor(tapable, name, key, ...args),
tapPromise: (...args) =>
exports.tapPromiseFor(tapable, name, key, ...args),
call: (...args) => exports.callFor(tapable, name, key, ...args),
promise: (...args) =>
exports.promiseFor(tapable, name, key, ...args),
};
return _forCache[key];
},
tap: (...args) => exports.tapFor(tapable, name, ...args),
tapPromise: (...args) =>
exports.tapPromiseFor(tapable, name, ...args),
call: (...args) => exports.callFor(tapable, name, ...args),
promise: (...args) => exports.promiseFor(tapable, name, ...args),
};
} else {
tapable.__hardSource_proxy[name] = {
tap: (...args) => exports.tap(tapable, name, ...args),
tapPromise: (...args) => exports.tapPromise(tapable, name, ...args),
call: (...args) => exports.call(tapable, name, args),
promise: (...args) => exports.promise(tapable, name, args),
};
}
}
}
};
exports.tap = (tapable, name, reason, callback) => {
if (tapable.hooks) {
tapable.hooks[name].tap(reason, callback);
} else {
if (!tapable.__hardSource_hooks || !tapable.__hardSource_hooks[name]) {
const registration =
knownPluginRegistrations[tapable.constructor.name][name];
exports.register(tapable, name, registration[0], registration[1]);
}
const dashName = tapable.__hardSource_hooks[name].dashName;
if (tapable.__hardSource_hooks[name].async) {
tapable.plugin(dashName, (...args) => {
const cb = args.pop();
cb(null, callback(...args));
});
} else {
tapable.plugin(dashName, callback);
}
}
};
exports.tapPromise = (tapable, name, reason, callback) => {
if (tapable.hooks) {
tapable.hooks[name].tapPromise(reason, callback);
} else {
if (!tapable.__hardSource_hooks || !tapable.__hardSource_hooks[name]) {
const registration =
knownPluginRegistrations[tapable.constructor.name][name];
exports.register(tapable, name, registration[0], registration[1]);
}
const dashName = tapable.__hardSource_hooks[name].dashName;
tapable.plugin(dashName, (...args) => {
const cb = args.pop();
return callback(...args).then(value => cb(null, value), cb);
});
}
};
exports.tapAsync = (tapable, name, reason, callback) => {
if (tapable.hooks) {
tapable.hooks[name].tapAsync(reason, callback);
} else {
if (!tapable.__hardSource_hooks || !tapable.__hardSource_hooks[name]) {
const registration =
knownPluginRegistrations[tapable.constructor.name][name];
exports.register(tapable, name, registration[0], registration[1]);
}
const dashName = tapable.__hardSource_hooks[name].dashName;
tapable.plugin(dashName, callback);
}
};
exports.call = (tapable, name, args) => {
if (tapable.hooks) {
const hook = tapable.hooks[name];
return hook.call(...args);
} else {
const dashName = tapable.__hardSource_hooks[name].dashName;
const style = tapable.__hardSource_hooks[name].style;
return tapable[callStyles[style]](...[dashName].concat(args));
}
};
exports.promise = (tapable, name, args) => {
if (tapable.hooks) {
const hook = tapable.hooks[name];
return hook.promise(...args);
} else {
const dashName = tapable.__hardSource_hooks[name].dashName;
const style = tapable.__hardSource_hooks[name].style;
return new Promise((resolve, reject) => {
tapable[callStyles[style]](
...[dashName].concat(args, (err, value) => {
if (err) {
reject(err);
} else {
resolve(value);
}
}),
);
});
}
};
exports.tapFor = (tapable, name, key, reason, callback) => {
if (tapable.hooks) {
tapable.hooks[name].for(key).tap(reason, callback);
} else {
exports.tap(tapable, name, reason, callback);
}
};
exports.tapPromiseFor = (tapable, name, key, reason, callback) => {
if (tapable.hooks) {
tapable.hooks[name].for(key).tapPromise(reason, callback);
} else {
exports.tapPromise(tapable, name, reason, callback);
}
};
exports.callFor = (tapable, name, key, args) => {
if (tapable.hooks) {
tapable.hooks[name].for(key).call(...args);
} else {
exports.call(tapable, name, args);
}
};
exports.promiseFor = (tapable, name, key, args) => {
if (tapable.hooks) {
tapable.hooks[name].for(key).promise(...args);
} else {
exports.promise(tapable, name, args);
}
};
exports.hooks = tapable => {
if (tapable.hooks) {
return tapable.hooks;
}
if (!tapable.__hardSource_proxy) {
tapable.__hardSource_proxy = {};
}
const registrations = knownPluginRegistrations[tapable.constructor.name];
if (registrations) {
for (const name in registrations) {
const registration = registrations[name];
exports.register(tapable, name, registration[0], registration[1]);
}
}
return tapable.__hardSource_proxy;
};
+15
View File
@@ -0,0 +1,15 @@
module.exports = function promisify(f, o) {
const ctx = (o && o.context) || null;
return function promisify_wrap() {
const args = Array.from(arguments);
return new Promise(function promisify_resolver(resolve, reject) {
args.push(function promisify_callback(err, value) {
if (err) {
return reject(err);
}
return resolve(value);
});
f.apply(ctx, args);
});
};
};
+195
View File
@@ -0,0 +1,195 @@
const path = require('path');
const rootCompiler = compiler => {
while (compiler.parentCompilation) {
compiler = compiler.parentCompilation.compiler;
}
return compiler;
};
const compilerContext = (exports.compilerContext = function compilerContext(
compiler,
) {
return rootCompiler(compiler.compiler ? compiler.compiler : compiler).context;
});
const relateNormalPath = (exports.relateNormalPath = function relateNormalPath(
compiler,
key,
) {
if (typeof key !== 'string') {
return key;
}
if (compilerContext(compiler) === key) {
return '.';
}
if (key === '') {
return key;
}
const rel = path.relative(compilerContext(compiler), key.split('?')[0]);
return [rel.replace(/\\/g, '/')].concat(key.split('?').slice(1)).join('?');
});
const relateNormalRequest = (exports.relateNormalRequest = function relateNormalRequest(
compiler,
key,
) {
return key
.split('!')
.map(subkey => relateNormalPath(compiler, subkey))
.join('!');
});
const relateNormalModuleId = (exports.relateNormalModuleId = function relateNormalModuleId(
compiler,
id,
) {
return id.substring(0, 24) + relateNormalRequest(compiler, id.substring(24));
});
const relateNormalLoaders = (exports.relateNormalLoaders = function relateNormalLoaders(
compiler,
loaders,
) {
return loaders.map(loader =>
Object.assign({}, loader, {
loader: relateNormalPath(compiler, loader.loader),
}),
);
});
const relateNormalPathArray = (exports.relateNormalPathArray = function relateNormalPathArray(
compiler,
paths,
) {
return paths.map(subpath => relateNormalPath(compiler, subpath));
});
const relateNormalPathSet = (exports.relateNormalPathSet = function relateNormalPathSet(
compiler,
paths,
) {
return relateNormalPathArray(compiler, Array.from(paths));
});
/**
*
*/
// Cache whether we need to replace path.sep because contextNormalPath is called _very_ frequently
const resolveRelativeCompilerContext =
'/' === path.sep
? function(context, key) {
return path.resolve(context, key);
}
: function(context, key) {
return path.resolve(context, key).replace(/\//g, path.sep);
};
const contextNormalPath = (exports.contextNormalPath = function contextNormalPath(
compiler,
key,
) {
if (typeof key !== 'string' || key === '') {
return key;
}
const context = compilerContext(compiler);
if (key === '.') {
return context;
}
const markIndex = key.indexOf('?');
if (markIndex === -1) {
return resolveRelativeCompilerContext(context, key);
}
const abs = resolveRelativeCompilerContext(
context,
key.substring(0, markIndex),
);
return abs + '?' + key.substring(markIndex + 1);
});
const contextNormalRequest = (exports.contextNormalRequest = function contextNormalRequest(
compiler,
key,
) {
// return key
// .split('!')
// .map(subkey => contextNormalPath(compiler, subkey))
// .join('!');
let i = -1;
let j = -1;
let _newkey = '';
while ((i = key.indexOf('!', i + 1)) !== -1) {
_newkey += contextNormalPath(compiler, key.substring(j + 1, i));
_newkey += '!';
j = i;
}
_newkey += contextNormalPath(compiler, key.substring(j + 1));
return _newkey;
});
const contextNormalModuleId = (exports.contextNormalModuleId = function contextNormalModuleId(
compiler,
id,
) {
return id.substring(0, 24) + contextNormalRequest(compiler, id.substring(24));
});
const contextNormalLoaders = (exports.contextNormalLoaders = function contextNormalLoaders(
compiler,
loaders,
) {
return loaders.map(loader =>
Object.assign({}, loader, {
loader: contextNormalPath(compiler, loader.loader),
}),
);
});
const contextNormalPathArray = (exports.contextNormalPathArray = function contextNormalPathArray(
compiler,
paths,
) {
return paths.map(subpath => contextNormalPath(compiler, subpath));
});
const contextNormalPathSet = (exports.contextNormalPathSet = function contextNormalPathSet(
compiler,
paths,
) {
return new Set(contextNormalPathArray(compiler, paths));
});
/**
*
*/
const maybeAbsolutePath = (exports.maybeAbsolutePath = function maybeAbsolutePath(
path,
) {
return /^([a-zA-Z]:\\\\|\/)/.test(path);
});
const relateAbsolutePath = (exports.relateAbsolutePath = function relateAbsolutePath(
context,
absPath,
) {
if (maybeAbsolutePath(absPath)) {
return path.relative(context, absPath);
}
return absPath;
});
const relateAbsoluteRequest = (exports.relateAbsoluteRequest = function relateAbsoluteRequest(
context,
absReq,
) {
return absReq
.split(/!/g)
.map(path => relateAbsolutePath(context, path))
.join('!');
});
+220
View File
@@ -0,0 +1,220 @@
const relateContext = require('./relate-context');
const pipe = (exports.pipe = (...fns) => ({
freeze(arg, module, extra, methods) {
for (const fn of fns) {
arg = fn.freeze(arg, module, extra, methods);
}
return arg;
},
thaw(arg, frozen, extra, methods) {
for (const fn of fns) {
arg = fn.thaw(arg, frozen, extra, methods);
}
return arg;
},
}));
const serialMap = (exports.map = (keyOp, valueOp) => ({
freeze(arg, module, extra) {
const resolved = [];
for (const key in arg) {
resolved.push([
keyOp.freeze(key, key, extra),
valueOp.freeze(arg[key], arg[key], extra),
]);
}
return resolved;
},
thaw(arg, frozen, extra) {
const resolved = {};
for (const item of arg) {
const key = keyOp.thaw(item[0], item[0], extra);
const value = valueOp.thaw(item[1], item[1], extra);
resolved[key] = value;
}
return resolved;
},
}));
const contextual = (exports.contextual = fnname => {
const relate = relateContext[`relateNormal${fnname}`];
const context = relateContext[`contextNormal${fnname}`];
return {
freeze: (arg, module, { compiler, compilation }, methods) =>
arg ? relate(compiler || compilation.compiler, arg) : arg,
thaw: (arg, module, { compiler, compilation }, methods) =>
arg ? context(compiler || compilation.compiler, arg) : arg,
};
});
const archetype = (exports.archetype = type => ({
freeze: (arg, module, extra, { freeze }) => freeze(type, null, arg, extra),
thaw: (arg, module, extra, { thaw }) => thaw(type, null, arg, extra),
}));
const mapArchetype = (exports.mapArchetype = type => ({
freeze: (arg, module, extra, { mapFreeze }) =>
mapFreeze(type, null, arg, extra),
thaw: (arg, module, extra, { mapThaw }) => mapThaw(type, null, arg, extra),
}));
const path = (exports.path = contextual('Path'));
const pathArray = (exports.pathArray = contextual('PathArray'));
const pathSet = (exports.pathSet = contextual('PathSet'));
const request = (exports.request = contextual('Request'));
const _loaders = (exports._loaders = contextual('Loaders'));
const loaders = (exports.loaders = {
freeze: _loaders.freeze,
thaw(arg, frozen, extra, methods) {
return _loaders.thaw(arg, frozen, extra, methods).map(loader => {
if (loader.ident) {
let ruleSet =
extra.normalModuleFactory && extra.normalModuleFactory.ruleSet;
if (!ruleSet) {
ruleSet = extra.compiler.__hardSource_ruleSet;
if (!ruleSet) {
const RuleSet = require('webpack/lib/RuleSet');
if (extra.compiler.options.module.defaultRules) {
// webpack 4
ruleSet = extra.compiler.__hardSource_ruleSet = new RuleSet(
extra.compiler.options.module.defaultRules.concat(
extra.compiler.options.module.rules,
),
);
} else {
// webpack <4
ruleSet = extra.compiler.__hardSource_ruleSet = new RuleSet(
extra.compiler.options.module.rules ||
extra.compiler.options.module.loaders,
);
}
}
}
return {
loader: loader.loader,
ident: loader.ident,
options: ruleSet.findOptionsByIdent(loader.ident),
};
}
return loader;
});
},
});
const regExp = (exports.regExp = {
freeze: arg => (arg ? arg.source : false),
thaw: arg => (arg ? new RegExp(arg) : false),
});
const parser = (exports.parser = archetype('Parser'));
const generator = (exports.generator = archetype('Generator'));
const source = (exports.source = archetype('Source'));
const moduleAssets = (exports.moduleAssets = archetype('ModuleAssets'));
const moduleError = (exports.moduleError = mapArchetype('ModuleError'));
const moduleWarning = (exports.moduleWarning = mapArchetype('ModuleWarning'));
const dependencyBlock = (exports.dependencyBlock = {
freeze: (arg, module, extra, { freeze }) =>
freeze('DependencyBlock', null, arg, extra),
thaw: (arg, module, extra, { thaw }) =>
thaw('DependencyBlock', arg, module, extra),
});
const _null = (exports.null = {
freeze: () => null,
thaw: () => null,
});
const identity = (exports.identity = {
freeze: (arg, module, extra, methods) => arg,
thaw: (arg, module, extra, methods) => arg,
});
const assigned = (exports.assigned = members => ({
freeze(arg, module, extra, methods) {
const out = {};
for (const key in members) {
out[key] = members[key].freeze(arg[key], module, extra, methods);
}
return out;
},
thaw(arg, frozen, extra, methods) {
for (const key in members) {
arg[key] = members[key].thaw(frozen[key], frozen, extra, methods);
}
return arg;
},
}));
const created = (exports.created = members => ({
freeze(arg, module, extra, methods) {
if (!arg) {
return null;
}
const out = {};
for (const key in members) {
out[key] = members[key].freeze(arg[key], module, extra, methods);
}
return out;
},
thaw(arg, frozen, extra, methods) {
if (!arg) {
return null;
}
const out = {};
for (const key in members) {
out[key] = members[key].thaw(arg[key], frozen, extra, methods);
}
return out;
},
}));
const objectAssign = (exports.objectAssign = opts => ({
freeze(arg, module, extra) {
const out = Object.assign({}, arg);
for (const key in opts) {
out[key] = opts[key].freeze(arg[key], arg, extra);
}
return out;
},
thaw(arg, frozen, extra) {
const out = Object.assign({}, arg);
for (const key in opts) {
out[key] = opts[key].thaw(arg[key], arg, extra);
}
return out;
},
}));
const constructed = (exports.constructed = (Type, args) => ({
freeze(arg, module, extra, methods) {
const out = {};
for (const key in args) {
out[key] = args[key].freeze(arg[key], module, extra, methods);
}
return out;
},
thaw(arg, frozen, extra, methods) {
const newArgs = [];
for (const key in args) {
newArgs.push(args[key].thaw(frozen[key], frozen, extra, methods));
}
return new Type(...newArgs);
},
}));
const serial = (exports.serial = (name, stages) => ({
freeze(arg, module, extra, methods) {
const out = {
type: name,
};
for (const key in stages) {
out[key] = stages[key].freeze(module, module, extra, methods);
}
return out;
},
thaw(arg, frozen, extra, methods) {
let out = arg;
for (const key in stages) {
out = stages[key].thaw(out, frozen[key], extra, methods);
}
return out;
},
}));