forked from mzgoddard/hard-source-webpack-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
2071 lines (1850 loc) · 66.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
var crypto = require('crypto');
var fs = require('fs');
var path = require('path');
var lodash = require('lodash');
var _mkdirp = require('mkdirp');
var _rimraf = require('rimraf');
var nodeObjectHash = require('node-object-hash');
var envHash = require('./lib/env-hash');
var defaultConfigHash = require('./lib/default-config-hash');
var promisify = require('./lib/util/promisify');
var values = require('./lib/util/Object.values');
var relateContext = require('./lib/util/relate-context');
var pluginCompat = require('./lib/util/plugin-compat');
var AMDRequireContextDependency = require('webpack/lib/dependencies/AMDRequireContextDependency');
var CommonJsRequireContextDependency = require('webpack/lib/dependencies/CommonJsRequireContextDependency');
var ContextDependency = require('webpack/lib/dependencies/ContextDependency');
var RequireContextDependency = require('webpack/lib/dependencies/RequireContextDependency');
var RequireResolveContextDependency = require('webpack/lib/dependencies/RequireResolveContextDependency');
var ImportContextDependency;
try {
ImportContextDependency = require('webpack/lib/dependencies/ImportContextDependency');
}
catch (_) {}
var HardContextModuleFactory = require('./lib/hard-context-module-factory');
var HardModule = require('./lib/hard-module');
var LoggerFactory = require('./lib/logger-factory');
var cachePrefix = require('./lib/util').cachePrefix;
var CacheSerializerFactory = require('./lib/cache-serializer-factory');
var HardSourceJsonSerializerPlugin =
require('./lib/hard-source-json-serializer-plugin');
var HardSourceAppendSerializerPlugin =
require('./lib/hard-source-append-serializer-plugin');
var HardSourceLevelDbSerializerPlugin =
require('./lib/hard-source-leveldb-serializer-plugin');
var hardSourceVersion = require('./package.json').version;
function requestHash(request) {
return crypto.createHash('sha1').update(request).digest().hexSlice();
}
var mkdirp = promisify(_mkdirp, {context: _mkdirp});
mkdirp.sync = _mkdirp.sync.bind(_mkdirp);
var rimraf = promisify(_rimraf);
rimraf.sync = _rimraf.sync.bind(_rimraf);
var fsReadFile = promisify(fs.readFile, {context: fs});
var fsWriteFile = promisify(fs.writeFile, {context: fs});
var NS;
NS = fs.realpathSync(__dirname);
var bulkFsTask = function(array, each) {
return new Promise(function(resolve, reject) {
var ops = 0;
var out = [];
array.forEach(function(item, i) {
out[i] = each(item, function(back, callback) {
ops++;
return function(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);
}
});
};
var compilerContext = relateContext.compilerContext;
var relateNormalPath = relateContext.relateNormalPath;
var contextNormalPath = relateContext.contextNormalPath;
var contextNormalPathSet = relateContext.contextNormalPathSet;
function relateNormalRequest(compiler, key) {
return key
.split('!')
.map(function(subkey) {
return relateNormalPath(compiler, subkey);
})
.join('!');
}
function relateNormalModuleId(compiler, id) {
return id.substring(0, 24) + relateNormalRequest(compiler, id.substring(24));
}
function contextNormalRequest(compiler, key) {
return key
.split('!')
.map(function(subkey) {
return contextNormalPath(compiler, subkey);
})
.join('!');
}
function contextNormalModuleId(compiler, id) {
return id.substring(0, 24) + contextNormalRequest(compiler, id.substring(24));
}
function contextNormalLoaders(compiler, loaders) {
return loaders.map(function(loader) {
return Object.assign({}, loader, {
loader: contextNormalPath(compiler, loader.loader),
});
});
}
function contextNormalPathArray(compiler, paths) {
return paths.map(function(subpath) {
return contextNormalPath(compiler, subpath);
});
}
function HardSourceWebpackPlugin(options) {
this.options = options || {};
}
HardSourceWebpackPlugin.prototype.getPath = function(dirName, suffix) {
var confighashIndex = dirName.search(/\[confighash\]/);
if (confighashIndex !== -1) {
dirName = dirName.replace(/\[confighash\]/, this.configHash);
}
var cachePath = path.resolve(
process.cwd(), this.compilerOutputOptions.path, dirName
);
if (suffix) {
cachePath = path.join(cachePath, suffix);
}
return cachePath;
};
HardSourceWebpackPlugin.prototype.getCachePath = function(suffix) {
return this.getPath(this.options.cacheDirectory, suffix);
};
HardSourceWebpackPlugin.prototype.apply = function(compiler) {
var options = this.options;
var active = true;
var logger = new LoggerFactory(compiler).create();
var loggerCore = logger.from('core');
logger.lock();
if (!compiler.options.cache) {
compiler.options.cache = true;
}
if (!options.cacheDirectory) {
options.cacheDirectory = path.resolve(
process.cwd(),
compiler.options.context,
'node_modules/.cache/hard-source/[confighash]'
);
}
this.compilerOutputOptions = compiler.options.output;
if (!options.configHash) {
options.configHash = defaultConfigHash;
}
if (options.configHash) {
if (typeof options.configHash === 'string') {
this.configHash = options.configHash;
}
else if (typeof options.configHash === 'function') {
this.configHash = options.configHash(compiler.options);
}
}
var configHashInDirectory =
options.cacheDirectory.search(/\[confighash\]/) !== -1;
if (configHashInDirectory && !this.configHash) {
loggerCore.error(
{
id: 'confighash-directory-no-confighash',
cacheDirectory: options.cacheDirectory
},
'HardSourceWebpackPlugin cannot use [confighash] in cacheDirectory ' +
'without configHash option being set and returning a non-falsy value.'
);
active = false;
compiler.plugin(['watch-run', 'run'], function(compiler, cb) {
logger.unlock();
cb();
});
return;
}
var environmentHasher = null;
if (typeof options.environmentHash !== 'undefined') {
if (options.environmentHash === false) {
environmentHasher = function() {
return Promise.resolve('');
};
}
else if (typeof options.environmentHash === 'string') {
environmentHasher = function() {
return Promise.resolve(options.environmentHash);
};
}
else if (typeof options.environmentHash === 'object') {
environmentHasher = function() {
return envHash(options.environmentHash);
};
}
else if (typeof options.environmentHash === 'function') {
environmentHasher = function() {
return Promise.resolve(options.environmentHash());
};
}
}
if (!environmentHasher) {
environmentHasher = envHash;
}
if (options.recordsInputPath || options.recordsPath) {
if (compiler.options.recordsInputPath || compiler.options.recordsPath) {
loggerCore.error(
{
id: 'records-input-path-set-in-root-config',
webpackRecordsInputPath: compiler.options.recordsInputPath,
webpackRecordsPath: compiler.options.recordsPath,
hardSourceRecordsInputPath: options.recordsInputPath,
hardSourceRecordsPath: options.recordsPath,
},
'recordsInputPath option to HardSourceWebpackPlugin is deprecated. ' +
'You do not need to set it and recordsInputPath in webpack root ' +
'configuration.'
);
}
else {
compiler.options.recordsInputPath =
this.getPath(options.recordsInputPath || options.recordsPath);
}
}
if (options.recordsOutputPath || options.recordsPath) {
if (compiler.options.recordsOutputPath || compiler.options.recordsPath) {
loggerCore.error(
{
id: 'records-output-path-set-in-root-config',
webpackRecordsOutputPath: compiler.options.recordsInputPath,
webpackRecordsPath: compiler.options.recordsPath,
hardSourceRecordsOutputPath: options.recordsOutputPath,
hardSourceRecordsPath: options.recordsPath,
},
'recordsOutputPath option to HardSourceWebpackPlugin is deprecated. ' +
'You do not need to set it and recordsOutputPath in webpack root ' +
'configuration.'
);
}
else {
compiler.options.recordsOutputPath =
this.getPath(options.recordsOutputPath || options.recordsPath);
}
}
var cacheDirPath = this.getCachePath();
var cacheAssetDirPath = path.join(cacheDirPath, 'assets');
var resolveCachePath = path.join(cacheDirPath, 'resolve.json');
var moduleCache = {};
var assetCache = {};
var dataCache = {};
var moduleResolveCache = {};
var md5Cache = {};
var missingCache = {normal: {},loader: {},context: {}};
var resolverCache = {normal: {},loader: {},context: {}};
var currentStamp = '';
var moduleResolveCacheChange = [];
var fileMd5s = {};
var cachedMd5s = {};
var fileTimestamps = {};
var contextMd5s = {};
var contextTimestamps = {};
var cacheSerializerFactory = new CacheSerializerFactory(compiler);
var assetCacheSerializer;
var moduleCacheSerializer;
var dataCacheSerializer;
var md5CacheSerializer;
var moduleResolveCacheSerializer;
var missingCacheSerializer;
var resolverCacheSerializer;
var _this = this;
var stat, readdir, readFile, mtime, md5, fileStamp, contextStamps;
function bindFS() {
stat = promisify(
compiler.inputFileSystem.stat,
{context: compiler.inputFileSystem}
);
// stat = promisify(fs.stat, {context: fs});
readdir = promisify(
compiler.inputFileSystem.readdir,
{context: compiler.inputFileSystem}
);
readFile = promisify(
compiler.inputFileSystem.readFile,
{context: compiler.inputFileSystem}
);
mtime = function(file) {
return stat(file)
.then(function(stat) {return +stat.mtime;})
.catch(function() {return 0;});
};
md5 = function(file) {
return readFile(file)
.then(function(contents) {
return crypto.createHash('md5').update(contents, 'utf8').digest('hex');
})
.catch(function() {return '';});
};
fileStamp = function(file, stats) {
if (compiler.__hardSource_fileTimestamps[file]) {
return compiler.__hardSource_fileTimestamps[file];
}
else {
if (!stats[file]) {stats[file] = stat(file);}
return stats[file]
.then(function(stat) {
var mtime = +stat.mtime;
compiler.__hardSource_fileTimestamps[file] = mtime;
return mtime;
});
}
};
contextStamp = function(dir, stats) {
var context = {};
var selfTime = 0;
function walk(dir) {
return readdir(dir)
.then(function(items) {
return Promise.all(items.map(function(item) {
var file = path.join(dir, item);
if (!stats[file]) {stats[file] = stat(file);}
return stats[file]
.then(function(stat) {
if (stat.isDirectory()) {
return walk(path.join(dir, item))
.then(function(items2) {
return items2.map(function(item2) {
return path.join(item, item2);
});
});
}
if (+stat.mtime > selfTime) {
selfTime = +stat.mtime;
}
return item;
}, function() {
return;
});
}));
})
.catch(() => [])
.then(function(items) {
return items.reduce(function(carry, item) {
return carry.concat(item);
}, [])
.filter(Boolean);
});
}
return walk(dir)
.then(function(items) {
items.sort();
var selfHash = crypto.createHash('md5');
items.forEach(function(item) {
selfHash.update(item);
});
context.mtime = selfTime;
context.hash = selfHash.digest('hex');
return context;
});
};
contextStamps = function(contextDependencies, stats) {
stats = stats || {};
var contexts = {};
contextDependencies.forEach(function(context) {
contexts[context] = {files: [], mtime: 0, hash: ''};
});
var compilerContextTs = compiler.contextTimestamps;
contextDependencies.forEach(function(contextPath) {
const _context = contextStamp(contextPath, stats);
if (!_context.then) {
contexts[contextPath] = _context;
}
else {
contexts[contextPath] = _context
.then(function(context) {
contexts[contextPath] = context;
return context;
});
}
});
return contexts;
};
}
if (compiler.inputFileSystem) {
bindFS();
}
else {
compiler.plugin('after-environment', bindFS);
}
compiler.plugin(['watch-run', 'run'], function(compiler, cb) {
logger.unlock();
if (!active) {return cb();}
try {
fs.statSync(cacheAssetDirPath);
}
catch (_) {
mkdirp.sync(cacheAssetDirPath);
if (configHashInDirectory) {
loggerCore.warn(
{
id: 'new-config-hash',
cacheDirPath: cacheDirPath
},
'HardSourceWebpackPlugin is writing to a new confighash path for ' +
'the first time: ' + cacheDirPath
);
}
if (options.recordsPath || options.recordsOutputPath || options.recordsInputPath) {
loggerCore.warn(
{
id: 'deprecated-recordsPath',
recordsPath: options.recordsPath,
recordsOutputPath: options.recordsOutputPath,
recordsInputPath: options.recordsInputPath,
},
[
'The `recordsPath` option to HardSourceWebpackPlugin is deprecated',
' in 0.6 and will be removed in 0.7. 0.6 and later do not need ',
'recordsPath. If you still need it outside HardSourceWebpackPlugin',
' you can set recordsPath on the root of your webpack ',
'configuration.'
].join('')
);
}
}
var start = Date.now();
if (!assetCacheSerializer) {
try {
assetCacheSerializer = cacheSerializerFactory.create({
name: 'assets',
type: 'file',
cacheDirPath: cacheDirPath,
});
moduleCacheSerializer = cacheSerializerFactory.create({
name: 'module',
type: 'data',
cacheDirPath: cacheDirPath,
autoParse: true,
});
dataCacheSerializer = cacheSerializerFactory.create({
name: 'data',
type: 'data',
cacheDirPath: cacheDirPath,
});
md5CacheSerializer = cacheSerializerFactory.create({
name: 'md5',
type: 'data',
cacheDirPath: cacheDirPath,
});
moduleResolveCacheSerializer = cacheSerializerFactory.create({
name: 'module-resolve',
type: 'data',
cacheDirPath: cacheDirPath,
});
missingCacheSerializer = cacheSerializerFactory.create({
name: 'missing-resolve',
type: 'data',
cacheDirPath: cacheDirPath,
});
resolverCacheSerializer = cacheSerializerFactory.create({
name: 'resolver',
type: 'data',
cacheDirPath: cacheDirPath,
});
}
catch (err) {
return cb(err);
}
}
Promise.all([
fsReadFile(path.join(cacheDirPath, 'stamp'), 'utf8')
.catch(function() {return '';}),
environmentHasher(),
fsReadFile(path.join(cacheDirPath, 'version'), 'utf8')
.catch(function() {return '';}),
])
.then(function(stamps) {
var stamp = stamps[0];
var hash = stamps[1];
var versionStamp = stamps[2];
if (!configHashInDirectory && options.configHash) {
hash += '_' + _this.configHash;
}
currentStamp = hash;
if (!hash || hash !== stamp || hardSourceVersion !== versionStamp) {
if (hash && stamp) {
loggerCore.error(
{
id: 'environment-changed'
},
'Environment has changed (node_modules or configuration was ' +
'updated).\nHardSourceWebpackPlugin will reset the cache and ' +
'store a fresh one.'
);
}
else if (versionStamp && hardSourceVersion !== versionStamp) {
loggerCore.error(
{
id: 'hard-source-changed'
},
'Installed HardSource version does not match the saved ' +
'cache.\nHardSourceWebpackPlugin will reset the cache and store ' +
'a fresh one.'
);
}
// Reset the cache, we can't use it do to an environment change.
moduleCache = {};
assetCache = {};
dataCache = {};
moduleResolveCache = {};
md5Cache = {};
missingCache = {normal: {},loader: {},context: {}};
resolverCache = {normal: {},loader: {},context: {}};
fileTimestamps = {};
contextTimestamps = {};
return rimraf(cacheDirPath);
}
if (Object.keys(moduleCache).length) {return Promise.resolve();}
function contextKeys(compiler, fn) {
return function(source) {
var dest = {};
Object.keys(source).forEach(function(key) {
dest[fn(compiler, key)] = source[key];
});
return dest;
}
}
function contextValues(compiler, fn) {
return function(source) {
var dest = {};
Object.keys(source).forEach(function(key) {
dest[key] = fn(compiler, source[key]);
});
return dest;
}
}
function contextNormalModuleResolveKey(compiler, key) {
var parsed = JSON.parse(key);
if (Array.isArray(parsed)) {
return JSON.stringify([parsed[0], contextNormalPath(compiler, parsed[1]), parsed[2]]);
}
else {
return JSON.stringify(Object.assign({}, parsed, {
context: contextNormalPath(compiler, parsed.context),
}));
}
}
function contextNormalModuleResolve(compiler, resolved) {
if (typeof resolved === 'string') {
resolved = JSON.parse(resolved);
}
if (resolved.type === 'context') {
return (Object.assign({}, resolved, {
identifier: contextNormalModuleId(compiler, resolved.identifier),
resource: contextNormalRequest(compiler, resolved.resource),
}));
}
return (Object.assign({}, resolved, {
context: contextNormalRequest(compiler, resolved.context),
request: contextNormalRequest(compiler, resolved.request),
userRequest: contextNormalRequest(compiler, resolved.userRequest),
rawRequest: contextNormalRequest(compiler, resolved.rawRequest),
resource: contextNormalRequest(compiler, resolved.resource),
loaders: resolved.loaders.map(function(loader) {
return Object.assign({}, loader, {
loader: contextNormalPath(compiler, loader.loader),
});
}),
}));
}
function copyWithDeser(dest, source) {
Object.keys(source).forEach(function(key) {
var item = source[key];
dest[key] = typeof item === 'string' ? JSON.parse(item) : item;
});
}
return Promise.all([
assetCacheSerializer.read()
.then(function(_assetCache) {assetCache = _assetCache;}),
moduleCacheSerializer.read()
.then(contextKeys(compiler, contextNormalModuleId))
.then(copyWithDeser.bind(null, moduleCache)),
dataCacheSerializer.read()
.then(copyWithDeser.bind(null, dataCache))
.then(function() {
dataCache.fileDependencies = dataCache.fileDependencies
.map(function(dep) {
return contextNormalPath(compiler, dep);
});
dataCache.contextDependencies = dataCache.contextDependencies
.map(function(dep) {
return contextNormalPath(compiler, dep);
});
}),
md5CacheSerializer.read()
.then(contextKeys(compiler, contextNormalPath))
.then(function(_md5Cache) {
Object.keys(_md5Cache).forEach(function(key) {
if (typeof _md5Cache[key] === 'string') {
_md5Cache[key] = JSON.parse(_md5Cache[key]);
}
cachedMd5s[key] = _md5Cache[key].hash;
});
md5Cache = _md5Cache;
}),
moduleResolveCacheSerializer.read()
.then(contextKeys(compiler, contextNormalModuleResolveKey))
.then(contextValues(compiler, contextNormalModuleResolve))
.then(copyWithDeser.bind(null, moduleResolveCache)),
missingCacheSerializer.read()
.then(function(_missingCache) {
missingCache = {normal: {},loader: {}, context: {}};
function contextNormalMissingKey(compiler, key) {
var parsed = JSON.parse(key);
return JSON.stringify([
contextNormalPath(compiler, parsed[0]),
contextNormalPath(compiler, parsed[1])
]);
}
function contextNormalMissing(compiler, missing) {
return missing.map(function(missed) {
return contextNormalRequest(compiler, missed);
});
}
Object.keys(_missingCache).forEach(function(key) {
var item = _missingCache[key];
if (typeof item === 'string') {
item = JSON.parse(item);
}
var splitIndex = key.indexOf('/');
var group = key.substring(0, splitIndex);
var keyName = contextNormalMissingKey(compiler, key.substring(splitIndex + 1));
missingCache[group] = missingCache[group] || {};
missingCache[group][keyName] = contextNormalMissing(compiler, item);
});
}),
resolverCacheSerializer.read()
.then(function(_resolverCache) {
resolverCache = {normal: {},loader: {}, context: {}};
function contextNormalResolvedKey(compiler, key) {
var parsed = JSON.parse(key);
return JSON.stringify([contextNormalPath(compiler, parsed[0]), parsed[1]]);
}
function contextNormalResolved(compiler, resolved) {
return Object.assign({}, resolved, {
result: contextNormalPath(compiler, resolved.result),
});
}
Object.keys(_resolverCache).forEach(function(key) {
var item = _resolverCache[key];
if (typeof item === 'string') {
item = JSON.parse(item);
}
var splitIndex = key.indexOf('/');
var group = key.substring(0, splitIndex);
var keyName = contextNormalResolvedKey(compiler, key.substring(splitIndex + 1));
resolverCache[group] = resolverCache[group] || {};
resolverCache[group][keyName] = contextNormalResolved(compiler, item);
});
}),
])
.then(function() {
// console.log('cache in', Date.now() - start);
});
})
.then(cb, cb);
});
compiler.plugin(['watch-run', 'run'], function(_compiler, cb) {
if (!active) {return cb();}
// No previous build to verify.
if (!dataCache.fileDependencies) return cb();
var stats = {};
return Promise.all([
(function() {
var compilerFileTs = compiler.__hardSource_fileTimestamps = {};
var fileTs = fileTimestamps = {};
return bulkFsTask(dataCache.fileDependencies, function(file, task) {
if (compiler.__hardSource_fileTimestamps[file]) {
return compiler.__hardSource_fileTimestamps[file];
}
else {
compiler.inputFileSystem.stat(file, task(function(err, value) {
if (err) {
return 0;
}
var mtime = +value.mtime;
compiler.__hardSource_fileTimestamps[file] = mtime;
return mtime;
}));
}
})
.then(function(mtimes) {
const bulk = lodash.zip(dataCache.fileDependencies, mtimes);
return bulkFsTask(bulk, function(item, task) {
var file = item[0];
var mtime = item[1];
fileTs[file] = mtime || 0;
if (!compiler.__hardSource_fileTimestamps[file]) {
compiler.__hardSource_fileTimestamps[file] = mtime;
}
// if (
// fileTs[file] &&
// md5Cache[file] &&
// fileTs[file] < md5Cache[file].mtime
// ) {
// fileTs[file] = md5Cache[file].mtime;
// fileMd5s[file] = md5Cache[file].hash;
// }
// else {
compiler.inputFileSystem.readFile(file, task(function(err, body) {
if (err) {
fileMd5s[file] = '';
return;
}
const hash = crypto.createHash('md5')
.update(body, 'utf8').digest('hex');
fileMd5s[file] = hash;
}));
// }
});
});
})(),
(function() {
compiler.contextTimestamps = compiler.contextTimestamps || {};
var contextTs = contextTimestamps = {};
const contexts = contextStamps(dataCache.contextDependencies, stats);
return Promise.all(values(contexts))
.then(function() {
for (var contextPath in contexts) {
var context = contexts[contextPath];
if (!compiler.contextTimestamps[contextPath]) {
compiler.contextTimestamps[contextPath] = context.mtime;
}
contextTimestamps[contextPath] = context.mtime;
fileMd5s[contextPath] = context.hash;
}
});
})(),
(function() {
var bulk = lodash.flatten(Object.keys(missingCache)
.map(function(group) {
return lodash.flatten(Object.keys(missingCache[group])
.map(function(key) {
var missingItem = missingCache[group][key];
if (!missingItem) {return;}
return missingItem.map(function(missed, index) {
return [group, key, missed, index];
});
})
.filter(Boolean));
}));
return bulkFsTask(bulk, function(item, task) {
var group = item[0];
var key = item[1];
var missingItem = missingCache[group][key];
var missed = item[2];
var missedPath = missed.split('?')[0];
var missedIndex = item[3];
// The missed index is the resolved item. Invalidate if it does not
// exist.
if (missedIndex === missingItem.length - 1) {
compiler.inputFileSystem.stat(missed, task(function(err, stat) {
if (err) {
missingItem.invalid = true;
missingItem.invalidReason = 'resolved now missing';
}
}));
}
else {
compiler.inputFileSystem.stat(missed, task(function(err, stat) {
if (err) {return;}
if (stat.isDirectory()) {
if (group === 'context') {
missingItem.invalid = true;
}
}
if (stat.isFile()) {
if (group === 'loader' || group.startsWith('normal')) {
missingItem.invalid = true;
missingItem.invalidReason = 'missing now found';
}
}
}));
}
});
})(),
])
.then(function() {
// Invalidate resolve cache items.
Object.keys(moduleResolveCache).forEach(function(key) {
var resolveKey = JSON.parse(key);
var resolveItem = moduleResolveCache[key];
var normalId = 'normal';
if (resolveItem.resolveOptions) {
normalId = `normal-${new nodeObjectHash({sort: false}).hash(resolveItem.resolveOptions)}`;
}
if (resolveItem.type === 'context') {
var contextMissing = missingCache.context[JSON.stringify([
resolveKey.context,
resolveItem.resource.split('?')[0]
])];
if (!contextMissing || contextMissing.invalid) {
resolveItem.invalid = true;
resolveItem.invalidReason = 'resolved context invalid';
}
}
else {
var normalMissing = missingCache[normalId][JSON.stringify([
resolveKey[1],
resolveItem.resource.split('?')[0]
])];
if (!normalMissing || normalMissing.invalid) {
resolveItem.invalid = true;
resolveItem.invalidReason = 'resolved normal invalid' + (
normalMissing ? (' ' + normalMissing.invalidReason) : ': resolve entry not in cache'
);
}
resolveItem.loaders.forEach(function(loader) {
if (typeof loader === 'object') {
loader = loader.loader;
}
// Loaders specified in a dependency are searched for from the
// context of the module containing that dependency.
var loaderMissing = missingCache.loader[JSON.stringify([
resolveKey[1],
loader.split('?')[0]
])];
if (!loaderMissing) {
// webpack searches for rule based loaders from the project
// context.
loaderMissing = missingCache.loader[JSON.stringify([
// compiler may be a Watching instance, which refers to the
// compiler
(compiler.options || compiler.compiler.options).context,
loader.split('?')[0]
])];
}
if (!loaderMissing || loaderMissing.invalid) {
resolveItem.invalid = true;
resolveItem.invalidReason = 'resolved loader invalid';
}
});
}
});
})
.then(function() {cb();}, cb);
});
compiler.plugin('after-plugins', function() {
compiler.plugin('compilation', function(compilation, params) {
var factories = compilation.dependencyFactories;
var contextFactory = factories.get(RequireContextDependency) ||
params.contextModuleFactory;
var hardContextFactory = new HardContextModuleFactory({
compilation: compilation,
factory: contextFactory,
resolveCache: moduleResolveCache,
resolveCacheChange: moduleResolveCacheChange,
moduleCache: moduleCache,
fileTimestamps: fileTimestamps,
fileMd5s: fileMd5s,
cachedMd5s: cachedMd5s,
});
factories.set(AMDRequireContextDependency, hardContextFactory);
factories.set(CommonJsRequireContextDependency, hardContextFactory);
factories.set(RequireContextDependency, hardContextFactory);
factories.set(RequireResolveContextDependency, hardContextFactory);
if (ImportContextDependency) {
factories.set(ImportContextDependency, hardContextFactory);
}
});
});
function bindResolvers() {
function configureMissing(key, resolver) {
// missingCache[key] = missingCache[key] || {};
// resolverCache[key] = resolverCache[key] || {};
var _resolve = resolver.resolve;
resolver.resolve = function(info, context, request, cb, cb2) {
var numArgs = 4;
if (!cb) {
numArgs = 3;
cb = request;
request = context;
context = info;
}
var resolveContext;
if (cb2) {
numArgs = 5;
resolveContext = cb;
cb = cb2;
}
if (info && info.resolveOptions) {
key = `normal-${new nodeObjectHash({sort: false}).hash(info.resolveOptions)}`;
resolverCache[key] = resolverCache[key] || {};
missingCache[key] = missingCache[key] || {};
}
var resolveId = JSON.stringify([context, request]);