保誠-保戶業務員媒合平台
HelenHuang
2022-06-09 9bdb95c9e34cef640534e5e5a1e2225a80442000
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
const path = require('path');
 
const lodash = require('lodash');
const nodeObjectHash = require('node-object-hash');
const parseJson = require('parse-json');
 
const pluginCompat = require('./util/plugin-compat');
const promisify = require('./util/promisify');
const relateContext = require('./util/relate-context');
const serial = require('./util/serial');
const values = require('./util/Object.values');
const bulkFsTask = require('./util/bulk-fs-task');
const { parityCacheFromCache, pushParityWriteOps } = require('./util/parity');
 
const serialNormalResolved = serial.created({
  result: serial.path,
  resourceResolveData: serial.objectAssign({
    context: serial.created({
      issuer: serial.request,
      resolveOptions: serial.identity,
    }),
    path: serial.path,
    descriptionFilePath: serial.path,
    descriptionFileRoot: serial.path,
  }),
});
 
class EnhancedResolveCache {
  apply(compiler) {
    let missingCacheSerializer;
    let resolverCacheSerializer;
 
    let missingCache = { normal: {}, loader: {}, context: {} };
    let resolverCache = { normal: {}, loader: {}, context: {} };
    let parityCache = {};
 
    const compilerHooks = pluginCompat.hooks(compiler);
 
    compilerHooks._hardSourceCreateSerializer.tap(
      'HardSource - EnhancedResolveCache',
      (cacheSerializerFactory, cacheDirPath) => {
        missingCacheSerializer = cacheSerializerFactory.create({
          name: 'missing-resolve',
          type: 'data',
          autoParse: true,
          cacheDirPath,
        });
        resolverCacheSerializer = cacheSerializerFactory.create({
          name: 'resolver',
          type: 'data',
          autoParse: true,
          cacheDirPath,
        });
      },
    );
 
    compilerHooks._hardSourceResetCache.tap(
      'HardSource - EnhancedResolveCache',
      () => {
        missingCache = { normal: {}, loader: {}, context: {} };
        resolverCache = { normal: {}, loader: {}, context: {} };
        parityCache = {};
 
        compiler.__hardSource_missingCache = missingCache;
      },
    );
 
    compilerHooks._hardSourceReadCache.tapPromise(
      'HardSource - EnhancedResolveCache',
      ({ contextNormalPath, contextNormalRequest }) => {
        return Promise.all([
          missingCacheSerializer.read().then(_missingCache => {
            missingCache = { normal: {}, loader: {}, context: {} };
 
            compiler.__hardSource_missingCache = missingCache;
 
            function contextNormalMissingKey(compiler, key) {
              const parsed = parseJson(key);
              return JSON.stringify([
                contextNormalPath(compiler, parsed[0]),
                contextNormalPath(compiler, parsed[1]),
              ]);
            }
 
            function contextNormalMissing(compiler, missing) {
              return missing.map(missed =>
                contextNormalRequest(compiler, missed),
              );
            }
 
            Object.keys(_missingCache).forEach(key => {
              let item = _missingCache[key];
              if (typeof item === 'string') {
                item = parseJson(item);
              }
              const splitIndex = key.indexOf('/');
              const group = key.substring(0, splitIndex);
              const keyName = contextNormalMissingKey(
                compiler,
                key.substring(splitIndex + 1),
              );
              missingCache[group] = missingCache[group] || {};
              missingCache[group][keyName] = contextNormalMissing(
                compiler,
                item,
              );
            });
          }),
 
          resolverCacheSerializer.read().then(_resolverCache => {
            resolverCache = { normal: {}, loader: {}, context: {} };
            parityCache = {};
 
            function contextNormalResolvedKey(compiler, key) {
              const parsed = parseJson(key);
              return JSON.stringify([
                contextNormalPath(compiler, parsed[0]),
                parsed[1],
              ]);
            }
 
            function contextNormalResolved(compiler, resolved) {
              return serialNormalResolved.thaw(resolved, resolved, {
                compiler,
              });
            }
 
            Object.keys(_resolverCache).forEach(key => {
              let item = _resolverCache[key];
              if (typeof item === 'string') {
                item = parseJson(item);
              }
              if (key.startsWith('__hardSource_parityToken')) {
                parityCache[key] = item;
                return;
              }
              const splitIndex = key.indexOf('/');
              const group = key.substring(0, splitIndex);
              const keyName = contextNormalResolvedKey(
                compiler,
                key.substring(splitIndex + 1),
              );
              resolverCache[group] = resolverCache[group] || {};
              resolverCache[group][keyName] = contextNormalResolved(
                compiler,
                item,
              );
            });
          }),
        ]);
      },
    );
 
    compilerHooks._hardSourceParityCache.tap(
      'HardSource - EnhancedResolveCache',
      parityRoot => {
        parityCacheFromCache('EnhancedResolve', parityRoot, parityCache);
      },
    );
 
    let missingVerifyResolve;
    compiler.__hardSource_missingVerify = new Promise(resolve => {
      missingVerifyResolve = resolve;
    });
 
    compilerHooks._hardSourceVerifyCache.tapPromise(
      'HardSource - EnhancedResolveCache',
      () =>
        (() => {
          compiler.__hardSource_missingVerify = new Promise(resolve => {
            missingVerifyResolve = resolve;
          });
 
          const bulk = lodash.flatten(
            Object.keys(missingCache).map(group =>
              lodash.flatten(
                Object.keys(missingCache[group])
                  .map(key => {
                    const missingItem = missingCache[group][key];
                    if (!missingItem) {
                      return;
                    }
                    return missingItem.map((missed, index) => [
                      group,
                      key,
                      missed,
                      index,
                    ]);
                  })
                  .filter(Boolean),
              ),
            ),
          );
 
          return bulkFsTask(bulk, (item, task) => {
            const group = item[0];
            const key = item[1];
            const missingItem = missingCache[group][key];
            const missed = item[2];
            const missedPath = missed.split('?')[0];
            const 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((err, stat) => {
                  if (err) {
                    missingItem.invalid = true;
                    missingItem.invalidReason = 'resolved now missing';
                  }
                }),
              );
            } else {
              compiler.inputFileSystem.stat(
                missed,
                task((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(missingVerifyResolve),
    );
 
    function bindResolvers() {
      function configureMissing(key, resolver) {
        // missingCache[key] = missingCache[key] || {};
        // resolverCache[key] = resolverCache[key] || {};
 
        const _resolve = resolver.resolve;
        resolver.resolve = function(info, context, request, cb, cb2) {
          let numArgs = 4;
          if (!cb) {
            numArgs = 3;
            cb = request;
            request = context;
            context = info;
          }
          let 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] || {};
          }
 
          const resolveId = JSON.stringify([context, request]);
          const absResolveId = JSON.stringify([
            context,
            relateContext.relateAbsolutePath(context, request),
          ]);
          const resolve =
            resolverCache[key][resolveId] || resolverCache[key][absResolveId];
          if (resolve && !resolve.invalid) {
            const missingId = JSON.stringify([context, resolve.result]);
            const missing = missingCache[key][missingId];
            if (missing && !missing.invalid) {
              return cb(
                null,
                [resolve.result].concat(request.split('?').slice(1)).join('?'),
                resolve.resourceResolveData,
              );
            } else {
              resolve.invalid = true;
              resolve.invalidReason = 'out of date';
            }
          }
          let localMissing = [];
          const callback = (err, result, result2) => {
            if (result) {
              const inverseId = JSON.stringify([context, result.split('?')[0]]);
              const resolveId = JSON.stringify([context, request]);
 
              // Skip recording missing for any dependency in node_modules.
              // Changes to them will be handled by the environment hash. If we
              // tracked the stuff in node_modules too, we'd be adding a whole
              // bunch of reduntant work.
              if (result.includes('node_modules')) {
                localMissing = localMissing.filter(
                  missed => !missed.includes('node_modules'),
                );
              }
 
              // In case of other cache layers, if we already have missing
              // recorded and we get a new empty array of missing, keep the old
              // value.
              if (localMissing.length === 0 && missingCache[key][inverseId]) {
                return cb(err, result, result2);
              }
 
              missingCache[key][inverseId] = localMissing
                .filter((missed, missedIndex) => {
                  const index = localMissing.indexOf(missed);
                  if (index === -1 || index < missedIndex) {
                    return false;
                  }
                  if (missed === result) {
                    return false;
                  }
                  return true;
                })
                .concat(result.split('?')[0]);
              missingCache[key][inverseId].new = true;
              resolverCache[key][resolveId] = {
                result: result.split('?')[0],
                resourceResolveData: result2,
                new: true,
              };
            }
            cb(err, result, result2);
          };
          const _missing =
            cb.missing || (resolveContext && resolveContext.missing);
          if (_missing) {
            callback.missing = {
              push(path) {
                localMissing.push(path);
                _missing.push(path);
              },
              add(path) {
                localMissing.push(path);
                _missing.add(path);
              },
            };
            if (resolveContext) {
              resolveContext.missing = callback.missing;
            }
          } else {
            callback.missing = Object.assign(localMissing, {
              add(path) {
                localMissing.push(path);
              },
            });
            if (resolveContext) {
              resolveContext.missing = callback.missing;
            }
          }
 
          if (numArgs === 3) {
            _resolve.call(this, context, request, callback);
          } else if (numArgs === 5) {
            _resolve.call(
              this,
              info,
              context,
              request,
              resolveContext,
              callback,
            );
          } else {
            _resolve.call(this, info, context, request, callback);
          }
        };
      }
 
      if (compiler.resolverFactory) {
        compiler.resolverFactory.hooks.resolver
          .for('normal')
          .tap('HardSource resolve cache', (resolver, options) => {
            const normalCacheId = `normal-${new nodeObjectHash({
              sort: false,
            }).hash(Object.assign({}, options, { fileSystem: null }))}`;
            resolverCache[normalCacheId] = resolverCache[normalCacheId] || {};
            missingCache[normalCacheId] = missingCache[normalCacheId] || {};
            configureMissing(normalCacheId, resolver);
            return resolver;
          });
        compiler.resolverFactory.hooks.resolver
          .for('loader')
          .tap('HardSource resolve cache', resolver => {
            configureMissing('loader', resolver);
            return resolver;
          });
        compiler.resolverFactory.hooks.resolver
          .for('context')
          .tap('HardSource resolve cache', resolver => {
            configureMissing('context', resolver);
            return resolver;
          });
      } else {
        configureMissing('normal', compiler.resolvers.normal);
        configureMissing('loader', compiler.resolvers.loader);
        configureMissing('context', compiler.resolvers.context);
      }
    }
 
    compilerHooks.afterPlugins.tap('HardSource - EnhancedResolveCache', () => {
      if (compiler.resolvers.normal) {
        bindResolvers();
      } else {
        compilerHooks.afterResolvers.tap(
          'HardSource - EnhancedResolveCache',
          bindResolvers,
        );
      }
    });
 
    compilerHooks._hardSourceWriteCache.tapPromise(
      'HardSource - EnhancedResolveCache',
      (compilation, { relateNormalPath, relateNormalRequest }) => {
        if (compilation.compiler.parentCompilation) {
          const resolverOps = [];
          pushParityWriteOps(compilation, resolverOps);
 
          return resolverCacheSerializer.write(resolverOps);
        }
 
        const missingOps = [];
        const resolverOps = [];
 
        function relateNormalMissingKey(compiler, key) {
          const parsed = parseJson(key);
          return JSON.stringify([
            relateNormalPath(compiler, parsed[0]),
            relateNormalPath(compiler, parsed[1]),
          ]);
        }
 
        function relateNormalMissing(compiler, missing) {
          return missing.map(missed => relateNormalRequest(compiler, missed));
        }
 
        Object.keys(missingCache).forEach(group => {
          Object.keys(missingCache[group]).forEach(key => {
            if (!missingCache[group][key]) {
              return;
            }
            if (missingCache[group][key].new) {
              missingCache[group][key].new = false;
              missingOps.push({
                key: `${group}/${relateNormalMissingKey(compiler, key)}`,
                value: JSON.stringify(
                  relateNormalMissing(compiler, missingCache[group][key]),
                ),
              });
            } else if (missingCache[group][key].invalid) {
              missingCache[group][key] = null;
              missingOps.push({
                key: `${group}/${relateNormalMissingKey(compiler, key)}`,
                value: null,
              });
            }
          });
        });
 
        function relateNormalResolvedKey(compiler, key) {
          const parsed = parseJson(key);
          return JSON.stringify([
            relateNormalPath(compiler, parsed[0]),
            relateContext.relateAbsolutePath(parsed[0], parsed[1]),
          ]);
        }
 
        function relateNormalResolved(compiler, resolved) {
          return serialNormalResolved.freeze(resolved, resolved, {
            compiler,
          });
        }
 
        Object.keys(resolverCache).forEach(group => {
          Object.keys(resolverCache[group]).forEach(key => {
            if (!resolverCache[group][key]) {
              return;
            }
            if (resolverCache[group][key].new) {
              resolverCache[group][key].new = false;
              resolverOps.push({
                key: `${group}/${relateNormalResolvedKey(compiler, key)}`,
                value: JSON.stringify(
                  relateNormalResolved(compiler, resolverCache[group][key]),
                ),
              });
            } else if (resolverCache[group][key].invalid) {
              resolverCache[group][key] = null;
              resolverOps.push({
                key: `${group}/${relateNormalResolvedKey(compiler, key)}`,
                value: null,
              });
            }
          });
        });
 
        pushParityWriteOps(compilation, resolverOps);
 
        return Promise.all([
          missingCacheSerializer.write(missingOps),
          resolverCacheSerializer.write(resolverOps),
        ]);
      },
    );
  }
}
 
module.exports = EnhancedResolveCache;