-
Notifications
You must be signed in to change notification settings - Fork 1.7k
/
79fb1_turbopack-tests_tests_snapshot_swc_transforms_preset_env_input_index_9dcfd0.js
1572 lines (1409 loc) · 46.1 KB
/
79fb1_turbopack-tests_tests_snapshot_swc_transforms_preset_env_input_index_9dcfd0.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
(globalThis.TURBOPACK = globalThis.TURBOPACK || []).push([
"output/79fb1_turbopack-tests_tests_snapshot_swc_transforms_preset_env_input_index_9dcfd0.js",
{},
{"otherChunks":[{"path":"output/63a02_@swc_helpers____class_call_check_f08d44.js","included":["[project]/crates/turbopack-tests/tests/node_modules/@swc/helpers/_/_class_call_check.js (ecmascript)"]},{"path":"output/79fb1_turbopack-tests_tests_snapshot_swc_transforms_preset_env_input_index_b53fce.js","included":["[project]/crates/turbopack-tests/tests/snapshot/swc_transforms/preset_env/input/index.js (ecmascript)"]}],"runtimeModuleIds":["[project]/crates/turbopack-tests/tests/snapshot/swc_transforms/preset_env/input/index.js (ecmascript)"]}
]);
(() => {
if (!Array.isArray(globalThis.TURBOPACK)) {
return;
}
/* eslint-disable @next/next/no-assign-module-variable */
/** @typedef {import('../types').ChunkRegistration} ChunkRegistration */
/** @typedef {import('../types').ModuleFactory} ModuleFactory */
/** @typedef {import('../types').ChunkPath} ChunkPath */
/** @typedef {import('../types').ModuleId} ModuleId */
/** @typedef {import('../types').GetFirstModuleChunk} GetFirstModuleChunk */
/** @typedef {import('../types').ChunkList} ChunkList */
/** @typedef {import('../types').Module} Module */
/** @typedef {import('../types').ChunkData} ChunkData */
/** @typedef {import('../types').SourceInfo} SourceInfo */
/** @typedef {import('../types').SourceType} SourceType */
/** @typedef {import('../types').SourceType.Runtime} SourceTypeRuntime */
/** @typedef {import('../types').SourceType.Parent} SourceTypeParent */
/** @typedef {import('../types').SourceType.Update} SourceTypeUpdate */
/** @typedef {import('../types').Exports} Exports */
/** @typedef {import('../types').EsmInteropNamespace} EsmInteropNamespace */
/** @typedef {import('../types').RefreshHelpers} RefreshHelpers */
/** @typedef {import('../types/hot').Hot} Hot */
/** @typedef {import('../types/hot').HotData} HotData */
/** @typedef {import('../types/hot').AcceptCallback} AcceptCallback */
/** @typedef {import('../types/hot').AcceptErrorHandler} AcceptErrorHandler */
/** @typedef {import('../types/hot').HotState} HotState */
/** @typedef {import('../types/protocol').PartialUpdate} PartialUpdate */
/** @typedef {import('../types/protocol').ChunkListUpdate} ChunkListUpdate */
/** @typedef {import('../types/protocol').EcmascriptMergedUpdate} EcmascriptMergedUpdate */
/** @typedef {import('../types/protocol').EcmascriptMergedChunkUpdate} EcmascriptMergedChunkUpdate */
/** @typedef {import('../types/protocol').EcmascriptModuleEntry} EcmascriptModuleEntry */
/** @typedef {import('../types/runtime').ModuleEffect} ModuleEffect */
/** @type {Object.<ModuleId, ModuleFactory>} */
const moduleFactories = { __proto__: null };
/** @type {Object.<ModuleId, Module>} */
const moduleCache = { __proto__: null };
/**
* Maps module IDs to persisted data between executions of their hot module
* implementation (`hot.data`).
*
* @type {Map<ModuleId, HotData>}
*/
const moduleHotData = new Map();
/**
* Maps module instances to their hot module state.
*
* @type {Map<Module, HotState>}
*/
const moduleHotState = new Map();
/**
* Module IDs that are instantiated as part of the runtime of a chunk.
*
* @type {Set<ModuleId>}
*/
const runtimeModules = new Set();
/**
* Map from module ID to the chunks that contain this module.
*
* In HMR, we need to keep track of which modules are contained in which so
* chunks. This is so we don't eagerly dispose of a module when it is removed
* from chunk A, but still exists in chunk B.
*
* @type {Map<ModuleId, Set<ChunkPath>>}
*/
const moduleChunksMap = new Map();
/**
* Map from chunk path to all modules it contains.
* @type {Map<ModuleId, Set<ChunkPath>>}
*/
const chunkModulesMap = new Map();
/**
* Chunk lists that contain a runtime. When these chunk lists receive an update
* that can't be reconciled with the current state of the page, we need to
* reload the runtime entirely.
* @type {Set<ChunkPath>}
*/
const runtimeChunkLists = new Set();
/**
* Map from chunk list to the chunk paths it contains.
* @type {Map<ChunkPath, Set<ChunkPath>>}
*/
const chunkListChunksMap = new Map();
/**
* Map from chunk path to the chunk lists it belongs to.
* @type {Map<ChunkPath, Set<ChunkPath>>}
*/
const chunkChunkListsMap = new Map();
const hOP = Object.prototype.hasOwnProperty;
const toStringTag = typeof Symbol !== "undefined" && Symbol.toStringTag;
/**
* @param {any} obj
* @param {PropertyKey} name
* @param {PropertyDescriptor & ThisType<any>} options
*/
function defineProp(obj, name, options) {
if (!hOP.call(obj, name)) Object.defineProperty(obj, name, options);
}
/**
* Adds the getters to the exports object
*
* @param {Exports} exports
* @param {Record<string, () => any>} getters
*/
function esm(exports, getters) {
defineProp(exports, "__esModule", { value: true });
if (toStringTag) defineProp(exports, toStringTag, { value: "Module" });
for (const key in getters) {
defineProp(exports, key, { get: getters[key], enumerable: true });
}
}
/**
* Adds the getters to the exports object
*
* @param {Exports} exports
* @param {Record<string, any>} props
*/
function cjs(exports, props) {
for (const key in props) {
defineProp(exports, key, { get: () => props[key], enumerable: true });
}
}
/**
* @param {Module} module
* @param {any} value
*/
function exportValue(module, value) {
module.exports = value;
}
/**
* @param {Record<string, any>} obj
* @param {string} key
*/
function createGetter(obj, key) {
return () => obj[key];
}
/**
* @param {Exports} raw
* @param {EsmInteropNamespace} ns
* @param {boolean} [allowExportDefault]
*/
function interopEsm(raw, ns, allowExportDefault) {
/** @type {Object.<string, () => any>} */
const getters = { __proto__: null };
for (const key in raw) {
getters[key] = createGetter(raw, key);
}
if (!(allowExportDefault && "default" in getters)) {
getters["default"] = () => raw;
}
esm(ns, getters);
}
/**
* @param {Module} sourceModule
* @param {ModuleId} id
* @param {boolean} allowExportDefault
* @returns {EsmInteropNamespace}
*/
function esmImport(sourceModule, id, allowExportDefault) {
const module = getOrInstantiateModuleFromParent(id, sourceModule);
if (module.error) throw module.error;
const raw = module.exports;
if (raw.__esModule) return raw;
if (module.interopNamespace) return module.interopNamespace;
const ns = (module.interopNamespace = {});
interopEsm(raw, ns, allowExportDefault);
return ns;
}
/**
* @param {Module} sourceModule
* @param {ModuleId} id
* @returns {Exports}
*/
function commonJsRequire(sourceModule, id) {
const module = getOrInstantiateModuleFromParent(id, sourceModule);
if (module.error) throw module.error;
return module.exports;
}
function externalRequire(id, esm) {
let raw;
try {
raw = require(id);
} catch (err) {
// TODO(alexkirsz) This can happen when a client-side module tries to load
// an external module we don't provide a shim for (e.g. querystring, url).
// For now, we fail semi-silently, but in the future this should be a
// compilation error.
throw new Error(`Failed to load external module ${id}: ${err}`);
}
if (!esm || raw.__esModule) {
return raw;
}
const ns = {};
interopEsm(raw, ns, true);
return ns;
}
externalRequire.resolve = (name, opt) => {
return require.resolve(name, opt);
};
/** @type {Map<ModuleId, Promise<any> | true>} */
const availableModules = new Map();
/**
* @param {SourceInfo} source
* @param {ChunkData} chunkData
* @returns {Promise<any>}
*/
async function loadChunk(source, chunkData) {
if (typeof chunkData === "string") {
return loadChunkPath(source, chunkData);
} else {
const includedList = chunkData.included || [];
const promises = includedList.map((included) => {
if (moduleFactories[included]) return true;
return availableModules.get(included);
});
if (promises.length > 0 && promises.every((p) => p)) {
// When all included items are already loaded or loading, we can skip loading ourselves
return Promise.all(promises);
}
const promise = loadChunkPath(source, chunkData.path);
for (const included of includedList) {
if (!availableModules.has(included)) {
// It might be better to race old and new promises, but it's rare that the new promise will be faster than a request started earlier.
// In production it's even more rare, because the chunk optimization tries to deduplicate modules anyway.
availableModules.set(included, promise);
}
}
return promise;
}
}
/**
* @param {SourceInfo} source
* @param {ChunkPath} chunkPath
* @returns {Promise<any>}
*/
async function loadChunkPath(source, chunkPath) {
try {
await BACKEND.loadChunk(chunkPath, source);
} catch (error) {
let loadReason;
switch (source.type) {
case SourceTypeRuntime:
loadReason = `as a runtime dependency of chunk ${source.chunkPath}`;
break;
case SourceTypeParent:
loadReason = `from module ${source.parentId}`;
break;
case SourceTypeUpdate:
loadReason = "from an HMR update";
break;
}
throw new Error(
`Failed to load chunk ${chunkPath} ${loadReason}${
error ? `: ${error}` : ""
}`
);
}
}
/** @type {SourceTypeRuntime} */
const SourceTypeRuntime = 0;
/** @type {SourceTypeParent} */
const SourceTypeParent = 1;
/** @type {SourceTypeUpdate} */
const SourceTypeUpdate = 2;
/**
*
* @param {ModuleId} id
* @param {SourceInfo} source
* @returns {Module}
*/
function instantiateModule(id, source) {
const moduleFactory = moduleFactories[id];
if (typeof moduleFactory !== "function") {
// This can happen if modules incorrectly handle HMR disposes/updates,
// e.g. when they keep a `setTimeout` around which still executes old code
// and contains e.g. a `require("something")` call.
let instantiationReason;
switch (source.type) {
case SourceTypeRuntime:
instantiationReason = `as a runtime entry of chunk ${source.chunkPath}`;
break;
case SourceTypeParent:
instantiationReason = `because it was required from module ${source.parentId}`;
break;
case SourceTypeUpdate:
instantiationReason = "because of an HMR update";
break;
}
throw new Error(
`Module ${id} was instantiated ${instantiationReason}, but the module factory is not available. It might have been deleted in an HMR update.`
);
}
const hotData = moduleHotData.get(id);
const { hot, hotState } = createModuleHot(hotData);
/** @type {Module} */
const module = {
exports: {},
error: undefined,
loaded: false,
id,
parents: undefined,
children: [],
interopNamespace: undefined,
hot,
};
moduleCache[id] = module;
moduleHotState.set(module, hotState);
switch (source.type) {
case SourceTypeRuntime:
runtimeModules.add(id);
module.parents = [];
break;
case SourceTypeParent:
// No need to add this module as a child of the parent module here, this
// has already been taken care of in `getOrInstantiateModuleFromParent`.
module.parents = [source.parentId];
break;
case SourceTypeUpdate:
module.parents = source.parents || [];
break;
}
runModuleExecutionHooks(module, () => {
try {
moduleFactory.call(module.exports, {
e: module.exports,
r: commonJsRequire.bind(null, module),
x: externalRequire,
i: esmImport.bind(null, module),
s: esm.bind(null, module.exports),
j: cjs.bind(null, module.exports),
v: exportValue.bind(null, module),
m: module,
c: moduleCache,
l: loadChunk.bind(null, { type: SourceTypeParent, parentId: id }),
g: globalThis,
__dirname: module.id.replace(/(^|\/)[\/]+$/, ""),
});
} catch (error) {
module.error = error;
throw error;
}
});
module.loaded = true;
if (module.interopNamespace) {
// in case of a circular dependency: cjs1 -> esm2 -> cjs1
interopEsm(module.exports, module.interopNamespace);
}
return module;
}
/**
* NOTE(alexkirsz) Webpack has an "module execution" interception hook that
* Next.js' React Refresh runtime hooks into to add module context to the
* refresh registry.
*
* @param {Module} module
* @param {() => void} executeModule
*/
function runModuleExecutionHooks(module, executeModule) {
const cleanupReactRefreshIntercept =
typeof globalThis.$RefreshInterceptModuleExecution$ === "function"
? globalThis.$RefreshInterceptModuleExecution$(module.id)
: () => {};
executeModule();
if ("$RefreshHelpers$" in globalThis) {
// This pattern can also be used to register the exports of
// a module with the React Refresh runtime.
registerExportsAndSetupBoundaryForReactRefresh(
module,
globalThis.$RefreshHelpers$
);
}
cleanupReactRefreshIntercept();
}
/**
* Retrieves a module from the cache, or instantiate it if it is not cached.
*
* @param {ModuleId} id
* @param {Module} sourceModule
* @returns {Module}
*/
function getOrInstantiateModuleFromParent(id, sourceModule) {
if (!sourceModule.hot.active) {
console.warn(
`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`
);
}
const module = moduleCache[id];
if (sourceModule.children.indexOf(id) === -1) {
sourceModule.children.push(id);
}
if (module) {
if (module.parents.indexOf(sourceModule.id) === -1) {
module.parents.push(sourceModule.id);
}
return module;
}
return instantiateModule(id, {
type: SourceTypeParent,
parentId: sourceModule.id,
});
}
/**
* This is adapted from https://github.com/vercel/next.js/blob/3466862d9dc9c8bb3131712134d38757b918d1c0/packages/react-refresh-utils/internal/ReactRefreshModule.runtime.ts
*
* @param {Module} module
* @param {RefreshHelpers} helpers
*/
function registerExportsAndSetupBoundaryForReactRefresh(module, helpers) {
const currentExports = module.exports;
const prevExports = module.hot.data.prevExports ?? null;
helpers.registerExportsForReactRefresh(currentExports, module.id);
// A module can be accepted automatically based on its exports, e.g. when
// it is a Refresh Boundary.
if (helpers.isReactRefreshBoundary(currentExports)) {
// Save the previous exports on update so we can compare the boundary
// signatures.
module.hot.dispose((data) => {
data.prevExports = currentExports;
});
// Unconditionally accept an update to this module, we'll check if it's
// still a Refresh Boundary later.
module.hot.accept();
// This field is set when the previous version of this module was a
// Refresh Boundary, letting us know we need to check for invalidation or
// enqueue an update.
if (prevExports !== null) {
// A boundary can become ineligible if its exports are incompatible
// with the previous exports.
//
// For example, if you add/remove/change exports, we'll want to
// re-execute the importing modules, and force those components to
// re-render. Similarly, if you convert a class component to a
// function, we want to invalidate the boundary.
if (
helpers.shouldInvalidateReactRefreshBoundary(
prevExports,
currentExports
)
) {
module.hot.invalidate();
} else {
helpers.scheduleUpdate();
}
}
} else {
// Since we just executed the code for the module, it's possible that the
// new exports made it ineligible for being a boundary.
// We only care about the case when we were _previously_ a boundary,
// because we already accepted this update (accidental side effect).
const isNoLongerABoundary = prevExports !== null;
if (isNoLongerABoundary) {
module.hot.invalidate();
}
}
}
/**
* @param {ModuleId[]} dependencyChain
* @returns {string}
*/
function formatDependencyChain(dependencyChain) {
return `Dependency chain: ${dependencyChain.join(" -> ")}`;
}
/**
* @param {EcmascriptModuleEntry} entry
* @returns {ModuleFactory}
* @private
*/
function _eval({ code, url, map }) {
code += `\n\n//# sourceURL=${location.origin}${url}`;
if (map) code += `\n//# sourceMappingURL=${map}`;
return eval(code);
}
/**
* @param {Map<ModuleId, EcmascriptModuleEntry | undefined>} added
* @param {Map<ModuleId, EcmascriptModuleEntry>} modified
* @returns {{outdatedModules: Set<any>, newModuleFactories: Map<any, any>}}
*/
function computeOutdatedModules(added, modified) {
const outdatedModules = new Set();
const newModuleFactories = new Map();
for (const [moduleId, entry] of added) {
if (entry != null) {
newModuleFactories.set(moduleId, _eval(entry));
}
}
for (const [moduleId, entry] of modified) {
const effect = getAffectedModuleEffects(moduleId);
switch (effect.type) {
case "unaccepted":
throw new Error(
`cannot apply update: unaccepted module. ${formatDependencyChain(
effect.dependencyChain
)}.`
);
case "self-declined":
throw new Error(
`cannot apply update: self-declined module. ${formatDependencyChain(
effect.dependencyChain
)}.`
);
case "accepted":
newModuleFactories.set(moduleId, _eval(entry));
for (const outdatedModuleId of effect.outdatedModules) {
outdatedModules.add(outdatedModuleId);
}
break;
// TODO(alexkirsz) Dependencies: handle dependencies effects.
}
}
return { outdatedModules, newModuleFactories };
}
/**
* @param {Iterable<ModuleId>} outdatedModules
* @returns {{ moduleId: ModuleId, errorHandler: true | Function }[]}
*/
function computeOutdatedSelfAcceptedModules(outdatedModules) {
const outdatedSelfAcceptedModules = [];
for (const moduleId of outdatedModules) {
const module = moduleCache[moduleId];
const hotState = moduleHotState.get(module);
if (module && hotState.selfAccepted && !hotState.selfInvalidated) {
outdatedSelfAcceptedModules.push({
moduleId,
errorHandler: hotState.selfAccepted,
});
}
}
return outdatedSelfAcceptedModules;
}
/**
* Adds, deletes, and moves modules between chunks. This must happen before the
* dispose phase as it needs to know which modules were removed from all chunks,
* which we can only compute *after* taking care of added and moved modules.
*
* @param {Map<ChunkPath, Set<ModuleId>>} chunksAddedModules
* @param {Map<ChunkPath, Set<ModuleId>>} chunksDeletedModules
* @returns {{ disposedModules: Set<ModuleId> }}
*/
function updateChunksPhase(chunksAddedModules, chunksDeletedModules) {
for (const [chunkPath, addedModuleIds] of chunksAddedModules) {
for (const moduleId of addedModuleIds) {
addModuleToChunk(moduleId, chunkPath);
}
}
const disposedModules = new Set();
for (const [chunkPath, addedModuleIds] of chunksDeletedModules) {
for (const moduleId of addedModuleIds) {
if (removeModuleFromChunk(moduleId, chunkPath)) {
disposedModules.add(moduleId);
}
}
}
return { disposedModules };
}
/**
* @param {Iterable<ModuleId>} outdatedModules
* @param {Set<ModuleId>} disposedModules
* @return {{ outdatedModuleParents: Map<ModuleId, Array<ModuleId>> }}
*/
function disposePhase(outdatedModules, disposedModules) {
for (const moduleId of outdatedModules) {
disposeModule(moduleId, "replace");
}
for (const moduleId of disposedModules) {
disposeModule(moduleId, "clear");
}
// Removing modules from the module cache is a separate step.
// We also want to keep track of previous parents of the outdated modules.
const outdatedModuleParents = new Map();
for (const moduleId of outdatedModules) {
const oldModule = moduleCache[moduleId];
outdatedModuleParents.set(moduleId, oldModule?.parents);
delete moduleCache[moduleId];
}
// TODO(alexkirsz) Dependencies: remove outdated dependency from module
// children.
return { outdatedModuleParents };
}
/**
* Disposes of an instance of a module.
*
* Returns the persistent hot data that should be kept for the next module
* instance.
*
* NOTE: mode = "replace" will not remove modules from the moduleCache.
* This must be done in a separate step afterwards.
* This is important because all modules need to be diposed to update the
* parent/child relationships before they are actually removed from the moduleCache.
* If this would be done in this method, following disposeModulecalls won't find
* the module from the module id in the cache.
*
* @param {ModuleId} moduleId
* @param {"clear" | "replace"} mode
*/
function disposeModule(moduleId, mode) {
const module = moduleCache[moduleId];
if (!module) {
return;
}
const hotState = moduleHotState.get(module);
const data = {};
// Run the `hot.dispose` handler, if any, passing in the persistent
// `hot.data` object.
for (const disposeHandler of hotState.disposeHandlers) {
disposeHandler(data);
}
// This used to warn in `getOrInstantiateModuleFromParent` when a disposed
// module is still importing other modules.
module.hot.active = false;
moduleHotState.delete(module);
// TODO(alexkirsz) Dependencies: delete the module from outdated deps.
// Remove the disposed module from its children's parents list.
// It will be added back once the module re-instantiates and imports its
// children again.
for (const childId of module.children) {
const child = moduleCache[childId];
if (!child) {
continue;
}
const idx = child.parents.indexOf(module.id);
if (idx >= 0) {
child.parents.splice(idx, 1);
}
}
switch (mode) {
case "clear":
delete moduleCache[module.id];
moduleHotData.delete(module.id);
break;
case "replace":
moduleHotData.set(module.id, data);
break;
default:
invariant(mode, (mode) => `invalid mode: ${mode}`);
}
}
/**
*
* @param {{ moduleId: ModuleId, errorHandler: true | Function }[]} outdatedSelfAcceptedModules
* @param {Map<ModuleId, ModuleFactory>} newModuleFactories
* @param {Map<ModuleId, Array<ModuleId>>} outdatedModuleParents
*/
function applyPhase(
outdatedSelfAcceptedModules,
newModuleFactories,
outdatedModuleParents
) {
// Update module factories.
for (const [moduleId, factory] of newModuleFactories.entries()) {
moduleFactories[moduleId] = factory;
}
// TODO(alexkirsz) Run new runtime entries here.
// TODO(alexkirsz) Dependencies: call accept handlers for outdated deps.
// Re-instantiate all outdated self-accepted modules.
for (const { moduleId, errorHandler } of outdatedSelfAcceptedModules) {
try {
instantiateModule(moduleId, {
type: SourceTypeUpdate,
parents: outdatedModuleParents.get(moduleId),
});
} catch (err) {
if (typeof errorHandler === "function") {
try {
errorHandler(err, { moduleId, module: moduleCache[moduleId] });
} catch (_) {
// Ignore error.
}
}
}
}
}
/**
* Utility function to ensure all variants of an enum are handled.
* @param {never} never
* @param {(arg: any) => string} computeMessage
* @returns {never}
*/
function invariant(never, computeMessage) {
throw new Error(`Invariant: ${computeMessage(never)}`);
}
/**
*
* @param {ChunkPath} chunkListPath
* @param {PartialUpdate} update
*/
function applyUpdate(chunkListPath, update) {
switch (update.type) {
case "ChunkListUpdate":
applyChunkListUpdate(chunkListPath, update);
break;
default:
invariant(update, (update) => `Unknown update type: ${update.type}`);
}
}
/**
*
* @param {ChunkPath} chunkListPath
* @param {ChunkListUpdate} update
*/
function applyChunkListUpdate(chunkListPath, update) {
if (update.merged != null) {
for (const merged of update.merged) {
switch (merged.type) {
case "EcmascriptMergedUpdate":
applyEcmascriptMergedUpdate(chunkListPath, merged);
break;
default:
invariant(merged, (merged) => `Unknown merged type: ${merged.type}`);
}
}
}
if (update.chunks != null) {
for (const [chunkPath, chunkUpdate] of Object.entries(update.chunks)) {
switch (chunkUpdate.type) {
case "added":
BACKEND.loadChunk(chunkPath, { type: SourceTypeUpdate });
break;
case "total":
BACKEND.reloadChunk?.(chunkPath);
break;
case "deleted":
BACKEND.unloadChunk?.(chunkPath);
break;
case "partial":
invariant(
chunkUpdate.instruction,
(instruction) =>
`Unknown partial instruction: ${JSON.stringify(instruction)}.`
);
default:
invariant(
chunkUpdate,
(chunkUpdate) => `Unknown chunk update type: ${chunkUpdate.type}`
);
}
}
}
}
/**
* @param {ChunkPath} chunkPath
* @param {EcmascriptMergedUpdate} update
*/
function applyEcmascriptMergedUpdate(chunkPath, update) {
const { entries = {}, chunks = {} } = update;
const { added, modified, deleted, chunksAdded, chunksDeleted } =
computeChangedModules(entries, chunks);
const { outdatedModules, newModuleFactories } = computeOutdatedModules(
added,
modified
);
const outdatedSelfAcceptedModules =
computeOutdatedSelfAcceptedModules(outdatedModules);
const { disposedModules } = updateChunksPhase(chunksAdded, chunksDeleted);
const { outdatedModuleParents } = disposePhase(
outdatedModules,
disposedModules
);
applyPhase(
outdatedSelfAcceptedModules,
newModuleFactories,
outdatedModuleParents
);
}
/**
* @param {Record<ModuleId, EcmascriptModuleEntry>} entries
* @param {Record<ChunkPath, EcmascriptMergedChunkUpdate>} updates
* @returns {{
* added: Map<ModuleId, EcmascriptModuleEntry | undefined>,
* modified: Map<ModuleId, EcmascriptModuleEntry>,
* deleted: Set<ModuleId>,
* chunksAdded: Map<ChunkPath, Set<ModuleId>>,
* chunksDeleted: Map<ChunkPath, Set<ModuleId>>,
* }}
*/
function computeChangedModules(entries, updates) {
const chunksAdded = new Map();
const chunksDeleted = new Map();
const added = new Map();
const modified = new Map();
const deleted = new Set();
for (const [chunkPath, mergedChunkUpdate] of Object.entries(updates)) {
switch (mergedChunkUpdate.type) {
case "added": {
const updateAdded = new Set(mergedChunkUpdate.modules);
for (const moduleId of updateAdded) {
added.set(moduleId, entries[moduleId]);
}
chunksAdded.set(chunkPath, updateAdded);
break;
}
case "deleted": {
// We could also use `mergedChunkUpdate.modules` here.
const updateDeleted = new Set(chunkModulesMap.get(chunkPath));
for (const moduleId of updateDeleted) {
deleted.add(moduleId);
}
chunksDeleted.set(chunkPath, updateDeleted);
break;
}
case "partial": {
const updateAdded = new Set(mergedChunkUpdate.added);
const updateDeleted = new Set(mergedChunkUpdate.deleted);
for (const moduleId of updateAdded) {
added.set(moduleId, entries[moduleId]);
}
for (const moduleId of updateDeleted) {
deleted.add([moduleId, chunkPath]);
}
chunksAdded.set(chunkPath, updateAdded);
chunksDeleted.set(chunkPath, updateDeleted);
break;
}
default:
invariant(
mergedChunkUpdate,
(mergedChunkUpdate) =>
`Unknown merged chunk update type: ${mergedChunkUpdate.type}`
);
}
}
// If a module was added from one chunk and deleted from another in the same update,
// consider it to be modified, as it means the module was moved from one chunk to another
// AND has new code in a single update.
for (const moduleId of added.keys()) {
if (deleted.has(moduleId)) {
added.delete(moduleId);
deleted.delete(moduleId);
}
}
for (const [moduleId, entry] of Object.entries(entries)) {
// Modules that haven't been added to any chunk but have new code are considered
// to be modified.
// This needs to be under the previous loop, as we need it to get rid of modules
// that were added and deleted in the same update.
if (!added.has(moduleId)) {
modified.set(moduleId, entry);
}
}
return { added, deleted, modified, chunksAdded, chunksDeleted };
}
/**
*
* @param {ModuleId} moduleId
* @returns {ModuleEffect}
*/
function getAffectedModuleEffects(moduleId) {
const outdatedModules = new Set();
/** @typedef {{moduleId?: ModuleId, dependencyChain: ModuleId[]}} QueueItem */
/** @type {QueueItem[]} */
const queue = [
{
moduleId,
dependencyChain: [],
},
];
while (queue.length > 0) {
const { moduleId, dependencyChain } =
/** @type {QueueItem} */ queue.shift();
outdatedModules.add(moduleId);
// We've arrived at the runtime of the chunk, which means that nothing
// else above can accept this update.
if (moduleId === undefined) {
return {
type: "unaccepted",
dependencyChain,
};
}
const module = moduleCache[moduleId];
const hotState = moduleHotState.get(module);
if (
// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before.
!module || // The module accepted itself without invalidating globalThis.
// TODO is that right?
(hotState.selfAccepted && !hotState.selfInvalidated)
) {
continue;
}
if (hotState.selfDeclined) {
return {
type: "self-declined",
dependencyChain,
moduleId,
};
}
if (runtimeModules.has(moduleId)) {
queue.push({
moduleId: undefined,
dependencyChain: [...dependencyChain, moduleId],
});
continue;
}
for (const parentId of module.parents) {
const parent = moduleCache[parentId];
if (!parent) {
// TODO(alexkirsz) Is this even possible?
continue;
}
// TODO(alexkirsz) Dependencies: check accepted and declined
// dependencies here.
queue.push({
moduleId: parentId,