Unverified Commit 45f4b19c authored by Luke Sandberg's avatar Luke Sandberg Committed by GitHub

Store the Turbopack module cache in a Map (#98947)

Maps are faster than Objects for map-like usecases such as the module
cache

The one complexity is `require.cache` which exposes the module cache as
an object, this however is an extremely rare usecase, so we support it
via a runtime module that re-exposes the module cache as an Object using
a `Proxy`.

### Performance

Measured with `bench/module-cost` 

Module **execution** time — the phase that actually hits the cache:

| measurement | obj | map | delta | 95% CI | rel |
| --- | --- | --- | --- | --- | --- |
| client commonjs | 13.60 ms | 13.00 ms | **−0.60 ms** | [−0.65, −0.30]
| −4.4% |
| pages api commonjs | 21.59 ms | 20.64 ms | **−0.95 ms** | [−1.39,
−0.74] | −4.4% |
| pages api esm | 33.24 ms | 32.55 ms | **−0.69 ms** | [−1.06, −0.47] |
−2.1% |
| client esm | 20.55 ms | 20.60 ms | +0.05 ms | [−0.25, +0.30] | noise |


Caveat: this benchmark is a deep require chain that deliberately slams
this codepath, so this really just confirms the claim that Maps are
faster and this is relevant to the bundled codepaths.

---------
Co-authored-by: 's avatarClaude Opus 5 (1M context) <noreply@anthropic.com>
parent 8542feb8
...@@ -228,6 +228,7 @@ const summarizeDurations = (data) => { ...@@ -228,6 +228,7 @@ const summarizeDurations = (data) => {
average, average,
median, median,
percentile75, percentile75,
samples: durations,
} }
} }
......
/// <reference path="./runtime-base.ts" /> /// <reference path="./runtime-base.ts" />
/// <reference path="./dummy.ts" /> /// <reference path="./dummy.ts" />
const moduleCache: ModuleCache<Module> = {} const moduleCache: ModuleCache<Module> = new Map()
contextPrototype.c = moduleCache contextPrototype.c = moduleCache
/** /**
...@@ -13,7 +13,7 @@ function getOrInstantiateRuntimeModule( ...@@ -13,7 +13,7 @@ function getOrInstantiateRuntimeModule(
chunkPath: ChunkPath | undefined, chunkPath: ChunkPath | undefined,
moduleId: ModuleId moduleId: ModuleId
): Module { ): Module {
const module = moduleCache[moduleId] const module = moduleCache.get(moduleId)
if (module) { if (module) {
if (module.error) { if (module.error) {
throw module.error throw module.error
...@@ -33,7 +33,7 @@ function getOrInstantiateRuntimeModule( ...@@ -33,7 +33,7 @@ function getOrInstantiateRuntimeModule(
const getOrInstantiateModuleFromParent: GetOrInstantiateModuleFromParent< const getOrInstantiateModuleFromParent: GetOrInstantiateModuleFromParent<
Module Module
> = (id, sourceModule) => { > = (id, sourceModule) => {
const module = moduleCache[id] const module = moduleCache.get(id)
if (module) { if (module) {
if (module.error) { if (module.error) {
...@@ -61,7 +61,7 @@ function instantiateModule( ...@@ -61,7 +61,7 @@ function instantiateModule(
const module: Module = createModuleObject(id) const module: Module = createModuleObject(id)
const exports = module.exports const exports = module.exports
moduleCache[id] = module moduleCache.set(id, module)
// NOTE(alexkirsz) This can fail when the module encounters a runtime error. // NOTE(alexkirsz) This can fail when the module encounters a runtime error.
const context = new (Context as any as ContextConstructor<Module>)( const context = new (Context as any as ContextConstructor<Module>)(
......
...@@ -18,7 +18,7 @@ const devContextPrototype = Context.prototype as TurbopackDevContext ...@@ -18,7 +18,7 @@ const devContextPrototype = Context.prototype as TurbopackDevContext
/* eslint-disable @typescript-eslint/no-unused-vars */ /* eslint-disable @typescript-eslint/no-unused-vars */
// Assign browser's module cache and runtime modules to shared HMR state // Assign browser's module cache and runtime modules to shared HMR state
devModuleCache = Object.create(null) devModuleCache = new Map()
devContextPrototype.c = devModuleCache devContextPrototype.c = devModuleCache
runtimeModules = new Set() runtimeModules = new Set()
...@@ -90,7 +90,7 @@ function getOrInstantiateRuntimeModule( ...@@ -90,7 +90,7 @@ function getOrInstantiateRuntimeModule(
chunkPath: ChunkPath | undefined, chunkPath: ChunkPath | undefined,
moduleId: ModuleId moduleId: ModuleId
): HotModule { ): HotModule {
const module = devModuleCache[moduleId] const module = devModuleCache.get(moduleId)
if (module) { if (module) {
if (module.error) { if (module.error) {
throw module.error throw module.error
...@@ -115,7 +115,7 @@ const getOrInstantiateModuleFromParent: GetOrInstantiateModuleFromParent< ...@@ -115,7 +115,7 @@ const getOrInstantiateModuleFromParent: GetOrInstantiateModuleFromParent<
) )
} }
const module = devModuleCache[id] const module = devModuleCache.get(id)
if (sourceModule.children.indexOf(id) === -1) { if (sourceModule.children.indexOf(id) === -1) {
sourceModule.children.push(id) sourceModule.children.push(id)
......
...@@ -136,7 +136,7 @@ function applyEcmascriptMergedUpdate( ...@@ -136,7 +136,7 @@ function applyEcmascriptMergedUpdate(
// were moved to a renamed chunk. Treat them as modified so the dependency // were moved to a renamed chunk. Treat them as modified so the dependency
// walk runs and they get re-instantiated with the new factory. // walk runs and they get re-instantiated with the new factory.
for (const [moduleId, entry] of added) { for (const [moduleId, entry] of added) {
if (entry != null && devModuleCache[moduleId] != null) { if (entry != null && devModuleCache.has(moduleId)) {
added.delete(moduleId) added.delete(moduleId)
modified.set(moduleId, entry) modified.set(moduleId, entry)
} }
......
...@@ -44,7 +44,7 @@ function instantiateModule( ...@@ -44,7 +44,7 @@ function instantiateModule(
const module: ModuleWithDirection = createModuleWithDirection(id) const module: ModuleWithDirection = createModuleWithDirection(id)
const exports = module.exports const exports = module.exports
moduleCache[id] = module moduleCache.set(id, module)
const context = const context =
new (Context as any as ContextConstructor<ModuleWithDirection>)( new (Context as any as ContextConstructor<ModuleWithDirection>)(
...@@ -76,7 +76,7 @@ function getOrInstantiateModuleFromParent( ...@@ -76,7 +76,7 @@ function getOrInstantiateModuleFromParent(
id: ModuleId, id: ModuleId,
sourceModule: ModuleWithDirection sourceModule: ModuleWithDirection
): ModuleWithDirection { ): ModuleWithDirection {
const module = moduleCache[id] const module = moduleCache.get(id)
if (module) { if (module) {
if (module.error) { if (module.error) {
...@@ -107,7 +107,7 @@ function getOrInstantiateRuntimeModule( ...@@ -107,7 +107,7 @@ function getOrInstantiateRuntimeModule(
chunkPath: ChunkPath, chunkPath: ChunkPath,
moduleId: ModuleId moduleId: ModuleId
): ModuleWithDirection { ): ModuleWithDirection {
const module = moduleCache[moduleId] const module = moduleCache.get(moduleId)
if (module) { if (module) {
if (module.error) { if (module.error) {
......
...@@ -130,7 +130,7 @@ function getOrInstantiateRuntimeModule( ...@@ -130,7 +130,7 @@ function getOrInstantiateRuntimeModule(
chunkPath: ChunkPath, chunkPath: ChunkPath,
moduleId: ModuleId moduleId: ModuleId
): HotModule { ): HotModule {
const module = devModuleCache[moduleId] const module = devModuleCache.get(moduleId)
if (module) { if (module) {
if (module.error) { if (module.error) {
...@@ -152,9 +152,8 @@ function getOrInstantiateModuleFromParent( ...@@ -152,9 +152,8 @@ function getOrInstantiateModuleFromParent(
sourceModule: HotModule sourceModule: HotModule
): HotModule { ): HotModule {
// Track parent-child relationship // Track parent-child relationship
trackModuleImport(sourceModule, id, devModuleCache[id]) const module = devModuleCache.get(id)
trackModuleImport(sourceModule, id, module)
const module = devModuleCache[id]
if (module) { if (module) {
if (module.error) { if (module.error) {
......
...@@ -15,7 +15,7 @@ process.env.TURBOPACK = '1' ...@@ -15,7 +15,7 @@ process.env.TURBOPACK = '1'
const url = require('url') as typeof import('url') const url = require('url') as typeof import('url')
const moduleFactories: ModuleFactories = new Map() const moduleFactories: ModuleFactories = new Map()
const moduleCache: ModuleCache<Module> = Object.create(null) const moduleCache: ModuleCache<Module> = new Map()
/** /**
* Returns an absolute path to the given module's id. * Returns an absolute path to the given module's id.
......
'use turbopack: no side effects'
/**
* `require.cache` compatibility shim.
*
* The runtime stores instantiated modules in a `Map` (see `ModuleCache` in
* `runtime-types.d.ts`), but `require.cache` is specified as a object, so we
* use a Proxy to paper over the deltas
*/
// Access the module cache through the magic context param
// Technically it is also available as a global, but it would be difficult to name.
declare const __turbopack_context__: { c: Map<ModuleId, unknown>; m: Module }
const moduleCache = __turbopack_context__.c
/**
* Property keys always reach a `Proxy` trap as strings, but `ModuleId` is
* `string | number` and the id kind is fixed for a build: either every id is a
* number or every id is a string. Detect this by testing our own id.
*/
const idsAreNumeric = typeof __turbopack_context__.m.id === 'number'
// Coerce a string object propty to a ModuleId so it can match the cache.
function toKey(key: string): ModuleId {
if (!idsAreNumeric) return key
// A non-canonical spelling (`"0123"`, `"1e3"`, `" 1"`) is not any module's
// id, so leave it as a string: it will simply miss, as it would have against
// the object cache. Without this "1x" would coerce to 1 which might match a module, incorrectly
const numeric = Number(key)
return String(numeric) === key ? numeric : key
}
export const cache: Record<string, unknown> = new Proxy(
// Use an empty object as the 'target' so we can implement ownKeys
{} as Record<string, unknown>,
{
get(_target, key) {
if (typeof key !== 'string') return undefined
return moduleCache.get(toKey(key))
},
set(_target, key, value) {
if (typeof key !== 'string') return false
moduleCache.set(toKey(key), value)
return true
},
has(_target, key) {
return typeof key === 'string' && moduleCache.has(toKey(key))
},
deleteProperty(_target, key) {
if (typeof key !== 'string') return false
moduleCache.delete(toKey(key))
return true
},
ownKeys() {
return Array.from(moduleCache.keys(), String)
},
// `ownKeys` alone is not enough: `Object.keys()` filters by enumerability, so
// it invokes this trap for every key returned above.
getOwnPropertyDescriptor(_target, key) {
if (typeof key !== 'string') return undefined
const id = toKey(key)
if (!moduleCache.has(id)) return undefined
return {
value: moduleCache.get(id),
writable: true,
enumerable: true,
configurable: true,
}
},
}
)
...@@ -21,7 +21,7 @@ type HotModuleFactoryFunction = ModuleFactoryFunction< ...@@ -21,7 +21,7 @@ type HotModuleFactoryFunction = ModuleFactoryFunction<
* Browser runtime declares this directly. * Browser runtime declares this directly.
* Node.js runtime assigns globalThis.__turbopack_module_cache__ to this. * Node.js runtime assigns globalThis.__turbopack_module_cache__ to this.
*/ */
let devModuleCache: Record<ModuleId, any> let devModuleCache: ModuleCache<any>
/** /**
* Module IDs that are instantiated as part of the runtime of a chunk. * Module IDs that are instantiated as part of the runtime of a chunk.
...@@ -161,7 +161,7 @@ function getAffectedModuleEffects( ...@@ -161,7 +161,7 @@ function getAffectedModuleEffects(
} }
} }
const module = devModuleCache[moduleId] const module = devModuleCache.get(moduleId)
const hotState = moduleHotState.get(module)! const hotState = moduleHotState.get(module)!
if ( if (
...@@ -194,7 +194,7 @@ function getAffectedModuleEffects( ...@@ -194,7 +194,7 @@ function getAffectedModuleEffects(
} }
for (const parentId of module.parents) { for (const parentId of module.parents) {
const parent = devModuleCache[parentId] const parent = devModuleCache.get(parentId)
if (!parent) { if (!parent) {
continue continue
...@@ -461,7 +461,7 @@ function computeOutdatedSelfAcceptedModules( ...@@ -461,7 +461,7 @@ function computeOutdatedSelfAcceptedModules(
errorHandler: true | Function errorHandler: true | Function
}[] = [] }[] = []
for (const moduleId of outdatedModules) { for (const moduleId of outdatedModules) {
const module = devModuleCache[moduleId] const module = devModuleCache.get(moduleId)
const hotState = moduleHotState.get(module) const hotState = moduleHotState.get(module)
if (module && hotState?.selfAccepted && !hotState.selfInvalidated) { if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {
outdatedSelfAcceptedModules.push({ outdatedSelfAcceptedModules.push({
...@@ -481,7 +481,7 @@ function computeOutdatedSelfAcceptedModules( ...@@ -481,7 +481,7 @@ function computeOutdatedSelfAcceptedModules(
* This must be done in a separate step afterwards. * This must be done in a separate step afterwards.
*/ */
function disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') { function disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') {
const module = devModuleCache[moduleId] const module = devModuleCache.get(moduleId)
if (!module) { if (!module) {
return return
} }
...@@ -511,7 +511,7 @@ function disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') { ...@@ -511,7 +511,7 @@ function disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') {
// It will be added back once the module re-instantiates and imports its // It will be added back once the module re-instantiates and imports its
// children again. // children again.
for (const childId of module.children) { for (const childId of module.children) {
const child = devModuleCache[childId] const child = devModuleCache.get(childId)
if (!child) { if (!child) {
continue continue
} }
...@@ -524,7 +524,7 @@ function disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') { ...@@ -524,7 +524,7 @@ function disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') {
switch (mode) { switch (mode) {
case 'clear': case 'clear':
delete devModuleCache[module.id] devModuleCache.delete(module.id)
moduleHotData.delete(module.id) moduleHotData.delete(module.id)
break break
case 'replace': case 'replace':
...@@ -557,9 +557,9 @@ function disposePhase( ...@@ -557,9 +557,9 @@ function disposePhase(
// We also want to keep track of previous parents of the outdated modules. // We also want to keep track of previous parents of the outdated modules.
const outdatedModuleParents = new Map<ModuleId, Array<ModuleId>>() const outdatedModuleParents = new Map<ModuleId, Array<ModuleId>>()
for (const moduleId of outdatedModules) { for (const moduleId of outdatedModules) {
const oldModule = devModuleCache[moduleId] const oldModule = devModuleCache.get(moduleId)
outdatedModuleParents.set(moduleId, oldModule?.parents) outdatedModuleParents.set(moduleId, oldModule?.parents)
delete devModuleCache[moduleId] devModuleCache.delete(moduleId)
} }
// Remove outdated dependencies from parent module's children list. // Remove outdated dependencies from parent module's children list.
...@@ -567,7 +567,7 @@ function disposePhase( ...@@ -567,7 +567,7 @@ function disposePhase(
// but the parent stays alive. We remove the old child reference so it // but the parent stays alive. We remove the old child reference so it
// gets re-added when the child re-imports. // gets re-added when the child re-imports.
for (const [parentId, deps] of outdatedDependencies) { for (const [parentId, deps] of outdatedDependencies) {
const module = devModuleCache[parentId] const module = devModuleCache.get(parentId)
if (module) { if (module) {
for (const dep of deps) { for (const dep of deps) {
const idx = module.children.indexOf(dep) const idx = module.children.indexOf(dep)
...@@ -642,7 +642,7 @@ function instantiateModuleShared( ...@@ -642,7 +642,7 @@ function instantiateModuleShared(
module.children = [] module.children = []
module.hot = hot module.hot = hot
devModuleCache[id] = module devModuleCache.set(id, module)
moduleHotState.set(module, hotState) moduleHotState.set(module, hotState)
// 5. Module execution (React Refresh hooks are platform-specific) // 5. Module execution (React Refresh hooks are platform-specific)
...@@ -825,7 +825,7 @@ function applyPhase( ...@@ -825,7 +825,7 @@ function applyPhase(
// This runs BEFORE re-instantiating self-accepted modules, matching // This runs BEFORE re-instantiating self-accepted modules, matching
// webpack's behavior. // webpack's behavior.
for (const [parentId, deps] of outdatedDependencies) { for (const [parentId, deps] of outdatedDependencies) {
const module = devModuleCache[parentId] const module = devModuleCache.get(parentId)
if (!module) continue if (!module) continue
const hotState = moduleHotState.get(module) const hotState = moduleHotState.get(module)
...@@ -888,7 +888,7 @@ function applyPhase( ...@@ -888,7 +888,7 @@ function applyPhase(
} catch (err) { } catch (err) {
if (typeof errorHandler === 'function') { if (typeof errorHandler === 'function') {
try { try {
errorHandler(err, { moduleId, module: devModuleCache[moduleId] }) errorHandler(err, { moduleId, module: devModuleCache.get(moduleId) })
} catch (err2) { } catch (err2) {
reportError(err2) reportError(err2)
reportError(err) reportError(err)
......
...@@ -92,7 +92,10 @@ type DynamicExport = ( ...@@ -92,7 +92,10 @@ type DynamicExport = (
type LoadChunk = (chunkPath: ChunkPath) => Promise<any> | undefined type LoadChunk = (chunkPath: ChunkPath) => Promise<any> | undefined
type LoadChunkByUrl = (chunkUrl: ChunkUrl) => Promise<any> | undefined type LoadChunkByUrl = (chunkUrl: ChunkUrl) => Promise<any> | undefined
type ModuleCache<M> = Record<ModuleId, M> /**
* The runtime's module cache. Stores the memoized 'Module' object for each instantiated module.
*/
type ModuleCache<M> = Map<ModuleId, M>
// TODO properly type values here // TODO properly type values here
type ModuleFactories = Map<ModuleId, Function> type ModuleFactories = Map<ModuleId, Function>
/** /**
......
...@@ -118,15 +118,15 @@ function getOverwrittenModule( ...@@ -118,15 +118,15 @@ function getOverwrittenModule(
moduleCache: ModuleCache<Module>, moduleCache: ModuleCache<Module>,
id: ModuleId id: ModuleId
): Module { ): Module {
let module = moduleCache[id] let module = moduleCache.get(id)
if (!module) { if (module === undefined) {
if (createModuleWithDirectionFlag) { if (createModuleWithDirectionFlag) {
// set in development modes for hmr support // set in development modes for hmr support
module = createModuleWithDirection(id) module = createModuleWithDirection(id)
} else { } else {
module = createModuleObject(id) module = createModuleObject(id)
} }
moduleCache[id] = module moduleCache.set(id, module)
} }
return module return module
} }
......
...@@ -41,7 +41,8 @@ pub async fn embed_static_code( ...@@ -41,7 +41,8 @@ pub async fn embed_static_code(
/// Returns an [ImportMap] containing: /// Returns an [ImportMap] containing:
/// - The `@vercel/turbopack-ecmascript-runtime/*` wildcard alias pointing to the embedded runtime /// - The `@vercel/turbopack-ecmascript-runtime/*` wildcard alias pointing to the embedded runtime
/// filesystem. /// filesystem.
/// - All built-in `@turbopack/*` module aliases (e.g. `@turbopack/base64`). /// - All built-in `@turbopack/*` module aliases (e.g. `@turbopack/base64`,
/// `@turbopack/module-cache`).
/// ///
/// This import map is injected automatically by /// This import map is injected automatically by
/// [`ModuleAssetContext::resolve_options`] so that every Turbopack-processed /// [`ModuleAssetContext::resolve_options`] so that every Turbopack-processed
...@@ -64,7 +65,14 @@ pub async fn turbopack_runtime_import_map() -> Result<Vc<ImportMap>> { ...@@ -64,7 +65,14 @@ pub async fn turbopack_runtime_import_map() -> Result<Vc<ImportMap>> {
// Exact alias: @turbopack/base64 // Exact alias: @turbopack/base64
import_map.insert_exact_alias( import_map.insert_exact_alias(
rcstr!("@turbopack/base64"), rcstr!("@turbopack/base64"),
ImportMapping::PrimaryAlternative(rcstr!("./shared/base64.ts"), Some(embed_root)) ImportMapping::PrimaryAlternative(rcstr!("./shared/base64.ts"), Some(embed_root.clone()))
.resolved_cell(),
);
// Exact alias: @turbopack/module-cache
import_map.insert_exact_alias(
rcstr!("@turbopack/module-cache"),
ImportMapping::PrimaryAlternative(rcstr!("./shared/module-cache.ts"), Some(embed_root))
.resolved_cell(), .resolved_cell(),
); );
......
...@@ -21,7 +21,7 @@ use crate::{ ...@@ -21,7 +21,7 @@ use crate::{
references::{ references::{
amd::AmdDefineWithDependenciesCodeGen, amd::AmdDefineWithDependenciesCodeGen,
cjs::{ cjs::{
CjsExportsDropCodeGen, CjsRequireAssetReferenceCodeGen, CjsRequireCacheAccess, CjsExportsDropCodeGen, CjsRequireAssetReferenceCodeGen,
CjsRequireResolveAssetReferenceCodeGen, CjsRequireResolveAssetReferenceCodeGen,
}, },
constant_condition::ConstantConditionCodeGen, constant_condition::ConstantConditionCodeGen,
...@@ -184,7 +184,6 @@ pub enum CodeGen { ...@@ -184,7 +184,6 @@ pub enum CodeGen {
// AMD occurs very rarely and makes the enum much bigger // AMD occurs very rarely and makes the enum much bigger
AmdDefineWithDependenciesCodeGen(Box<AmdDefineWithDependenciesCodeGen>), AmdDefineWithDependenciesCodeGen(Box<AmdDefineWithDependenciesCodeGen>),
CollectReferenceCodeGen(CollectReferenceCodeGen), CollectReferenceCodeGen(CollectReferenceCodeGen),
CjsRequireCacheAccess(CjsRequireCacheAccess),
ConstantConditionCodeGen(ConstantConditionCodeGen), ConstantConditionCodeGen(ConstantConditionCodeGen),
ConstantValueCodeGen(ConstantValueCodeGen), ConstantValueCodeGen(ConstantValueCodeGen),
DynamicExpression(DynamicExpression), DynamicExpression(DynamicExpression),
...@@ -222,7 +221,6 @@ impl CodeGen { ...@@ -222,7 +221,6 @@ impl CodeGen {
) -> Result<CodeGeneration> { ) -> Result<CodeGeneration> {
match self { match self {
Self::AmdDefineWithDependenciesCodeGen(v) => v.code_generation(trie, ctx).await, Self::AmdDefineWithDependenciesCodeGen(v) => v.code_generation(trie, ctx).await,
Self::CjsRequireCacheAccess(v) => v.code_generation(trie, ctx).await,
Self::ConstantConditionCodeGen(v) => v.code_generation(trie, ctx).await, Self::ConstantConditionCodeGen(v) => v.code_generation(trie, ctx).await,
Self::CollectReferenceCodeGen(v) => v.code_generation(trie, ctx).await, Self::CollectReferenceCodeGen(v) => v.code_generation(trie, ctx).await,
Self::ConstantValueCodeGen(v) => v.code_generation(trie, ctx).await, Self::ConstantValueCodeGen(v) => v.code_generation(trie, ctx).await,
......
...@@ -35,7 +35,6 @@ use crate::{ ...@@ -35,7 +35,6 @@ use crate::{
pattern_mapping::{PatternMapping, ResolveType}, pattern_mapping::{PatternMapping, ResolveType},
util::SpecifiedChunkingType, util::SpecifiedChunkingType,
}, },
runtime_functions::TURBOPACK_CACHE,
}; };
/// Generic CommonJS reference that doesn't perform any codegen. Used for tracing /// Generic CommonJS reference that doesn't perform any codegen. Used for tracing
...@@ -401,45 +400,6 @@ impl CjsRequireResolveAssetReferenceCodeGen { ...@@ -401,45 +400,6 @@ impl CjsRequireResolveAssetReferenceCodeGen {
} }
} }
#[derive(PartialEq, Eq, ValueDebugFormat, NonLocalValue, Debug, Hash, Encode, Decode)]
pub struct CjsRequireCacheAccess {
pub path: AstPathId,
}
impl CjsRequireCacheAccess {
pub fn new(path: AstPathId) -> Self {
CjsRequireCacheAccess { path }
}
pub async fn code_generation(
&self,
trie: &AstPathTrie,
_chunking_context: Vc<Box<dyn ChunkingContext>>,
) -> Result<CodeGeneration> {
let mut visitors = Vec::new();
visitors.push(create_visitor!(
trie,
self.path,
visit_mut_expr,
|expr: &mut Expr| {
if let Expr::Member(_) = expr {
*expr = TURBOPACK_CACHE.into();
} else {
unreachable!("`CjsRequireCacheAccess` is only created from `MemberExpr`");
}
}
));
Ok(CodeGeneration::visitors(visitors))
}
}
impl From<CjsRequireCacheAccess> for CodeGen {
fn from(val: CjsRequireCacheAccess) -> Self {
CodeGen::CjsRequireCacheAccess(val)
}
}
/// Removes each named CommonJS export the module graph proved unused. Built by the /// Removes each named CommonJS export the module graph proved unused. Built by the
/// analyzer for statically-analyzable CommonJS modules; recognition happens inline /// analyzer for statically-analyzable CommonJS modules; recognition happens inline
/// during the walk (see `analyzer::graph::visitor`). /// during the walk (see `analyzer::graph::visitor`).
......
...@@ -124,10 +124,7 @@ use crate::{ ...@@ -124,10 +124,7 @@ use crate::{
AmdDefineWithDependenciesCodeGen, AmdDefineWithDependenciesCodeGen,
}, },
async_module::{AsyncModule, OptionAsyncModule}, async_module::{AsyncModule, OptionAsyncModule},
cjs::{ cjs::{CjsAssetReference, CjsRequireAssetReference, CjsRequireResolveAssetReference},
CjsAssetReference, CjsRequireAssetReference, CjsRequireCacheAccess,
CjsRequireResolveAssetReference,
},
cross_module_constants::{ cross_module_constants::{
is_import_name_eligible_for_exports, module_value_to_constants_module, is_import_name_eligible_for_exports, module_value_to_constants_module,
}, },
...@@ -3663,16 +3660,33 @@ async fn handle_membership<'a>( ...@@ -3663,16 +3660,33 @@ async fn handle_membership<'a>(
if is_prop_cache if is_prop_cache
&& let JsValue::WellKnownFunction(WellKnownFunctionKind::Require) = &obj && let JsValue::WellKnownFunction(WellKnownFunctionKind::Require) = &obj
{ {
analysis.add_code_gen::<CodeGen>(match ty { match ty {
MembershipType::Member { .. } => { MembershipType::Member { .. } => {
CjsRequireCacheAccess::new(analysis.intern_path(ast_path)).into() // Only add references if we are performing codegen
if analysis.analyze_mode.is_codegen {
handle_free_var_reference(
ast_path,
// Import the `cache` proxy wrapper helper to satisfy require.cache
// This re-exposes the `Map` the runtime uses as a object.
&FreeVarReference::EcmaScriptModule {
request: rcstr!("@turbopack/module-cache"),
lookup_path: None,
export: Some(rcstr!("cache")),
},
span,
state,
analysis,
)
.await?;
}
} }
MembershipType::In => ConstantValueCodeGen::new( MembershipType::In => {
CompileTimeDefineValue::Bool(true), analysis.add_code_gen(ConstantValueCodeGen::new(
analysis.intern_path(ast_path), CompileTimeDefineValue::Bool(true),
) analysis.intern_path(ast_path),
.into(), ));
}); }
}
return Ok(()); return Ok(());
} }
} }
......
...@@ -99,14 +99,13 @@ pub const TURBOPACK_ASSET_SUFFIX: &TurbopackRuntimeFunctionShortcut = make_short ...@@ -99,14 +99,13 @@ pub const TURBOPACK_ASSET_SUFFIX: &TurbopackRuntimeFunctionShortcut = make_short
/// Adding an entry to this list will automatically ensure that `__turbopack_XXX__` can be called /// Adding an entry to this list will automatically ensure that `__turbopack_XXX__` can be called
/// from user code (by inserting a replacement into free_var_references) /// from user code (by inserting a replacement into free_var_references)
pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctionShortcut); 25] = [ pub const TURBOPACK_RUNTIME_FUNCTION_SHORTCUTS: [(&str, &TurbopackRuntimeFunctionShortcut); 24] = [
("__turbopack_require__", TURBOPACK_REQUIRE), ("__turbopack_require__", TURBOPACK_REQUIRE),
("__turbopack_module_context__", TURBOPACK_MODULE_CONTEXT), ("__turbopack_module_context__", TURBOPACK_MODULE_CONTEXT),
("__turbopack_import__", TURBOPACK_IMPORT), ("__turbopack_import__", TURBOPACK_IMPORT),
("__turbopack_export_value__", TURBOPACK_EXPORT_VALUE), ("__turbopack_export_value__", TURBOPACK_EXPORT_VALUE),
("__turbopack_export_url__", TURBOPACK_EXPORT_URL), ("__turbopack_export_url__", TURBOPACK_EXPORT_URL),
("__turbopack_export_namespace__", TURBOPACK_EXPORT_NAMESPACE), ("__turbopack_export_namespace__", TURBOPACK_EXPORT_NAMESPACE),
("__turbopack_cache__", TURBOPACK_CACHE),
("__turbopack_modules__", TURBOPACK_MODULES), ("__turbopack_modules__", TURBOPACK_MODULES),
("__turbopack_load__", TURBOPACK_LOAD), ("__turbopack_load__", TURBOPACK_LOAD),
("__turbopack_load_by_url__", TURBOPACK_LOAD_BY_URL), ("__turbopack_load_by_url__", TURBOPACK_LOAD_BY_URL),
......
...@@ -290,6 +290,10 @@ struct TestOptions { ...@@ -290,6 +290,10 @@ struct TestOptions {
production_chunking: bool, production_chunking: bool,
#[serde(default)] #[serde(default)]
global_module_ids: bool, global_module_ids: bool,
/// Assign numeric module ids, as production builds do, instead of the
/// human-readable ident-based ids tests use by default.
#[serde(default)]
numeric_module_ids: bool,
/// Packages that are assumed to be side effect free, unless they declare otherwise in their /// Packages that are assumed to be side effect free, unless they declare otherwise in their
/// package.json. /// package.json.
#[serde(default)] #[serde(default)]
...@@ -321,6 +325,7 @@ impl Default for TestOptions { ...@@ -321,6 +325,7 @@ impl Default for TestOptions {
minify: false, minify: false,
production_chunking: false, production_chunking: false,
global_module_ids: false, global_module_ids: false,
numeric_module_ids: false,
side_effect_free_packages: Vec::new(), side_effect_free_packages: Vec::new(),
server_relative_root: default_true(), server_relative_root: default_true(),
} }
...@@ -607,7 +612,10 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V ...@@ -607,7 +612,10 @@ async fn run_test_operation(prepared_test: ResolvedVc<PreparedTest>) -> Result<V
None None
}); });
if options.global_module_ids { // Production builds assign numeric module ids; the default ident-based ids are strings.
// Exercising both matters for code that keys off the module cache, since `ModuleId` is
// `string | number`.
if options.global_module_ids || options.numeric_module_ids {
builder = builder.module_id_strategy( builder = builder.module_id_strategy(
get_global_module_id_strategy(module_graph) get_global_module_id_strategy(module_graph)
.to_resolved() .to_resolved()
......
globalThis.depEvalCount = (globalThis.depEvalCount ?? 0) + 1
module.exports = { value: 'dep' }
// `require.cache` is exposed through the `@turbopack/module-cache` helper,
// which wraps the runtime's `Map` in a `Proxy` with object semantics.
it('should read entries with bracket access', () => {
const dep = require('./dep')
const id = require.resolve('./dep')
const entry = require.cache[id]
expect(entry).toBeDefined()
expect(entry.exports).toBe(dep)
})
it('should report membership with `in` and hasOwnProperty', () => {
require('./other')
const id = require.resolve('./other')
expect(id in require.cache).toBe(true)
expect(Object.prototype.hasOwnProperty.call(require.cache, id)).toBe(true)
expect('./definitely-not-a-module' in require.cache).toBe(false)
expect(require.cache['./definitely-not-a-module']).toBeUndefined()
})
it('should enumerate entries', () => {
require('./dep')
require('./other')
const depId = require.resolve('./dep')
const otherId = require.resolve('./other')
// Keys always come back as strings, even when module ids are numbers.
const keys = Object.keys(require.cache)
expect(keys).toContain(String(depId))
expect(keys).toContain(String(otherId))
// Object.values / entries / spread / for-in all go through the same
// ownKeys + getOwnPropertyDescriptor trap pair.
expect(Object.values(require.cache).length).toBe(keys.length)
expect(Object.entries(require.cache).length).toBe(keys.length)
expect(Object.keys({ ...require.cache }).length).toBe(keys.length)
const seen = []
for (const key in require.cache) {
seen.push(key)
}
expect(seen).toContain(String(depId))
})
it('should re-evaluate a module after its entry is deleted', () => {
const id = require.resolve('./dep')
// Earlier tests may already have instantiated `./dep`; start from a known
// state so the eval counter reflects only this test.
delete require.cache[id]
globalThis.depEvalCount = 0
require('./dep')
expect(globalThis.depEvalCount).toBe(1)
// Cached: not re-evaluated.
require('./dep')
expect(globalThis.depEvalCount).toBe(1)
delete require.cache[id]
expect(id in require.cache).toBe(false)
require('./dep')
expect(globalThis.depEvalCount).toBe(2)
})
it('should re-evaluate a module after its entry is assigned undefined', () => {
const id = require.resolve('./dep')
delete require.cache[id]
globalThis.depEvalCount = 0
require('./dep')
expect(globalThis.depEvalCount).toBe(1)
// Node keeps the key present but falsy; the runtime treats it as a miss.
require.cache[id] = undefined
expect(require.cache[id]).toBeUndefined()
require('./dep')
expect(globalThis.depEvalCount).toBe(2)
})
it('should keep a written entry reachable by require()', () => {
// A write has to store the key under the id type the runtime looks up with,
// not the string the Proxy trap received. Otherwise the entry is stranded:
// visible via `Object.keys`, but never found by `require()`.
//
// Re-insert the runtime's own module object rather than a hand-made one, so
// this exercises the key type without depending on a module's internal shape.
const id = require.resolve('./other')
require('./other')
const entry = require.cache[id]
expect(entry).toBeDefined()
delete require.cache[id]
expect(id in require.cache).toBe(false)
require.cache[id] = entry
expect(require.cache[id]).toBe(entry)
// The real proof: the runtime finds the re-inserted entry and returns its
// exports instead of re-instantiating the module.
expect(require('./other')).toBe(entry.exports)
})
globalThis.depEvalCount = (globalThis.depEvalCount ?? 0) + 1
module.exports = { value: 'dep' }
// Same suite as `../basic`, but built with numeric module ids (see
// options.json), which is what production builds use. Property keys reach a
// `Proxy` trap as strings, so the shim has to map `"123"` back onto the `123`
// key the `Map` actually holds.
it('should be running with numeric module ids', () => {
// Guards against this suite silently degrading into a copy of `../basic`
// if the id strategy ever stops applying.
const id = require.resolve('./dep')
expect(typeof id).toBe('number')
})
it('should read entries with bracket access', () => {
const dep = require('./dep')
const id = require.resolve('./dep')
const entry = require.cache[id]
expect(entry).toBeDefined()
expect(entry.exports).toBe(dep)
})
it('should report membership with `in` and hasOwnProperty', () => {
require('./other')
const id = require.resolve('./other')
expect(id in require.cache).toBe(true)
expect(Object.prototype.hasOwnProperty.call(require.cache, id)).toBe(true)
expect('./definitely-not-a-module' in require.cache).toBe(false)
expect(require.cache['./definitely-not-a-module']).toBeUndefined()
})
it('should enumerate entries', () => {
require('./dep')
require('./other')
const depId = require.resolve('./dep')
const otherId = require.resolve('./other')
// Keys always come back as strings, even when module ids are numbers.
const keys = Object.keys(require.cache)
expect(keys).toContain(String(depId))
expect(keys).toContain(String(otherId))
// Object.values / entries / spread / for-in all go through the same
// ownKeys + getOwnPropertyDescriptor trap pair.
expect(Object.values(require.cache).length).toBe(keys.length)
expect(Object.entries(require.cache).length).toBe(keys.length)
expect(Object.keys({ ...require.cache }).length).toBe(keys.length)
const seen = []
for (const key in require.cache) {
seen.push(key)
}
expect(seen).toContain(String(depId))
})
it('should re-evaluate a module after its entry is deleted', () => {
const id = require.resolve('./dep')
// Earlier tests may already have instantiated `./dep`; start from a known
// state so the eval counter reflects only this test.
delete require.cache[id]
globalThis.depEvalCount = 0
require('./dep')
expect(globalThis.depEvalCount).toBe(1)
// Cached: not re-evaluated.
require('./dep')
expect(globalThis.depEvalCount).toBe(1)
delete require.cache[id]
expect(id in require.cache).toBe(false)
require('./dep')
expect(globalThis.depEvalCount).toBe(2)
})
it('should re-evaluate a module after its entry is assigned undefined', () => {
const id = require.resolve('./dep')
delete require.cache[id]
globalThis.depEvalCount = 0
require('./dep')
expect(globalThis.depEvalCount).toBe(1)
// Node keeps the key present but falsy; the runtime treats it as a miss.
require.cache[id] = undefined
expect(require.cache[id]).toBeUndefined()
require('./dep')
expect(globalThis.depEvalCount).toBe(2)
})
it('should keep a written entry reachable by require()', () => {
// A write has to store the key under the id type the runtime looks up with,
// not the string the Proxy trap received. Otherwise the entry is stranded:
// visible via `Object.keys`, but never found by `require()`.
//
// Re-insert the runtime's own module object rather than a hand-made one, so
// this exercises the key type without depending on a module's internal shape.
const id = require.resolve('./other')
require('./other')
const entry = require.cache[id]
expect(entry).toBeDefined()
delete require.cache[id]
expect(id in require.cache).toBe(false)
require.cache[id] = entry
expect(require.cache[id]).toBe(entry)
// The real proof: the runtime finds the re-inserted entry and returns its
// exports instead of re-instantiating the module.
expect(require('./other')).toBe(entry.exports)
})
;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="976638d9-7f7b-0f2e-7bd5-80a2f6b9ac86")}catch(e){}}(); ;!function(){try { var e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{},n=(new e.Error).stack;n&&((e._debugIds|| (e._debugIds={}))[n]="c43766b6-b61f-49ce-2bc6-d270f17e82af")}catch(e){}}();
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([ (globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/0rv8_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js", "output/0rv8_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js",
{"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvsq4xsbk.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]} {"otherChunks":["output/0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_03ibyvsq4xsbk.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
...@@ -78,15 +78,15 @@ function defineProp(obj, name, options) { ...@@ -78,15 +78,15 @@ function defineProp(obj, name, options) {
if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options); if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options);
} }
function getOverwrittenModule(moduleCache, id) { function getOverwrittenModule(moduleCache, id) {
let module = moduleCache[id]; let module = moduleCache.get(id);
if (!module) { if (module === undefined) {
if (createModuleWithDirectionFlag) { if (createModuleWithDirectionFlag) {
// set in development modes for hmr support // set in development modes for hmr support
module = createModuleWithDirection(id); module = createModuleWithDirection(id);
} else { } else {
module = createModuleObject(id); module = createModuleObject(id);
} }
moduleCache[id] = module; moduleCache.set(id, module);
} }
return module; return module;
} }
...@@ -1252,7 +1252,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1252,7 +1252,7 @@ function formatDependencyChain(dependencyChain) {
dependencyChain dependencyChain
}; };
} }
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update, if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before. // it means that the module was never instantiated before.
...@@ -1280,7 +1280,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1280,7 +1280,7 @@ function formatDependencyChain(dependencyChain) {
continue; continue;
} }
for (const parentId of module.parents){ for (const parentId of module.parents){
const parent = devModuleCache[parentId]; const parent = devModuleCache.get(parentId);
if (!parent) { if (!parent) {
continue; continue;
} }
...@@ -1479,7 +1479,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1479,7 +1479,7 @@ function formatDependencyChain(dependencyChain) {
*/ function computeOutdatedSelfAcceptedModules(outdatedModules) { */ function computeOutdatedSelfAcceptedModules(outdatedModules) {
const outdatedSelfAcceptedModules = []; const outdatedSelfAcceptedModules = [];
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (module && hotState?.selfAccepted && !hotState.selfInvalidated) { if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {
outdatedSelfAcceptedModules.push({ outdatedSelfAcceptedModules.push({
...@@ -1497,7 +1497,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1497,7 +1497,7 @@ function formatDependencyChain(dependencyChain) {
* NOTE: mode = "replace" will not remove modules from devModuleCache. * NOTE: mode = "replace" will not remove modules from devModuleCache.
* This must be done in a separate step afterwards. * This must be done in a separate step afterwards.
*/ function disposeModule(moduleId, mode) { */ function disposeModule(moduleId, mode) {
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
if (!module) { if (!module) {
return; return;
} }
...@@ -1521,7 +1521,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1521,7 +1521,7 @@ function formatDependencyChain(dependencyChain) {
// It will be added back once the module re-instantiates and imports its // It will be added back once the module re-instantiates and imports its
// children again. // children again.
for (const childId of module.children){ for (const childId of module.children){
const child = devModuleCache[childId]; const child = devModuleCache.get(childId);
if (!child) { if (!child) {
continue; continue;
} }
...@@ -1532,7 +1532,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1532,7 +1532,7 @@ function formatDependencyChain(dependencyChain) {
} }
switch(mode){ switch(mode){
case 'clear': case 'clear':
delete devModuleCache[module.id]; devModuleCache.delete(module.id);
moduleHotData.delete(module.id); moduleHotData.delete(module.id);
break; break;
case 'replace': case 'replace':
...@@ -1556,16 +1556,16 @@ function formatDependencyChain(dependencyChain) { ...@@ -1556,16 +1556,16 @@ function formatDependencyChain(dependencyChain) {
// We also want to keep track of previous parents of the outdated modules. // We also want to keep track of previous parents of the outdated modules.
const outdatedModuleParents = new Map(); const outdatedModuleParents = new Map();
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const oldModule = devModuleCache[moduleId]; const oldModule = devModuleCache.get(moduleId);
outdatedModuleParents.set(moduleId, oldModule?.parents); outdatedModuleParents.set(moduleId, oldModule?.parents);
delete devModuleCache[moduleId]; devModuleCache.delete(moduleId);
} }
// Remove outdated dependencies from parent module's children list. // Remove outdated dependencies from parent module's children list.
// When a parent accepts a child's update, the child is re-instantiated // When a parent accepts a child's update, the child is re-instantiated
// but the parent stays alive. We remove the old child reference so it // but the parent stays alive. We remove the old child reference so it
// gets re-added when the child re-imports. // gets re-added when the child re-imports.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (module) { if (module) {
for (const dep of deps){ for (const dep of deps){
const idx = module.children.indexOf(dep); const idx = module.children.indexOf(dep);
...@@ -1617,7 +1617,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1617,7 +1617,7 @@ function formatDependencyChain(dependencyChain) {
module.parents = parents; module.parents = parents;
module.children = []; module.children = [];
module.hot = hot; module.hot = hot;
devModuleCache[id] = module; devModuleCache.set(id, module);
moduleHotState.set(module, hotState); moduleHotState.set(module, hotState);
// 5. Module execution (React Refresh hooks are platform-specific) // 5. Module execution (React Refresh hooks are platform-specific)
try { try {
...@@ -1751,7 +1751,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1751,7 +1751,7 @@ function formatDependencyChain(dependencyChain) {
// This runs BEFORE re-instantiating self-accepted modules, matching // This runs BEFORE re-instantiating self-accepted modules, matching
// webpack's behavior. // webpack's behavior.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (!module) continue; if (!module) continue;
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (!hotState) continue; if (!hotState) continue;
...@@ -1801,7 +1801,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1801,7 +1801,7 @@ function formatDependencyChain(dependencyChain) {
try { try {
errorHandler(err, { errorHandler(err, {
moduleId, moduleId,
module: devModuleCache[moduleId] module: devModuleCache.get(moduleId)
}); });
} catch (err2) { } catch (err2) {
reportError(err2); reportError(err2);
...@@ -1861,7 +1861,7 @@ const devContextPrototype = Context.prototype; ...@@ -1861,7 +1861,7 @@ const devContextPrototype = Context.prototype;
* It will be appended to the runtime code of each runtime right after the * It will be appended to the runtime code of each runtime right after the
* shared runtime utils. * shared runtime utils.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ // Assign browser's module cache and runtime modules to shared HMR state */ /* eslint-disable @typescript-eslint/no-unused-vars */ // Assign browser's module cache and runtime modules to shared HMR state
devModuleCache = Object.create(null); devModuleCache = new Map();
devContextPrototype.c = devModuleCache; devContextPrototype.c = devModuleCache;
runtimeModules = new Set(); runtimeModules = new Set();
// Set flag to indicate we use ModuleWithDirection // Set flag to indicate we use ModuleWithDirection
...@@ -1891,7 +1891,7 @@ createModuleWithDirectionFlag = true; ...@@ -1891,7 +1891,7 @@ createModuleWithDirectionFlag = true;
* Gets or instantiates a runtime module. * Gets or instantiates a runtime module.
*/ // @ts-ignore */ // @ts-ignore
function getOrInstantiateRuntimeModule(chunkPath, moduleId) { function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
if (module) { if (module) {
if (module.error) { if (module.error) {
throw module.error; throw module.error;
...@@ -1908,7 +1908,7 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{ ...@@ -1908,7 +1908,7 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{
if (!sourceModule.hot.active) { if (!sourceModule.hot.active) {
console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`); console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`);
} }
const module = devModuleCache[id]; const module = devModuleCache.get(id);
if (sourceModule.children.indexOf(id) === -1) { if (sourceModule.children.indexOf(id) === -1) {
sourceModule.children.push(id); sourceModule.children.push(id);
} }
...@@ -2614,5 +2614,5 @@ chunkListsToRegister.forEach(registerChunkList); ...@@ -2614,5 +2614,5 @@ chunkListsToRegister.forEach(registerChunkList);
})(); })();
//# debugId=976638d9-7f7b-0f2e-7bd5-80a2f6b9ac86 //# debugId=c43766b6-b61f-49ce-2bc6-d270f17e82af
//# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js.map //# sourceMappingURL=0_9x_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0bjegbrfzt05o.js.map
\ No newline at end of file
...@@ -55,15 +55,15 @@ function defineProp(obj, name, options) { ...@@ -55,15 +55,15 @@ function defineProp(obj, name, options) {
if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options); if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options);
} }
function getOverwrittenModule(moduleCache, id) { function getOverwrittenModule(moduleCache, id) {
let module = moduleCache[id]; let module = moduleCache.get(id);
if (!module) { if (module === undefined) {
if (createModuleWithDirectionFlag) { if (createModuleWithDirectionFlag) {
// set in development modes for hmr support // set in development modes for hmr support
module = createModuleWithDirection(id); module = createModuleWithDirection(id);
} else { } else {
module = createModuleObject(id); module = createModuleObject(id);
} }
moduleCache[id] = module; moduleCache.set(id, module);
} }
return module; return module;
} }
...@@ -738,7 +738,7 @@ Context.prototype.F = resolveFileUrl; ...@@ -738,7 +738,7 @@ Context.prototype.F = resolveFileUrl;
*/ process.env.TURBOPACK = '1'; */ process.env.TURBOPACK = '1';
const url = require('url'); const url = require('url');
const moduleFactories = new Map(); const moduleFactories = new Map();
const moduleCache = Object.create(null); const moduleCache = new Map();
/** /**
* Returns an absolute path to the given module's id. * Returns an absolute path to the given module's id.
*/ function resolvePathFromModule(moduleId) { */ function resolvePathFromModule(moduleId) {
...@@ -941,7 +941,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -941,7 +941,7 @@ function formatDependencyChain(dependencyChain) {
dependencyChain dependencyChain
}; };
} }
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update, if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before. // it means that the module was never instantiated before.
...@@ -969,7 +969,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -969,7 +969,7 @@ function formatDependencyChain(dependencyChain) {
continue; continue;
} }
for (const parentId of module.parents){ for (const parentId of module.parents){
const parent = devModuleCache[parentId]; const parent = devModuleCache.get(parentId);
if (!parent) { if (!parent) {
continue; continue;
} }
...@@ -1168,7 +1168,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1168,7 +1168,7 @@ function formatDependencyChain(dependencyChain) {
*/ function computeOutdatedSelfAcceptedModules(outdatedModules) { */ function computeOutdatedSelfAcceptedModules(outdatedModules) {
const outdatedSelfAcceptedModules = []; const outdatedSelfAcceptedModules = [];
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (module && hotState?.selfAccepted && !hotState.selfInvalidated) { if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {
outdatedSelfAcceptedModules.push({ outdatedSelfAcceptedModules.push({
...@@ -1186,7 +1186,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1186,7 +1186,7 @@ function formatDependencyChain(dependencyChain) {
* NOTE: mode = "replace" will not remove modules from devModuleCache. * NOTE: mode = "replace" will not remove modules from devModuleCache.
* This must be done in a separate step afterwards. * This must be done in a separate step afterwards.
*/ function disposeModule(moduleId, mode) { */ function disposeModule(moduleId, mode) {
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
if (!module) { if (!module) {
return; return;
} }
...@@ -1210,7 +1210,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1210,7 +1210,7 @@ function formatDependencyChain(dependencyChain) {
// It will be added back once the module re-instantiates and imports its // It will be added back once the module re-instantiates and imports its
// children again. // children again.
for (const childId of module.children){ for (const childId of module.children){
const child = devModuleCache[childId]; const child = devModuleCache.get(childId);
if (!child) { if (!child) {
continue; continue;
} }
...@@ -1221,7 +1221,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1221,7 +1221,7 @@ function formatDependencyChain(dependencyChain) {
} }
switch(mode){ switch(mode){
case 'clear': case 'clear':
delete devModuleCache[module.id]; devModuleCache.delete(module.id);
moduleHotData.delete(module.id); moduleHotData.delete(module.id);
break; break;
case 'replace': case 'replace':
...@@ -1245,16 +1245,16 @@ function formatDependencyChain(dependencyChain) { ...@@ -1245,16 +1245,16 @@ function formatDependencyChain(dependencyChain) {
// We also want to keep track of previous parents of the outdated modules. // We also want to keep track of previous parents of the outdated modules.
const outdatedModuleParents = new Map(); const outdatedModuleParents = new Map();
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const oldModule = devModuleCache[moduleId]; const oldModule = devModuleCache.get(moduleId);
outdatedModuleParents.set(moduleId, oldModule?.parents); outdatedModuleParents.set(moduleId, oldModule?.parents);
delete devModuleCache[moduleId]; devModuleCache.delete(moduleId);
} }
// Remove outdated dependencies from parent module's children list. // Remove outdated dependencies from parent module's children list.
// When a parent accepts a child's update, the child is re-instantiated // When a parent accepts a child's update, the child is re-instantiated
// but the parent stays alive. We remove the old child reference so it // but the parent stays alive. We remove the old child reference so it
// gets re-added when the child re-imports. // gets re-added when the child re-imports.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (module) { if (module) {
for (const dep of deps){ for (const dep of deps){
const idx = module.children.indexOf(dep); const idx = module.children.indexOf(dep);
...@@ -1306,7 +1306,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1306,7 +1306,7 @@ function formatDependencyChain(dependencyChain) {
module.parents = parents; module.parents = parents;
module.children = []; module.children = [];
module.hot = hot; module.hot = hot;
devModuleCache[id] = module; devModuleCache.set(id, module);
moduleHotState.set(module, hotState); moduleHotState.set(module, hotState);
// 5. Module execution (React Refresh hooks are platform-specific) // 5. Module execution (React Refresh hooks are platform-specific)
try { try {
...@@ -1440,7 +1440,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1440,7 +1440,7 @@ function formatDependencyChain(dependencyChain) {
// This runs BEFORE re-instantiating self-accepted modules, matching // This runs BEFORE re-instantiating self-accepted modules, matching
// webpack's behavior. // webpack's behavior.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (!module) continue; if (!module) continue;
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (!hotState) continue; if (!hotState) continue;
...@@ -1490,7 +1490,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1490,7 +1490,7 @@ function formatDependencyChain(dependencyChain) {
try { try {
errorHandler(err, { errorHandler(err, {
moduleId, moduleId,
module: devModuleCache[moduleId] module: devModuleCache.get(moduleId)
}); });
} catch (err2) { } catch (err2) {
reportError(err2); reportError(err2);
...@@ -1604,7 +1604,7 @@ if (globalThis.__turbopack_ensure_chunk__ !== undefined) { ...@@ -1604,7 +1604,7 @@ if (globalThis.__turbopack_ensure_chunk__ !== undefined) {
* Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached. * Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.
*/ // @ts-ignore TypeScript doesn't separate this module space from the browser runtime */ // @ts-ignore TypeScript doesn't separate this module space from the browser runtime
function getOrInstantiateRuntimeModule(chunkPath, moduleId) { function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
const module1 = devModuleCache[moduleId]; const module1 = devModuleCache.get(moduleId);
if (module1) { if (module1) {
if (module1.error) { if (module1.error) {
throw module1.error; throw module1.error;
...@@ -1619,8 +1619,8 @@ function getOrInstantiateRuntimeModule(chunkPath, moduleId) { ...@@ -1619,8 +1619,8 @@ function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
*/ // @ts-ignore */ // @ts-ignore
function getOrInstantiateModuleFromParent(id, sourceModule) { function getOrInstantiateModuleFromParent(id, sourceModule) {
// Track parent-child relationship // Track parent-child relationship
trackModuleImport(sourceModule, id, devModuleCache[id]); const module1 = devModuleCache.get(id);
const module1 = devModuleCache[id]; trackModuleImport(sourceModule, id, module1);
if (module1) { if (module1) {
if (module1.error) { if (module1.error) {
throw module1.error; throw module1.error;
...@@ -1722,7 +1722,7 @@ function applyEcmascriptMergedUpdate(instruction, moduleFactories, devModuleCach ...@@ -1722,7 +1722,7 @@ function applyEcmascriptMergedUpdate(instruction, moduleFactories, devModuleCach
// were moved to a renamed chunk. Treat them as modified so the dependency // were moved to a renamed chunk. Treat them as modified so the dependency
// walk runs and they get re-instantiated with the new factory. // walk runs and they get re-instantiated with the new factory.
for (const [moduleId, entry] of added){ for (const [moduleId, entry] of added){
if (entry != null && devModuleCache[moduleId] != null) { if (entry != null && devModuleCache.has(moduleId)) {
added.delete(moduleId); added.delete(moduleId);
modified.set(moduleId, entry); modified.set(moduleId, entry);
} }
......
...@@ -55,15 +55,15 @@ function defineProp(obj, name, options) { ...@@ -55,15 +55,15 @@ function defineProp(obj, name, options) {
if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options); if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options);
} }
function getOverwrittenModule(moduleCache, id) { function getOverwrittenModule(moduleCache, id) {
let module = moduleCache[id]; let module = moduleCache.get(id);
if (!module) { if (module === undefined) {
if (createModuleWithDirectionFlag) { if (createModuleWithDirectionFlag) {
// set in development modes for hmr support // set in development modes for hmr support
module = createModuleWithDirection(id); module = createModuleWithDirection(id);
} else { } else {
module = createModuleObject(id); module = createModuleObject(id);
} }
moduleCache[id] = module; moduleCache.set(id, module);
} }
return module; return module;
} }
...@@ -738,7 +738,7 @@ Context.prototype.F = resolveFileUrl; ...@@ -738,7 +738,7 @@ Context.prototype.F = resolveFileUrl;
*/ process.env.TURBOPACK = '1'; */ process.env.TURBOPACK = '1';
const url = require('url'); const url = require('url');
const moduleFactories = new Map(); const moduleFactories = new Map();
const moduleCache = Object.create(null); const moduleCache = new Map();
/** /**
* Returns an absolute path to the given module's id. * Returns an absolute path to the given module's id.
*/ function resolvePathFromModule(moduleId) { */ function resolvePathFromModule(moduleId) {
...@@ -867,7 +867,7 @@ function instantiateModule(id, sourceType, sourceData) { ...@@ -867,7 +867,7 @@ function instantiateModule(id, sourceType, sourceData) {
} }
const module1 = createModuleWithDirection(id); const module1 = createModuleWithDirection(id);
const exports = module1.exports; const exports = module1.exports;
moduleCache[id] = module1; moduleCache.set(id, module1);
const context = new Context(module1, exports); const context = new Context(module1, exports);
// NOTE(alexkirsz) This can fail when the module encounters a runtime error. // NOTE(alexkirsz) This can fail when the module encounters a runtime error.
try { try {
...@@ -888,7 +888,7 @@ function instantiateModule(id, sourceType, sourceData) { ...@@ -888,7 +888,7 @@ function instantiateModule(id, sourceType, sourceData) {
* Retrieves a module from the cache, or instantiate it if it is not cached. * Retrieves a module from the cache, or instantiate it if it is not cached.
*/ // @ts-ignore */ // @ts-ignore
function getOrInstantiateModuleFromParent(id, sourceModule) { function getOrInstantiateModuleFromParent(id, sourceModule) {
const module1 = moduleCache[id]; const module1 = moduleCache.get(id);
if (module1) { if (module1) {
if (module1.error) { if (module1.error) {
throw module1.error; throw module1.error;
...@@ -906,7 +906,7 @@ function getOrInstantiateModuleFromParent(id, sourceModule) { ...@@ -906,7 +906,7 @@ function getOrInstantiateModuleFromParent(id, sourceModule) {
* Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached. * Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.
*/ // @ts-ignore TypeScript doesn't separate this module space from the browser runtime */ // @ts-ignore TypeScript doesn't separate this module space from the browser runtime
function getOrInstantiateRuntimeModule(chunkPath, moduleId) { function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
const module1 = moduleCache[moduleId]; const module1 = moduleCache.get(moduleId);
if (module1) { if (module1) {
if (module1.error) { if (module1.error) {
throw module1.error; throw module1.error;
......
...@@ -77,15 +77,15 @@ function defineProp(obj, name, options) { ...@@ -77,15 +77,15 @@ function defineProp(obj, name, options) {
if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options); if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options);
} }
function getOverwrittenModule(moduleCache, id) { function getOverwrittenModule(moduleCache, id) {
let module = moduleCache[id]; let module = moduleCache.get(id);
if (!module) { if (module === undefined) {
if (createModuleWithDirectionFlag) { if (createModuleWithDirectionFlag) {
// set in development modes for hmr support // set in development modes for hmr support
module = createModuleWithDirection(id); module = createModuleWithDirection(id);
} else { } else {
module = createModuleObject(id); module = createModuleObject(id);
} }
moduleCache[id] = module; moduleCache.set(id, module);
} }
return module; return module;
} }
...@@ -1251,7 +1251,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1251,7 +1251,7 @@ function formatDependencyChain(dependencyChain) {
dependencyChain dependencyChain
}; };
} }
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update, if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before. // it means that the module was never instantiated before.
...@@ -1279,7 +1279,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1279,7 +1279,7 @@ function formatDependencyChain(dependencyChain) {
continue; continue;
} }
for (const parentId of module.parents){ for (const parentId of module.parents){
const parent = devModuleCache[parentId]; const parent = devModuleCache.get(parentId);
if (!parent) { if (!parent) {
continue; continue;
} }
...@@ -1478,7 +1478,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1478,7 +1478,7 @@ function formatDependencyChain(dependencyChain) {
*/ function computeOutdatedSelfAcceptedModules(outdatedModules) { */ function computeOutdatedSelfAcceptedModules(outdatedModules) {
const outdatedSelfAcceptedModules = []; const outdatedSelfAcceptedModules = [];
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (module && hotState?.selfAccepted && !hotState.selfInvalidated) { if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {
outdatedSelfAcceptedModules.push({ outdatedSelfAcceptedModules.push({
...@@ -1496,7 +1496,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1496,7 +1496,7 @@ function formatDependencyChain(dependencyChain) {
* NOTE: mode = "replace" will not remove modules from devModuleCache. * NOTE: mode = "replace" will not remove modules from devModuleCache.
* This must be done in a separate step afterwards. * This must be done in a separate step afterwards.
*/ function disposeModule(moduleId, mode) { */ function disposeModule(moduleId, mode) {
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
if (!module) { if (!module) {
return; return;
} }
...@@ -1520,7 +1520,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1520,7 +1520,7 @@ function formatDependencyChain(dependencyChain) {
// It will be added back once the module re-instantiates and imports its // It will be added back once the module re-instantiates and imports its
// children again. // children again.
for (const childId of module.children){ for (const childId of module.children){
const child = devModuleCache[childId]; const child = devModuleCache.get(childId);
if (!child) { if (!child) {
continue; continue;
} }
...@@ -1531,7 +1531,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1531,7 +1531,7 @@ function formatDependencyChain(dependencyChain) {
} }
switch(mode){ switch(mode){
case 'clear': case 'clear':
delete devModuleCache[module.id]; devModuleCache.delete(module.id);
moduleHotData.delete(module.id); moduleHotData.delete(module.id);
break; break;
case 'replace': case 'replace':
...@@ -1555,16 +1555,16 @@ function formatDependencyChain(dependencyChain) { ...@@ -1555,16 +1555,16 @@ function formatDependencyChain(dependencyChain) {
// We also want to keep track of previous parents of the outdated modules. // We also want to keep track of previous parents of the outdated modules.
const outdatedModuleParents = new Map(); const outdatedModuleParents = new Map();
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const oldModule = devModuleCache[moduleId]; const oldModule = devModuleCache.get(moduleId);
outdatedModuleParents.set(moduleId, oldModule?.parents); outdatedModuleParents.set(moduleId, oldModule?.parents);
delete devModuleCache[moduleId]; devModuleCache.delete(moduleId);
} }
// Remove outdated dependencies from parent module's children list. // Remove outdated dependencies from parent module's children list.
// When a parent accepts a child's update, the child is re-instantiated // When a parent accepts a child's update, the child is re-instantiated
// but the parent stays alive. We remove the old child reference so it // but the parent stays alive. We remove the old child reference so it
// gets re-added when the child re-imports. // gets re-added when the child re-imports.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (module) { if (module) {
for (const dep of deps){ for (const dep of deps){
const idx = module.children.indexOf(dep); const idx = module.children.indexOf(dep);
...@@ -1616,7 +1616,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1616,7 +1616,7 @@ function formatDependencyChain(dependencyChain) {
module.parents = parents; module.parents = parents;
module.children = []; module.children = [];
module.hot = hot; module.hot = hot;
devModuleCache[id] = module; devModuleCache.set(id, module);
moduleHotState.set(module, hotState); moduleHotState.set(module, hotState);
// 5. Module execution (React Refresh hooks are platform-specific) // 5. Module execution (React Refresh hooks are platform-specific)
try { try {
...@@ -1750,7 +1750,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1750,7 +1750,7 @@ function formatDependencyChain(dependencyChain) {
// This runs BEFORE re-instantiating self-accepted modules, matching // This runs BEFORE re-instantiating self-accepted modules, matching
// webpack's behavior. // webpack's behavior.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (!module) continue; if (!module) continue;
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (!hotState) continue; if (!hotState) continue;
...@@ -1800,7 +1800,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1800,7 +1800,7 @@ function formatDependencyChain(dependencyChain) {
try { try {
errorHandler(err, { errorHandler(err, {
moduleId, moduleId,
module: devModuleCache[moduleId] module: devModuleCache.get(moduleId)
}); });
} catch (err2) { } catch (err2) {
reportError(err2); reportError(err2);
...@@ -1860,7 +1860,7 @@ const devContextPrototype = Context.prototype; ...@@ -1860,7 +1860,7 @@ const devContextPrototype = Context.prototype;
* It will be appended to the runtime code of each runtime right after the * It will be appended to the runtime code of each runtime right after the
* shared runtime utils. * shared runtime utils.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ // Assign browser's module cache and runtime modules to shared HMR state */ /* eslint-disable @typescript-eslint/no-unused-vars */ // Assign browser's module cache and runtime modules to shared HMR state
devModuleCache = Object.create(null); devModuleCache = new Map();
devContextPrototype.c = devModuleCache; devContextPrototype.c = devModuleCache;
runtimeModules = new Set(); runtimeModules = new Set();
// Set flag to indicate we use ModuleWithDirection // Set flag to indicate we use ModuleWithDirection
...@@ -1890,7 +1890,7 @@ createModuleWithDirectionFlag = true; ...@@ -1890,7 +1890,7 @@ createModuleWithDirectionFlag = true;
* Gets or instantiates a runtime module. * Gets or instantiates a runtime module.
*/ // @ts-ignore */ // @ts-ignore
function getOrInstantiateRuntimeModule(chunkPath, moduleId) { function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
if (module) { if (module) {
if (module.error) { if (module.error) {
throw module.error; throw module.error;
...@@ -1907,7 +1907,7 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{ ...@@ -1907,7 +1907,7 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{
if (!sourceModule.hot.active) { if (!sourceModule.hot.active) {
console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`); console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`);
} }
const module = devModuleCache[id]; const module = devModuleCache.get(id);
if (sourceModule.children.indexOf(id) === -1) { if (sourceModule.children.indexOf(id) === -1) {
sourceModule.children.push(id); sourceModule.children.push(id);
} }
......
...@@ -202,15 +202,15 @@ function defineProp(obj, name, options) { ...@@ -202,15 +202,15 @@ function defineProp(obj, name, options) {
if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options); if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options);
} }
function getOverwrittenModule(moduleCache, id) { function getOverwrittenModule(moduleCache, id) {
var module = moduleCache[id]; var module = moduleCache.get(id);
if (!module) { if (module === undefined) {
if (createModuleWithDirectionFlag) { if (createModuleWithDirectionFlag) {
// set in development modes for hmr support // set in development modes for hmr support
module = createModuleWithDirection(id); module = createModuleWithDirection(id);
} else { } else {
module = createModuleObject(id); module = createModuleObject(id);
} }
moduleCache[id] = module; moduleCache.set(id, module);
} }
return module; return module;
} }
...@@ -1543,14 +1543,14 @@ function isCss(chunkUrl) { ...@@ -1543,14 +1543,14 @@ function isCss(chunkUrl) {
} }
/// <reference path="./runtime-base.ts" /> /// <reference path="./runtime-base.ts" />
/// <reference path="./dummy.ts" /> /// <reference path="./dummy.ts" />
var moduleCache = {}; var moduleCache = new Map();
contextPrototype.c = moduleCache; contextPrototype.c = moduleCache;
/** /**
* Gets or instantiates a runtime module. * Gets or instantiates a runtime module.
*/ // @ts-ignore */ // @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
function getOrInstantiateRuntimeModule(chunkPath, moduleId) { function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
var module = moduleCache[moduleId]; var module = moduleCache.get(moduleId);
if (module) { if (module) {
if (module.error) { if (module.error) {
throw module.error; throw module.error;
...@@ -1565,7 +1565,7 @@ function getOrInstantiateRuntimeModule(chunkPath, moduleId) { ...@@ -1565,7 +1565,7 @@ function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
// @ts-ignore // @ts-ignore
// eslint-disable-next-line @typescript-eslint/no-unused-vars // eslint-disable-next-line @typescript-eslint/no-unused-vars
var getOrInstantiateModuleFromParent = function getOrInstantiateModuleFromParent(id, sourceModule) { var getOrInstantiateModuleFromParent = function getOrInstantiateModuleFromParent(id, sourceModule) {
var module = moduleCache[id]; var module = moduleCache.get(id);
if (module) { if (module) {
if (module.error) { if (module.error) {
throw module.error; throw module.error;
...@@ -1584,7 +1584,7 @@ function instantiateModule(id, sourceType, sourceData) { ...@@ -1584,7 +1584,7 @@ function instantiateModule(id, sourceType, sourceData) {
} }
var module = createModuleObject(id); var module = createModuleObject(id);
var exports = module.exports; var exports = module.exports;
moduleCache[id] = module; moduleCache.set(id, module);
// NOTE(alexkirsz) This can fail when the module encounters a runtime error. // NOTE(alexkirsz) This can fail when the module encounters a runtime error.
var context = new Context(module, exports); var context = new Context(module, exports);
try { try {
......
...@@ -77,15 +77,15 @@ function defineProp(obj, name, options) { ...@@ -77,15 +77,15 @@ function defineProp(obj, name, options) {
if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options); if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options);
} }
function getOverwrittenModule(moduleCache, id) { function getOverwrittenModule(moduleCache, id) {
let module = moduleCache[id]; let module = moduleCache.get(id);
if (!module) { if (module === undefined) {
if (createModuleWithDirectionFlag) { if (createModuleWithDirectionFlag) {
// set in development modes for hmr support // set in development modes for hmr support
module = createModuleWithDirection(id); module = createModuleWithDirection(id);
} else { } else {
module = createModuleObject(id); module = createModuleObject(id);
} }
moduleCache[id] = module; moduleCache.set(id, module);
} }
return module; return module;
} }
...@@ -1251,7 +1251,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1251,7 +1251,7 @@ function formatDependencyChain(dependencyChain) {
dependencyChain dependencyChain
}; };
} }
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update, if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before. // it means that the module was never instantiated before.
...@@ -1279,7 +1279,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1279,7 +1279,7 @@ function formatDependencyChain(dependencyChain) {
continue; continue;
} }
for (const parentId of module.parents){ for (const parentId of module.parents){
const parent = devModuleCache[parentId]; const parent = devModuleCache.get(parentId);
if (!parent) { if (!parent) {
continue; continue;
} }
...@@ -1478,7 +1478,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1478,7 +1478,7 @@ function formatDependencyChain(dependencyChain) {
*/ function computeOutdatedSelfAcceptedModules(outdatedModules) { */ function computeOutdatedSelfAcceptedModules(outdatedModules) {
const outdatedSelfAcceptedModules = []; const outdatedSelfAcceptedModules = [];
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (module && hotState?.selfAccepted && !hotState.selfInvalidated) { if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {
outdatedSelfAcceptedModules.push({ outdatedSelfAcceptedModules.push({
...@@ -1496,7 +1496,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1496,7 +1496,7 @@ function formatDependencyChain(dependencyChain) {
* NOTE: mode = "replace" will not remove modules from devModuleCache. * NOTE: mode = "replace" will not remove modules from devModuleCache.
* This must be done in a separate step afterwards. * This must be done in a separate step afterwards.
*/ function disposeModule(moduleId, mode) { */ function disposeModule(moduleId, mode) {
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
if (!module) { if (!module) {
return; return;
} }
...@@ -1520,7 +1520,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1520,7 +1520,7 @@ function formatDependencyChain(dependencyChain) {
// It will be added back once the module re-instantiates and imports its // It will be added back once the module re-instantiates and imports its
// children again. // children again.
for (const childId of module.children){ for (const childId of module.children){
const child = devModuleCache[childId]; const child = devModuleCache.get(childId);
if (!child) { if (!child) {
continue; continue;
} }
...@@ -1531,7 +1531,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1531,7 +1531,7 @@ function formatDependencyChain(dependencyChain) {
} }
switch(mode){ switch(mode){
case 'clear': case 'clear':
delete devModuleCache[module.id]; devModuleCache.delete(module.id);
moduleHotData.delete(module.id); moduleHotData.delete(module.id);
break; break;
case 'replace': case 'replace':
...@@ -1555,16 +1555,16 @@ function formatDependencyChain(dependencyChain) { ...@@ -1555,16 +1555,16 @@ function formatDependencyChain(dependencyChain) {
// We also want to keep track of previous parents of the outdated modules. // We also want to keep track of previous parents of the outdated modules.
const outdatedModuleParents = new Map(); const outdatedModuleParents = new Map();
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const oldModule = devModuleCache[moduleId]; const oldModule = devModuleCache.get(moduleId);
outdatedModuleParents.set(moduleId, oldModule?.parents); outdatedModuleParents.set(moduleId, oldModule?.parents);
delete devModuleCache[moduleId]; devModuleCache.delete(moduleId);
} }
// Remove outdated dependencies from parent module's children list. // Remove outdated dependencies from parent module's children list.
// When a parent accepts a child's update, the child is re-instantiated // When a parent accepts a child's update, the child is re-instantiated
// but the parent stays alive. We remove the old child reference so it // but the parent stays alive. We remove the old child reference so it
// gets re-added when the child re-imports. // gets re-added when the child re-imports.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (module) { if (module) {
for (const dep of deps){ for (const dep of deps){
const idx = module.children.indexOf(dep); const idx = module.children.indexOf(dep);
...@@ -1616,7 +1616,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1616,7 +1616,7 @@ function formatDependencyChain(dependencyChain) {
module.parents = parents; module.parents = parents;
module.children = []; module.children = [];
module.hot = hot; module.hot = hot;
devModuleCache[id] = module; devModuleCache.set(id, module);
moduleHotState.set(module, hotState); moduleHotState.set(module, hotState);
// 5. Module execution (React Refresh hooks are platform-specific) // 5. Module execution (React Refresh hooks are platform-specific)
try { try {
...@@ -1750,7 +1750,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1750,7 +1750,7 @@ function formatDependencyChain(dependencyChain) {
// This runs BEFORE re-instantiating self-accepted modules, matching // This runs BEFORE re-instantiating self-accepted modules, matching
// webpack's behavior. // webpack's behavior.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (!module) continue; if (!module) continue;
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (!hotState) continue; if (!hotState) continue;
...@@ -1800,7 +1800,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1800,7 +1800,7 @@ function formatDependencyChain(dependencyChain) {
try { try {
errorHandler(err, { errorHandler(err, {
moduleId, moduleId,
module: devModuleCache[moduleId] module: devModuleCache.get(moduleId)
}); });
} catch (err2) { } catch (err2) {
reportError(err2); reportError(err2);
...@@ -1860,7 +1860,7 @@ const devContextPrototype = Context.prototype; ...@@ -1860,7 +1860,7 @@ const devContextPrototype = Context.prototype;
* It will be appended to the runtime code of each runtime right after the * It will be appended to the runtime code of each runtime right after the
* shared runtime utils. * shared runtime utils.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ // Assign browser's module cache and runtime modules to shared HMR state */ /* eslint-disable @typescript-eslint/no-unused-vars */ // Assign browser's module cache and runtime modules to shared HMR state
devModuleCache = Object.create(null); devModuleCache = new Map();
devContextPrototype.c = devModuleCache; devContextPrototype.c = devModuleCache;
runtimeModules = new Set(); runtimeModules = new Set();
// Set flag to indicate we use ModuleWithDirection // Set flag to indicate we use ModuleWithDirection
...@@ -1890,7 +1890,7 @@ createModuleWithDirectionFlag = true; ...@@ -1890,7 +1890,7 @@ createModuleWithDirectionFlag = true;
* Gets or instantiates a runtime module. * Gets or instantiates a runtime module.
*/ // @ts-ignore */ // @ts-ignore
function getOrInstantiateRuntimeModule(chunkPath, moduleId) { function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
if (module) { if (module) {
if (module.error) { if (module.error) {
throw module.error; throw module.error;
...@@ -1907,7 +1907,7 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{ ...@@ -1907,7 +1907,7 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{
if (!sourceModule.hot.active) { if (!sourceModule.hot.active) {
console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`); console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`);
} }
const module = devModuleCache[id]; const module = devModuleCache.get(id);
if (sourceModule.children.indexOf(id) === -1) { if (sourceModule.children.indexOf(id) === -1) {
sourceModule.children.push(id); sourceModule.children.push(id);
} }
......
...@@ -77,15 +77,15 @@ function defineProp(obj, name, options) { ...@@ -77,15 +77,15 @@ function defineProp(obj, name, options) {
if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options); if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options);
} }
function getOverwrittenModule(moduleCache, id) { function getOverwrittenModule(moduleCache, id) {
let module = moduleCache[id]; let module = moduleCache.get(id);
if (!module) { if (module === undefined) {
if (createModuleWithDirectionFlag) { if (createModuleWithDirectionFlag) {
// set in development modes for hmr support // set in development modes for hmr support
module = createModuleWithDirection(id); module = createModuleWithDirection(id);
} else { } else {
module = createModuleObject(id); module = createModuleObject(id);
} }
moduleCache[id] = module; moduleCache.set(id, module);
} }
return module; return module;
} }
...@@ -1251,7 +1251,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1251,7 +1251,7 @@ function formatDependencyChain(dependencyChain) {
dependencyChain dependencyChain
}; };
} }
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update, if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before. // it means that the module was never instantiated before.
...@@ -1279,7 +1279,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1279,7 +1279,7 @@ function formatDependencyChain(dependencyChain) {
continue; continue;
} }
for (const parentId of module.parents){ for (const parentId of module.parents){
const parent = devModuleCache[parentId]; const parent = devModuleCache.get(parentId);
if (!parent) { if (!parent) {
continue; continue;
} }
...@@ -1478,7 +1478,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1478,7 +1478,7 @@ function formatDependencyChain(dependencyChain) {
*/ function computeOutdatedSelfAcceptedModules(outdatedModules) { */ function computeOutdatedSelfAcceptedModules(outdatedModules) {
const outdatedSelfAcceptedModules = []; const outdatedSelfAcceptedModules = [];
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (module && hotState?.selfAccepted && !hotState.selfInvalidated) { if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {
outdatedSelfAcceptedModules.push({ outdatedSelfAcceptedModules.push({
...@@ -1496,7 +1496,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1496,7 +1496,7 @@ function formatDependencyChain(dependencyChain) {
* NOTE: mode = "replace" will not remove modules from devModuleCache. * NOTE: mode = "replace" will not remove modules from devModuleCache.
* This must be done in a separate step afterwards. * This must be done in a separate step afterwards.
*/ function disposeModule(moduleId, mode) { */ function disposeModule(moduleId, mode) {
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
if (!module) { if (!module) {
return; return;
} }
...@@ -1520,7 +1520,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1520,7 +1520,7 @@ function formatDependencyChain(dependencyChain) {
// It will be added back once the module re-instantiates and imports its // It will be added back once the module re-instantiates and imports its
// children again. // children again.
for (const childId of module.children){ for (const childId of module.children){
const child = devModuleCache[childId]; const child = devModuleCache.get(childId);
if (!child) { if (!child) {
continue; continue;
} }
...@@ -1531,7 +1531,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1531,7 +1531,7 @@ function formatDependencyChain(dependencyChain) {
} }
switch(mode){ switch(mode){
case 'clear': case 'clear':
delete devModuleCache[module.id]; devModuleCache.delete(module.id);
moduleHotData.delete(module.id); moduleHotData.delete(module.id);
break; break;
case 'replace': case 'replace':
...@@ -1555,16 +1555,16 @@ function formatDependencyChain(dependencyChain) { ...@@ -1555,16 +1555,16 @@ function formatDependencyChain(dependencyChain) {
// We also want to keep track of previous parents of the outdated modules. // We also want to keep track of previous parents of the outdated modules.
const outdatedModuleParents = new Map(); const outdatedModuleParents = new Map();
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const oldModule = devModuleCache[moduleId]; const oldModule = devModuleCache.get(moduleId);
outdatedModuleParents.set(moduleId, oldModule?.parents); outdatedModuleParents.set(moduleId, oldModule?.parents);
delete devModuleCache[moduleId]; devModuleCache.delete(moduleId);
} }
// Remove outdated dependencies from parent module's children list. // Remove outdated dependencies from parent module's children list.
// When a parent accepts a child's update, the child is re-instantiated // When a parent accepts a child's update, the child is re-instantiated
// but the parent stays alive. We remove the old child reference so it // but the parent stays alive. We remove the old child reference so it
// gets re-added when the child re-imports. // gets re-added when the child re-imports.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (module) { if (module) {
for (const dep of deps){ for (const dep of deps){
const idx = module.children.indexOf(dep); const idx = module.children.indexOf(dep);
...@@ -1616,7 +1616,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1616,7 +1616,7 @@ function formatDependencyChain(dependencyChain) {
module.parents = parents; module.parents = parents;
module.children = []; module.children = [];
module.hot = hot; module.hot = hot;
devModuleCache[id] = module; devModuleCache.set(id, module);
moduleHotState.set(module, hotState); moduleHotState.set(module, hotState);
// 5. Module execution (React Refresh hooks are platform-specific) // 5. Module execution (React Refresh hooks are platform-specific)
try { try {
...@@ -1750,7 +1750,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1750,7 +1750,7 @@ function formatDependencyChain(dependencyChain) {
// This runs BEFORE re-instantiating self-accepted modules, matching // This runs BEFORE re-instantiating self-accepted modules, matching
// webpack's behavior. // webpack's behavior.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (!module) continue; if (!module) continue;
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (!hotState) continue; if (!hotState) continue;
...@@ -1800,7 +1800,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1800,7 +1800,7 @@ function formatDependencyChain(dependencyChain) {
try { try {
errorHandler(err, { errorHandler(err, {
moduleId, moduleId,
module: devModuleCache[moduleId] module: devModuleCache.get(moduleId)
}); });
} catch (err2) { } catch (err2) {
reportError(err2); reportError(err2);
...@@ -1860,7 +1860,7 @@ const devContextPrototype = Context.prototype; ...@@ -1860,7 +1860,7 @@ const devContextPrototype = Context.prototype;
* It will be appended to the runtime code of each runtime right after the * It will be appended to the runtime code of each runtime right after the
* shared runtime utils. * shared runtime utils.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ // Assign browser's module cache and runtime modules to shared HMR state */ /* eslint-disable @typescript-eslint/no-unused-vars */ // Assign browser's module cache and runtime modules to shared HMR state
devModuleCache = Object.create(null); devModuleCache = new Map();
devContextPrototype.c = devModuleCache; devContextPrototype.c = devModuleCache;
runtimeModules = new Set(); runtimeModules = new Set();
// Set flag to indicate we use ModuleWithDirection // Set flag to indicate we use ModuleWithDirection
...@@ -1890,7 +1890,7 @@ createModuleWithDirectionFlag = true; ...@@ -1890,7 +1890,7 @@ createModuleWithDirectionFlag = true;
* Gets or instantiates a runtime module. * Gets or instantiates a runtime module.
*/ // @ts-ignore */ // @ts-ignore
function getOrInstantiateRuntimeModule(chunkPath, moduleId) { function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
if (module) { if (module) {
if (module.error) { if (module.error) {
throw module.error; throw module.error;
...@@ -1907,7 +1907,7 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{ ...@@ -1907,7 +1907,7 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{
if (!sourceModule.hot.active) { if (!sourceModule.hot.active) {
console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`); console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`);
} }
const module = devModuleCache[id]; const module = devModuleCache.get(id);
if (sourceModule.children.indexOf(id) === -1) { if (sourceModule.children.indexOf(id) === -1) {
sourceModule.children.push(id); sourceModule.children.push(id);
} }
......
...@@ -77,15 +77,15 @@ function defineProp(obj, name, options) { ...@@ -77,15 +77,15 @@ function defineProp(obj, name, options) {
if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options); if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options);
} }
function getOverwrittenModule(moduleCache, id) { function getOverwrittenModule(moduleCache, id) {
let module = moduleCache[id]; let module = moduleCache.get(id);
if (!module) { if (module === undefined) {
if (createModuleWithDirectionFlag) { if (createModuleWithDirectionFlag) {
// set in development modes for hmr support // set in development modes for hmr support
module = createModuleWithDirection(id); module = createModuleWithDirection(id);
} else { } else {
module = createModuleObject(id); module = createModuleObject(id);
} }
moduleCache[id] = module; moduleCache.set(id, module);
} }
return module; return module;
} }
...@@ -1251,7 +1251,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1251,7 +1251,7 @@ function formatDependencyChain(dependencyChain) {
dependencyChain dependencyChain
}; };
} }
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update, if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before. // it means that the module was never instantiated before.
...@@ -1279,7 +1279,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1279,7 +1279,7 @@ function formatDependencyChain(dependencyChain) {
continue; continue;
} }
for (const parentId of module.parents){ for (const parentId of module.parents){
const parent = devModuleCache[parentId]; const parent = devModuleCache.get(parentId);
if (!parent) { if (!parent) {
continue; continue;
} }
...@@ -1478,7 +1478,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1478,7 +1478,7 @@ function formatDependencyChain(dependencyChain) {
*/ function computeOutdatedSelfAcceptedModules(outdatedModules) { */ function computeOutdatedSelfAcceptedModules(outdatedModules) {
const outdatedSelfAcceptedModules = []; const outdatedSelfAcceptedModules = [];
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (module && hotState?.selfAccepted && !hotState.selfInvalidated) { if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {
outdatedSelfAcceptedModules.push({ outdatedSelfAcceptedModules.push({
...@@ -1496,7 +1496,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1496,7 +1496,7 @@ function formatDependencyChain(dependencyChain) {
* NOTE: mode = "replace" will not remove modules from devModuleCache. * NOTE: mode = "replace" will not remove modules from devModuleCache.
* This must be done in a separate step afterwards. * This must be done in a separate step afterwards.
*/ function disposeModule(moduleId, mode) { */ function disposeModule(moduleId, mode) {
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
if (!module) { if (!module) {
return; return;
} }
...@@ -1520,7 +1520,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1520,7 +1520,7 @@ function formatDependencyChain(dependencyChain) {
// It will be added back once the module re-instantiates and imports its // It will be added back once the module re-instantiates and imports its
// children again. // children again.
for (const childId of module.children){ for (const childId of module.children){
const child = devModuleCache[childId]; const child = devModuleCache.get(childId);
if (!child) { if (!child) {
continue; continue;
} }
...@@ -1531,7 +1531,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1531,7 +1531,7 @@ function formatDependencyChain(dependencyChain) {
} }
switch(mode){ switch(mode){
case 'clear': case 'clear':
delete devModuleCache[module.id]; devModuleCache.delete(module.id);
moduleHotData.delete(module.id); moduleHotData.delete(module.id);
break; break;
case 'replace': case 'replace':
...@@ -1555,16 +1555,16 @@ function formatDependencyChain(dependencyChain) { ...@@ -1555,16 +1555,16 @@ function formatDependencyChain(dependencyChain) {
// We also want to keep track of previous parents of the outdated modules. // We also want to keep track of previous parents of the outdated modules.
const outdatedModuleParents = new Map(); const outdatedModuleParents = new Map();
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const oldModule = devModuleCache[moduleId]; const oldModule = devModuleCache.get(moduleId);
outdatedModuleParents.set(moduleId, oldModule?.parents); outdatedModuleParents.set(moduleId, oldModule?.parents);
delete devModuleCache[moduleId]; devModuleCache.delete(moduleId);
} }
// Remove outdated dependencies from parent module's children list. // Remove outdated dependencies from parent module's children list.
// When a parent accepts a child's update, the child is re-instantiated // When a parent accepts a child's update, the child is re-instantiated
// but the parent stays alive. We remove the old child reference so it // but the parent stays alive. We remove the old child reference so it
// gets re-added when the child re-imports. // gets re-added when the child re-imports.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (module) { if (module) {
for (const dep of deps){ for (const dep of deps){
const idx = module.children.indexOf(dep); const idx = module.children.indexOf(dep);
...@@ -1616,7 +1616,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1616,7 +1616,7 @@ function formatDependencyChain(dependencyChain) {
module.parents = parents; module.parents = parents;
module.children = []; module.children = [];
module.hot = hot; module.hot = hot;
devModuleCache[id] = module; devModuleCache.set(id, module);
moduleHotState.set(module, hotState); moduleHotState.set(module, hotState);
// 5. Module execution (React Refresh hooks are platform-specific) // 5. Module execution (React Refresh hooks are platform-specific)
try { try {
...@@ -1750,7 +1750,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1750,7 +1750,7 @@ function formatDependencyChain(dependencyChain) {
// This runs BEFORE re-instantiating self-accepted modules, matching // This runs BEFORE re-instantiating self-accepted modules, matching
// webpack's behavior. // webpack's behavior.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (!module) continue; if (!module) continue;
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (!hotState) continue; if (!hotState) continue;
...@@ -1800,7 +1800,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1800,7 +1800,7 @@ function formatDependencyChain(dependencyChain) {
try { try {
errorHandler(err, { errorHandler(err, {
moduleId, moduleId,
module: devModuleCache[moduleId] module: devModuleCache.get(moduleId)
}); });
} catch (err2) { } catch (err2) {
reportError(err2); reportError(err2);
...@@ -1860,7 +1860,7 @@ const devContextPrototype = Context.prototype; ...@@ -1860,7 +1860,7 @@ const devContextPrototype = Context.prototype;
* It will be appended to the runtime code of each runtime right after the * It will be appended to the runtime code of each runtime right after the
* shared runtime utils. * shared runtime utils.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ // Assign browser's module cache and runtime modules to shared HMR state */ /* eslint-disable @typescript-eslint/no-unused-vars */ // Assign browser's module cache and runtime modules to shared HMR state
devModuleCache = Object.create(null); devModuleCache = new Map();
devContextPrototype.c = devModuleCache; devContextPrototype.c = devModuleCache;
runtimeModules = new Set(); runtimeModules = new Set();
// Set flag to indicate we use ModuleWithDirection // Set flag to indicate we use ModuleWithDirection
...@@ -1890,7 +1890,7 @@ createModuleWithDirectionFlag = true; ...@@ -1890,7 +1890,7 @@ createModuleWithDirectionFlag = true;
* Gets or instantiates a runtime module. * Gets or instantiates a runtime module.
*/ // @ts-ignore */ // @ts-ignore
function getOrInstantiateRuntimeModule(chunkPath, moduleId) { function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
if (module) { if (module) {
if (module.error) { if (module.error) {
throw module.error; throw module.error;
...@@ -1907,7 +1907,7 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{ ...@@ -1907,7 +1907,7 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{
if (!sourceModule.hot.active) { if (!sourceModule.hot.active) {
console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`); console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`);
} }
const module = devModuleCache[id]; const module = devModuleCache.get(id);
if (sourceModule.children.indexOf(id) === -1) { if (sourceModule.children.indexOf(id) === -1) {
sourceModule.children.push(id); sourceModule.children.push(id);
} }
......
...@@ -77,15 +77,15 @@ function defineProp(obj, name, options) { ...@@ -77,15 +77,15 @@ function defineProp(obj, name, options) {
if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options); if (!hasOwnProperty.call(obj, name)) Object.defineProperty(obj, name, options);
} }
function getOverwrittenModule(moduleCache, id) { function getOverwrittenModule(moduleCache, id) {
let module = moduleCache[id]; let module = moduleCache.get(id);
if (!module) { if (module === undefined) {
if (createModuleWithDirectionFlag) { if (createModuleWithDirectionFlag) {
// set in development modes for hmr support // set in development modes for hmr support
module = createModuleWithDirection(id); module = createModuleWithDirection(id);
} else { } else {
module = createModuleObject(id); module = createModuleObject(id);
} }
moduleCache[id] = module; moduleCache.set(id, module);
} }
return module; return module;
} }
...@@ -1251,7 +1251,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1251,7 +1251,7 @@ function formatDependencyChain(dependencyChain) {
dependencyChain dependencyChain
}; };
} }
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update, if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before. // it means that the module was never instantiated before.
...@@ -1279,7 +1279,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1279,7 +1279,7 @@ function formatDependencyChain(dependencyChain) {
continue; continue;
} }
for (const parentId of module.parents){ for (const parentId of module.parents){
const parent = devModuleCache[parentId]; const parent = devModuleCache.get(parentId);
if (!parent) { if (!parent) {
continue; continue;
} }
...@@ -1478,7 +1478,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1478,7 +1478,7 @@ function formatDependencyChain(dependencyChain) {
*/ function computeOutdatedSelfAcceptedModules(outdatedModules) { */ function computeOutdatedSelfAcceptedModules(outdatedModules) {
const outdatedSelfAcceptedModules = []; const outdatedSelfAcceptedModules = [];
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (module && hotState?.selfAccepted && !hotState.selfInvalidated) { if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {
outdatedSelfAcceptedModules.push({ outdatedSelfAcceptedModules.push({
...@@ -1496,7 +1496,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1496,7 +1496,7 @@ function formatDependencyChain(dependencyChain) {
* NOTE: mode = "replace" will not remove modules from devModuleCache. * NOTE: mode = "replace" will not remove modules from devModuleCache.
* This must be done in a separate step afterwards. * This must be done in a separate step afterwards.
*/ function disposeModule(moduleId, mode) { */ function disposeModule(moduleId, mode) {
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
if (!module) { if (!module) {
return; return;
} }
...@@ -1520,7 +1520,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1520,7 +1520,7 @@ function formatDependencyChain(dependencyChain) {
// It will be added back once the module re-instantiates and imports its // It will be added back once the module re-instantiates and imports its
// children again. // children again.
for (const childId of module.children){ for (const childId of module.children){
const child = devModuleCache[childId]; const child = devModuleCache.get(childId);
if (!child) { if (!child) {
continue; continue;
} }
...@@ -1531,7 +1531,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1531,7 +1531,7 @@ function formatDependencyChain(dependencyChain) {
} }
switch(mode){ switch(mode){
case 'clear': case 'clear':
delete devModuleCache[module.id]; devModuleCache.delete(module.id);
moduleHotData.delete(module.id); moduleHotData.delete(module.id);
break; break;
case 'replace': case 'replace':
...@@ -1555,16 +1555,16 @@ function formatDependencyChain(dependencyChain) { ...@@ -1555,16 +1555,16 @@ function formatDependencyChain(dependencyChain) {
// We also want to keep track of previous parents of the outdated modules. // We also want to keep track of previous parents of the outdated modules.
const outdatedModuleParents = new Map(); const outdatedModuleParents = new Map();
for (const moduleId of outdatedModules){ for (const moduleId of outdatedModules){
const oldModule = devModuleCache[moduleId]; const oldModule = devModuleCache.get(moduleId);
outdatedModuleParents.set(moduleId, oldModule?.parents); outdatedModuleParents.set(moduleId, oldModule?.parents);
delete devModuleCache[moduleId]; devModuleCache.delete(moduleId);
} }
// Remove outdated dependencies from parent module's children list. // Remove outdated dependencies from parent module's children list.
// When a parent accepts a child's update, the child is re-instantiated // When a parent accepts a child's update, the child is re-instantiated
// but the parent stays alive. We remove the old child reference so it // but the parent stays alive. We remove the old child reference so it
// gets re-added when the child re-imports. // gets re-added when the child re-imports.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (module) { if (module) {
for (const dep of deps){ for (const dep of deps){
const idx = module.children.indexOf(dep); const idx = module.children.indexOf(dep);
...@@ -1616,7 +1616,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1616,7 +1616,7 @@ function formatDependencyChain(dependencyChain) {
module.parents = parents; module.parents = parents;
module.children = []; module.children = [];
module.hot = hot; module.hot = hot;
devModuleCache[id] = module; devModuleCache.set(id, module);
moduleHotState.set(module, hotState); moduleHotState.set(module, hotState);
// 5. Module execution (React Refresh hooks are platform-specific) // 5. Module execution (React Refresh hooks are platform-specific)
try { try {
...@@ -1750,7 +1750,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1750,7 +1750,7 @@ function formatDependencyChain(dependencyChain) {
// This runs BEFORE re-instantiating self-accepted modules, matching // This runs BEFORE re-instantiating self-accepted modules, matching
// webpack's behavior. // webpack's behavior.
for (const [parentId, deps] of outdatedDependencies){ for (const [parentId, deps] of outdatedDependencies){
const module = devModuleCache[parentId]; const module = devModuleCache.get(parentId);
if (!module) continue; if (!module) continue;
const hotState = moduleHotState.get(module); const hotState = moduleHotState.get(module);
if (!hotState) continue; if (!hotState) continue;
...@@ -1800,7 +1800,7 @@ function formatDependencyChain(dependencyChain) { ...@@ -1800,7 +1800,7 @@ function formatDependencyChain(dependencyChain) {
try { try {
errorHandler(err, { errorHandler(err, {
moduleId, moduleId,
module: devModuleCache[moduleId] module: devModuleCache.get(moduleId)
}); });
} catch (err2) { } catch (err2) {
reportError(err2); reportError(err2);
...@@ -1860,7 +1860,7 @@ const devContextPrototype = Context.prototype; ...@@ -1860,7 +1860,7 @@ const devContextPrototype = Context.prototype;
* It will be appended to the runtime code of each runtime right after the * It will be appended to the runtime code of each runtime right after the
* shared runtime utils. * shared runtime utils.
*/ /* eslint-disable @typescript-eslint/no-unused-vars */ // Assign browser's module cache and runtime modules to shared HMR state */ /* eslint-disable @typescript-eslint/no-unused-vars */ // Assign browser's module cache and runtime modules to shared HMR state
devModuleCache = Object.create(null); devModuleCache = new Map();
devContextPrototype.c = devModuleCache; devContextPrototype.c = devModuleCache;
runtimeModules = new Set(); runtimeModules = new Set();
// Set flag to indicate we use ModuleWithDirection // Set flag to indicate we use ModuleWithDirection
...@@ -1890,7 +1890,7 @@ createModuleWithDirectionFlag = true; ...@@ -1890,7 +1890,7 @@ createModuleWithDirectionFlag = true;
* Gets or instantiates a runtime module. * Gets or instantiates a runtime module.
*/ // @ts-ignore */ // @ts-ignore
function getOrInstantiateRuntimeModule(chunkPath, moduleId) { function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
const module = devModuleCache[moduleId]; const module = devModuleCache.get(moduleId);
if (module) { if (module) {
if (module.error) { if (module.error) {
throw module.error; throw module.error;
...@@ -1907,7 +1907,7 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{ ...@@ -1907,7 +1907,7 @@ const getOrInstantiateModuleFromParent = (id, sourceModule)=>{
if (!sourceModule.hot.active) { if (!sourceModule.hot.active) {
console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`); console.warn(`Unexpected import of module ${id} from module ${sourceModule.id}, which was deleted by an HMR update`);
} }
const module = devModuleCache[id]; const module = devModuleCache.get(id);
if (sourceModule.children.indexOf(id) === -1) { if (sourceModule.children.indexOf(id) === -1) {
sourceModule.children.push(id); sourceModule.children.push(id);
} }
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment