Commit 44d2756a authored by Will Binns-Smith's avatar Will Binns-Smith

Move browser HMR client to browser/runtime/base

parent 6b060d06
......@@ -10154,6 +10154,9 @@ dependencies = [
"anyhow",
"bincode 2.0.1",
"indoc",
"serde",
"serde_json",
"serde_qs",
"tracing",
"turbo-bincode",
"turbo-rcstr",
......
......@@ -59,7 +59,6 @@ if (process.env.NODE_ENV === 'development') {
SegmentViewStateNode = mod.SegmentViewStateNode
}
// For hot-reloader
declare global {
var __next__clear_chunk_cache__: (() => void) | null | undefined
var __turbopack_clear_chunk_cache__: () => void | null | undefined
......
......@@ -150,11 +150,20 @@ declare const __turbopack_server_hmr_apply__:
| ((update: NodeJsPartialHmrUpdate) => boolean)
| undefined
function setupServerHmr(project: Project) {
const serverHmrSubscriptions = new Map<
string,
AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
>()
type ServerHmrSubscriptions = Map<
string,
AsyncIterableIterator<TurbopackResult<NodeJsHmrUpdate>>
>
function setupServerHmr(
project: Project,
{
onUpdateFailed,
}: {
onUpdateFailed: () => void | Promise<void>
}
) {
const serverHmrSubscriptions: ServerHmrSubscriptions = new Map()
/**
* Subscribe to HMR updates for a server chunk.
......@@ -175,67 +184,69 @@ function setupServerHmr(project: Project) {
for await (const result of subscription) {
const update = result as NodeJsHmrUpdate
// Only process partial updates with actual code changes
if (update.type !== 'partial') {
continue
}
const entries = update.instruction?.entries
if (!entries || Object.keys(entries).length === 0) {
const instruction = update.instruction
if (!instruction || instruction.type !== 'EcmascriptMergedUpdate') {
continue
}
if (typeof __turbopack_server_hmr_apply__ === 'function') {
const applied = __turbopack_server_hmr_apply__(update as any)
if (applied) {
console.log(`[Server HMR] Applied update for ${chunkPath}`)
// TODO: Notify clients to refresh and get updated server content
// This will trigger the client to re-fetch the page with new server components
const applied = __turbopack_server_hmr_apply__(update)
if (!applied) {
await onUpdateFailed()
}
}
}
})().catch((err) => {
})().catch(async (err) => {
console.error('[Server HMR] Subscription error:', err)
serverHmrSubscriptions.delete(chunkPath)
await onUpdateFailed()
})
}
// Listen to the Rust bindings update us on changing server HMR chunk paths
;(async () => {
const serverHmrChunkPaths = project.hmrChunkNamesSubscribe(HmrTarget.Server)
// Process chunk paths (both initial and subsequent updates)
for await (const data of serverHmrChunkPaths) {
const currentChunkPaths = new Set(
data.chunkNames.filter((path) => path.endsWith('.js'))
try {
const serverHmrChunkPaths = project.hmrChunkNamesSubscribe(
HmrTarget.Server
)
// Clean up subscriptions for removed chunk paths (like when pages are deleted)
const chunkPathsToRemove = []
for (const chunkPath of serverHmrSubscriptions.keys()) {
if (!currentChunkPaths.has(chunkPath)) {
chunkPathsToRemove.push(chunkPath)
// Process chunk paths (both initial and subsequent updates)
for await (const data of serverHmrChunkPaths) {
const currentChunkPaths = new Set<string>(
data.chunkNames.filter((path) => path.endsWith('.js'))
)
// Clean up subscriptions for removed chunk paths (like when pages are deleted)
const chunkPathsToRemove: string[] = []
for (const chunkPath of serverHmrSubscriptions.keys()) {
if (!currentChunkPaths.has(chunkPath)) {
chunkPathsToRemove.push(chunkPath)
}
}
}
for (const chunkPath of chunkPathsToRemove) {
const subscription = serverHmrSubscriptions.get(chunkPath)
subscription?.return?.()
serverHmrSubscriptions.delete(chunkPath)
}
for (const chunkPath of chunkPathsToRemove) {
const subscription = serverHmrSubscriptions.get(chunkPath)
subscription?.return?.()
serverHmrSubscriptions.delete(chunkPath)
}
// Subscribe to HMR events for new server chunks
for (const chunkPath of currentChunkPaths) {
if (!serverHmrSubscriptions.has(chunkPath)) {
subscribeToServerHmr(chunkPath)
// Subscribe to HMR events for new server chunks
for (const chunkPath of currentChunkPaths) {
if (!serverHmrSubscriptions.has(chunkPath)) {
subscribeToServerHmr(chunkPath)
}
}
}
} catch (err) {
console.error('[Server HMR Setup] Error in chunk path subscription:', err)
}
})().catch((err) => {
console.error('[Server HMR] error:', err)
})
})()
return serverHmrSubscriptions
}
/**
......@@ -552,22 +563,35 @@ export async function createHotReloaderTurbopack(
resetFetch()
// Not available in:
// - Pages Router (no server-side HMR)
// - Edge Runtime (uses browser runtime which already disposes chunks individually)
if (typeof __next__clear_chunk_cache__ === 'function') {
__next__clear_chunk_cache__()
}
const serverPaths = writtenEndpoint.serverPaths.map(({ path: p }) =>
join(distDir, p)
)
for (const file of serverPaths) {
// Skip clearing cache for server chunks with active HMR subscriptions
// Server HMR already applied granular updates to the turbopack module cache
const relativePath = relative(distDir, file)
if (serverHmrSubscriptions?.has(relativePath)) {
continue
}
clearModuleContext(file)
deleteCache(file)
}
// Clear Turbopack's module cache when server HMR is not active.
// When server HMR IS active, HMR manages the module cache granularly,
// so we must not clear it here.
// Not available in:
// - Pages Router (no server-side HMR)
// - Edge Runtime (uses browser runtime which already disposes chunks individually)
if (
!serverHmrSubscriptions &&
typeof __next__clear_chunk_cache__ === 'function'
) {
__next__clear_chunk_cache__()
}
return true
}
......@@ -606,9 +630,7 @@ export async function createHotReloaderTurbopack(
}
}
if (experimentalServerFastRefresh) {
setupServerHmr(project)
}
let serverHmrSubscriptions: ServerHmrSubscriptions | undefined
let hmrEventHappened = false
let hmrHash = 0
......@@ -1754,5 +1776,24 @@ export async function createHotReloaderTurbopack(
process.exit(1)
})
if (experimentalServerFastRefresh) {
serverHmrSubscriptions = setupServerHmr(project, {
onUpdateFailed: async () => {
if (typeof __next__clear_chunk_cache__ === 'function') {
__next__clear_chunk_cache__()
}
// Clear all module contexts so they're re-evaluated on next request
await clearAllModuleContexts()
// Tell browsers to refetch RSC (soft refresh, not full page reload)
hotReloader.send({
type: HMR_MESSAGE_SENT_TO_BROWSER.SERVER_COMPONENT_CHANGES,
hash: String(++hmrHash),
})
},
})
}
return hotReloader
}
import { message, evaluatedAt } from '../child-module'
export default function Page() {
return (
<div>
<p id="message">{message}</p>
<p id="eval-time">Module evaluated at: {evaluatedAt}</p>
</div>
)
}
export const message = 'Initial message'
export const evaluatedAt = Date.now()
declare const module: any
if (typeof module !== 'undefined' && module.hot) {
module.hot.accept()
}
import { evaluatedAt } from './unmodified-module'
import { evaluatedAt } from '../unmodified-module'
const pageLoadId = Math.random().toString(36).slice(2)
......
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('server-hmr', () => {
const { next, isTurbopack, isNextDev } = nextTestSetup({
files: __dirname,
startArgs: ['--experimental-server-fast-refresh'],
})
// Server HMR is a Turbopack-only feature, only available in dev mode
const itTurbopackDev = isTurbopack && isNextDev ? it : it.skip
describe('module preservation', () => {
itTurbopackDev(
'does not re-evaluate an unmodified module when page module changes',
async () => {
const browser = await next.browser('/module-preservation')
// Wait for initial render with module timestamp
await retry(async () => {
const text = await browser.elementByCss('#module-eval-time').text()
expect(text).toMatch(/Module Evaluated At: \d+/)
})
// Capture the initial module evaluation timestamp
const initialModuleEvalTime = await browser
.elementByCss('#module-eval-time')
.text()
// Make a change to the page that doesn't affect the unmodified module
await next.patchFile('app/module-preservation/page.tsx', (content) =>
content.replace('hello world', 'hello universe')
)
// Wait for HMR to apply and verify the page updated
await retry(async () => {
const text = await browser.elementByCss('#greeting').text()
expect(text).toBe('hello universe')
})
// The unmodified module should NOT have been re-evaluated (same timestamp)
const newModuleEvalTime = await browser
.elementByCss('#module-eval-time')
.text()
expect(newModuleEvalTime).toBe(initialModuleEvalTime)
}
)
itTurbopackDev(
're-evaluates a module when the module itself changes',
async () => {
const browser = await next.browser('/module-preservation')
// Wait for initial render
await retry(async () => {
const text = await browser.elementByCss('#module-eval-time').text()
expect(text).toMatch(/Module Evaluated At: \d+/)
})
// Capture the initial module evaluation timestamp
const initialModuleEvalTime = await browser
.elementByCss('#module-eval-time')
.text()
// Make a change to the module itself to trigger re-evaluation
await next.patchFile('app/unmodified-module.ts', (content) =>
content.replace('_hmrTrigger = 0', '_hmrTrigger = 1')
)
// Wait for HMR to apply - the module should be re-evaluated
// and the timestamp should change
await retry(async () => {
// Refresh to trigger re-evaluation of changed modules
await browser.refresh()
const newModuleEvalTime = await browser
.elementByCss('#module-eval-time')
.text()
expect(newModuleEvalTime).not.toBe(initialModuleEvalTime)
})
}
)
})
describe('child module accept', () => {
itTurbopackDev(
'allows child modules to accept hot updates using module.hot.accept',
async () => {
const browser = await next.browser('/child-accept')
// Wait for initial render
await retry(async () => {
const text = await browser.elementByCss('#message').text()
expect(text).toBe('Initial message')
})
const initialEvalTime = await browser.elementByCss('#eval-time').text()
expect(initialEvalTime).toMatch(/Module evaluated at: \d+/)
// Make a change to the child module
// The child module calls module.hot.accept(), which allows it to
// accept updates. While pages auto-accept at the top level in server HMR,
// this test verifies that module.hot.accept() is available and functional
// in non-page, user-authored child modules.
await next.patchFile('app/child-module.ts', (content) =>
content.replace('Initial message', 'Updated message')
)
// Wait for HMR to apply - the child module should accept the update
await retry(async () => {
const text = await browser.elementByCss('#message').text()
expect(text).toBe('Updated message')
})
// The module should have been re-evaluated (new timestamp)
const newEvalTime = await browser.elementByCss('#eval-time').text()
expect(newEvalTime).not.toBe(initialEvalTime)
// Apply another update to verify the module continues to accept updates
await next.patchFile('app/child-module.ts', (content) =>
content.replace('Updated message', 'Second update')
)
await retry(async () => {
const text = await browser.elementByCss('#message').text()
expect(text).toBe('Second update')
})
}
)
})
})
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
describe('server-hmr-module-preservation', () => {
const { next, isTurbopack, isNextDev } = nextTestSetup({
files: __dirname,
startArgs: ['--experimental-server-fast-refresh'],
})
// Server HMR is a Turbopack-only feature, only available in dev mode
const itTurbopackDev = isTurbopack && isNextDev ? it : it.skip
itTurbopackDev(
'should preserve unmodified module when page module changes',
async () => {
const browser = await next.browser('/')
// Wait for initial render with module timestamp
await retry(async () => {
const text = await browser.elementByCss('#module-eval-time').text()
expect(text).toMatch(/Module Evaluated At: \d+/)
})
// Capture the initial module evaluation timestamp
const initialModuleEvalTime = await browser
.elementByCss('#module-eval-time')
.text()
// Mark where we are in CLI output
const cliOutputBeforePatch = next.cliOutput.length
// Make a change to the page that doesn't affect the unmodified module
await next.patchFile('app/page.tsx', (content) =>
content.replace('hello world', 'hello universe')
)
// Wait for HMR to apply and verify the page updated
await retry(async () => {
const text = await browser.elementByCss('#greeting').text()
expect(text).toBe('hello universe')
})
// The unmodified module should NOT have been re-evaluated (same timestamp)
const newModuleEvalTime = await browser
.elementByCss('#module-eval-time')
.text()
expect(newModuleEvalTime).toBe(initialModuleEvalTime)
// Also verify via CLI output that unmodified module wasn't re-evaluated
const cliOutputAfterPatch = next.cliOutput.slice(cliOutputBeforePatch)
expect(cliOutputAfterPatch).not.toContain('[Module] evaluated')
}
)
itTurbopackDev(
'should re-evaluate module when the module itself changes',
async () => {
const browser = await next.browser('/')
// Wait for initial render
await retry(async () => {
const text = await browser.elementByCss('#module-eval-time').text()
expect(text).toMatch(/Module Evaluated At: \d+/)
})
// Capture the initial module evaluation timestamp
const initialModuleEvalTime = await browser
.elementByCss('#module-eval-time')
.text()
// Mark CLI output position
const cliOutputBeforePatch = next.cliOutput.length
// Make a change to the unmodified module itself
await next.patchFile('app/unmodified-module.ts', (content) =>
content.replace(
"console.log('[Module] evaluated')",
"console.log('[Module] RE-evaluated')"
)
)
// Wait for HMR to apply - the module should be re-evaluated
// and the timestamp should change
await retry(async () => {
// Refresh to trigger re-evaluation of changed modules
await browser.refresh()
const newModuleEvalTime = await browser
.elementByCss('#module-eval-time')
.text()
expect(newModuleEvalTime).not.toBe(initialModuleEvalTime)
})
// Verify via CLI output that module was re-evaluated
const cliOutputAfterPatch = next.cliOutput.slice(cliOutputBeforePatch)
expect(cliOutputAfterPatch).toContain('[Module] RE-evaluated')
}
)
})
// Adapted from https://github.com/vercel/next.js/blob/canary/packages/next/src/client/dev/error-overlay/websocket.ts
import type { WebSocketMessage } from '@vercel/turbopack-ecmascript-runtime/browser/dev/hmr-client/hmr-client'
import type { HmrMessage } from '@vercel/turbopack-ecmascript-runtime/browser/dev/hmr-client/hmr-client'
let source: WebSocket
const messageCallbacks: ((message: WebSocketMessage) => void)[] = []
const messageCallbacks: ((message: HmrMessage) => void)[] = []
// TODO: add timeout again
// let lastActivity = Date.now()
......@@ -19,7 +19,7 @@ function getSocketProtocol(assetPrefix: string): string {
return protocol === 'http:' ? 'ws' : 'wss'
}
export function addMessageListener(cb: (message: WebSocketMessage) => void) {
export function addMessageListener(cb: (message: HmrMessage) => void) {
messageCallbacks.push(cb)
}
......
......@@ -381,11 +381,12 @@ function applyEcmascriptMergedUpdate(update: EcmascriptMergedUpdate) {
modified,
disposedModules,
evalModuleEntry: _eval, // browser's eval with source maps
instantiateModuleFn: instantiateModule, // now wraps shared logic
applyModuleFactoryNameFn: applyModuleFactoryName,
instantiateModule, // now wraps shared logic
applyModuleFactoryName,
moduleFactories,
devModuleCache,
autoAcceptRootModules: false, // Browser HMR requires explicit accept calls
runtimeModules,
autoAcceptAtRoot: false,
})
}
......
/// <reference path="../../shared/runtime/dev-globals.d.ts" />
/// <reference path="../../shared/runtime/dev-protocol.d.ts" />
/// <reference path="./hmr-client.ts" />
/**
* Note: hmr-runtime.ts is embedded before this file, so its functions
* (initializeServerHmr, emitMessage) are available in the same scope.
*/
// Initialize server HMR client (connects to shared HMR infrastructure)
let hmrClientInitialized = false
function ensureHmrClientInitialized() {
if (hmrClientInitialized) return
hmrClientInitialized = true
// initializeServerHmr is from hmr-client.ts (embedded before this file)
// moduleFactories, runtimeModules, and instantiateModule are from dev-runtime.ts
// devModuleCache is the HotModule-typed cache from dev-runtime.ts
initializeServerHmr(
moduleFactories,
devModuleCache,
runtimeModules,
instantiateModule
)
}
function __turbopack_server_hmr_apply__(update: NodeJsHmrPayload): boolean {
try {
ensureHmrClientInitialized()
// emitMessage returns false if any listener failed to apply the update
return emitMessage({
type: 'turbopack-message',
data: update,
})
} catch (err) {
console.error('[Server HMR] Failed to apply update:', err)
return false
}
}
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__
/// <reference path="../../shared/runtime/dev-protocol.d.ts" />
/// <reference path="../../shared/runtime/hmr-runtime.ts" />
/* eslint-disable @typescript-eslint/no-unused-vars */
/**
* Node.js HMR client implementation.
* Simplified for concatenated runtime - no ESM imports.
*/
// Node.js HMR payload with direct EcmascriptMergedUpdate (no ChunkListUpdate wrapper)
type NodeJsHmrPayload = {
resource: {
path: string
headers?: Record<string, string>
}
issues: Issue[]
type: 'partial'
instruction: EcmascriptMergedUpdate
}
/**
* Emits an HMR message to registered update listeners.
* In Node.js, we directly invoke the listeners rather than going through
* a full message backend like the browser does.
*/
function emitMessage(msg: { type: string; data: any }): boolean {
// Find and invoke listeners registered in TURBOPACK_CHUNK_UPDATE_LISTENERS
let success = true
if (globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS) {
for (const [
_chunkPath,
listener,
] of globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS) {
try {
listener(msg.data)
} catch (err) {
console.error('[Server HMR] Listener error:', err)
success = false
}
}
}
return success
}
/**
* Handles server message updates and applies them to the Node.js runtime.
* Uses shared HMR update logic from hmr-runtime.ts.
*/
function handleNodejsUpdate(
msg: NodeJsHmrPayload,
moduleFactories: ModuleFactories,
devModuleCache: ModuleCache<HotModule>,
runtimeModules: Set<ModuleId>,
instantiateModuleFn: (
moduleId: ModuleId,
sourceType: SourceType,
sourceData: SourceData
) => HotModule
): void {
if (msg.type !== 'partial') {
return
}
const instruction = msg.instruction
if (instruction.type !== 'EcmascriptMergedUpdate') {
return
}
try {
const { entries = {}, chunks = {} } = instruction
// Node.js eval function (no source maps)
const evalModuleEntry = (entry: EcmascriptModuleEntry) => {
// eslint-disable-next-line no-eval
return (0, eval)(entry.code)
}
const { added, modified } = computeChangedModules(
entries,
chunks,
undefined // no chunkModulesMap for Node.js
)
// Use shared HMR update implementation
applyEcmascriptMergedUpdateShared({
added,
modified,
disposedModules: [], // no disposedModules for Node.js (no chunk management)
evalModuleEntry,
instantiateModule,
applyModuleFactoryName: () => {}, // Node doesn't use this
moduleFactories,
devModuleCache,
runtimeModules,
autoAcceptAtRoot: true,
})
} catch (e) {
console.error('[Server HMR] Update failed, full reload needed:', e)
throw e
}
}
let initialized = false
function initializeServerHmr(
moduleFactories: ModuleFactories,
devModuleCache: ModuleCache<HotModule>,
runtimeModules: Set<ModuleId>,
instantiateModuleFn: (
moduleId: ModuleId,
sourceType: SourceType,
sourceData: SourceData
) => HotModule
): void {
if (initialized) {
return
}
initialized = true
const queued = globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS
if (queued != null && !Array.isArray(queued)) {
throw new Error('A separate HMR handler was already registered')
}
if (!Array.isArray(globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS)) {
globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS = []
}
// Register an update callback for the server runtime
// The chunk path doesn't matter much for Node.js server since we get updates
// directly, but we use '__server__' as a placeholder
const serverChunkPath = '__server__' as ChunkListPath
globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS.push([
serverChunkPath,
(msg: NodeJsHmrPayload) => {
handleNodejsUpdate(
msg,
moduleFactories,
devModuleCache,
runtimeModules,
instantiateModuleFn
)
},
])
}
/* eslint-disable @typescript-eslint/no-unused-vars */
/// <reference path="./runtime-base.ts" />
/**
* Production Node.js runtime.
* Uses ModuleWithDirection and simple module instantiation without HMR support.
*/
// moduleCache and moduleFactories are declared in runtime-base.ts
interface TurbopackNodeBuildContext
extends TurbopackBaseContext<ModuleWithDirection> {
R: ResolvePathFromModule
x: ExternalRequire
y: ExternalImport
C: typeof clearChunkCache
}
const nodeContextPrototype = Context.prototype as TurbopackNodeBuildContext
nodeContextPrototype.q = exportUrl
nodeContextPrototype.M = moduleFactories
// Cast moduleCache to ModuleWithDirection for production mode
nodeContextPrototype.c = moduleCache as ModuleCache<ModuleWithDirection>
nodeContextPrototype.R = resolvePathFromModule
nodeContextPrototype.b = getWorkerURL
nodeContextPrototype.C = clearChunkCache
function instantiateModule(
id: ModuleId,
sourceType: SourceType,
sourceData: SourceData
): ModuleWithDirection {
const moduleFactory = moduleFactories.get(id)
if (typeof moduleFactory !== 'function') {
// This can happen if modules incorrectly handle HMR disposes/updates,
// e.g. when they keep a `setTimeout` around which still executes old code
// and contains e.g. a `require("something")` call.
let instantiationReason: string
switch (sourceType) {
case SourceType.Runtime:
instantiationReason = `as a runtime entry of chunk ${sourceData}`
break
case SourceType.Parent:
instantiationReason = `because it was required from module ${sourceData}`
break
default:
invariant(
sourceType,
(sourceType) => `Unknown source type: ${sourceType}`
)
}
throw new Error(
`Module ${id} was instantiated ${instantiationReason}, but the module factory is not available.`
)
}
const module: ModuleWithDirection = createModuleWithDirection(id)
const exports = module.exports
moduleCache[id] = module
const context =
new (Context as any as ContextConstructor<ModuleWithDirection>)(
module,
exports
)
// NOTE(alexkirsz) This can fail when the module encounters a runtime error.
try {
moduleFactory(context, module, exports)
} catch (error) {
module.error = error as any
throw error
}
;(module as any).loaded = true
if (module.namespaceObject && module.exports !== module.namespaceObject) {
// in case of a circular dependency: cjs1 -> esm2 -> cjs1
interopEsm(module.exports, module.namespaceObject)
}
return module
}
/**
* Retrieves a module from the cache, or instantiate it if it is not cached.
*/
// @ts-ignore
function getOrInstantiateModuleFromParent(
id: ModuleId,
sourceModule: ModuleWithDirection
): ModuleWithDirection {
const module = moduleCache[id]
if (module) {
if (module.error) {
throw module.error
}
return module
}
return instantiateModule(id, SourceType.Parent, sourceModule.id)
}
/**
* Instantiates a runtime module.
*/
function instantiateRuntimeModule(
chunkPath: ChunkPath,
moduleId: ModuleId
): ModuleWithDirection {
return instantiateModule(moduleId, SourceType.Runtime, chunkPath)
}
/**
* 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
function getOrInstantiateRuntimeModule(
chunkPath: ChunkPath,
moduleId: ModuleId
): ModuleWithDirection {
const module = moduleCache[moduleId]
if (module) {
if (module.error) {
throw module.error
}
return module
}
return instantiateRuntimeModule(chunkPath, moduleId)
}
module.exports = (sourcePath: ChunkPath) => ({
m: (id: ModuleId) => getOrInstantiateRuntimeModule(sourcePath, id),
c: (chunkData: ChunkData) => loadRuntimeChunk(sourcePath, chunkData),
})
/* eslint-disable @typescript-eslint/no-unused-vars */
/// <reference path="./runtime-base.ts" />
/// <reference path="../../shared/runtime/dev-extensions.ts" />
/// <reference path="../../shared/runtime/hmr-runtime.ts" />
/**
* Development Node.js runtime.
* Uses HotModule and shared HMR logic for hot module replacement support.
*/
// Cast the module cache to HotModule for development mode
// (hmr-runtime.ts declares devModuleCache as `let` variable expecting assignment)
// This is safe because HotModule extends Module
devModuleCache = moduleCache as ModuleCache<HotModule>
if (!globalThis.__turbopack_runtime_modules__) {
globalThis.__turbopack_runtime_modules__ = new Set()
}
runtimeModules = globalThis.__turbopack_runtime_modules__
interface TurbopackNodeDevBuildContext extends TurbopackBaseContext<HotModule> {
R: ResolvePathFromModule
x: ExternalRequire
y: ExternalImport
C: typeof clearChunkCache
}
const nodeDevContextPrototype =
Context.prototype as TurbopackNodeDevBuildContext
nodeDevContextPrototype.q = exportUrl
nodeDevContextPrototype.M = moduleFactories
nodeDevContextPrototype.c = devModuleCache
nodeDevContextPrototype.R = resolvePathFromModule
nodeDevContextPrototype.b = getWorkerURL
nodeDevContextPrototype.C = clearChunkCache
/**
* Instantiates a module in development mode using shared HMR logic.
*/
function instantiateModule(
id: ModuleId,
sourceType: SourceType,
sourceData: SourceData
): HotModule {
// Node.js: creates base module object (hot API added by shared code)
const createModuleObjectFn = (moduleId: ModuleId) => {
return createModuleWithDirection(moduleId) as HotModule
}
// Node.js: creates Context (no refresh parameter)
const createContext = (
module: HotModule,
exports: Exports,
_refresh?: any
) => {
return new (Context as any as ContextConstructor<HotModule>)(
module,
exports
)
}
// Node.js: no hooks wrapper, just execute directly
const runWithHooks = (module: HotModule, exec: (refresh: any) => void) => {
exec(undefined) // no refresh context
}
// Use shared instantiation logic (includes hot API setup)
const newModule = instantiateModuleShared(
id,
sourceType,
sourceData,
moduleFactories,
devModuleCache,
runtimeModules,
createModuleObjectFn,
createContext,
runWithHooks
)
// Node.js-specific: mark module as loaded
;(newModule as any).loaded = true
return newModule
}
/**
* Instantiates a runtime module in development mode.
*/
function instantiateRuntimeModule(
chunkPath: ChunkPath,
moduleId: ModuleId
): HotModule {
return instantiateModule(moduleId, SourceType.Runtime, chunkPath)
}
/**
* 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
function getOrInstantiateRuntimeModule(
chunkPath: ChunkPath,
moduleId: ModuleId
): HotModule {
const module = devModuleCache[moduleId]
if (module) {
if (module.error) {
throw module.error
}
return module
}
return instantiateRuntimeModule(chunkPath, moduleId)
}
/**
* Retrieves a module from the cache, or instantiate it if it is not cached.
* Also tracks parent-child relationships for HMR dependency tracking.
*/
// @ts-ignore
function getOrInstantiateModuleFromParent(
id: ModuleId,
sourceModule: HotModule
): HotModule {
// Track parent-child relationship
trackModuleImport(sourceModule, id, devModuleCache[id])
const module = devModuleCache[id]
if (module) {
if (module.error) {
throw module.error
}
return module
}
const newModule = instantiateModule(id, SourceType.Parent, sourceModule.id)
// Track again after instantiation to ensure the relationship is recorded
trackModuleImport(sourceModule, id, newModule)
return newModule
}
module.exports = (sourcePath: ChunkPath) => ({
m: (id: ModuleId) => getOrInstantiateRuntimeModule(sourcePath, id),
c: (chunkData: ChunkData) => loadRuntimeChunk(sourcePath, chunkData),
})
/// <reference path="../../shared/runtime-types.d.ts" />
/**
* Global type definitions for Node.js Turbopack runtime.
* These properties are stored on globalThis to persist across chunk reloads during HMR.
*/
declare global {
var __turbopack_module_factories__: ModuleFactories
var __turbopack_module_cache__: Record<ModuleId, any>
var __turbopack_runtime_modules__: Set<ModuleId>
}
export {}
/* eslint-disable @typescript-eslint/no-unused-vars */
/// <reference path="../hmr-types.d.ts" />
/// <reference path="../../shared/runtime/runtime-utils.ts" />
/// <reference path="../../shared-node/base-externals-utils.ts" />
/// <reference path="../../shared-node/node-externals-utils.ts" />
/// <reference path="../../shared-node/node-wasm-utils.ts" />
/// <reference path="./nodejs-globals.d.ts" />
enum SourceType {
/**
* The module was instantiated because it was included in an evaluated chunk's
* runtime.
* SourceData is a ChunkPath.
*/
Runtime = 0,
/**
* The module was instantiated because a parent module imported it.
* SourceData is a ModuleId.
*/
Parent = 1,
}
type SourceData = ChunkPath | ModuleId
/**
* Base Node.js runtime shared between production and development.
* Contains chunk loading, module caching, and other non-HMR functionality.
*/
process.env.TURBOPACK = '1'
interface TurbopackNodeBuildContext extends TurbopackBaseContext<Module> {
R: ResolvePathFromModule
x: ExternalRequire
y: ExternalImport
q: ExportUrl
}
const nodeContextPrototype = Context.prototype as TurbopackNodeBuildContext
const url = require('url') as typeof import('url')
type ModuleFactory = (
this: Module['exports'],
context: TurbopackNodeBuildContext
) => unknown
// Use global module factories and cache to persist across chunk reloads during HMR
// This ensures that when Node.js clears the require cache for a chunk file,
// we don't lose our granular HMR updates to individual modules
if (!globalThis.__turbopack_module_factories__) {
globalThis.__turbopack_module_factories__ = new Map()
}
if (!globalThis.__turbopack_module_cache__) {
globalThis.__turbopack_module_cache__ = Object.create(null)
}
const url = require('url') as typeof import('url')
const moduleFactories: ModuleFactories =
globalThis.__turbopack_module_factories__
const moduleFactories: ModuleFactories = new Map()
nodeContextPrototype.M = moduleFactories
const moduleCache: ModuleCache<Module> = Object.create(null)
nodeContextPrototype.c = moduleCache
// Module cache - typed as base Module, can be cast to HotModule in dev mode
const moduleCache: ModuleCache<Module> = globalThis.__turbopack_module_cache__
/**
* Returns an absolute path to the given module's id.
......@@ -63,7 +49,6 @@ function resolvePathFromModule(
return url.pathToFileURL(resolved).href
}
nodeContextPrototype.R = resolvePathFromModule
/**
* Exports a URL value. No suffix is added in Node.js runtime.
......@@ -75,7 +60,6 @@ function exportUrl(
) {
exportValue.call(this, urlValue, id)
}
nodeContextPrototype.q = exportUrl
function loadRuntimeChunk(sourcePath: ChunkPath, chunkData: ChunkData): void {
if (typeof chunkData === 'string') {
......@@ -90,8 +74,17 @@ const unsupportedLoadChunk = Promise.resolve(undefined)
const loadedChunk: Promise<void> = Promise.resolve(undefined)
const chunkCache = new Map<ChunkPath, Promise<void>>()
/**
* Clear all chunk and module state to force re-evaluation on next require.
* Called by Next.js when server HMR is disabled to implement the "reload everything" behavior.
*/
function clearChunkCache() {
chunkCache.clear()
loadedChunks.clear()
moduleFactories.clear()
for (const key in moduleCache) {
delete moduleCache[key]
}
}
function loadRuntimeChunkPath(
......@@ -127,7 +120,7 @@ function loadRuntimeChunkPath(
}
function loadChunkAsync(
this: TurbopackBaseContext<Module>,
this: TurbopackBaseContext<any>,
chunkData: ChunkData
): Promise<void> {
const chunkPath = typeof chunkData === 'string' ? chunkData : chunkData.path
......@@ -163,7 +156,7 @@ function loadChunkAsync(
contextPrototype.l = loadChunkAsync
function loadChunkAsyncByUrl(
this: TurbopackBaseContext<Module>,
this: TurbopackBaseContext<any>,
chunkUrl: string
) {
const path = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT)) as ChunkPath
......@@ -200,112 +193,6 @@ function getWorkerURL(
throw new Error('Worker urls are not implemented yet for Node.js')
}
nodeContextPrototype.b = getWorkerURL
function instantiateModule(
id: ModuleId,
sourceType: SourceType,
sourceData: SourceData
): Module {
const moduleFactory = moduleFactories.get(id)
if (typeof moduleFactory !== 'function') {
// This can happen if modules incorrectly handle HMR disposes/updates,
// e.g. when they keep a `setTimeout` around which still executes old code
// and contains e.g. a `require("something")` call.
let instantiationReason: string
switch (sourceType) {
case SourceType.Runtime:
instantiationReason = `as a runtime entry of chunk ${sourceData}`
break
case SourceType.Parent:
instantiationReason = `because it was required from module ${sourceData}`
break
default:
invariant(
sourceType,
(sourceType) => `Unknown source type: ${sourceType}`
)
}
throw new Error(
`Module ${id} was instantiated ${instantiationReason}, but the module factory is not available.`
)
}
const module: Module = createModuleObject(id)
const exports = module.exports
moduleCache[id] = module
const context = new (Context as any as ContextConstructor<Module>)(
module,
exports
)
// NOTE(alexkirsz) This can fail when the module encounters a runtime error.
try {
moduleFactory(context, module, exports)
} catch (error) {
module.error = error as any
throw error
}
module.loaded = true
if (module.namespaceObject && module.exports !== module.namespaceObject) {
// in case of a circular dependency: cjs1 -> esm2 -> cjs1
interopEsm(module.exports, module.namespaceObject)
}
return module
}
/**
* Retrieves a module from the cache, or instantiate it if it is not cached.
*/
// @ts-ignore
function getOrInstantiateModuleFromParent(
id: ModuleId,
sourceModule: Module
): Module {
const module = moduleCache[id]
if (module) {
if (module.error) {
throw module.error
}
return module
}
return instantiateModule(id, SourceType.Parent, sourceModule.id)
}
/**
* Instantiates a runtime module.
*/
function instantiateRuntimeModule(
chunkPath: ChunkPath,
moduleId: ModuleId
): Module {
return instantiateModule(moduleId, SourceType.Runtime, chunkPath)
}
/**
* 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
function getOrInstantiateRuntimeModule(
chunkPath: ChunkPath,
moduleId: ModuleId
): Module {
const module = moduleCache[moduleId]
if (module) {
if (module.error) {
throw module.error
}
return module
}
return instantiateRuntimeModule(chunkPath, moduleId)
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/
/**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
......@@ -313,18 +200,3 @@ const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/
function isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {
return regexJsUrl.test(chunkUrlOrPath)
}
function __turbopack_server_hmr_apply__(
_update: NodeJsPartialHmrUpdate
): boolean {
// TODO: Implement actual HMR logic to update module factories
// For now, just return true to indicate we "accepted" the update
return true
}
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__
module.exports = (sourcePath: ChunkPath) => ({
m: (id: ModuleId) => getOrInstantiateRuntimeModule(sourcePath, id),
c: (chunkData: ChunkData) => loadRuntimeChunk(sourcePath, chunkData),
})
......@@ -83,12 +83,19 @@ function trackModuleImport(
childModule: ModuleWithDirection | undefined
): void {
// Record that parent imports child
if (parentModule.children.indexOf(childModuleId) === -1) {
if (
parentModule.children &&
parentModule.children.indexOf(childModuleId) === -1
) {
parentModule.children.push(childModuleId)
}
// Record that child is imported by parent
if (childModule && childModule.parents.indexOf(parentModule.id) === -1) {
if (
childModule &&
childModule.parents &&
childModule.parents.indexOf(parentModule.id) === -1
) {
childModule.parents.push(parentModule.id)
}
}
......@@ -102,14 +109,13 @@ function formatDependencyChain(dependencyChain: ModuleId[]): string {
* Returns information about whether the update can be accepted and which
* modules need to be invalidated.
*
* Copied directly from browser implementation.
*
* @param moduleId - The module to check for effects
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
* @param moduleId - The module that changed
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept().
* This is used for server-side HMR where pages auto-accept at the top level.
*/
function getAffectedModuleEffects(
moduleId: ModuleId,
autoAcceptRootModules: boolean
autoAcceptAtRoot: boolean
): ModuleEffect {
const outdatedModules: Set<ModuleId> = new Set()
......@@ -124,25 +130,34 @@ function getAffectedModuleEffects(
let nextItem
while ((nextItem = queue.shift())) {
const { moduleId: currentModuleId, dependencyChain } = nextItem
const { moduleId, dependencyChain } = nextItem
if (moduleId != null) {
if (outdatedModules.has(moduleId)) {
// Avoid infinite loops caused by cycles between modules in the dependency chain.
continue
}
outdatedModules.add(moduleId)
}
// We've arrived at the runtime of the chunk, which means that nothing
// else above can accept this update.
if (currentModuleId === undefined) {
if (moduleId === undefined) {
if (autoAcceptAtRoot) {
return {
type: 'accepted',
moduleId,
outdatedModules,
}
}
return {
type: 'unaccepted',
dependencyChain,
}
}
if (outdatedModules.has(currentModuleId)) {
// Avoid infinite loops caused by cycles between modules in the dependency chain.
continue
}
outdatedModules.add(currentModuleId)
const module = devModuleCache[currentModuleId]
const module = devModuleCache[moduleId]
const hotState = moduleHotState.get(module)!
if (
......@@ -159,14 +174,17 @@ function getAffectedModuleEffects(
return {
type: 'self-declined',
dependencyChain,
moduleId: currentModuleId,
moduleId,
}
}
if (runtimeModules.has(currentModuleId)) {
if (runtimeModules.has(moduleId)) {
if (autoAcceptAtRoot) {
continue
}
queue.push({
moduleId: undefined,
dependencyChain: [...dependencyChain, currentModuleId],
dependencyChain: [...dependencyChain, moduleId],
})
continue
}
......@@ -184,9 +202,14 @@ function getAffectedModuleEffects(
queue.push({
moduleId: parentId,
dependencyChain: [...dependencyChain, currentModuleId],
dependencyChain: [...dependencyChain, moduleId],
})
}
// If no parents and we're at a root module, auto-accept if configured
if (module.parents.length === 0 && autoAcceptAtRoot) {
continue
}
}
return {
......@@ -199,19 +222,17 @@ function getAffectedModuleEffects(
/**
* Computes all modules that need to be invalidated based on which modules changed.
*
* Copied directly from browser implementation.
*
* @param invalidated - The modules to check for invalidation
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
* @param invalidated - The modules that have been invalidated
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/
function computedInvalidatedModules(
invalidated: Iterable<ModuleId>,
autoAcceptRootModules: boolean
autoAcceptAtRoot: boolean
): Set<ModuleId> {
const outdatedModules = new Set<ModuleId>()
for (const moduleId of invalidated) {
const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules)
const effect = getAffectedModuleEffects(moduleId, autoAcceptAtRoot)
switch (effect.type) {
case 'unaccepted':
......@@ -331,18 +352,17 @@ function createModuleHot(
* Processes queued invalidated modules and adds them to the outdated modules set.
* Modules that call module.hot.invalidate() are queued and processed here.
*
* @param outdatedModules - The set of already outdated modules
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
* @param outdatedModules - The current set of outdated modules
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/
function applyInvalidatedModules(
outdatedModules: Set<ModuleId>,
autoAcceptRootModules: boolean
autoAcceptAtRoot: boolean
): Set<ModuleId> {
if (queuedInvalidatedModules.size > 0) {
computedInvalidatedModules(
queuedInvalidatedModules,
autoAcceptRootModules
autoAcceptAtRoot
).forEach((moduleId) => {
outdatedModules.add(moduleId)
})
......@@ -611,7 +631,7 @@ function computeChangedModules(
break
}
default:
throw new Error(`Unknown merged chunk update`)
throw new Error('Unknown merged chunk update type')
}
}
......@@ -645,13 +665,13 @@ function computeChangedModules(
* @param added - Map of added modules
* @param modified - Map of modified modules
* @param evalModuleEntry - Function to compile module code
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/
function computeOutdatedModules(
added: Map<ModuleId, EcmascriptModuleEntry | undefined>,
modified: Map<ModuleId, EcmascriptModuleEntry>,
evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction,
autoAcceptRootModules: boolean
autoAcceptAtRoot: boolean
): {
outdatedModules: Set<ModuleId>
newModuleFactories: Map<ModuleId, HotModuleFactoryFunction>
......@@ -668,9 +688,10 @@ function computeOutdatedModules(
// Walk dependency tree to find all modules affected by modifications
const outdatedModules = computedInvalidatedModules(
modified.keys(),
autoAcceptRootModules
autoAcceptAtRoot
)
// Compile modified modules
for (const [moduleId, entry] of modified) {
newModuleFactories.set(moduleId, evalModuleEntry(entry))
}
......@@ -736,7 +757,7 @@ function applyPhase(
* Internal implementation that orchestrates the full HMR update flow:
* invalidation, disposal, and application of new modules.
*
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/
function applyInternal(
outdatedModules: Set<ModuleId>,
......@@ -750,12 +771,9 @@ function applyInternal(
sourceData: SourceData
) => HotModule,
applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,
autoAcceptRootModules: boolean
autoAcceptAtRoot: boolean
) {
outdatedModules = applyInvalidatedModules(
outdatedModules,
autoAcceptRootModules
)
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptAtRoot)
// Find self-accepted modules to re-instantiate
const outdatedSelfAcceptedModules =
......@@ -798,7 +816,7 @@ function applyInternal(
devModuleCache,
instantiateModuleFn,
applyModuleFactoryNameFn,
autoAcceptRootModules
autoAcceptAtRoot
)
}
}
......@@ -806,39 +824,44 @@ function applyInternal(
/**
* Main entry point for applying an ECMAScript merged update.
* This is called by both browser and Node.js runtimes with platform-specific callbacks.
*
* @param options.autoAcceptAtRoot - If true, root modules auto-accept updates without explicit
* module.hot.accept(). Used for server-side HMR where pages
* auto-accept at the top level.
*/
function applyEcmascriptMergedUpdateShared(options: {
added: Map<ModuleId, EcmascriptModuleEntry | undefined>
modified: Map<ModuleId, EcmascriptModuleEntry>
disposedModules: Iterable<ModuleId>
evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction
instantiateModuleFn: (
instantiateModule: (
moduleId: ModuleId,
sourceType: SourceType,
sourceData: SourceData
) => HotModule
applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void
applyModuleFactoryName: (factory: HotModuleFactoryFunction) => void
moduleFactories: ModuleFactories
devModuleCache: ModuleCache<HotModule>
autoAcceptRootModules: boolean
runtimeModules: Set<ModuleId>
autoAcceptAtRoot: boolean
}) {
const {
added,
modified,
disposedModules,
evalModuleEntry,
instantiateModuleFn,
applyModuleFactoryNameFn,
instantiateModule,
applyModuleFactoryName,
moduleFactories,
devModuleCache,
autoAcceptRootModules,
autoAcceptAtRoot,
} = options
const { outdatedModules, newModuleFactories } = computeOutdatedModules(
added,
modified,
evalModuleEntry,
autoAcceptRootModules
autoAcceptAtRoot
)
applyInternal(
......@@ -847,8 +870,8 @@ function applyEcmascriptMergedUpdateShared(options: {
newModuleFactories,
moduleFactories,
devModuleCache,
instantiateModuleFn,
applyModuleFactoryNameFn,
autoAcceptRootModules
instantiateModule,
applyModuleFactoryName,
autoAcceptAtRoot
)
}
......@@ -76,14 +76,6 @@ type LoadWebAssemblyModule = (
type ModuleCache<M> = Record<ModuleId, M>
// TODO properly type values here
type ModuleFactories = Map<ModuleId, Function>
/**
* Constraint for module factory functions used in HMR.
* Platform-specific runtimes define their own ModuleFactory types that must satisfy this constraint.
*/
type ModuleFactoryFunction<
TModule extends Module,
TContext extends TurbopackBaseContext<TModule>,
> = (this: TContext, ...args: unknown[]) => unknown
/**
* This is an alternating, non-empty arrow of module factory functions and module ids
* `[id1, id2..., factory1, id3, factory2, id4, id5, factory3]`
......
......@@ -6,12 +6,13 @@ use turbopack_core::{
environment::Environment,
};
use crate::{asset_context::get_runtime_asset_context, embed_js::embed_static_code};
use crate::{RuntimeType, asset_context::get_runtime_asset_context, embed_js::embed_static_code};
/// Returns the code for the Node.js production ECMAScript runtime.
/// Returns the code for the Node.js ECMAScript runtime.
#[turbo_tasks::function]
pub async fn get_nodejs_runtime_code(
environment: ResolvedVc<Environment>,
runtime_type: RuntimeType,
generate_source_map: bool,
) -> Result<Vc<Code>> {
let asset_context = get_runtime_asset_context(*environment).resolve().await?;
......@@ -36,7 +37,9 @@ pub async fn get_nodejs_runtime_code(
rcstr!("shared-node/node-wasm-utils.ts"),
generate_source_map,
);
let runtime_code = embed_static_code(
// Runtime base is shared between production and development
let runtime_base_code = embed_static_code(
asset_context,
rcstr!("nodejs/runtime/runtime-base.ts"),
generate_source_map,
......@@ -47,7 +50,65 @@ pub async fn get_nodejs_runtime_code(
code.push_code(&*shared_base_external_utils_code.await?);
code.push_code(&*shared_node_external_utils_code.await?);
code.push_code(&*shared_node_wasm_utils_code.await?);
code.push_code(&*runtime_code.await?);
code.push_code(&*runtime_base_code.await?);
match runtime_type {
RuntimeType::Production => {
code.push_code(
&*embed_static_code(
asset_context,
rcstr!("nodejs/runtime/build-base.ts"),
generate_source_map,
)
.await?,
);
}
RuntimeType::Development => {
// Include shared HMR runtime (includes instantiateModuleShared, etc.)
code.push_code(
&*embed_static_code(
asset_context,
rcstr!("shared/runtime/hmr-runtime.ts"),
generate_source_map,
)
.await?,
);
// Include Node.js-specific dev runtime
code.push_code(
&*embed_static_code(
asset_context,
rcstr!("nodejs/runtime/dev-base.ts"),
generate_source_map,
)
.await?,
);
// Include Node.js HMR client (standalone, doesn't use shared ESM client)
code.push_code(
&*embed_static_code(
asset_context,
rcstr!("nodejs/dev/hmr-client.ts"),
generate_source_map,
)
.await?,
);
// Include dev-nodejs (HMR initialization and __turbopack_server_hmr_apply__)
code.push_code(
&*embed_static_code(
asset_context,
rcstr!("nodejs/dev/dev-nodejs.ts"),
generate_source_map,
)
.await?,
);
}
#[cfg(feature = "test")]
RuntimeType::Dummy => {
panic!("Dummy runtime is not supported in Node.js runtime")
}
}
Ok(Code::cell(code.build()))
}
......@@ -22,6 +22,9 @@ workspace = true
anyhow = { workspace = true }
bincode = { workspace = true }
indoc = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
serde_qs = { workspace = true }
tracing = { workspace = true }
urlencoding = { workspace = true }
......
......@@ -7,11 +7,14 @@ use turbopack_core::{
code_builder::{Code, CodeBuilder},
output::OutputAsset,
source_map::{GenerateSourceMap, SourceMapAsset},
version::{Version, VersionedContent},
version::{Update, Version, VersionedContent},
};
use turbopack_ecmascript::{chunk::EcmascriptChunkContent, minify::minify, utils::StringifyJs};
use super::{chunk::EcmascriptBuildNodeChunk, version::EcmascriptBuildNodeChunkVersion};
use super::{
chunk::EcmascriptBuildNodeChunk, update::update_node_chunk,
version::EcmascriptBuildNodeChunkVersion,
};
use crate::NodeJsChunkingContext;
#[turbo_tasks::value]
......@@ -114,4 +117,12 @@ impl VersionedContent for EcmascriptBuildNodeChunkContent {
fn version(self: Vc<Self>) -> Vc<Box<dyn Version>> {
Vc::upcast(self.own_version())
}
#[turbo_tasks::function]
async fn update(
self: Vc<Self>,
from_version: ResolvedVc<Box<dyn Version>>,
) -> Result<Vc<Update>> {
Ok(update_node_chunk(self, from_version).await?.cell())
}
}
......@@ -69,6 +69,7 @@ impl EcmascriptBuildNodeRuntimeChunk {
RuntimeType::Development => {
let runtime_code = turbopack_ecmascript_runtime::get_nodejs_runtime_code(
this.chunking_context.environment(),
RuntimeType::Development,
generate_source_map,
);
code.push_code(&*runtime_code.await?);
......@@ -76,6 +77,7 @@ impl EcmascriptBuildNodeRuntimeChunk {
RuntimeType::Production => {
let runtime_code = turbopack_ecmascript_runtime::get_nodejs_runtime_code(
this.chunking_context.environment(),
RuntimeType::Production,
generate_source_map,
);
code.push_code(&*runtime_code.await?);
......
pub(crate) mod chunk;
pub(crate) mod content;
pub(crate) mod entry;
pub(crate) mod update;
pub(crate) mod version;
use std::sync::Arc;
use anyhow::Result;
use serde::Serialize;
use turbo_tasks::{FxIndexMap, FxIndexSet, IntoTraitRef, ReadRef, ResolvedVc, Vc};
use turbo_tasks_fs::rope::Rope;
use turbopack_core::{
chunk::ModuleId,
code_builder::Code,
source_map::GenerateSourceMap,
version::{PartialUpdate, TotalUpdate, Update, Version},
};
use super::{content::EcmascriptBuildNodeChunkContent, version::EcmascriptBuildNodeChunkVersion};
#[derive(Serialize, Default)]
#[serde(
tag = "type",
rename = "EcmascriptMergedUpdate",
rename_all = "camelCase"
)]
struct EcmascriptMergedUpdate<'a> {
/// A map from module id to latest module entry.
#[serde(skip_serializing_if = "FxIndexMap::is_empty")]
entries: FxIndexMap<ModuleId, EcmascriptModuleEntry>,
/// A map from chunk path to the chunk update.
#[serde(skip_serializing_if = "FxIndexMap::is_empty")]
chunks: FxIndexMap<&'a str, EcmascriptMergedChunkUpdate>,
}
impl EcmascriptMergedUpdate<'_> {
fn is_empty(&self) -> bool {
self.entries.is_empty() && self.chunks.is_empty()
}
}
#[derive(Serialize)]
#[serde(tag = "type", rename_all = "camelCase")]
enum EcmascriptMergedChunkUpdate {
Partial(EcmascriptMergedChunkPartial),
}
#[derive(Serialize, Default)]
#[serde(rename_all = "camelCase")]
struct EcmascriptMergedChunkPartial {
#[serde(skip_serializing_if = "FxIndexSet::is_empty")]
added: FxIndexSet<ModuleId>,
#[serde(skip_serializing_if = "FxIndexSet::is_empty")]
deleted: FxIndexSet<ModuleId>,
}
#[derive(Serialize)]
struct EcmascriptModuleEntry {
#[serde(with = "turbo_tasks_fs::rope::ser_as_string")]
code: Rope,
url: String,
#[serde(with = "turbo_tasks_fs::rope::ser_option_as_string")]
map: Option<Rope>,
}
impl EcmascriptModuleEntry {
async fn from_code(id: &ModuleId, code: Vc<Code>, chunk_path: &str) -> Result<Self> {
let map = &*code.generate_source_map().await?;
let map = map.as_content().map(|f| f.content().clone());
/// serde_qs can't serialize a lone enum when it's [serde::untagged].
#[derive(Serialize)]
struct Id<'a> {
id: &'a ModuleId,
}
let id = serde_qs::to_string(&Id { id }).unwrap();
Ok(EcmascriptModuleEntry {
// Cloning a rope is cheap.
code: code.await?.source_code().clone(),
url: format!("{}?{}", chunk_path, &id),
map,
})
}
}
pub(super) async fn update_node_chunk(
content: Vc<EcmascriptBuildNodeChunkContent>,
from_version: ResolvedVc<Box<dyn Version>>,
) -> Result<Update> {
let to_version = content.own_version();
let from_version = if let Some(from) =
ResolvedVc::try_downcast_type::<EcmascriptBuildNodeChunkVersion>(from_version)
{
from
} else {
// It's likely `from_version` is `NotFoundVersion`.
return Ok(Update::Total(TotalUpdate {
to: Vc::upcast::<Box<dyn Version>>(to_version)
.into_trait_ref()
.await?,
}));
};
let to = to_version.await?;
let from = from_version.await?;
// When to and from point to the same value we can skip comparing them
if from.ptr_eq(&to) {
return Ok(Update::None);
}
let chunk_path = &to.chunk_path;
let chunk_update = update_ecmascript_node_chunk_content(&to, &from).await?;
let mut merged_update = EcmascriptMergedUpdate::default();
match chunk_update {
NodeChunkUpdate::None => {
return Ok(Update::None);
}
NodeChunkUpdate::Partial {
added,
modified,
deleted,
} => {
let mut partial = EcmascriptMergedChunkPartial::default();
for (module_id, module_code) in added {
partial.added.insert(module_id.clone());
let entry =
EcmascriptModuleEntry::from_code(&module_id, module_code, chunk_path).await?;
merged_update.entries.insert(module_id, entry);
}
partial.deleted.extend(deleted.into_keys());
for (module_id, module_code) in modified {
let entry =
EcmascriptModuleEntry::from_code(&module_id, module_code, chunk_path).await?;
merged_update.entries.insert(module_id, entry);
}
merged_update
.chunks
.insert(chunk_path, EcmascriptMergedChunkUpdate::Partial(partial));
}
}
let update = if merged_update.is_empty() {
Update::None
} else {
// Serialize EcmascriptMergedUpdate directly
// The hot-reloader will wrap it in ChunkListUpdate format for the runtime
let instruction_value = serde_json::to_value(&merged_update)?;
Update::Partial(PartialUpdate {
to: Vc::upcast::<Box<dyn Version>>(to_version)
.into_trait_ref()
.await?,
instruction: Arc::new(instruction_value),
})
};
Ok(update)
}
enum NodeChunkUpdate {
None,
Partial {
added: FxIndexMap<ModuleId, Vc<Code>>,
modified: FxIndexMap<ModuleId, Vc<Code>>,
deleted: FxIndexMap<ModuleId, u64>,
},
}
async fn update_ecmascript_node_chunk_content(
to: &ReadRef<EcmascriptBuildNodeChunkVersion>,
from: &ReadRef<EcmascriptBuildNodeChunkVersion>,
) -> Result<NodeChunkUpdate> {
let mut added = FxIndexMap::default();
let mut modified = FxIndexMap::default();
let mut deleted = FxIndexMap::default();
// Build a map of module_id -> Vc<Code> for the "to" version
let mut to_entries: FxIndexMap<ModuleId, Vc<Code>> = FxIndexMap::default();
for item in &to.chunk_items {
for (id, code) in item {
// Convert ReadRef<Code> to Vc<Code>
to_entries.insert(id.clone(), ReadRef::cell(code.clone()));
}
}
// Check for deleted and modified modules
for (id, from_hash) in &from.entries_hashes {
if let Some(to_hash) = to.entries_hashes.get(id) {
if *to_hash != *from_hash {
// Module was modified
if let Some(code) = to_entries.get(id) {
modified.insert(id.clone(), *code);
}
}
} else {
// Module was deleted
deleted.insert(id.clone(), *from_hash);
}
}
// Check for added modules
for (id, _hash) in &to.entries_hashes {
if !from.entries_hashes.contains_key(id)
&& let Some(code) = to_entries.get(id)
{
added.insert(id.clone(), *code);
}
}
let update = if added.is_empty() && modified.is_empty() && deleted.is_empty() {
NodeChunkUpdate::None
} else {
NodeChunkUpdate::Partial {
added,
modified,
deleted,
}
};
Ok(update)
}
use anyhow::{Result, bail};
use turbo_rcstr::RcStr;
use turbo_tasks::{ReadRef, Vc};
use turbo_tasks::{FxIndexMap, ReadRef, Vc};
use turbo_tasks_fs::FileSystemPath;
use turbo_tasks_hash::{Xxh3Hash64Hasher, encode_hex};
use turbopack_core::{chunk::MinifyType, version::Version};
use turbopack_core::{
chunk::{MinifyType, ModuleId},
version::Version,
};
use turbopack_ecmascript::chunk::{CodeAndIds, EcmascriptChunkContent};
#[turbo_tasks::value(serialization = "none")]
pub(super) struct EcmascriptBuildNodeChunkVersion {
chunk_path: String,
chunk_items: Vec<ReadRef<CodeAndIds>>,
minify_type: MinifyType,
pub(super) chunk_path: String,
pub(super) chunk_items: Vec<ReadRef<CodeAndIds>>,
pub(super) minify_type: MinifyType,
pub(super) entries_hashes: FxIndexMap<ModuleId, u64>,
}
#[turbo_tasks::value_impl]
......@@ -30,10 +34,25 @@ impl EcmascriptBuildNodeChunkVersion {
bail!("chunk path {chunk_path} is not in client root {output_root}");
};
let chunk_items = content.await?.chunk_item_code_and_ids().await?;
// Compute per-module hashes for fine-grained HMR tracking
let mut entries_hashes = FxIndexMap::default();
for item in &chunk_items {
for (module_id, code) in item {
let mut hasher = Xxh3Hash64Hasher::new();
let source = code.source_code();
hasher.write_ref(source);
let hash = hasher.finish();
entries_hashes.insert(module_id.clone(), hash);
}
}
Ok(EcmascriptBuildNodeChunkVersion {
chunk_path: chunk_path.to_string(),
chunk_items,
minify_type,
entries_hashes,
}
.cell())
}
......@@ -46,11 +65,13 @@ impl Version for EcmascriptBuildNodeChunkVersion {
let mut hasher = Xxh3Hash64Hasher::new();
hasher.write_ref(&self.chunk_path);
hasher.write_ref(&self.minify_type);
hasher.write_value(self.chunk_items.len());
for item in &self.chunk_items {
for (module_id, code) in item {
hasher.write_value((module_id, code.source_code()));
}
let sorted_hashes = {
let mut hashes: Vec<_> = self.entries_hashes.values().copied().collect();
hashes.sort();
hashes
};
for hash in sorted_hashes {
hasher.write_value(hash);
}
let hash = hasher.finish();
let hex_hash = encode_hex(hash);
......
;!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]="8e07a901-341e-9c72-a112-26357796b0d4")}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]="00b321a1-9cfd-c201-59b4-bbeaba1d658a")}catch(e){}}();
(globalThis["TURBOPACK"] || (globalThis["TURBOPACK"] = [])).push([
"output/ba425_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js",
{"otherChunks":["output/aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0b8736b3.js"],"runtimeModuleIds":["[project]/turbopack/crates/turbopack-tests/tests/snapshot/debug-ids/browser/input/index.js [test] (ecmascript)"]}
......@@ -854,11 +854,11 @@ class UpdateApplyError extends Error {
*/ // eslint-disable-next-line @typescript-eslint/no-unused-vars
function trackModuleImport(parentModule, childModuleId, childModule) {
// Record that parent imports child
if (parentModule.children.indexOf(childModuleId) === -1) {
if (parentModule.children && parentModule.children.indexOf(childModuleId) === -1) {
parentModule.children.push(childModuleId);
}
// Record that child is imported by parent
if (childModule && childModule.parents.indexOf(parentModule.id) === -1) {
if (childModule && childModule.parents && childModule.parents.indexOf(parentModule.id) === -1) {
childModule.parents.push(parentModule.id);
}
}
......@@ -870,11 +870,10 @@ function formatDependencyChain(dependencyChain) {
* Returns information about whether the update can be accepted and which
* modules need to be invalidated.
*
* Copied directly from browser implementation.
*
* @param moduleId - The module to check for effects
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function getAffectedModuleEffects(moduleId, autoAcceptRootModules) {
* @param moduleId - The module that changed
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept().
* This is used for server-side HMR where pages auto-accept at the top level.
*/ function getAffectedModuleEffects(moduleId, autoAcceptAtRoot) {
const outdatedModules = new Set();
const queue = [
{
......@@ -884,20 +883,29 @@ function formatDependencyChain(dependencyChain) {
];
let nextItem;
while(nextItem = queue.shift()){
const { moduleId: currentModuleId, dependencyChain } = nextItem;
const { moduleId, dependencyChain } = nextItem;
if (moduleId != null) {
if (outdatedModules.has(moduleId)) {
continue;
}
outdatedModules.add(moduleId);
}
// We've arrived at the runtime of the chunk, which means that nothing
// else above can accept this update.
if (currentModuleId === undefined) {
if (moduleId === undefined) {
if (autoAcceptAtRoot) {
return {
type: 'accepted',
moduleId,
outdatedModules
};
}
return {
type: 'unaccepted',
dependencyChain
};
}
if (outdatedModules.has(currentModuleId)) {
continue;
}
outdatedModules.add(currentModuleId);
const module = devModuleCache[currentModuleId];
const module = devModuleCache[moduleId];
const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before.
......@@ -908,15 +916,18 @@ function formatDependencyChain(dependencyChain) {
return {
type: 'self-declined',
dependencyChain,
moduleId: currentModuleId
moduleId
};
}
if (runtimeModules.has(currentModuleId)) {
if (runtimeModules.has(moduleId)) {
if (autoAcceptAtRoot) {
continue;
}
queue.push({
moduleId: undefined,
dependencyChain: [
...dependencyChain,
currentModuleId
moduleId
]
});
continue;
......@@ -932,10 +943,14 @@ function formatDependencyChain(dependencyChain) {
moduleId: parentId,
dependencyChain: [
...dependencyChain,
currentModuleId
moduleId
]
});
}
// If no parents and we're at a root module, auto-accept if configured
if (module.parents.length === 0 && autoAcceptAtRoot) {
continue;
}
}
return {
type: 'accepted',
......@@ -946,14 +961,12 @@ function formatDependencyChain(dependencyChain) {
/**
* Computes all modules that need to be invalidated based on which modules changed.
*
* Copied directly from browser implementation.
*
* @param invalidated - The modules to check for invalidation
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computedInvalidatedModules(invalidated, autoAcceptRootModules) {
* @param invalidated - The modules that have been invalidated
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computedInvalidatedModules(invalidated, autoAcceptAtRoot) {
const outdatedModules = new Set();
for (const moduleId of invalidated){
const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules);
const effect = getAffectedModuleEffects(moduleId, autoAcceptAtRoot);
switch(effect.type){
case 'unaccepted':
throw new UpdateApplyError(`cannot apply update: unaccepted module. ${formatDependencyChain(effect.dependencyChain)}.`, effect.dependencyChain);
......@@ -1041,11 +1054,11 @@ function formatDependencyChain(dependencyChain) {
* Processes queued invalidated modules and adds them to the outdated modules set.
* Modules that call module.hot.invalidate() are queued and processed here.
*
* @param outdatedModules - The set of already outdated modules
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInvalidatedModules(outdatedModules, autoAcceptRootModules) {
* @param outdatedModules - The current set of outdated modules
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInvalidatedModules(outdatedModules, autoAcceptAtRoot) {
if (queuedInvalidatedModules.size > 0) {
computedInvalidatedModules(queuedInvalidatedModules, autoAcceptRootModules).forEach((moduleId)=>{
computedInvalidatedModules(queuedInvalidatedModules, autoAcceptAtRoot).forEach((moduleId)=>{
outdatedModules.add(moduleId);
});
queuedInvalidatedModules.clear();
......@@ -1246,7 +1259,7 @@ function formatDependencyChain(dependencyChain) {
break;
}
default:
throw new Error(`Unknown merged chunk update`);
throw new Error('Unknown merged chunk update type');
}
}
// If a module was added from one chunk and deleted from another in the same update,
......@@ -1282,8 +1295,8 @@ function formatDependencyChain(dependencyChain) {
* @param added - Map of added modules
* @param modified - Map of modified modules
* @param evalModuleEntry - Function to compile module code
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptRootModules) {
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot) {
const newModuleFactories = new Map();
// Compile added modules
for (const [moduleId, entry] of added){
......@@ -1292,7 +1305,8 @@ function formatDependencyChain(dependencyChain) {
}
}
// Walk dependency tree to find all modules affected by modifications
const outdatedModules = computedInvalidatedModules(modified.keys(), autoAcceptRootModules);
const outdatedModules = computedInvalidatedModules(modified.keys(), autoAcceptAtRoot);
// Compile modified modules
for (const [moduleId, entry] of modified){
newModuleFactories.set(moduleId, evalModuleEntry(entry));
}
......@@ -1337,9 +1351,9 @@ function formatDependencyChain(dependencyChain) {
* Internal implementation that orchestrates the full HMR update flow:
* invalidation, disposal, and application of new modules.
*
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules) {
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptRootModules);
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot) {
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptAtRoot);
// Find self-accepted modules to re-instantiate
const outdatedSelfAcceptedModules = computeOutdatedSelfAcceptedModules(outdatedModules);
// Run dispose handlers, save hot.data, clear caches
......@@ -1354,16 +1368,20 @@ function formatDependencyChain(dependencyChain) {
}
// Recursively apply any queued invalidations from new module execution
if (queuedInvalidatedModules.size > 0) {
applyInternal(new Set(), [], new Map(), moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules);
applyInternal(new Set(), [], new Map(), moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot);
}
}
/**
* Main entry point for applying an ECMAScript merged update.
* This is called by both browser and Node.js runtimes with platform-specific callbacks.
*
* @param options.autoAcceptAtRoot - If true, root modules auto-accept updates without explicit
* module.hot.accept(). Used for server-side HMR where pages
* auto-accept at the top level.
*/ function applyEcmascriptMergedUpdateShared(options) {
const { added, modified, disposedModules, evalModuleEntry, instantiateModuleFn, applyModuleFactoryNameFn, moduleFactories, devModuleCache, autoAcceptRootModules } = options;
const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptRootModules);
applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules);
const { added, modified, disposedModules, evalModuleEntry, instantiateModule, applyModuleFactoryName, moduleFactories, devModuleCache, autoAcceptAtRoot } = options;
const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot);
applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModule, applyModuleFactoryName, autoAcceptAtRoot);
}
/// <reference path="../../../shared/runtime/dev-globals.d.ts" />
/// <reference path="../../../shared/runtime/dev-protocol.d.ts" />
......@@ -1602,11 +1620,12 @@ function applyEcmascriptMergedUpdate(update) {
modified,
disposedModules,
evalModuleEntry: _eval,
instantiateModuleFn: instantiateModule,
applyModuleFactoryNameFn: applyModuleFactoryName,
instantiateModule,
applyModuleFactoryName,
moduleFactories,
devModuleCache,
autoAcceptRootModules: false
runtimeModules,
autoAcceptAtRoot: false
});
}
function handleApply(chunkListPath, update) {
......@@ -2048,5 +2067,5 @@ chunkListsToRegister.forEach(registerChunkList);
})();
//# debugId=8e07a901-341e-9c72-a112-26357796b0d4
//# debugId=00b321a1-9cfd-c201-59b4-bbeaba1d658a
//# sourceMappingURL=aaf3a_crates_turbopack-tests_tests_snapshot_debug-ids_browser_input_index_0151fefb.js.map
\ No newline at end of file
......@@ -625,30 +625,28 @@ async function instantiateWebAssemblyFromPath(path, importsObj) {
const { instance } = await WebAssembly.instantiateStreaming(response, importsObj);
return instance.exports;
}
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../hmr-types.d.ts" />
/// <reference path="../../shared/runtime/runtime-utils.ts" />
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../shared/runtime/runtime-utils.ts" />
/// <reference path="../../shared-node/base-externals-utils.ts" />
/// <reference path="../../shared-node/node-externals-utils.ts" />
/// <reference path="../../shared-node/node-wasm-utils.ts" />
var SourceType = /*#__PURE__*/ function(SourceType) {
/**
* The module was instantiated because it was included in an evaluated chunk's
* runtime.
* SourceData is a ChunkPath.
*/ SourceType[SourceType["Runtime"] = 0] = "Runtime";
/**
* The module was instantiated because a parent module imported it.
* SourceData is a ModuleId.
*/ SourceType[SourceType["Parent"] = 1] = "Parent";
return SourceType;
}(SourceType || {});
process.env.TURBOPACK = '1';
const nodeContextPrototype = Context.prototype;
/// <reference path="./nodejs-globals.d.ts" />
/**
* Base Node.js runtime shared between production and development.
* Contains chunk loading, module caching, and other non-HMR functionality.
*/ process.env.TURBOPACK = '1';
const url = require('url');
const moduleFactories = new Map();
nodeContextPrototype.M = moduleFactories;
const moduleCache = Object.create(null);
nodeContextPrototype.c = moduleCache;
// Use global module factories and cache to persist across chunk reloads during HMR
// This ensures that when Node.js clears the require cache for a chunk file,
// we don't lose our granular HMR updates to individual modules
if (!globalThis.__turbopack_module_factories__) {
globalThis.__turbopack_module_factories__ = new Map();
}
if (!globalThis.__turbopack_module_cache__) {
globalThis.__turbopack_module_cache__ = Object.create(null);
}
const moduleFactories = globalThis.__turbopack_module_factories__;
// Module cache - typed as base Module, can be cast to HotModule in dev mode
const moduleCache = globalThis.__turbopack_module_cache__;
/**
* Returns an absolute path to the given module's id.
*/ function resolvePathFromModule(moduleId) {
......@@ -661,13 +659,11 @@ nodeContextPrototype.c = moduleCache;
const resolved = path.resolve(RUNTIME_ROOT, strippedAssetPrefix);
return url.pathToFileURL(resolved).href;
}
nodeContextPrototype.R = resolvePathFromModule;
/**
* Exports a URL value. No suffix is added in Node.js runtime.
*/ function exportUrl(urlValue, id) {
exportValue.call(this, urlValue, id);
}
nodeContextPrototype.q = exportUrl;
function loadRuntimeChunk(sourcePath, chunkData) {
if (typeof chunkData === 'string') {
loadRuntimeChunkPath(sourcePath, chunkData);
......@@ -679,8 +675,16 @@ const loadedChunks = new Set();
const unsupportedLoadChunk = Promise.resolve(undefined);
const loadedChunk = Promise.resolve(undefined);
const chunkCache = new Map();
function clearChunkCache() {
/**
* Clear all chunk and module state to force re-evaluation on next require.
* Called by Next.js when server HMR is disabled to implement the "reload everything" behavior.
*/ function clearChunkCache() {
chunkCache.clear();
loadedChunks.clear();
moduleFactories.clear();
for(const key in moduleCache){
delete moduleCache[key];
}
}
function loadRuntimeChunkPath(sourcePath, chunkPath) {
if (!isJs(chunkPath)) {
......@@ -758,67 +762,635 @@ contextPrototype.u = loadWebAssemblyModule;
function getWorkerURL(_entrypoint, _moduleChunks, _shared) {
throw new Error('Worker urls are not implemented yet for Node.js');
}
nodeContextPrototype.b = getWorkerURL;
function instantiateModule(id, sourceType, sourceData) {
const moduleFactory = moduleFactories.get(id);
if (typeof moduleFactory !== 'function') {
// This can happen if modules incorrectly handle HMR disposes/updates,
// e.g. when they keep a `setTimeout` around which still executes old code
// and contains e.g. a `require("something")` call.
let instantiationReason;
switch(sourceType){
case 0:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
instantiationReason = `because it was required from module ${sourceData}`;
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
*/ function isJs(chunkUrlOrPath) {
return regexJsUrl.test(chunkUrlOrPath);
}
/// <reference path="./runtime-utils.ts" />
/// <reference path="./runtime-types.d.ts" />
/// <reference path="./dev-extensions.ts" />
/// <reference path="./dev-protocol.d.ts" />
/**
* Shared HMR (Hot Module Replacement) implementation.
*
* This file contains the complete HMR implementation that's shared between
* browser and Node.js runtimes. It manages module hot state, dependency
* tracking, the module.hot API, and the full HMR update flow.
*/ /**
* The development module cache shared across the runtime.
* Browser runtime declares this directly.
* Node.js runtime assigns globalThis.__turbopack_module_cache__ to this.
*/ let devModuleCache;
/**
* Module IDs that are instantiated as part of the runtime of a chunk.
*/ let runtimeModules;
/**
* Maps module IDs to persisted data between executions of their hot module
* implementation (`hot.data`).
*/ const moduleHotData = new Map();
/**
* Maps module instances to their hot module state.
* Uses WeakMap so it works with both HotModule and ModuleWithDirection.
*/ const moduleHotState = new WeakMap();
/**
* Modules that call `module.hot.invalidate()` (while being updated).
*/ const queuedInvalidatedModules = new Set();
class UpdateApplyError extends Error {
name = 'UpdateApplyError';
dependencyChain;
constructor(message, dependencyChain){
super(message);
this.dependencyChain = dependencyChain;
}
}
/**
* Records parent-child relationship when a module imports another.
* Should be called during module instantiation.
*/ // eslint-disable-next-line @typescript-eslint/no-unused-vars
function trackModuleImport(parentModule, childModuleId, childModule) {
// Record that parent imports child
if (parentModule.children && parentModule.children.indexOf(childModuleId) === -1) {
parentModule.children.push(childModuleId);
}
// Record that child is imported by parent
if (childModule && childModule.parents && childModule.parents.indexOf(parentModule.id) === -1) {
childModule.parents.push(parentModule.id);
}
}
function formatDependencyChain(dependencyChain) {
return `Dependency chain: ${dependencyChain.join(' -> ')}`;
}
/**
* Walks the dependency tree to find all modules affected by a change.
* Returns information about whether the update can be accepted and which
* modules need to be invalidated.
*
* @param moduleId - The module that changed
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept().
* This is used for server-side HMR where pages auto-accept at the top level.
*/ function getAffectedModuleEffects(moduleId, autoAcceptAtRoot) {
const outdatedModules = new Set();
const queue = [
{
moduleId,
dependencyChain: []
}
];
let nextItem;
while(nextItem = queue.shift()){
const { moduleId, dependencyChain } = nextItem;
if (moduleId != null) {
if (outdatedModules.has(moduleId)) {
continue;
}
outdatedModules.add(moduleId);
}
// We've arrived at the runtime of the chunk, which means that nothing
// else above can accept this update.
if (moduleId === undefined) {
if (autoAcceptAtRoot) {
return {
type: 'accepted',
moduleId,
outdatedModules
};
}
return {
type: 'unaccepted',
dependencyChain
};
}
const module = devModuleCache[moduleId];
const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before.
!module || hotState.selfAccepted && !hotState.selfInvalidated) {
continue;
}
if (hotState.selfDeclined) {
return {
type: 'self-declined',
dependencyChain,
moduleId
};
}
if (runtimeModules.has(moduleId)) {
if (autoAcceptAtRoot) {
continue;
}
queue.push({
moduleId: undefined,
dependencyChain: [
...dependencyChain,
moduleId
]
});
continue;
}
for (const parentId of module.parents){
const parent = devModuleCache[parentId];
if (!parent) {
continue;
}
// TODO(alexkirsz) Dependencies: check accepted and declined
// dependencies here.
queue.push({
moduleId: parentId,
dependencyChain: [
...dependencyChain,
moduleId
]
});
}
// If no parents and we're at a root module, auto-accept if configured
if (module.parents.length === 0 && autoAcceptAtRoot) {
continue;
}
}
return {
type: 'accepted',
moduleId,
outdatedModules
};
}
/**
* Computes all modules that need to be invalidated based on which modules changed.
*
* @param invalidated - The modules that have been invalidated
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computedInvalidatedModules(invalidated, autoAcceptAtRoot) {
const outdatedModules = new Set();
for (const moduleId of invalidated){
const effect = getAffectedModuleEffects(moduleId, autoAcceptAtRoot);
switch(effect.type){
case 'unaccepted':
throw new UpdateApplyError(`cannot apply update: unaccepted module. ${formatDependencyChain(effect.dependencyChain)}.`, effect.dependencyChain);
case 'self-declined':
throw new UpdateApplyError(`cannot apply update: self-declined module. ${formatDependencyChain(effect.dependencyChain)}.`, effect.dependencyChain);
case 'accepted':
for (const outdatedModuleId of effect.outdatedModules){
outdatedModules.add(outdatedModuleId);
}
break;
// TODO(alexkirsz) Dependencies: handle dependencies effects.
default:
invariant(sourceType, (sourceType)=>`Unknown source type: ${sourceType}`);
invariant(effect, (effect)=>`Unknown effect type: ${effect?.type}`);
}
}
return outdatedModules;
}
/**
* Creates the module.hot API object and its internal state.
* This provides the HMR API that user code calls (module.hot.accept(), etc.)
*/ function createModuleHot(moduleId, hotData) {
const hotState = {
selfAccepted: false,
selfDeclined: false,
selfInvalidated: false,
disposeHandlers: []
};
const hot = {
// TODO(alexkirsz) This is not defined in the HMR API. It was used to
// decide whether to warn whenever an HMR-disposed module required other
// modules. We might want to remove it.
active: true,
data: hotData ?? {},
// TODO(alexkirsz) Support full (dep, callback, errorHandler) form.
accept: (modules, _callback, _errorHandler)=>{
if (modules === undefined) {
hotState.selfAccepted = true;
} else if (typeof modules === 'function') {
hotState.selfAccepted = modules;
} else {
throw new Error('unsupported `accept` signature');
}
},
decline: (dep)=>{
if (dep === undefined) {
hotState.selfDeclined = true;
} else {
throw new Error('unsupported `decline` signature');
}
},
dispose: (callback)=>{
hotState.disposeHandlers.push(callback);
},
addDisposeHandler: (callback)=>{
hotState.disposeHandlers.push(callback);
},
removeDisposeHandler: (callback)=>{
const idx = hotState.disposeHandlers.indexOf(callback);
if (idx >= 0) {
hotState.disposeHandlers.splice(idx, 1);
}
},
invalidate: ()=>{
hotState.selfInvalidated = true;
queuedInvalidatedModules.add(moduleId);
},
// NOTE(alexkirsz) This is part of the management API, which we don't
// implement, but the Next.js React Refresh runtime uses this to decide
// whether to schedule an update.
status: ()=>'idle',
// NOTE(alexkirsz) Since we always return "idle" for now, these are no-ops.
addStatusHandler: (_handler)=>{},
removeStatusHandler: (_handler)=>{},
// NOTE(jridgewell) Check returns the list of updated modules, but we don't
// want the webpack code paths to ever update (the turbopack paths handle
// this already).
check: ()=>Promise.resolve(null)
};
return {
hot,
hotState
};
}
/**
* Processes queued invalidated modules and adds them to the outdated modules set.
* Modules that call module.hot.invalidate() are queued and processed here.
*
* @param outdatedModules - The current set of outdated modules
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInvalidatedModules(outdatedModules, autoAcceptAtRoot) {
if (queuedInvalidatedModules.size > 0) {
computedInvalidatedModules(queuedInvalidatedModules, autoAcceptAtRoot).forEach((moduleId)=>{
outdatedModules.add(moduleId);
});
queuedInvalidatedModules.clear();
}
return outdatedModules;
}
/**
* Computes which outdated modules have self-accepted and can be hot reloaded.
*/ function computeOutdatedSelfAcceptedModules(outdatedModules) {
const outdatedSelfAcceptedModules = [];
for (const moduleId of outdatedModules){
const module = devModuleCache[moduleId];
const hotState = moduleHotState.get(module);
if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {
outdatedSelfAcceptedModules.push({
moduleId,
errorHandler: hotState.selfAccepted
});
}
throw new Error(`Module ${id} was instantiated ${instantiationReason}, but the module factory is not available.`);
}
const module1 = createModuleObject(id);
const exports = module1.exports;
moduleCache[id] = module1;
const context = new Context(module1, exports);
// NOTE(alexkirsz) This can fail when the module encounters a runtime error.
return outdatedSelfAcceptedModules;
}
/**
* Disposes of an instance of a module.
* Runs hot.dispose handlers and manages persistent hot data.
*
* NOTE: mode = "replace" will not remove modules from devModuleCache.
* This must be done in a separate step afterwards.
*/ function disposeModule(moduleId, mode) {
const module = devModuleCache[moduleId];
if (!module) {
return;
}
const hotState = moduleHotState.get(module);
if (!hotState) {
return;
}
const data = {};
// Run the `hot.dispose` handler, if any, passing in the persistent
// `hot.data` object.
for (const disposeHandler of hotState.disposeHandlers){
disposeHandler(data);
}
// This used to warn in `getOrInstantiateModuleFromParent` when a disposed
// module is still importing other modules.
if (module.hot) {
module.hot.active = false;
}
moduleHotState.delete(module);
// TODO(alexkirsz) Dependencies: delete the module from outdated deps.
// Remove the disposed module from its children's parent list.
// It will be added back once the module re-instantiates and imports its
// children again.
for (const childId of module.children){
const child = devModuleCache[childId];
if (!child) {
continue;
}
const idx = child.parents.indexOf(module.id);
if (idx >= 0) {
child.parents.splice(idx, 1);
}
}
switch(mode){
case 'clear':
delete devModuleCache[module.id];
moduleHotData.delete(module.id);
break;
case 'replace':
moduleHotData.set(module.id, data);
break;
default:
invariant(mode, (mode)=>`invalid mode: ${mode}`);
}
}
/**
* Dispose phase: runs dispose handlers and cleans up outdated/disposed modules.
* Returns the parent modules of outdated modules for use in the apply phase.
*/ function disposePhase(outdatedModules, disposedModules) {
for (const moduleId of outdatedModules){
disposeModule(moduleId, 'replace');
}
for (const moduleId of disposedModules){
disposeModule(moduleId, 'clear');
}
// Removing modules from the module cache is a separate step.
// We also want to keep track of previous parents of the outdated modules.
const outdatedModuleParents = new Map();
for (const moduleId of outdatedModules){
const oldModule = devModuleCache[moduleId];
outdatedModuleParents.set(moduleId, oldModule?.parents);
delete devModuleCache[moduleId];
}
// TODO(alexkirsz) Dependencies: remove outdated dependency from module
// children.
return {
outdatedModuleParents
};
}
/* eslint-disable @typescript-eslint/no-unused-vars */ /**
* Shared module instantiation logic.
* This handles the full module instantiation flow for both browser and Node.js.
* Only React Refresh hooks differ between platforms (passed as callback).
*/ function instantiateModuleShared(moduleId, sourceType, sourceData, moduleFactories, devModuleCache, runtimeModules, createModuleObjectFn, createContextFn, runModuleExecutionHooksFn) {
// 1. Factory validation (same in both browser and Node.js)
const id = moduleId;
const moduleFactory = moduleFactories.get(id);
if (typeof moduleFactory !== 'function') {
throw new Error(`Module ${id} was instantiated, but the module factory is not available.`);
}
// 2. Hot API setup (same in both - works for browser, included for Node.js)
const hotData = moduleHotData.get(id);
const { hot, hotState } = createModuleHot(id, hotData);
// 3. Parent assignment logic (same in both)
let parents;
switch(sourceType){
case SourceType.Runtime:
runtimeModules.add(id);
parents = [];
break;
case SourceType.Parent:
parents = [
sourceData
];
break;
case SourceType.Update:
parents = sourceData || [];
break;
default:
throw new Error(`Unknown source type: ${sourceType}`);
}
// 4. Module creation (platform creates base module object)
const module = createModuleObjectFn(id);
const exports = module.exports;
module.parents = parents;
module.children = [];
module.hot = hot;
devModuleCache[id] = module;
moduleHotState.set(module, hotState);
// 5. Module execution (React Refresh hooks are platform-specific)
try {
moduleFactory(context, module1, exports);
runModuleExecutionHooksFn(module, (refresh)=>{
const context = createContextFn(module, exports, refresh);
moduleFactory.call(exports, context, module, exports);
});
} catch (error) {
module1.error = error;
module.error = error;
throw error;
}
module1.loaded = true;
if (module1.namespaceObject && module1.exports !== module1.namespaceObject) {
// 6. ESM interop (same in both)
if (module.namespaceObject && module.exports !== module.namespaceObject) {
// in case of a circular dependency: cjs1 -> esm2 -> cjs1
interopEsm(module1.exports, module1.namespaceObject);
interopEsm(module.exports, module.namespaceObject);
}
return module1;
return module;
}
/**
* Retrieves a module from the cache, or instantiate it if it is not cached.
*/ // @ts-ignore
function getOrInstantiateModuleFromParent(id, sourceModule) {
const module1 = moduleCache[id];
if (module1) {
if (module1.error) {
throw module1.error;
* Analyzes update entries and chunks to determine which modules were added, modified, or deleted.
* This is pure logic that doesn't depend on the runtime environment.
*/ function computeChangedModules(entries, updates, chunkModulesMap) {
const chunksAdded = new Map();
const chunksDeleted = new Map();
const added = new Map();
const modified = new Map();
const deleted = new Set();
for (const [chunkPath, mergedChunkUpdate] of Object.entries(updates)){
switch(mergedChunkUpdate.type){
case 'added':
{
const updateAdded = new Set(mergedChunkUpdate.modules);
for (const moduleId of updateAdded){
added.set(moduleId, entries[moduleId]);
}
chunksAdded.set(chunkPath, updateAdded);
break;
}
case 'deleted':
{
const updateDeleted = chunkModulesMap ? new Set(chunkModulesMap.get(chunkPath)) : new Set();
for (const moduleId of updateDeleted){
deleted.add(moduleId);
}
chunksDeleted.set(chunkPath, updateDeleted);
break;
}
case 'partial':
{
const updateAdded = new Set(mergedChunkUpdate.added);
const updateDeleted = new Set(mergedChunkUpdate.deleted);
for (const moduleId of updateAdded){
added.set(moduleId, entries[moduleId]);
}
for (const moduleId of updateDeleted){
deleted.add(moduleId);
}
chunksAdded.set(chunkPath, updateAdded);
chunksDeleted.set(chunkPath, updateDeleted);
break;
}
default:
throw new Error('Unknown merged chunk update type');
}
}
// If a module was added from one chunk and deleted from another in the same update,
// consider it to be modified, as it means the module was moved from one chunk to another
// AND has new code in a single update.
for (const moduleId of added.keys()){
if (deleted.has(moduleId)) {
added.delete(moduleId);
deleted.delete(moduleId);
}
}
for (const [moduleId, entry] of Object.entries(entries)){
// Modules that haven't been added to any chunk but have new code are considered
// to be modified.
// This needs to be under the previous loop, as we need it to get rid of modules
// that were added and deleted in the same update.
if (!added.has(moduleId)) {
modified.set(moduleId, entry);
}
return module1;
}
return instantiateModule(id, 1, sourceModule.id);
return {
added,
deleted,
modified,
chunksAdded,
chunksDeleted
};
}
/**
* Compiles new module code and walks the dependency tree to find all outdated modules.
* Uses the evalModuleEntry function to compile code (platform-specific).
*
* @param added - Map of added modules
* @param modified - Map of modified modules
* @param evalModuleEntry - Function to compile module code
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot) {
const newModuleFactories = new Map();
// Compile added modules
for (const [moduleId, entry] of added){
if (entry != null) {
newModuleFactories.set(moduleId, evalModuleEntry(entry));
}
}
// Walk dependency tree to find all modules affected by modifications
const outdatedModules = computedInvalidatedModules(modified.keys(), autoAcceptAtRoot);
// Compile modified modules
for (const [moduleId, entry] of modified){
newModuleFactories.set(moduleId, evalModuleEntry(entry));
}
return {
outdatedModules,
newModuleFactories
};
}
/**
* Updates module factories and re-instantiates self-accepted modules.
* Uses the instantiateModule function (platform-specific via callback).
*/ function applyPhase(outdatedSelfAcceptedModules, newModuleFactories, outdatedModuleParents, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, reportError) {
// Update module factories
for (const [moduleId, factory] of newModuleFactories.entries()){
applyModuleFactoryNameFn(factory);
moduleFactories.set(moduleId, factory);
}
// TODO(alexkirsz) Run new runtime entries here.
// TODO(alexkirsz) Dependencies: call accept handlers for outdated deps.
// Re-instantiate all outdated self-accepted modules
for (const { moduleId, errorHandler } of outdatedSelfAcceptedModules){
try {
instantiateModuleFn(moduleId, SourceType.Update, outdatedModuleParents.get(moduleId));
} catch (err) {
if (typeof errorHandler === 'function') {
try {
errorHandler(err, {
moduleId,
module: devModuleCache[moduleId]
});
} catch (err2) {
reportError(err2);
reportError(err);
}
} else {
reportError(err);
}
}
}
}
/**
* Internal implementation that orchestrates the full HMR update flow:
* invalidation, disposal, and application of new modules.
*
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot) {
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptAtRoot);
// Find self-accepted modules to re-instantiate
const outdatedSelfAcceptedModules = computeOutdatedSelfAcceptedModules(outdatedModules);
// Run dispose handlers, save hot.data, clear caches
const { outdatedModuleParents } = disposePhase(outdatedModules, disposedModules);
let error;
function reportError(err) {
if (!error) error = err; // Keep first error
}
applyPhase(outdatedSelfAcceptedModules, newModuleFactories, outdatedModuleParents, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, reportError);
if (error) {
throw error;
}
// Recursively apply any queued invalidations from new module execution
if (queuedInvalidatedModules.size > 0) {
applyInternal(new Set(), [], new Map(), moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot);
}
}
/**
* Main entry point for applying an ECMAScript merged update.
* This is called by both browser and Node.js runtimes with platform-specific callbacks.
*
* @param options.autoAcceptAtRoot - If true, root modules auto-accept updates without explicit
* module.hot.accept(). Used for server-side HMR where pages
* auto-accept at the top level.
*/ function applyEcmascriptMergedUpdateShared(options) {
const { added, modified, disposedModules, evalModuleEntry, instantiateModule, applyModuleFactoryName, moduleFactories, devModuleCache, autoAcceptAtRoot } = options;
const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot);
applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModule, applyModuleFactoryName, autoAcceptAtRoot);
}
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-base.ts" />
/// <reference path="../../shared/runtime/dev-extensions.ts" />
/// <reference path="../../shared/runtime/hmr-runtime.ts" />
/**
* Development Node.js runtime.
* Uses HotModule and shared HMR logic for hot module replacement support.
*/ // Cast the module cache to HotModule for development mode
// (hmr-runtime.ts declares devModuleCache as `let` variable expecting assignment)
// This is safe because HotModule extends Module
devModuleCache = moduleCache;
if (!globalThis.__turbopack_runtime_modules__) {
globalThis.__turbopack_runtime_modules__ = new Set();
}
runtimeModules = globalThis.__turbopack_runtime_modules__;
const nodeDevContextPrototype = Context.prototype;
nodeDevContextPrototype.q = exportUrl;
nodeDevContextPrototype.M = moduleFactories;
nodeDevContextPrototype.c = devModuleCache;
nodeDevContextPrototype.R = resolvePathFromModule;
nodeDevContextPrototype.b = getWorkerURL;
nodeDevContextPrototype.C = clearChunkCache;
/**
* Instantiates a module in development mode using shared HMR logic.
*/ function instantiateModule(id, sourceType, sourceData) {
// Node.js: creates base module object (hot API added by shared code)
const createModuleObjectFn = (moduleId)=>{
return createModuleWithDirection(moduleId);
};
// Node.js: creates Context (no refresh parameter)
const createContext = (module1, exports, _refresh)=>{
return new Context(module1, exports);
};
// Node.js: no hooks wrapper, just execute directly
const runWithHooks = (module1, exec)=>{
exec(undefined); // no refresh context
};
// Use shared instantiation logic (includes hot API setup)
const newModule = instantiateModuleShared(id, sourceType, sourceData, moduleFactories, devModuleCache, runtimeModules, createModuleObjectFn, createContext, runWithHooks);
newModule.loaded = true;
return newModule;
}
/**
* Instantiates a runtime module.
* Instantiates a runtime module in development mode.
*/ function instantiateRuntimeModule(chunkPath, moduleId) {
return instantiateModule(moduleId, 0, chunkPath);
return instantiateModule(moduleId, SourceType.Runtime, chunkPath);
}
/**
* 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
function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
const module1 = moduleCache[moduleId];
const module1 = devModuleCache[moduleId];
if (module1) {
if (module1.error) {
throw module1.error;
......@@ -827,22 +1399,147 @@ function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
}
return instantiateRuntimeModule(chunkPath, moduleId);
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
*/ function isJs(chunkUrlOrPath) {
return regexJsUrl.test(chunkUrlOrPath);
}
function __turbopack_server_hmr_apply__(_update) {
// TODO: Implement actual HMR logic to update module factories
// For now, just return true to indicate we "accepted" the update
return true;
* Retrieves a module from the cache, or instantiate it if it is not cached.
* Also tracks parent-child relationships for HMR dependency tracking.
*/ // @ts-ignore
function getOrInstantiateModuleFromParent(id, sourceModule) {
// Track parent-child relationship
trackModuleImport(sourceModule, id, devModuleCache[id]);
const module1 = devModuleCache[id];
if (module1) {
if (module1.error) {
throw module1.error;
}
return module1;
}
const newModule = instantiateModule(id, SourceType.Parent, sourceModule.id);
// Track again after instantiation to ensure the relationship is recorded
trackModuleImport(sourceModule, id, newModule);
return newModule;
}
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__;
module.exports = (sourcePath)=>({
m: (id)=>getOrInstantiateRuntimeModule(sourcePath, id),
c: (chunkData)=>loadRuntimeChunk(sourcePath, chunkData)
});
/// <reference path="../../shared/runtime/dev-protocol.d.ts" />
/// <reference path="../../shared/runtime/hmr-runtime.ts" />
/* eslint-disable @typescript-eslint/no-unused-vars */ /**
* Node.js HMR client implementation.
* Simplified for concatenated runtime - no ESM imports.
*/ // Node.js HMR payload with direct EcmascriptMergedUpdate (no ChunkListUpdate wrapper)
/**
* Emits an HMR message to registered update listeners.
* In Node.js, we directly invoke the listeners rather than going through
* a full message backend like the browser does.
*/ function emitMessage(msg) {
// Find and invoke listeners registered in TURBOPACK_CHUNK_UPDATE_LISTENERS
if (globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS) {
for (const [_chunkPath, listener] of globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS){
try {
listener(msg.data);
} catch (err) {
console.error('[Server HMR] Listener error:', err);
}
}
}
}
/**
* Handles server message updates and applies them to the Node.js runtime.
* Uses shared HMR update logic from hmr-runtime.ts.
*/ function handleNodejsUpdate(msg, moduleFactories, devModuleCache, runtimeModules, instantiateModuleFn) {
if (msg.type !== 'partial') {
return;
}
const instruction = msg.instruction;
if (instruction.type !== 'EcmascriptMergedUpdate') {
return;
}
try {
const { entries = {}, chunks = {} } = instruction;
// Node.js eval function (no source maps)
const evalModuleEntry = (entry)=>{
// eslint-disable-next-line no-eval
return (0, eval)(entry.code);
};
const { added, modified } = computeChangedModules(entries, chunks, undefined // no chunkModulesMap for Node.js
);
// Use shared HMR update implementation
applyEcmascriptMergedUpdateShared({
added,
modified,
disposedModules: [],
evalModuleEntry,
instantiateModule,
applyModuleFactoryName: ()=>{},
moduleFactories,
devModuleCache,
runtimeModules,
autoAcceptAtRoot: true
});
} catch (e) {
console.error('[Server HMR] Update failed, full reload needed:', e);
throw e;
}
}
let initialized = false;
function initializeServerHmr(moduleFactories, devModuleCache, runtimeModules, instantiateModuleFn) {
if (initialized) {
return;
}
initialized = true;
const queued = globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS;
if (queued != null && !Array.isArray(queued)) {
throw new Error('A separate HMR handler was already registered');
}
if (!Array.isArray(globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS)) {
globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS = [];
}
// Register an update callback for the server runtime
// The chunk path doesn't matter much for Node.js server since we get updates
// directly, but we use '__server__' as a placeholder
const serverChunkPath = '__server__';
globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS.push([
serverChunkPath,
(msg)=>{
handleNodejsUpdate(msg, moduleFactories, devModuleCache, runtimeModules, instantiateModuleFn);
}
]);
}
/// <reference path="../../shared/runtime/dev-globals.d.ts" />
/// <reference path="../../shared/runtime/dev-protocol.d.ts" />
/// <reference path="./hmr-client.ts" />
/**
* Note: hmr-runtime.ts is embedded before this file, so its functions
* (initializeServerHmr, emitMessage) are available in the same scope.
*/ // Initialize server HMR client (connects to shared HMR infrastructure)
let hmrClientInitialized = false;
function ensureHmrClientInitialized() {
if (hmrClientInitialized) return;
hmrClientInitialized = true;
// initializeServerHmr is from hmr-client.ts (embedded before this file)
// moduleFactories, runtimeModules, and instantiateModule are from dev-runtime.ts
// devModuleCache is the HotModule-typed cache from dev-runtime.ts
initializeServerHmr(moduleFactories, devModuleCache, runtimeModules, instantiateModule);
}
function __turbopack_server_hmr_apply__(update) {
try {
// Initialize HMR client on first update
ensureHmrClientInitialized();
// emitMessage is from hmr-client.ts (embedded before this file)
emitMessage({
type: 'turbopack-message',
data: update
});
return true;
} catch (err) {
console.error('[Server HMR] Failed to apply update:', err);
return false;
}
}
;
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__;
globalThis.__turbopack__server_hmr_apply__ = __turbopack_server_hmr_apply__;
//# sourceMappingURL=%5Bturbopack%5D_runtime.js.map
\ No newline at end of file
......@@ -6,5 +6,9 @@
{"offset": {"line": 544, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared-node/base-externals-utils.ts"],"sourcesContent":["/// <reference path=\"../shared/runtime/runtime-utils.ts\" />\n\n/// A 'base' utilities to support runtime can have externals.\n/// Currently this is for node.js / edge runtime both.\n/// If a fn requires node.js specific behavior, it should be placed in `node-external-utils` instead.\n\nasync function externalImport(id: DependencySpecifier) {\n let raw\n try {\n raw = await import(id)\n } catch (err) {\n // TODO(alexkirsz) This can happen when a client-side module tries to load\n // an external module we don't provide a shim for (e.g. querystring, url).\n // For now, we fail semi-silently, but in the future this should be a\n // compilation error.\n throw new Error(`Failed to load external module ${id}: ${err}`)\n }\n\n if (raw && raw.__esModule && raw.default && 'default' in raw.default) {\n return interopEsm(raw.default, createNS(raw), true)\n }\n\n return raw\n}\ncontextPrototype.y = externalImport\n\nfunction externalRequire(\n id: ModuleId,\n thunk: () => any,\n esm: boolean = false\n): Exports | EsmNamespaceObject {\n let raw\n try {\n raw = thunk()\n } catch (err) {\n // TODO(alexkirsz) This can happen when a client-side module tries to load\n // an external module we don't provide a shim for (e.g. querystring, url).\n // For now, we fail semi-silently, but in the future this should be a\n // compilation error.\n throw new Error(`Failed to load external module ${id}: ${err}`)\n }\n\n if (!esm || raw.__esModule) {\n return raw\n }\n\n return interopEsm(raw, createNS(raw), true)\n}\n\nexternalRequire.resolve = (\n id: string,\n options?: {\n paths?: string[]\n }\n) => {\n return require.resolve(id, options)\n}\ncontextPrototype.x = externalRequire\n"],"names":["externalImport","id","raw","err","Error","__esModule","default","interopEsm","createNS","contextPrototype","y","externalRequire","thunk","esm","resolve","options","require","x"],"mappings":"AAAA,2DAA2D;AAE3D,6DAA6D;AAC7D,sDAAsD;AACtD,qGAAqG;AAErG,eAAeA,eAAeC,EAAuB;IACnD,IAAIC;IACJ,IAAI;QACFA,MAAM,MAAM,MAAM,CAACD;IACrB,EAAE,OAAOE,KAAK;QACZ,0EAA0E;QAC1E,0EAA0E;QAC1E,qEAAqE;QACrE,qBAAqB;QACrB,MAAM,IAAIC,MAAM,CAAC,+BAA+B,EAAEH,GAAG,EAAE,EAAEE,KAAK;IAChE;IAEA,IAAID,OAAOA,IAAIG,UAAU,IAAIH,IAAII,OAAO,IAAI,aAAaJ,IAAII,OAAO,EAAE;QACpE,OAAOC,WAAWL,IAAII,OAAO,EAAEE,SAASN,MAAM;IAChD;IAEA,OAAOA;AACT;AACAO,iBAAiBC,CAAC,GAAGV;AAErB,SAASW,gBACPV,EAAY,EACZW,KAAgB,EAChBC,MAAe,KAAK;IAEpB,IAAIX;IACJ,IAAI;QACFA,MAAMU;IACR,EAAE,OAAOT,KAAK;QACZ,0EAA0E;QAC1E,0EAA0E;QAC1E,qEAAqE;QACrE,qBAAqB;QACrB,MAAM,IAAIC,MAAM,CAAC,+BAA+B,EAAEH,GAAG,EAAE,EAAEE,KAAK;IAChE;IAEA,IAAI,CAACU,OAAOX,IAAIG,UAAU,EAAE;QAC1B,OAAOH;IACT;IAEA,OAAOK,WAAWL,KAAKM,SAASN,MAAM;AACxC;AAEAS,gBAAgBG,OAAO,GAAG,CACxBb,IACAc;IAIA,OAAOC,QAAQF,OAAO,CAACb,IAAIc;AAC7B;AACAN,iBAAiBQ,CAAC,GAAGN","ignoreList":[0]}},
{"offset": {"line": 585, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared-node/node-externals-utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\ndeclare var RUNTIME_PUBLIC_PATH: string\ndeclare var RELATIVE_ROOT_PATH: string\ndeclare var ASSET_PREFIX: string\n\nconst path = require('path')\n\nconst relativePathToRuntimeRoot = path.relative(RUNTIME_PUBLIC_PATH, '.')\n// Compute the relative path to the `distDir`.\nconst relativePathToDistRoot = path.join(\n relativePathToRuntimeRoot,\n RELATIVE_ROOT_PATH\n)\nconst RUNTIME_ROOT = path.resolve(__filename, relativePathToRuntimeRoot)\n// Compute the absolute path to the root, by stripping distDir from the absolute path to this file.\nconst ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot)\n\n/**\n * Returns an absolute path to the given module path.\n * Module path should be relative, either path to a file or a directory.\n *\n * This fn allows to calculate an absolute path for some global static values, such as\n * `__dirname` or `import.meta.url` that Turbopack will not embeds in compile time.\n * See ImportMetaBinding::code_generation for the usage.\n */\nfunction resolveAbsolutePath(modulePath?: string): string {\n if (modulePath) {\n return path.join(ABSOLUTE_ROOT, modulePath)\n }\n return ABSOLUTE_ROOT\n}\nContext.prototype.P = resolveAbsolutePath\n"],"names":["path","require","relativePathToRuntimeRoot","relative","RUNTIME_PUBLIC_PATH","relativePathToDistRoot","join","RELATIVE_ROOT_PATH","RUNTIME_ROOT","resolve","__filename","ABSOLUTE_ROOT","resolveAbsolutePath","modulePath","Context","prototype","P"],"mappings":"AAAA,oDAAoD,GAMpD,MAAMA,OAAOC,QAAQ;AAErB,MAAMC,4BAA4BF,KAAKG,QAAQ,CAACC,qBAAqB;AACrE,8CAA8C;AAC9C,MAAMC,yBAAyBL,KAAKM,IAAI,CACtCJ,2BACAK;AAEF,MAAMC,eAAeR,KAAKS,OAAO,CAACC,YAAYR;AAC9C,mGAAmG;AACnG,MAAMS,gBAAgBX,KAAKS,OAAO,CAACC,YAAYL;AAE/C;;;;;;;CAOC,GACD,SAASO,oBAAoBC,UAAmB;IAC9C,IAAIA,YAAY;QACd,OAAOb,KAAKM,IAAI,CAACK,eAAeE;IAClC;IACA,OAAOF;AACT;AACAG,QAAQC,SAAS,CAACC,CAAC,GAAGJ","ignoreList":[0]}},
{"offset": {"line": 606, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared-node/node-wasm-utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../shared/runtime/runtime-utils.ts\" />\n\nfunction readWebAssemblyAsResponse(path: string) {\n const { createReadStream } = require('fs') as typeof import('fs')\n const { Readable } = require('stream') as typeof import('stream')\n\n const stream = createReadStream(path)\n\n // @ts-ignore unfortunately there's a slight type mismatch with the stream.\n return new Response(Readable.toWeb(stream), {\n headers: {\n 'content-type': 'application/wasm',\n },\n })\n}\n\nasync function compileWebAssemblyFromPath(\n path: string\n): Promise<WebAssembly.Module> {\n const response = readWebAssemblyAsResponse(path)\n\n return await WebAssembly.compileStreaming(response)\n}\n\nasync function instantiateWebAssemblyFromPath(\n path: string,\n importsObj: WebAssembly.Imports\n): Promise<Exports> {\n const response = readWebAssemblyAsResponse(path)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n response,\n importsObj\n )\n\n return instance.exports\n}\n"],"names":["readWebAssemblyAsResponse","path","createReadStream","require","Readable","stream","Response","toWeb","headers","compileWebAssemblyFromPath","response","WebAssembly","compileStreaming","instantiateWebAssemblyFromPath","importsObj","instance","instantiateStreaming","exports"],"mappings":"AAAA,oDAAoD,GAEpD,2DAA2D;AAE3D,SAASA,0BAA0BC,IAAY;IAC7C,MAAM,EAAEC,gBAAgB,EAAE,GAAGC,QAAQ;IACrC,MAAM,EAAEC,QAAQ,EAAE,GAAGD,QAAQ;IAE7B,MAAME,SAASH,iBAAiBD;IAEhC,2EAA2E;IAC3E,OAAO,IAAIK,SAASF,SAASG,KAAK,CAACF,SAAS;QAC1CG,SAAS;YACP,gBAAgB;QAClB;IACF;AACF;AAEA,eAAeC,2BACbR,IAAY;IAEZ,MAAMS,WAAWV,0BAA0BC;IAE3C,OAAO,MAAMU,YAAYC,gBAAgB,CAACF;AAC5C;AAEA,eAAeG,+BACbZ,IAAY,EACZa,UAA+B;IAE/B,MAAMJ,WAAWV,0BAA0BC;IAE3C,MAAM,EAAEc,QAAQ,EAAE,GAAG,MAAMJ,YAAYK,oBAAoB,CACzDN,UACAI;IAGF,OAAOC,SAASE,OAAO;AACzB","ignoreList":[0]}},
{"offset": {"line": 627, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/nodejs/runtime/runtime-base.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../hmr-types.d.ts\" />\n/// <reference path=\"../../shared/runtime/runtime-utils.ts\" />\n/// <reference path=\"../../shared-node/base-externals-utils.ts\" />\n/// <reference path=\"../../shared-node/node-externals-utils.ts\" />\n/// <reference path=\"../../shared-node/node-wasm-utils.ts\" />\n\nenum SourceType {\n /**\n * The module was instantiated because it was included in an evaluated chunk's\n * runtime.\n * SourceData is a ChunkPath.\n */\n Runtime = 0,\n /**\n * The module was instantiated because a parent module imported it.\n * SourceData is a ModuleId.\n */\n Parent = 1,\n}\n\ntype SourceData = ChunkPath | ModuleId\n\nprocess.env.TURBOPACK = '1'\n\ninterface TurbopackNodeBuildContext extends TurbopackBaseContext<Module> {\n R: ResolvePathFromModule\n x: ExternalRequire\n y: ExternalImport\n q: ExportUrl\n}\n\nconst nodeContextPrototype = Context.prototype as TurbopackNodeBuildContext\n\ntype ModuleFactory = (\n this: Module['exports'],\n context: TurbopackNodeBuildContext\n) => unknown\n\nconst url = require('url') as typeof import('url')\n\nconst moduleFactories: ModuleFactories = new Map()\nnodeContextPrototype.M = moduleFactories\nconst moduleCache: ModuleCache<Module> = Object.create(null)\nnodeContextPrototype.c = moduleCache\n\n/**\n * Returns an absolute path to the given module's id.\n */\nfunction resolvePathFromModule(\n this: TurbopackBaseContext<Module>,\n moduleId: string\n): string {\n const exported = this.r(moduleId)\n const exportedPath = exported?.default ?? exported\n if (typeof exportedPath !== 'string') {\n return exported as any\n }\n\n const strippedAssetPrefix = exportedPath.slice(ASSET_PREFIX.length)\n const resolved = path.resolve(RUNTIME_ROOT, strippedAssetPrefix)\n\n return url.pathToFileURL(resolved).href\n}\nnodeContextPrototype.R = resolvePathFromModule\n\n/**\n * Exports a URL value. No suffix is added in Node.js runtime.\n */\nfunction exportUrl(\n this: TurbopackBaseContext<Module>,\n urlValue: string,\n id: ModuleId | undefined\n) {\n exportValue.call(this, urlValue, id)\n}\nnodeContextPrototype.q = exportUrl\n\nfunction loadRuntimeChunk(sourcePath: ChunkPath, chunkData: ChunkData): void {\n if (typeof chunkData === 'string') {\n loadRuntimeChunkPath(sourcePath, chunkData)\n } else {\n loadRuntimeChunkPath(sourcePath, chunkData.path)\n }\n}\n\nconst loadedChunks = new Set<ChunkPath>()\nconst unsupportedLoadChunk = Promise.resolve(undefined)\nconst loadedChunk: Promise<void> = Promise.resolve(undefined)\nconst chunkCache = new Map<ChunkPath, Promise<void>>()\n\nfunction clearChunkCache() {\n chunkCache.clear()\n}\n\nfunction loadRuntimeChunkPath(\n sourcePath: ChunkPath,\n chunkPath: ChunkPath\n): void {\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return\n }\n\n if (loadedChunks.has(chunkPath)) {\n return\n }\n\n try {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n const chunkModules: CompressedModuleFactories = require(resolved)\n installCompressedModuleFactories(chunkModules, 0, moduleFactories)\n loadedChunks.add(chunkPath)\n } catch (cause) {\n let errorMessage = `Failed to load chunk ${chunkPath}`\n\n if (sourcePath) {\n errorMessage += ` from runtime for chunk ${sourcePath}`\n }\n\n const error = new Error(errorMessage, { cause })\n error.name = 'ChunkLoadError'\n throw error\n }\n}\n\nfunction loadChunkAsync(\n this: TurbopackBaseContext<Module>,\n chunkData: ChunkData\n): Promise<void> {\n const chunkPath = typeof chunkData === 'string' ? chunkData : chunkData.path\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return unsupportedLoadChunk\n }\n\n let entry = chunkCache.get(chunkPath)\n if (entry === undefined) {\n try {\n // resolve to an absolute path to simplify `require` handling\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n // TODO: consider switching to `import()` to enable concurrent chunk loading and async file io\n // However this is incompatible with hot reloading (since `import` doesn't use the require cache)\n const chunkModules: CompressedModuleFactories = require(resolved)\n installCompressedModuleFactories(chunkModules, 0, moduleFactories)\n entry = loadedChunk\n } catch (cause) {\n const errorMessage = `Failed to load chunk ${chunkPath} from module ${this.m.id}`\n const error = new Error(errorMessage, { cause })\n error.name = 'ChunkLoadError'\n\n // Cache the failure promise, future requests will also get this same rejection\n entry = Promise.reject(error)\n }\n chunkCache.set(chunkPath, entry)\n }\n // TODO: Return an instrumented Promise that React can use instead of relying on referential equality.\n return entry\n}\ncontextPrototype.l = loadChunkAsync\n\nfunction loadChunkAsyncByUrl(\n this: TurbopackBaseContext<Module>,\n chunkUrl: string\n) {\n const path = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT)) as ChunkPath\n return loadChunkAsync.call(this, path)\n}\ncontextPrototype.L = loadChunkAsyncByUrl\n\nfunction loadWebAssembly(\n chunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n imports: WebAssembly.Imports\n) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n return instantiateWebAssemblyFromPath(resolved, imports)\n}\ncontextPrototype.w = loadWebAssembly\n\nfunction loadWebAssemblyModule(\n chunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n return compileWebAssemblyFromPath(resolved)\n}\ncontextPrototype.u = loadWebAssemblyModule\n\nfunction getWorkerURL(\n _entrypoint: ChunkPath,\n _moduleChunks: ChunkPath[],\n _shared: boolean\n): URL {\n throw new Error('Worker urls are not implemented yet for Node.js')\n}\n\nnodeContextPrototype.b = getWorkerURL\n\nfunction instantiateModule(\n id: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module {\n const moduleFactory = moduleFactories.get(id)\n if (typeof moduleFactory !== 'function') {\n // This can happen if modules incorrectly handle HMR disposes/updates,\n // e.g. when they keep a `setTimeout` around which still executes old code\n // and contains e.g. a `require(\"something\")` call.\n let instantiationReason: string\n switch (sourceType) {\n case SourceType.Runtime:\n instantiationReason = `as a runtime entry of chunk ${sourceData}`\n break\n case SourceType.Parent:\n instantiationReason = `because it was required from module ${sourceData}`\n break\n default:\n invariant(\n sourceType,\n (sourceType) => `Unknown source type: ${sourceType}`\n )\n }\n throw new Error(\n `Module ${id} was instantiated ${instantiationReason}, but the module factory is not available.`\n )\n }\n\n const module: Module = createModuleObject(id)\n const exports = module.exports\n moduleCache[id] = module\n\n const context = new (Context as any as ContextConstructor<Module>)(\n module,\n exports\n )\n // NOTE(alexkirsz) This can fail when the module encounters a runtime error.\n try {\n moduleFactory(context, module, exports)\n } catch (error) {\n module.error = error as any\n throw error\n }\n\n module.loaded = true\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject)\n }\n\n return module\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// @ts-ignore\nfunction getOrInstantiateModuleFromParent(\n id: ModuleId,\n sourceModule: Module\n): Module {\n const module = moduleCache[id]\n\n if (module) {\n if (module.error) {\n throw module.error\n }\n\n return module\n }\n\n return instantiateModule(id, SourceType.Parent, sourceModule.id)\n}\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module {\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.\n */\n// @ts-ignore TypeScript doesn't separate this module space from the browser runtime\nfunction getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module {\n const module = moduleCache[moduleId]\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n return instantiateRuntimeModule(chunkPath, moduleId)\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath)\n}\n\nfunction __turbopack_server_hmr_apply__(\n _update: NodeJsPartialHmrUpdate\n): boolean {\n // TODO: Implement actual HMR logic to update module factories\n // For now, just return true to indicate we \"accepted\" the update\n return true\n}\n\nglobalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__\n\nmodule.exports = (sourcePath: ChunkPath) => ({\n m: (id: ModuleId) => getOrInstantiateRuntimeModule(sourcePath, id),\n c: (chunkData: ChunkData) => loadRuntimeChunk(sourcePath, chunkData),\n})\n"],"names":["SourceType","process","env","TURBOPACK","nodeContextPrototype","Context","prototype","url","require","moduleFactories","Map","M","moduleCache","Object","create","c","resolvePathFromModule","moduleId","exported","r","exportedPath","default","strippedAssetPrefix","slice","ASSET_PREFIX","length","resolved","path","resolve","RUNTIME_ROOT","pathToFileURL","href","R","exportUrl","urlValue","id","exportValue","call","q","loadRuntimeChunk","sourcePath","chunkData","loadRuntimeChunkPath","loadedChunks","Set","unsupportedLoadChunk","Promise","undefined","loadedChunk","chunkCache","clearChunkCache","clear","chunkPath","isJs","has","chunkModules","installCompressedModuleFactories","add","cause","errorMessage","error","Error","name","loadChunkAsync","entry","get","m","reject","set","contextPrototype","l","loadChunkAsyncByUrl","chunkUrl","path1","fileURLToPath","URL","L","loadWebAssembly","_edgeModule","imports","instantiateWebAssemblyFromPath","w","loadWebAssemblyModule","compileWebAssemblyFromPath","u","getWorkerURL","_entrypoint","_moduleChunks","_shared","b","instantiateModule","sourceType","sourceData","moduleFactory","instantiationReason","invariant","module1","createModuleObject","exports","context","loaded","namespaceObject","interopEsm","getOrInstantiateModuleFromParent","sourceModule","instantiateRuntimeModule","getOrInstantiateRuntimeModule","regexJsUrl","chunkUrlOrPath","test","__turbopack_server_hmr_apply__","_update","globalThis","module"],"mappings":"AAAA,oDAAoD,GAEpD,0CAA0C;AAC1C,8DAA8D;AAC9D,kEAAkE;AAClE,kEAAkE;AAClE,6DAA6D;AAE7D,IAAA,AAAKA,oCAAAA;IACH;;;;GAIC;IAED;;;GAGC;WAVEA;EAAAA;AAgBLC,QAAQC,GAAG,CAACC,SAAS,GAAG;AASxB,MAAMC,uBAAuBC,QAAQC,SAAS;AAO9C,MAAMC,MAAMC,QAAQ;AAEpB,MAAMC,kBAAmC,IAAIC;AAC7CN,qBAAqBO,CAAC,GAAGF;AACzB,MAAMG,cAAmCC,OAAOC,MAAM,CAAC;AACvDV,qBAAqBW,CAAC,GAAGH;AAEzB;;CAEC,GACD,SAASI,sBAEPC,QAAgB;IAEhB,MAAMC,WAAW,IAAI,CAACC,CAAC,CAACF;IACxB,MAAMG,eAAeF,UAAUG,WAAWH;IAC1C,IAAI,OAAOE,iBAAiB,UAAU;QACpC,OAAOF;IACT;IAEA,MAAMI,sBAAsBF,aAAaG,KAAK,CAACC,aAAaC,MAAM;IAClE,MAAMC,WAAWC,KAAKC,OAAO,CAACC,cAAcP;IAE5C,OAAOf,IAAIuB,aAAa,CAACJ,UAAUK,IAAI;AACzC;AACA3B,qBAAqB4B,CAAC,GAAGhB;AAEzB;;CAEC,GACD,SAASiB,UAEPC,QAAgB,EAChBC,EAAwB;IAExBC,YAAYC,IAAI,CAAC,IAAI,EAAEH,UAAUC;AACnC;AACA/B,qBAAqBkC,CAAC,GAAGL;AAEzB,SAASM,iBAAiBC,UAAqB,EAAEC,SAAoB;IACnE,IAAI,OA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SAAS;IACpC,IAAI+E,SAAQ;QACV,IAAIA,QAAOpC,KAAK,EAAE;YAChB,MAAMoC,QAAOpC,KAAK;QACpB;QACA,OAAOoC;IACT;IAEA,OAAOS,yBAAyBrD,WAAWnC;AAC7C;AAEA,MAAM0F,aAAa;AACnB;;CAEC,GACD,SAAStD,KAAKuD,cAAoC;IAChD,OAAOD,WAAWE,IAAI,CAACD;AACzB;AAEA,SAASE,+BACPC,OAA+B;IAE/B,8DAA8D;IAC9D,iEAAiE;IACjE,OAAO;AACT;AAEAC,WAAWF,8BAA8B,GAAGA;AAE5CG,OAAOf,OAAO,GAAG,CAAC1D,aAA0B,CAAC;QAC3C0B,GAAG,CAAC/B,KAAiBuE,8BAA8BlE,YAAYL;QAC/DpB,GAAG,CAAC0B,YAAyBF,iBAAiBC,YAAYC;IAC5D,CAAC","ignoreList":[0]}}]
{"offset": {"line": 627, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/nodejs/runtime/runtime-base.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../../shared/runtime/runtime-utils.ts\" />\n/// <reference path=\"../../shared-node/base-externals-utils.ts\" />\n/// <reference path=\"../../shared-node/node-externals-utils.ts\" />\n/// <reference path=\"../../shared-node/node-wasm-utils.ts\" />\n/// <reference path=\"./nodejs-globals.d.ts\" />\n\n/**\n * Base Node.js runtime shared between production and development.\n * Contains chunk loading, module caching, and other non-HMR functionality.\n */\n\nprocess.env.TURBOPACK = '1'\n\nconst url = require('url') as typeof import('url')\n\n// Use global module factories and cache to persist across chunk reloads during HMR\n// This ensures that when Node.js clears the require cache for a chunk file,\n// we don't lose our granular HMR updates to individual modules\nif (!globalThis.__turbopack_module_factories__) {\n globalThis.__turbopack_module_factories__ = new Map()\n}\nif (!globalThis.__turbopack_module_cache__) {\n globalThis.__turbopack_module_cache__ = Object.create(null)\n}\n\nconst moduleFactories: ModuleFactories =\n globalThis.__turbopack_module_factories__\n\n// Module cache - typed as base Module, can be cast to HotModule in dev mode\nconst moduleCache: ModuleCache<Module> = globalThis.__turbopack_module_cache__\n\n/**\n * Returns an absolute path to the given module's id.\n */\nfunction resolvePathFromModule(\n this: TurbopackBaseContext<Module>,\n moduleId: string\n): string {\n const exported = this.r(moduleId)\n const exportedPath = exported?.default ?? exported\n if (typeof exportedPath !== 'string') {\n return exported as any\n }\n\n const strippedAssetPrefix = exportedPath.slice(ASSET_PREFIX.length)\n const resolved = path.resolve(RUNTIME_ROOT, strippedAssetPrefix)\n\n return url.pathToFileURL(resolved).href\n}\n\n/**\n * Exports a URL value. No suffix is added in Node.js runtime.\n */\nfunction exportUrl(\n this: TurbopackBaseContext<Module>,\n urlValue: string,\n id: ModuleId | undefined\n) {\n exportValue.call(this, urlValue, id)\n}\n\nfunction loadRuntimeChunk(sourcePath: ChunkPath, chunkData: ChunkData): void {\n if (typeof chunkData === 'string') {\n loadRuntimeChunkPath(sourcePath, chunkData)\n } else {\n loadRuntimeChunkPath(sourcePath, chunkData.path)\n }\n}\n\nconst loadedChunks = new Set<ChunkPath>()\nconst unsupportedLoadChunk = Promise.resolve(undefined)\nconst loadedChunk: Promise<void> = Promise.resolve(undefined)\nconst chunkCache = new Map<ChunkPath, Promise<void>>()\n\n/**\n * Clear all chunk and module state to force re-evaluation on next require.\n * Called by Next.js when server HMR is disabled to implement the \"reload everything\" behavior.\n */\nfunction clearChunkCache() {\n chunkCache.clear()\n loadedChunks.clear()\n moduleFactories.clear()\n for (const key in moduleCache) {\n delete moduleCache[key]\n }\n}\n\nfunction loadRuntimeChunkPath(\n sourcePath: ChunkPath,\n chunkPath: ChunkPath\n): void {\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return\n }\n\n if (loadedChunks.has(chunkPath)) {\n return\n }\n\n try {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n const chunkModules: CompressedModuleFactories = require(resolved)\n installCompressedModuleFactories(chunkModules, 0, moduleFactories)\n loadedChunks.add(chunkPath)\n } catch (cause) {\n let errorMessage = `Failed to load chunk ${chunkPath}`\n\n if (sourcePath) {\n errorMessage += ` from runtime for chunk ${sourcePath}`\n }\n\n const error = new Error(errorMessage, { cause })\n error.name = 'ChunkLoadError'\n throw error\n }\n}\n\nfunction loadChunkAsync(\n this: TurbopackBaseContext<any>,\n chunkData: ChunkData\n): Promise<void> {\n const chunkPath = typeof chunkData === 'string' ? chunkData : chunkData.path\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return unsupportedLoadChunk\n }\n\n let entry = chunkCache.get(chunkPath)\n if (entry === undefined) {\n try {\n // resolve to an absolute path to simplify `require` handling\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n // TODO: consider switching to `import()` to enable concurrent chunk loading and async file io\n // However this is incompatible with hot reloading (since `import` doesn't use the require cache)\n const chunkModules: CompressedModuleFactories = require(resolved)\n installCompressedModuleFactories(chunkModules, 0, moduleFactories)\n entry = loadedChunk\n } catch (cause) {\n const errorMessage = `Failed to load chunk ${chunkPath} from module ${this.m.id}`\n const error = new Error(errorMessage, { cause })\n error.name = 'ChunkLoadError'\n\n // Cache the failure promise, future requests will also get this same rejection\n entry = Promise.reject(error)\n }\n chunkCache.set(chunkPath, entry)\n }\n // TODO: Return an instrumented Promise that React can use instead of relying on referential equality.\n return entry\n}\ncontextPrototype.l = loadChunkAsync\n\nfunction loadChunkAsyncByUrl(\n this: TurbopackBaseContext<any>,\n chunkUrl: string\n) {\n const path = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT)) as ChunkPath\n return loadChunkAsync.call(this, path)\n}\ncontextPrototype.L = loadChunkAsyncByUrl\n\nfunction loadWebAssembly(\n chunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n imports: WebAssembly.Imports\n) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n return instantiateWebAssemblyFromPath(resolved, imports)\n}\ncontextPrototype.w = loadWebAssembly\n\nfunction loadWebAssemblyModule(\n chunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n return compileWebAssemblyFromPath(resolved)\n}\ncontextPrototype.u = loadWebAssemblyModule\n\nfunction getWorkerURL(\n _entrypoint: ChunkPath,\n _moduleChunks: ChunkPath[],\n _shared: boolean\n): URL {\n throw new Error('Worker urls are not implemented yet for Node.js')\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath)\n}\n"],"names":["process","env","TURBOPACK","url","require","globalThis","__turbopack_module_factories__","Map","__turbopack_module_cache__","Object","create","moduleFactories","moduleCache","resolvePathFromModule","moduleId","exported","r","exportedPath","default","strippedAssetPrefix","slice","ASSET_PREFIX","length","resolved","path","resolve","RUNTIME_ROOT","pathToFileURL","href","exportUrl","urlValue","id","exportValue","call","loadRuntimeChunk","sourcePath","chunkData","loadRuntimeChunkPath","loadedChunks","Set","unsupportedLoadChunk","Promise","undefined","loadedChunk","chunkCache","clearChunkCache","clear","key","chunkPath","isJs","has","chunkModules","installCompressedModuleFactories","add","cause","errorMessage","error","Error","name","loadChunkAsync","entry","get","m","reject","set","contextPrototype","l","loadChunkAsyncByUrl","chunkUrl","path1","fileURLToPath","URL","L","loadWebAssembly","_edgeModule","imports","instantiateWebAssemblyFromPath","w","loadWebAssemblyModule","compileWebAssemblyFromPath","u","getWorkerURL","_entrypoint","_moduleChunks","_shared","regexJsUrl","chunkUrlOrPath","test"],"mappings":"AAAA,oDAAoD,GAEpD,8DAA8D;AAC9D,kEAAkE;AAClE,kEAAkE;AAClE,6DAA6D;AAC7D,8CAA8C;AAE9C;;;CAGC,GAEDA,QAAQC,GAAG,CAACC,SAAS,G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A+E;YAC/EE,QAAQnB,QAAQsB,MAAM,CAACP;QACzB;QACAZ,WAAWoB,GAAG,CAAChB,WAAWY;IAC5B;IACA,sGAAsG;IACtG,OAAOA;AACT;AACAK,iBAAiBC,CAAC,GAAGP;AAErB,SAASQ,oBAEPC,QAAgB;IAEhB,MAAMC,QAAOlE,IAAImE,aAAa,CAAC,IAAIC,IAAIH,UAAU1C;IACjD,OAAOiC,eAAe1B,IAAI,CAAC,IAAI,EAAEoC;AACnC;AACAJ,iBAAiBO,CAAC,GAAGL;AAErB,SAASM,gBACPzB,SAAoB,EACpB0B,WAAqC,EACrCC,OAA4B;IAE5B,MAAMpD,WAAWC,KAAKC,OAAO,CAACC,cAAcsB;IAE5C,OAAO4B,+BAA+BrD,UAAUoD;AAClD;AACAV,iBAAiBY,CAAC,GAAGJ;AAErB,SAASK,sBACP9B,SAAoB,EACpB0B,WAAqC;IAErC,MAAMnD,WAAWC,KAAKC,OAAO,CAACC,cAAcsB;IAE5C,OAAO+B,2BAA2BxD;AACpC;AACA0C,iBAAiBe,CAAC,GAAGF;AAErB,SAASG,aACPC,WAAsB,EACtBC,aAA0B,EAC1BC,OAAgB;IAEhB,MAAM,IAAI3B,MAAM;AAClB;AAEA,MAAM4B,aAAa;AACnB;;CAEC,GACD,SAASpC,KAAKqC,cAAoC;IAChD,OAAOD,WAAWE,IAAI,CAACD;AACzB","ignoreList":[0]}},
{"offset": {"line": 770, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared/runtime/hmr-runtime.ts"],"sourcesContent":["/// <reference path=\"./runtime-utils.ts\" />\n/// <reference path=\"./runtime-types.d.ts\" />\n/// <reference path=\"./dev-extensions.ts\" />\n/// <reference path=\"./dev-protocol.d.ts\" />\n\ntype HotModuleFactoryFunction = ModuleFactoryFunction<\n HotModule,\n TurbopackBaseContext<HotModule>\n>\n\n/**\n * Shared HMR (Hot Module Replacement) implementation.\n *\n * This file contains the complete HMR implementation that's shared between\n * browser and Node.js runtimes. It manages module hot state, dependency\n * tracking, the module.hot API, and the full HMR update flow.\n */\n\n/**\n * The development module cache shared across the runtime.\n * Browser runtime declares this directly.\n * Node.js runtime assigns globalThis.__turbopack_module_cache__ to this.\n */\nlet devModuleCache: Record<ModuleId, any>\n\n/**\n * Module IDs that are instantiated as part of the runtime of a chunk.\n */\nlet runtimeModules: Set<ModuleId>\n\n/**\n * Maps module IDs to persisted data between executions of their hot module\n * implementation (`hot.data`).\n */\nconst moduleHotData: Map<ModuleId, HotData> = new Map()\n\n/**\n * Maps module instances to their hot module state.\n * Uses WeakMap so it works with both HotModule and ModuleWithDirection.\n */\nconst moduleHotState: WeakMap<any, HotState> = new WeakMap()\n\n/**\n * Modules that call `module.hot.invalidate()` (while being updated).\n */\nconst queuedInvalidatedModules: Set<ModuleId> = new Set()\n\nclass UpdateApplyError extends Error {\n name = 'UpdateApplyError'\n\n dependencyChain: ModuleId[]\n\n constructor(message: string, dependencyChain: ModuleId[]) {\n super(message)\n this.dependencyChain = dependencyChain\n }\n}\n\ntype ModuleEffect =\n | {\n type: 'unaccepted'\n dependencyChain: ModuleId[]\n }\n | {\n type: 'self-declined'\n dependencyChain: ModuleId[]\n moduleId: ModuleId\n }\n | {\n type: 'accepted'\n moduleId: ModuleId\n outdatedModules: Set<ModuleId>\n }\n\n/**\n * Records parent-child relationship when a module imports another.\n * Should be called during module instantiation.\n */\n// eslint-disable-next-line @typescript-eslint/no-unused-vars\nfunction trackModuleImport(\n parentModule: ModuleWithDirection,\n childModuleId: ModuleId,\n childModule: ModuleWithDirection | undefined\n): void {\n // Record that parent imports child\n if (\n parentModule.children &&\n parentModule.children.indexOf(childModuleId) === -1\n ) {\n parentModule.children.push(childModuleId)\n }\n\n // Record that child is imported by parent\n if (\n childModule &&\n childModule.parents &&\n childModule.parents.indexOf(parentModule.id) === -1\n ) {\n childModule.parents.push(parentModule.id)\n }\n}\n\nfunction formatDependencyChain(dependencyChain: ModuleId[]): string {\n return `Dependency chain: ${dependencyChain.join(' -> ')}`\n}\n\n/**\n * Walks the dependency tree to find all modules affected by a change.\n * Returns information about whether the update can be accepted and which\n * modules need to be invalidated.\n *\n * @param moduleId - The module that changed\n * @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept().\n * This is used for server-side HMR where pages auto-accept at the top level.\n */\nfunction getAffectedModuleEffects(\n moduleId: ModuleId,\n autoAcceptAtRoot: boolean\n): ModuleEffect {\n const outdatedModules: Set<ModuleId> = new Set()\n\n type QueueItem = { moduleId?: ModuleId; dependencyChain: ModuleId[] }\n\n const queue: QueueItem[] = [\n {\n moduleId,\n dependencyChain: [],\n },\n ]\n\n let nextItem\n while ((nextItem = queue.shift())) {\n const { moduleId, dependencyChain } = nextItem\n\n if (moduleId != null) {\n if (outdatedModules.has(moduleId)) {\n // Avoid infinite loops caused by cycles between modules in the dependency chain.\n continue\n }\n\n outdatedModules.add(moduleId)\n }\n\n // We've arrived at the runtime of the chunk, which means that nothing\n // else above can accept this update.\n if (moduleId === undefined) {\n if (autoAcceptAtRoot) {\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n }\n }\n return {\n type: 'unaccepted',\n dependencyChain,\n }\n }\n\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)!\n\n if (\n // The module is not in the cache. Since this is a \"modified\" update,\n // it means that the module was never instantiated before.\n !module || // The module accepted itself without invalidating globalThis.\n // TODO is that right?\n (hotState.selfAccepted && !hotState.selfInvalidated)\n ) {\n continue\n }\n\n if (hotState.selfDeclined) {\n return {\n type: 'self-declined',\n dependencyChain,\n moduleId,\n }\n }\n\n if (runtimeModules.has(moduleId)) {\n if (autoAcceptAtRoot) {\n continue\n }\n queue.push({\n moduleId: undefined,\n dependencyChain: [...dependencyChain, moduleId],\n })\n continue\n }\n\n for (const parentId of module.parents) {\n const parent = devModuleCache[parentId]\n\n if (!parent) {\n // TODO(alexkirsz) Is this even possible?\n continue\n }\n\n // TODO(alexkirsz) Dependencies: check accepted and declined\n // dependencies here.\n\n queue.push({\n moduleId: parentId,\n dependencyChain: [...dependencyChain, moduleId],\n })\n }\n\n // If no parents and we're at a root module, auto-accept if configured\n if (module.parents.length === 0 && autoAcceptAtRoot) {\n continue\n }\n }\n\n return {\n type: 'accepted',\n moduleId,\n outdatedModules,\n }\n}\n\n/**\n * Computes all modules that need to be invalidated based on which modules changed.\n *\n * @param invalidated - The modules that have been invalidated\n * @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computedInvalidatedModules(\n invalidated: Iterable<ModuleId>,\n autoAcceptAtRoot: boolean\n): Set<ModuleId> {\n const outdatedModules = new Set<ModuleId>()\n\n for (const moduleId of invalidated) {\n const effect = getAffectedModuleEffects(moduleId, autoAcceptAtRoot)\n\n switch (effect.type) {\n case 'unaccepted':\n throw new UpdateApplyError(\n `cannot apply update: unaccepted module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'self-declined':\n throw new UpdateApplyError(\n `cannot apply update: self-declined module. ${formatDependencyChain(\n effect.dependencyChain\n )}.`,\n effect.dependencyChain\n )\n case 'accepted':\n for (const outdatedModuleId of effect.outdatedModules) {\n outdatedModules.add(outdatedModuleId)\n }\n break\n // TODO(alexkirsz) Dependencies: handle dependencies effects.\n default:\n invariant(effect, (effect) => `Unknown effect type: ${effect?.type}`)\n }\n }\n\n return outdatedModules\n}\n\n/**\n * Creates the module.hot API object and its internal state.\n * This provides the HMR API that user code calls (module.hot.accept(), etc.)\n */\n\nfunction createModuleHot(\n moduleId: ModuleId,\n hotData: HotData\n): { hot: Hot; hotState: HotState } {\n const hotState: HotState = {\n selfAccepted: false,\n selfDeclined: false,\n selfInvalidated: false,\n disposeHandlers: [],\n }\n\n const hot: Hot = {\n // TODO(alexkirsz) This is not defined in the HMR API. It was used to\n // decide whether to warn whenever an HMR-disposed module required other\n // modules. We might want to remove it.\n active: true,\n\n data: hotData ?? {},\n\n // TODO(alexkirsz) Support full (dep, callback, errorHandler) form.\n accept: (\n modules?: string | string[] | AcceptErrorHandler,\n _callback?: AcceptCallback,\n _errorHandler?: AcceptErrorHandler\n ) => {\n if (modules === undefined) {\n hotState.selfAccepted = true\n } else if (typeof modules === 'function') {\n hotState.selfAccepted = modules\n } else {\n throw new Error('unsupported `accept` signature')\n }\n },\n\n decline: (dep) => {\n if (dep === undefined) {\n hotState.selfDeclined = true\n } else {\n throw new Error('unsupported `decline` signature')\n }\n },\n\n dispose: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n addDisposeHandler: (callback) => {\n hotState.disposeHandlers.push(callback)\n },\n\n removeDisposeHandler: (callback) => {\n const idx = hotState.disposeHandlers.indexOf(callback)\n if (idx >= 0) {\n hotState.disposeHandlers.splice(idx, 1)\n }\n },\n\n invalidate: () => {\n hotState.selfInvalidated = true\n queuedInvalidatedModules.add(moduleId)\n },\n\n // NOTE(alexkirsz) This is part of the management API, which we don't\n // implement, but the Next.js React Refresh runtime uses this to decide\n // whether to schedule an update.\n status: () => 'idle',\n\n // NOTE(alexkirsz) Since we always return \"idle\" for now, these are no-ops.\n addStatusHandler: (_handler) => {},\n removeStatusHandler: (_handler) => {},\n\n // NOTE(jridgewell) Check returns the list of updated modules, but we don't\n // want the webpack code paths to ever update (the turbopack paths handle\n // this already).\n check: () => Promise.resolve(null),\n }\n\n return { hot, hotState }\n}\n\n/**\n * Processes queued invalidated modules and adds them to the outdated modules set.\n * Modules that call module.hot.invalidate() are queued and processed here.\n *\n * @param outdatedModules - The current set of outdated modules\n * @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInvalidatedModules(\n outdatedModules: Set<ModuleId>,\n autoAcceptAtRoot: boolean\n): Set<ModuleId> {\n if (queuedInvalidatedModules.size > 0) {\n computedInvalidatedModules(\n queuedInvalidatedModules,\n autoAcceptAtRoot\n ).forEach((moduleId) => {\n outdatedModules.add(moduleId)\n })\n\n queuedInvalidatedModules.clear()\n }\n\n return outdatedModules\n}\n\n/**\n * Computes which outdated modules have self-accepted and can be hot reloaded.\n */\n\nfunction computeOutdatedSelfAcceptedModules(\n outdatedModules: Iterable<ModuleId>\n): { moduleId: ModuleId; errorHandler: true | Function }[] {\n const outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[] = []\n for (const moduleId of outdatedModules) {\n const module = devModuleCache[moduleId]\n const hotState = moduleHotState.get(module)\n if (module && hotState?.selfAccepted && !hotState.selfInvalidated) {\n outdatedSelfAcceptedModules.push({\n moduleId,\n errorHandler: hotState.selfAccepted,\n })\n }\n }\n return outdatedSelfAcceptedModules\n}\n\n/**\n * Disposes of an instance of a module.\n * Runs hot.dispose handlers and manages persistent hot data.\n *\n * NOTE: mode = \"replace\" will not remove modules from devModuleCache.\n * This must be done in a separate step afterwards.\n */\nfunction disposeModule(moduleId: ModuleId, mode: 'clear' | 'replace') {\n const module = devModuleCache[moduleId]\n if (!module) {\n return\n }\n\n const hotState = moduleHotState.get(module)\n if (!hotState) {\n return\n }\n\n const data: HotData = {}\n\n // Run the `hot.dispose` handler, if any, passing in the persistent\n // `hot.data` object.\n for (const disposeHandler of hotState.disposeHandlers) {\n disposeHandler(data)\n }\n\n // This used to warn in `getOrInstantiateModuleFromParent` when a disposed\n // module is still importing other modules.\n if (module.hot) {\n module.hot.active = false\n }\n\n moduleHotState.delete(module)\n\n // TODO(alexkirsz) Dependencies: delete the module from outdated deps.\n\n // Remove the disposed module from its children's parent list.\n // It will be added back once the module re-instantiates and imports its\n // children again.\n for (const childId of module.children) {\n const child = devModuleCache[childId]\n if (!child) {\n continue\n }\n\n const idx = child.parents.indexOf(module.id)\n if (idx >= 0) {\n child.parents.splice(idx, 1)\n }\n }\n\n switch (mode) {\n case 'clear':\n delete devModuleCache[module.id]\n moduleHotData.delete(module.id)\n break\n case 'replace':\n moduleHotData.set(module.id, data)\n break\n default:\n invariant(mode, (mode) => `invalid mode: ${mode}`)\n }\n}\n\n/**\n * Dispose phase: runs dispose handlers and cleans up outdated/disposed modules.\n * Returns the parent modules of outdated modules for use in the apply phase.\n */\n\nfunction disposePhase(\n outdatedModules: Iterable<ModuleId>,\n disposedModules: Iterable<ModuleId>\n): { outdatedModuleParents: Map<ModuleId, Array<ModuleId>> } {\n for (const moduleId of outdatedModules) {\n disposeModule(moduleId, 'replace')\n }\n\n for (const moduleId of disposedModules) {\n disposeModule(moduleId, 'clear')\n }\n\n // Removing modules from the module cache is a separate step.\n // We also want to keep track of previous parents of the outdated modules.\n const outdatedModuleParents = new Map<ModuleId, Array<ModuleId>>()\n for (const moduleId of outdatedModules) {\n const oldModule = devModuleCache[moduleId]\n outdatedModuleParents.set(moduleId, oldModule?.parents)\n delete devModuleCache[moduleId]\n }\n\n // TODO(alexkirsz) Dependencies: remove outdated dependency from module\n // children.\n\n return { outdatedModuleParents }\n}\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/**\n * Shared module instantiation logic.\n * This handles the full module instantiation flow for both browser and Node.js.\n * Only React Refresh hooks differ between platforms (passed as callback).\n */\nfunction instantiateModuleShared(\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache<HotModule>,\n runtimeModules: Set<ModuleId>,\n createModuleObjectFn: (id: ModuleId) => HotModule,\n createContextFn: (module: HotModule, exports: Exports, refresh?: any) => any,\n runModuleExecutionHooksFn: (\n module: HotModule,\n exec: (refresh: any) => void\n ) => void\n): HotModule {\n // 1. Factory validation (same in both browser and Node.js)\n const id = moduleId as string\n const moduleFactory = moduleFactories.get(id)\n if (typeof moduleFactory !== 'function') {\n throw new Error(\n `Module ${id} was instantiated, but the module factory is not available.`\n )\n }\n\n // 2. Hot API setup (same in both - works for browser, included for Node.js)\n const hotData = moduleHotData.get(id)!\n const { hot, hotState } = createModuleHot(id, hotData)\n\n // 3. Parent assignment logic (same in both)\n let parents: ModuleId[]\n switch (sourceType) {\n case SourceType.Runtime:\n runtimeModules.add(id)\n parents = []\n break\n case SourceType.Parent:\n parents = [sourceData as ModuleId]\n break\n case SourceType.Update:\n parents = (sourceData as ModuleId[]) || []\n break\n default:\n throw new Error(`Unknown source type: ${sourceType}`)\n }\n\n // 4. Module creation (platform creates base module object)\n const module = createModuleObjectFn(id)\n const exports = module.exports\n module.parents = parents\n module.children = []\n module.hot = hot\n\n devModuleCache[id] = module\n moduleHotState.set(module, hotState)\n\n // 5. Module execution (React Refresh hooks are platform-specific)\n try {\n runModuleExecutionHooksFn(module, (refresh) => {\n const context = createContextFn(module, exports, refresh)\n moduleFactory.call(exports, context, module, exports)\n })\n } catch (error) {\n module.error = error as any\n throw error\n }\n\n // 6. ESM interop (same in both)\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject)\n }\n\n return module\n}\n\n/**\n * Analyzes update entries and chunks to determine which modules were added, modified, or deleted.\n * This is pure logic that doesn't depend on the runtime environment.\n */\nfunction computeChangedModules(\n entries: Record<ModuleId, EcmascriptModuleEntry>,\n updates: Record<ChunkPath, EcmascriptMergedChunkUpdate>,\n chunkModulesMap?: Map<ChunkPath, Set<ModuleId>>\n): {\n added: Map<ModuleId, EcmascriptModuleEntry | undefined>\n modified: Map<ModuleId, EcmascriptModuleEntry>\n deleted: Set<ModuleId>\n chunksAdded: Map<ChunkPath, Set<ModuleId>>\n chunksDeleted: Map<ChunkPath, Set<ModuleId>>\n} {\n const chunksAdded = new Map()\n const chunksDeleted = new Map()\n const added: Map<ModuleId, EcmascriptModuleEntry> = new Map()\n const modified = new Map()\n const deleted: Set<ModuleId> = new Set()\n\n for (const [chunkPath, mergedChunkUpdate] of Object.entries(updates) as Array<\n [ChunkPath, EcmascriptMergedChunkUpdate]\n >) {\n switch (mergedChunkUpdate.type) {\n case 'added': {\n const updateAdded = new Set(mergedChunkUpdate.modules)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n chunksAdded.set(chunkPath, updateAdded)\n break\n }\n case 'deleted': {\n const updateDeleted = chunkModulesMap\n ? new Set(chunkModulesMap.get(chunkPath))\n : new Set<ModuleId>()\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n case 'partial': {\n const updateAdded = new Set(mergedChunkUpdate.added)\n const updateDeleted = new Set(mergedChunkUpdate.deleted)\n for (const moduleId of updateAdded) {\n added.set(moduleId, entries[moduleId])\n }\n for (const moduleId of updateDeleted) {\n deleted.add(moduleId)\n }\n chunksAdded.set(chunkPath, updateAdded)\n chunksDeleted.set(chunkPath, updateDeleted)\n break\n }\n default:\n throw new Error('Unknown merged chunk update type')\n }\n }\n\n // If a module was added from one chunk and deleted from another in the same update,\n // consider it to be modified, as it means the module was moved from one chunk to another\n // AND has new code in a single update.\n for (const moduleId of added.keys()) {\n if (deleted.has(moduleId)) {\n added.delete(moduleId)\n deleted.delete(moduleId)\n }\n }\n\n for (const [moduleId, entry] of Object.entries(entries)) {\n // Modules that haven't been added to any chunk but have new code are considered\n // to be modified.\n // This needs to be under the previous loop, as we need it to get rid of modules\n // that were added and deleted in the same update.\n if (!added.has(moduleId)) {\n modified.set(moduleId, entry)\n }\n }\n\n return { added, deleted, modified, chunksAdded, chunksDeleted }\n}\n\n/**\n * Compiles new module code and walks the dependency tree to find all outdated modules.\n * Uses the evalModuleEntry function to compile code (platform-specific).\n *\n * @param added - Map of added modules\n * @param modified - Map of modified modules\n * @param evalModuleEntry - Function to compile module code\n * @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction computeOutdatedModules(\n added: Map<ModuleId, EcmascriptModuleEntry | undefined>,\n modified: Map<ModuleId, EcmascriptModuleEntry>,\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction,\n autoAcceptAtRoot: boolean\n): {\n outdatedModules: Set<ModuleId>\n newModuleFactories: Map<ModuleId, HotModuleFactoryFunction>\n} {\n const newModuleFactories = new Map<ModuleId, HotModuleFactoryFunction>()\n\n // Compile added modules\n for (const [moduleId, entry] of added) {\n if (entry != null) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n }\n\n // Walk dependency tree to find all modules affected by modifications\n const outdatedModules = computedInvalidatedModules(\n modified.keys(),\n autoAcceptAtRoot\n )\n\n // Compile modified modules\n for (const [moduleId, entry] of modified) {\n newModuleFactories.set(moduleId, evalModuleEntry(entry))\n }\n\n return { outdatedModules, newModuleFactories }\n}\n\n/**\n * Updates module factories and re-instantiates self-accepted modules.\n * Uses the instantiateModule function (platform-specific via callback).\n */\nfunction applyPhase(\n outdatedSelfAcceptedModules: {\n moduleId: ModuleId\n errorHandler: true | Function\n }[],\n newModuleFactories: Map<ModuleId, HotModuleFactoryFunction>,\n outdatedModuleParents: Map<ModuleId, Array<ModuleId>>,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache<HotModule>,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n reportError: (err: any) => void\n) {\n // Update module factories\n for (const [moduleId, factory] of newModuleFactories.entries()) {\n applyModuleFactoryNameFn(factory)\n moduleFactories.set(moduleId, factory)\n }\n\n // TODO(alexkirsz) Run new runtime entries here.\n\n // TODO(alexkirsz) Dependencies: call accept handlers for outdated deps.\n\n // Re-instantiate all outdated self-accepted modules\n for (const { moduleId, errorHandler } of outdatedSelfAcceptedModules) {\n try {\n instantiateModuleFn(\n moduleId,\n SourceType.Update,\n outdatedModuleParents.get(moduleId)\n )\n } catch (err) {\n if (typeof errorHandler === 'function') {\n try {\n errorHandler(err, { moduleId, module: devModuleCache[moduleId] })\n } catch (err2) {\n reportError(err2)\n reportError(err)\n }\n } else {\n reportError(err)\n }\n }\n }\n}\n\n/**\n * Internal implementation that orchestrates the full HMR update flow:\n * invalidation, disposal, and application of new modules.\n *\n * @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()\n */\nfunction applyInternal(\n outdatedModules: Set<ModuleId>,\n disposedModules: Iterable<ModuleId>,\n newModuleFactories: Map<ModuleId, HotModuleFactoryFunction>,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache<HotModule>,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule,\n applyModuleFactoryNameFn: (factory: HotModuleFactoryFunction) => void,\n autoAcceptAtRoot: boolean\n) {\n outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptAtRoot)\n\n // Find self-accepted modules to re-instantiate\n const outdatedSelfAcceptedModules =\n computeOutdatedSelfAcceptedModules(outdatedModules)\n\n // Run dispose handlers, save hot.data, clear caches\n const { outdatedModuleParents } = disposePhase(\n outdatedModules,\n disposedModules\n )\n\n let error: any\n\n function reportError(err: any) {\n if (!error) error = err // Keep first error\n }\n\n applyPhase(\n outdatedSelfAcceptedModules,\n newModuleFactories,\n outdatedModuleParents,\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n reportError\n )\n\n if (error) {\n throw error\n }\n\n // Recursively apply any queued invalidations from new module execution\n if (queuedInvalidatedModules.size > 0) {\n applyInternal(\n new Set(),\n [],\n new Map(),\n moduleFactories,\n devModuleCache,\n instantiateModuleFn,\n applyModuleFactoryNameFn,\n autoAcceptAtRoot\n )\n }\n}\n\n/**\n * Main entry point for applying an ECMAScript merged update.\n * This is called by both browser and Node.js runtimes with platform-specific callbacks.\n *\n * @param options.autoAcceptAtRoot - If true, root modules auto-accept updates without explicit\n * module.hot.accept(). Used for server-side HMR where pages\n * auto-accept at the top level.\n */\nfunction applyEcmascriptMergedUpdateShared(options: {\n added: Map<ModuleId, EcmascriptModuleEntry | undefined>\n modified: Map<ModuleId, EcmascriptModuleEntry>\n disposedModules: Iterable<ModuleId>\n evalModuleEntry: (entry: EcmascriptModuleEntry) => HotModuleFactoryFunction\n instantiateModule: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule\n applyModuleFactoryName: (factory: HotModuleFactoryFunction) => void\n moduleFactories: ModuleFactories\n devModuleCache: ModuleCache<HotModule>\n runtimeModules: Set<ModuleId>\n autoAcceptAtRoot: boolean\n}) {\n const {\n added,\n modified,\n disposedModules,\n evalModuleEntry,\n instantiateModule,\n applyModuleFactoryName,\n moduleFactories,\n devModuleCache,\n autoAcceptAtRoot,\n } = options\n\n const { outdatedModules, newModuleFactories } = computeOutdatedModules(\n added,\n modified,\n evalModuleEntry,\n autoAcceptAtRoot\n )\n\n applyInternal(\n outdatedModules,\n disposedModules,\n newModuleFactories,\n moduleFactories,\n devModuleCache,\n instantiateModule,\n applyModuleFactoryName,\n autoAcceptAtRoot\n )\n}\n"],"names":["devModuleCache","runtimeModules","moduleHotData","Map","moduleHotState","WeakMap","queuedInvalidatedModules","Set","UpdateApplyError","Error","name","dependencyChain","message","trackModuleImport","parentModule","childModuleId","childModule","children","indexOf","push","parents","id","formatDependencyChain","join","getAffectedModuleEffects","moduleId","autoAcceptAtRoot","outdatedModules","queue","nextItem","shift","has","add","undefined","type","module","hotState","get","selfAccepted","selfInvalidated","selfDeclined","parentId","parent","length","computedInvalidatedModules","invalidated","effect","outdatedModuleId","invariant","createModuleHot","hotData","disposeHandlers","hot","active","data","accept","modules","_callback","_errorHandler","decline","dep","dispose","callback","addDisposeHandler","removeDisposeHandler","idx","splice","invalidate","status","addStatusHandler","_handler","removeStatusHandler","check","Promise","resolve","applyInvalidatedModules","size","forEach","clear","computeOutdatedSelfAcceptedModules","outdatedSelfAcceptedModules","errorHandler","disposeModule","mode","disposeHandler","delete","childId","child","set","disposePhase","disposedModules","outdatedModuleParents","oldModule","instantiateModuleShared","sourceType","sourceData","moduleFactories","createModuleObjectFn","createContextFn","runModuleExecutionHooksFn","moduleFactory","SourceType","Runtime","Parent","Update","exports","refresh","context","call","error","namespaceObject","interopEsm","computeChangedModules","entries","updates","chunkModulesMap","chunksAdded","chunksDeleted","added","modified","deleted","chunkPath","mergedChunkUpdate","Object","updateAdded","updateDeleted","keys","entry","computeOutdatedModules","evalModuleEntry","newModuleFactories","applyPhase","instantiateModuleFn","applyModuleFactoryNameFn","reportError","factory","err","err2","applyInternal","applyEcmascriptMergedUpdateShared","options","instantiateModule","applyModuleFactoryName"],"mappings":"AAAA,2CAA2C;AAC3C,6CAA6C;AAC7C,4CAA4C;AAC5C,4CAA4C;AAO5C;;;;;;CAMC,GAED;;;;CAIC,GACD,IAAIA;AAEJ;;CAEC,GACD,IAAIC;AAEJ;;;CAGC,GACD,MAAMC,gBAAwC,IAAIC;AAElD;;;CAGC,GACD,MAAMC,iBAAyC,IAAIC;AAEnD;;CAEC,GACD,MAAMC,2BAA0C,IAAIC;AAEpD,MAAMC,yBAAyBC;IAC7BC,OAAO,mBAAkB;IAEzBC,gBAA2B;IAE3BH,YAAYI,OAAe,EAAED,eAA2B,CAAE;QACxD,KAAK,CAACC;QACN,IAAI,CAACD,eAAe,GAAGA;IACzB;AACF;AAkBA;;;CAGC,GACD,6DAA6D;AAC7D,SAASE,kBACPC,YAAiC,EACjCC,aAAuB,EACvBC,WAA4C;IAE5C,mCAAmC;IACnC,IACEF,aAAaG,QAAQ,IACrBH,aAAaG,QAAQ,CAACC,OAAO,CAACH,mBAAmB,CAAC,GAClD;QACAD,aAAaG,QAAQ,CAACE,IAAI,CAACJ;IAC7B;IAEA,0CAA0C;IAC1C,IACEC,eACAA,YAAYI,OAAO,IACnBJ,YAAYI,OAAO,CAACF,OAAO,CAACJ,aAAaO,EAAE,MAAM,CAAC,GAClD;QACAL,YAAYI,OAAO,CAACD,IAAI,CAACL,aAAaO,EAAE;IAC1C;AACF;AAEA,SAASC,sBAAsBX,eAA2B;IACxD,OAAO,CAAC,kBAAkB,EAAEA,gBAAgBY,IAAI,CAAC,SAAS;AAC5D;AAEA;;;;;;;;CAQC,GACD,SAASC,yBACPC,QAAkB,EAClBC,gBAAyB;IAEzB,MAAMC,k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;AAEA;;;;;CAKC,GACD,SAASE,cACP/G,eAA8B,EAC9B+D,eAAmC,EACnCwC,kBAA2D,EAC3DlC,eAAgC,EAChChG,cAAsC,EACtCoI,mBAIc,EACdC,wBAAqE,EACrE3G,gBAAyB;IAEzBC,kBAAkBgD,wBAAwBhD,iBAAiBD;IAE3D,+CAA+C;IAC/C,MAAMsD,8BACJD,mCAAmCpD;IAErC,oDAAoD;IACpD,MAAM,EAAEgE,qBAAqB,EAAE,GAAGF,aAChC9D,iBACA+D;IAGF,IAAImB;IAEJ,SAASyB,YAAYE,GAAQ;QAC3B,IAAI,CAAC3B,OAAOA,QAAQ2B,KAAI,mBAAmB;IAC7C;IAEAL,WACEnD,6BACAkD,oBACAvC,uBACAK,iBACAhG,gBACAoI,qBACAC,0BACAC;IAGF,IAAIzB,OAAO;QACT,MAAMA;IACR;IAEA,uEAAuE;IACvE,IAAIvG,yBAAyBsE,IAAI,GAAG,GAAG;QACrC8D,cACE,IAAInI,OACJ,EAAE,EACF,IAAIJ,OACJ6F,iBACAhG,gBACAoI,qBACAC,0BACA3G;IAEJ;AACF;AAEA;;;;;;;CAOC,GACD,SAASiH,kCAAkCC,OAe1C;IACC,MAAM,EACJtB,KAAK,EACLC,QAAQ,EACR7B,eAAe,EACfuC,eAAe,EACfY,iBAAiB,EACjBC,sBAAsB,EACtB9C,eAAe,EACfhG,cAAc,EACd0B,gBAAgB,EACjB,GAAGkH;IAEJ,MAAM,EAAEjH,eAAe,EAAEuG,kBAAkB,EAAE,GAAGF,uBAC9CV,OACAC,UACAU,iBACAvG;IAGFgH,cACE/G,iBACA+D,iBACAwC,oBACAlC,iBACAhG,gBACA6I,mBACAC,wBACApH;AAEJ","ignoreList":[0]}},
{"offset": {"line": 1342, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/nodejs/runtime/dev-base.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"./runtime-base.ts\" />\n/// <reference path=\"../../shared/runtime/dev-extensions.ts\" />\n/// <reference path=\"../../shared/runtime/hmr-runtime.ts\" />\n\n/**\n * Development Node.js runtime.\n * Uses HotModule and shared HMR logic for hot module replacement support.\n */\n\n// Cast the module cache to HotModule for development mode\n// (hmr-runtime.ts declares devModuleCache as `let` variable expecting assignment)\n// This is safe because HotModule extends Module\ndevModuleCache = moduleCache as ModuleCache<HotModule>\n\nif (!globalThis.__turbopack_runtime_modules__) {\n globalThis.__turbopack_runtime_modules__ = new Set()\n}\nruntimeModules = globalThis.__turbopack_runtime_modules__\n\ninterface TurbopackNodeDevBuildContext extends TurbopackBaseContext<HotModule> {\n R: ResolvePathFromModule\n x: ExternalRequire\n y: ExternalImport\n C: typeof clearChunkCache\n}\n\nconst nodeDevContextPrototype =\n Context.prototype as TurbopackNodeDevBuildContext\n\nnodeDevContextPrototype.q = exportUrl\nnodeDevContextPrototype.M = moduleFactories\nnodeDevContextPrototype.c = devModuleCache\nnodeDevContextPrototype.R = resolvePathFromModule\nnodeDevContextPrototype.b = getWorkerURL\nnodeDevContextPrototype.C = clearChunkCache\n\n/**\n * Instantiates a module in development mode using shared HMR logic.\n */\nfunction instantiateModule(\n id: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): HotModule {\n // Node.js: creates base module object (hot API added by shared code)\n const createModuleObjectFn = (moduleId: ModuleId) => {\n return createModuleWithDirection(moduleId) as HotModule\n }\n\n // Node.js: creates Context (no refresh parameter)\n const createContext = (\n module: HotModule,\n exports: Exports,\n _refresh?: any\n ) => {\n return new (Context as any as ContextConstructor<HotModule>)(\n module,\n exports\n )\n }\n\n // Node.js: no hooks wrapper, just execute directly\n const runWithHooks = (module: HotModule, exec: (refresh: any) => void) => {\n exec(undefined) // no refresh context\n }\n\n // Use shared instantiation logic (includes hot API setup)\n const newModule = instantiateModuleShared(\n id,\n sourceType,\n sourceData,\n moduleFactories,\n devModuleCache,\n runtimeModules,\n createModuleObjectFn,\n createContext,\n runWithHooks\n )\n\n // Node.js-specific: mark module as loaded\n ;(newModule as any).loaded = true\n\n return newModule\n}\n\n/**\n * Instantiates a runtime module in development mode.\n */\nfunction instantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): HotModule {\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.\n */\n// @ts-ignore TypeScript doesn't separate this module space from the browser runtime\nfunction getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): HotModule {\n const module = devModuleCache[moduleId]\n\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n return instantiateRuntimeModule(chunkPath, moduleId)\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n * Also tracks parent-child relationships for HMR dependency tracking.\n */\n// @ts-ignore\nfunction getOrInstantiateModuleFromParent(\n id: ModuleId,\n sourceModule: HotModule\n): HotModule {\n // Track parent-child relationship\n trackModuleImport(sourceModule, id, devModuleCache[id])\n\n const module = devModuleCache[id]\n\n if (module) {\n if (module.error) {\n throw module.error\n }\n\n return module\n }\n\n const newModule = instantiateModule(id, SourceType.Parent, sourceModule.id)\n\n // Track again after instantiation to ensure the relationship is recorded\n trackModuleImport(sourceModule, id, newModule)\n\n return newModule\n}\n\nmodule.exports = (sourcePath: ChunkPath) => ({\n m: (id: ModuleId) => getOrInstantiateRuntimeModule(sourcePath, id),\n c: (chunkData: ChunkData) => loadRuntimeChunk(sourcePath, chunkData),\n})\n"],"names":["devModuleCache","moduleCache","globalThis","__turbopack_runtime_modules__","Set","runtimeModules","nodeDevContextPrototype","Context","prototype","q","exportUrl","M","moduleFactories","c","R","resolvePathFromModule","b","getWorkerURL","C","clearChunkCache","instantiateModule","id","sourceType","sourceData","createModuleObjectFn","moduleId","createModuleWithDirection","createContext","module1","exports","_refresh","runWithHooks","exec","undefined","newModule","instantiateModuleShared","loaded","instantiateRuntimeModule","chunkPath","SourceType","Runtime","getOrInstantiateRuntimeModule","error","getOrInstantiateModuleFromParent","sourceModule","trackModuleImport","Parent","module","sourcePath","m","chunkData","loadRuntimeChunk"],"mappings":"AAAA,oDAAoD,GAEpD,0CAA0C;AAC1C,+DAA+D;AAC/D,4DAA4D;AAE5D;;;CAGC,GAED,0DAA0D;AAC1D,kFAAkF;AAClF,gDAAgD;AAChDA,iBAAiBC;AAEjB,IAAI,CAACC,WAAWC,6BAA6B,EAAE;IAC7CD,WAAWC,6BAA6B,GAAG,IAAIC;AACjD;AACAC,iBAAiBH,WAAWC,6BAA6B;AASzD,MAAMG,0BACJC,QAAQC,SAAS;AAEnBF,wBAAwBG,CAAC,GAAGC;AAC5BJ,wBAAwBK,CAAC,GAAGC;AAC5BN,wBAAwBO,CAAC,GAAGb;AAC5BM,wBAAwBQ,CAAC,GAAGC;AAC5BT,wBAAwBU,CAAC,GAAGC;AAC5BX,wBAAwBY,CAAC,GAAGC;AAE5B;;CAEC,GACD,SAASC,kBACPC,EAAY,EACZC,UAAsB,EACtBC,UAAsB;IAEtB,qEAAqE;IACrE,MAAMC,uBAAuB,CAACC;QAC5B,OAAOC,0BAA0BD;IACnC;IAEA,kDAAkD;IAClD,MAAME,gBAAgB,CACpBC,SACAC,SACAC;QAEA,OAAO,IAAKvB,QACVqB,SACAC;IAEJ;IAEA,mDAAmD;IACnD,MAAME,eAAe,CAACH,SAAmBI;QACvCA,KAAKC,YAAW,qBAAqB;IACvC;IAEA,0DAA0D;IAC1D,MAAMC,YAAYC,wBAChBd,IACAC,YACAC,YACAX,iBACAZ,gBACAK,gBACAmB,sBACAG,eACAI;IAIAG,UAAkBE,MAAM,GAAG;IAE7B,OAAOF;AACT;AAEA;;CAEC,GACD,SAASG,yBACPC,SAAoB,EACpBb,QAAkB;IAElB,OAAOL,kBAAkBK,UAAUc,WAAWC,OAAO,EAAEF;AACzD;AAEA;;CAEC,GACD,oFAAoF;AACpF,SAASG,8BACPH,SAAoB,EACpBb,QAAkB;IAElB,MAAMG,UAAS5B,cAAc,CAACyB,SAAS;IAEvC,IAAIG,SAAQ;QACV,IAAIA,QAAOc,KAAK,EAAE;YAChB,MAAMd,QAAOc,KAAK;QACpB;QACA,OAAOd;IACT;IAEA,OAAOS,yBAAyBC,WAAWb;AAC7C;AAEA;;;CAGC,GACD,aAAa;AACb,SAASkB,iCACPtB,EAAY,EACZuB,YAAuB;IAEvB,kCAAkC;IAClCC,kBAAkBD,cAAcvB,IAAIrB,cAAc,CAACqB,GAAG;IAEtD,MAAMO,UAAS5B,cAAc,CAACqB,GAAG;IAEjC,IAAIO,SAAQ;QACV,IAAIA,QAAOc,KAAK,EAAE;YAChB,MAAMd,QAAOc,KAAK;QACpB;QAEA,OAAOd;IACT;IAEA,MAAMM,YAAYd,kBAAkBC,IAAIkB,WAAWO,MAAM,EAAEF,aAAavB,EAAE;IAE1E,yEAAyE;IACzEwB,kBAAkBD,cAAcvB,IAAIa;IAEpC,OAAOA;AACT;AAEAa,OAAOlB,OAAO,GAAG,CAACmB,aAA0B,CAAC;QAC3CC,GAAG,CAAC5B,KAAiBoB,8BAA8BO,YAAY3B;QAC/DR,GAAG,CAACqC,YAAyBC,iBAAiBH,YAAYE;IAC5D,CAAC","ignoreList":[0]}},
{"offset": {"line": 1424, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/nodejs/dev/hmr-client.ts"],"sourcesContent":["/// <reference path=\"../../shared/runtime/dev-protocol.d.ts\" />\n/// <reference path=\"../../shared/runtime/hmr-runtime.ts\" />\n\n/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/**\n * Node.js HMR client implementation.\n * Simplified for concatenated runtime - no ESM imports.\n */\n\n// Node.js HMR payload with direct EcmascriptMergedUpdate (no ChunkListUpdate wrapper)\ntype NodeJsHmrPayload = {\n resource: {\n path: string\n headers?: Record<string, string>\n }\n issues: Issue[]\n type: 'partial'\n instruction: EcmascriptMergedUpdate\n}\n\n/**\n * Emits an HMR message to registered update listeners.\n * In Node.js, we directly invoke the listeners rather than going through\n * a full message backend like the browser does.\n */\nfunction emitMessage(msg: { type: string; data: any }): void {\n // Find and invoke listeners registered in TURBOPACK_CHUNK_UPDATE_LISTENERS\n if (globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS) {\n for (const [\n _chunkPath,\n listener,\n ] of globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS) {\n try {\n listener(msg.data)\n } catch (err) {\n console.error('[Server HMR] Listener error:', err)\n }\n }\n }\n}\n\n/**\n * Handles server message updates and applies them to the Node.js runtime.\n * Uses shared HMR update logic from hmr-runtime.ts.\n */\nfunction handleNodejsUpdate(\n msg: NodeJsHmrPayload,\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache<HotModule>,\n runtimeModules: Set<ModuleId>,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule\n): void {\n if (msg.type !== 'partial') {\n return\n }\n\n const instruction = msg.instruction\n if (instruction.type !== 'EcmascriptMergedUpdate') {\n return\n }\n\n try {\n const { entries = {}, chunks = {} } = instruction\n\n // Node.js eval function (no source maps)\n const evalModuleEntry = (entry: EcmascriptModuleEntry) => {\n // eslint-disable-next-line no-eval\n return (0, eval)(entry.code)\n }\n\n const { added, modified } = computeChangedModules(\n entries,\n chunks,\n undefined // no chunkModulesMap for Node.js\n )\n\n // Use shared HMR update implementation\n applyEcmascriptMergedUpdateShared({\n added,\n modified,\n disposedModules: [], // no disposedModules for Node.js (no chunk management)\n evalModuleEntry,\n instantiateModule,\n applyModuleFactoryName: () => {}, // Node doesn't use this\n moduleFactories,\n devModuleCache,\n runtimeModules,\n autoAcceptAtRoot: true,\n })\n } catch (e) {\n console.error('[Server HMR] Update failed, full reload needed:', e)\n throw e\n }\n}\n\nlet initialized = false\n\nfunction initializeServerHmr(\n moduleFactories: ModuleFactories,\n devModuleCache: ModuleCache<HotModule>,\n runtimeModules: Set<ModuleId>,\n instantiateModuleFn: (\n moduleId: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n ) => HotModule\n): void {\n if (initialized) {\n return\n }\n\n initialized = true\n\n const queued = globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS\n if (queued != null && !Array.isArray(queued)) {\n throw new Error('A separate HMR handler was already registered')\n }\n\n if (!Array.isArray(globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS)) {\n globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS = []\n }\n\n // Register an update callback for the server runtime\n // The chunk path doesn't matter much for Node.js server since we get updates\n // directly, but we use '__server__' as a placeholder\n const serverChunkPath = '__server__' as ChunkListPath\n globalThis.TURBOPACK_CHUNK_UPDATE_LISTENERS.push([\n serverChunkPath,\n (msg: NodeJsHmrPayload) => {\n handleNodejsUpdate(\n msg,\n moduleFactories,\n devModuleCache,\n runtimeModules,\n instantiateModuleFn\n )\n },\n ])\n}\n"],"names":["emitMessage","msg","globalThis","TURBOPACK_CHUNK_UPDATE_LISTENERS","_chunkPath","listener","data","err","console","error","handleNodejsUpdate","moduleFactories","devModuleCache","runtimeModules","instantiateModuleFn","type","instruction","entries","chunks","evalModuleEntry","entry","eval","code","added","modified","computeChangedModules","undefined","applyEcmascriptMergedUpdateShared","disposedModules","instantiateModule","applyModuleFactoryName","autoAcceptAtRoot","e","initialized","initializeServerHmr","queued","Array","isArray","Error","serverChunkPath","push"],"mappings":"AAAA,+DAA+D;AAC/D,4DAA4D;AAE5D,oDAAoD,GAEpD;;;CAGC,GAED,sFAAsF;AAWtF;;;;CAIC,GACD,SAASA,YAAYC,GAAgC;IACnD,2EAA2E;IAC3E,IAAIC,WAAWC,gCAAgC,EAAE;QAC/C,KAAK,MAAM,CACTC,YACAC,SACD,IAAIH,WAAWC,gCAAgC,CAAE;YAChD,IAAI;gBACFE,SAASJ,IAAIK,IAAI;YACnB,EAAE,OAAOC,KAAK;gBACZC,QAAQC,KAAK,CAAC,gCAAgCF;YAChD;QACF;IACF;AACF;AAEA;;;CAGC,GACD,SAASG,mBACPT,GAAqB,EACrBU,eAA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BACAC;QAEJ;KACD;AACH","ignoreList":[0]}},
{"offset": {"line": 1508, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/nodejs/dev/dev-nodejs.ts"],"sourcesContent":["/// <reference path=\"../../shared/runtime/dev-globals.d.ts\" />\n/// <reference path=\"../../shared/runtime/dev-protocol.d.ts\" />\n/// <reference path=\"./hmr-client.ts\" />\n\n/**\n * Note: hmr-runtime.ts is embedded before this file, so its functions\n * (initializeServerHmr, emitMessage) are available in the same scope.\n */\n\n// Initialize server HMR client (connects to shared HMR infrastructure)\nlet hmrClientInitialized = false\nfunction ensureHmrClientInitialized() {\n if (hmrClientInitialized) return\n hmrClientInitialized = true\n\n // initializeServerHmr is from hmr-client.ts (embedded before this file)\n // moduleFactories, runtimeModules, and instantiateModule are from dev-runtime.ts\n // devModuleCache is the HotModule-typed cache from dev-runtime.ts\n initializeServerHmr(\n moduleFactories,\n devModuleCache,\n runtimeModules,\n instantiateModule\n )\n}\n\nfunction __turbopack_server_hmr_apply__(update: NodeJsHmrPayload): boolean {\n try {\n // Initialize HMR client on first update\n ensureHmrClientInitialized()\n\n // emitMessage is from hmr-client.ts (embedded before this file)\n emitMessage({\n type: 'turbopack-message',\n data: update,\n })\n\n return true\n } catch (err) {\n console.error('[Server HMR] Failed to apply update:', err)\n return false\n }\n}\n\n;(globalThis as any).__turbopack_server_hmr_apply__ =\n __turbopack_server_hmr_apply__\n;(globalThis as any).__turbopack__server_hmr_apply__ =\n __turbopack_server_hmr_apply__\n"],"names":["hmrClientInitialized","ensureHmrClientInitialized","initializeServerHmr","moduleFactories","devModuleCache","runtimeModules","instantiateModule","__turbopack_server_hmr_apply__","update","emitMessage","type","data","err","console","error","globalThis","__turbopack__server_hmr_apply__"],"mappings":"AAAA,8DAA8D;AAC9D,+DAA+D;AAC/D,wCAAwC;AAExC;;;CAGC,GAED,uEAAuE;AACvE,IAAIA,uBAAuB;AAC3B,SAASC;IACP,IAAID,sBAAsB;IAC1BA,uBAAuB;IAEvB,wEAAwE;IACxE,iFAAiF;IACjF,kEAAkE;IAClEE,oBACEC,iBACAC,gBACAC,gBACAC;AAEJ;AAEA,SAASC,+BAA+BC,MAAwB;IAC9D,IAAI;QACF,wCAAwC;QACxCP;QAEA,gEAAgE;QAChEQ,YAAY;YACVC,MAAM;YACNC,MAAMH;QACR;QAEA,OAAO;IACT,EAAE,OAAOI,KAAK;QACZC,QAAQC,KAAK,CAAC,wCAAwCF;QACtD,OAAO;IACT;AACF;;AAEEG,WAAmBR,8BAA8B,GACjDA;AACAQ,WAAmBC,+BAA+B,GAClDT","ignoreList":[0]}}]
}
\ No newline at end of file
......@@ -625,30 +625,28 @@ async function instantiateWebAssemblyFromPath(path, importsObj) {
const { instance } = await WebAssembly.instantiateStreaming(response, importsObj);
return instance.exports;
}
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../hmr-types.d.ts" />
/// <reference path="../../shared/runtime/runtime-utils.ts" />
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="../../shared/runtime/runtime-utils.ts" />
/// <reference path="../../shared-node/base-externals-utils.ts" />
/// <reference path="../../shared-node/node-externals-utils.ts" />
/// <reference path="../../shared-node/node-wasm-utils.ts" />
var SourceType = /*#__PURE__*/ function(SourceType) {
/**
* The module was instantiated because it was included in an evaluated chunk's
* runtime.
* SourceData is a ChunkPath.
*/ SourceType[SourceType["Runtime"] = 0] = "Runtime";
/**
* The module was instantiated because a parent module imported it.
* SourceData is a ModuleId.
*/ SourceType[SourceType["Parent"] = 1] = "Parent";
return SourceType;
}(SourceType || {});
process.env.TURBOPACK = '1';
const nodeContextPrototype = Context.prototype;
/// <reference path="./nodejs-globals.d.ts" />
/**
* Base Node.js runtime shared between production and development.
* Contains chunk loading, module caching, and other non-HMR functionality.
*/ process.env.TURBOPACK = '1';
const url = require('url');
const moduleFactories = new Map();
nodeContextPrototype.M = moduleFactories;
const moduleCache = Object.create(null);
nodeContextPrototype.c = moduleCache;
// Use global module factories and cache to persist across chunk reloads during HMR
// This ensures that when Node.js clears the require cache for a chunk file,
// we don't lose our granular HMR updates to individual modules
if (!globalThis.__turbopack_module_factories__) {
globalThis.__turbopack_module_factories__ = new Map();
}
if (!globalThis.__turbopack_module_cache__) {
globalThis.__turbopack_module_cache__ = Object.create(null);
}
const moduleFactories = globalThis.__turbopack_module_factories__;
// Module cache - typed as base Module, can be cast to HotModule in dev mode
const moduleCache = globalThis.__turbopack_module_cache__;
/**
* Returns an absolute path to the given module's id.
*/ function resolvePathFromModule(moduleId) {
......@@ -661,13 +659,11 @@ nodeContextPrototype.c = moduleCache;
const resolved = path.resolve(RUNTIME_ROOT, strippedAssetPrefix);
return url.pathToFileURL(resolved).href;
}
nodeContextPrototype.R = resolvePathFromModule;
/**
* Exports a URL value. No suffix is added in Node.js runtime.
*/ function exportUrl(urlValue, id) {
exportValue.call(this, urlValue, id);
}
nodeContextPrototype.q = exportUrl;
function loadRuntimeChunk(sourcePath, chunkData) {
if (typeof chunkData === 'string') {
loadRuntimeChunkPath(sourcePath, chunkData);
......@@ -679,8 +675,16 @@ const loadedChunks = new Set();
const unsupportedLoadChunk = Promise.resolve(undefined);
const loadedChunk = Promise.resolve(undefined);
const chunkCache = new Map();
function clearChunkCache() {
/**
* Clear all chunk and module state to force re-evaluation on next require.
* Called by Next.js when server HMR is disabled to implement the "reload everything" behavior.
*/ function clearChunkCache() {
chunkCache.clear();
loadedChunks.clear();
moduleFactories.clear();
for(const key in moduleCache){
delete moduleCache[key];
}
}
function loadRuntimeChunkPath(sourcePath, chunkPath) {
if (!isJs(chunkPath)) {
......@@ -758,7 +762,25 @@ contextPrototype.u = loadWebAssemblyModule;
function getWorkerURL(_entrypoint, _moduleChunks, _shared) {
throw new Error('Worker urls are not implemented yet for Node.js');
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
*/ function isJs(chunkUrlOrPath) {
return regexJsUrl.test(chunkUrlOrPath);
}
/* eslint-disable @typescript-eslint/no-unused-vars */ /// <reference path="./runtime-base.ts" />
/**
* Production Node.js runtime.
* Uses ModuleWithDirection and simple module instantiation without HMR support.
*/ // moduleCache and moduleFactories are declared in runtime-base.ts
const nodeContextPrototype = Context.prototype;
nodeContextPrototype.q = exportUrl;
nodeContextPrototype.M = moduleFactories;
// Cast moduleCache to ModuleWithDirection for production mode
nodeContextPrototype.c = moduleCache;
nodeContextPrototype.R = resolvePathFromModule;
nodeContextPrototype.b = getWorkerURL;
nodeContextPrototype.C = clearChunkCache;
function instantiateModule(id, sourceType, sourceData) {
const moduleFactory = moduleFactories.get(id);
if (typeof moduleFactory !== 'function') {
......@@ -767,10 +789,10 @@ function instantiateModule(id, sourceType, sourceData) {
// and contains e.g. a `require("something")` call.
let instantiationReason;
switch(sourceType){
case 0:
case SourceType.Runtime:
instantiationReason = `as a runtime entry of chunk ${sourceData}`;
break;
case 1:
case SourceType.Parent:
instantiationReason = `because it was required from module ${sourceData}`;
break;
default:
......@@ -778,7 +800,7 @@ function instantiateModule(id, sourceType, sourceData) {
}
throw new Error(`Module ${id} was instantiated ${instantiationReason}, but the module factory is not available.`);
}
const module1 = createModuleObject(id);
const module1 = createModuleWithDirection(id);
const exports = module1.exports;
moduleCache[id] = module1;
const context = new Context(module1, exports);
......@@ -789,6 +811,7 @@ function instantiateModule(id, sourceType, sourceData) {
module1.error = error;
throw error;
}
;
module1.loaded = true;
if (module1.namespaceObject && module1.exports !== module1.namespaceObject) {
// in case of a circular dependency: cjs1 -> esm2 -> cjs1
......@@ -807,12 +830,12 @@ function getOrInstantiateModuleFromParent(id, sourceModule) {
}
return module1;
}
return instantiateModule(id, 1, sourceModule.id);
return instantiateModule(id, SourceType.Parent, sourceModule.id);
}
/**
* Instantiates a runtime module.
*/ function instantiateRuntimeModule(chunkPath, moduleId) {
return instantiateModule(moduleId, 0, chunkPath);
return instantiateModule(moduleId, SourceType.Runtime, chunkPath);
}
/**
* Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.
......@@ -827,18 +850,6 @@ function getOrInstantiateRuntimeModule(chunkPath, moduleId) {
}
return instantiateRuntimeModule(chunkPath, moduleId);
}
const regexJsUrl = /\.js(?:\?[^#]*)?(?:#.*)?$/;
/**
* Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.
*/ function isJs(chunkUrlOrPath) {
return regexJsUrl.test(chunkUrlOrPath);
}
function __turbopack_server_hmr_apply__(_update) {
// TODO: Implement actual HMR logic to update module factories
// For now, just return true to indicate we "accepted" the update
return true;
}
globalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__;
module.exports = (sourcePath)=>({
m: (id)=>getOrInstantiateRuntimeModule(sourcePath, id),
c: (chunkData)=>loadRuntimeChunk(sourcePath, chunkData)
......
......@@ -6,5 +6,6 @@
{"offset": {"line": 544, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared-node/base-externals-utils.ts"],"sourcesContent":["/// <reference path=\"../shared/runtime/runtime-utils.ts\" />\n\n/// A 'base' utilities to support runtime can have externals.\n/// Currently this is for node.js / edge runtime both.\n/// If a fn requires node.js specific behavior, it should be placed in `node-external-utils` instead.\n\nasync function externalImport(id: DependencySpecifier) {\n let raw\n try {\n raw = await import(id)\n } catch (err) {\n // TODO(alexkirsz) This can happen when a client-side module tries to load\n // an external module we don't provide a shim for (e.g. querystring, url).\n // For now, we fail semi-silently, but in the future this should be a\n // compilation error.\n throw new Error(`Failed to load external module ${id}: ${err}`)\n }\n\n if (raw && raw.__esModule && raw.default && 'default' in raw.default) {\n return interopEsm(raw.default, createNS(raw), true)\n }\n\n return raw\n}\ncontextPrototype.y = externalImport\n\nfunction externalRequire(\n id: ModuleId,\n thunk: () => any,\n esm: boolean = false\n): Exports | EsmNamespaceObject {\n let raw\n try {\n raw = thunk()\n } catch (err) {\n // TODO(alexkirsz) This can happen when a client-side module tries to load\n // an external module we don't provide a shim for (e.g. querystring, url).\n // For now, we fail semi-silently, but in the future this should be a\n // compilation error.\n throw new Error(`Failed to load external module ${id}: ${err}`)\n }\n\n if (!esm || raw.__esModule) {\n return raw\n }\n\n return interopEsm(raw, createNS(raw), true)\n}\n\nexternalRequire.resolve = (\n id: string,\n options?: {\n paths?: string[]\n }\n) => {\n return require.resolve(id, options)\n}\ncontextPrototype.x = externalRequire\n"],"names":["externalImport","id","raw","err","Error","__esModule","default","interopEsm","createNS","contextPrototype","y","externalRequire","thunk","esm","resolve","options","require","x"],"mappings":"AAAA,2DAA2D;AAE3D,6DAA6D;AAC7D,sDAAsD;AACtD,qGAAqG;AAErG,eAAeA,eAAeC,EAAuB;IACnD,IAAIC;IACJ,IAAI;QACFA,MAAM,MAAM,MAAM,CAACD;IACrB,EAAE,OAAOE,KAAK;QACZ,0EAA0E;QAC1E,0EAA0E;QAC1E,qEAAqE;QACrE,qBAAqB;QACrB,MAAM,IAAIC,MAAM,CAAC,+BAA+B,EAAEH,GAAG,EAAE,EAAEE,KAAK;IAChE;IAEA,IAAID,OAAOA,IAAIG,UAAU,IAAIH,IAAII,OAAO,IAAI,aAAaJ,IAAII,OAAO,EAAE;QACpE,OAAOC,WAAWL,IAAII,OAAO,EAAEE,SAASN,MAAM;IAChD;IAEA,OAAOA;AACT;AACAO,iBAAiBC,CAAC,GAAGV;AAErB,SAASW,gBACPV,EAAY,EACZW,KAAgB,EAChBC,MAAe,KAAK;IAEpB,IAAIX;IACJ,IAAI;QACFA,MAAMU;IACR,EAAE,OAAOT,KAAK;QACZ,0EAA0E;QAC1E,0EAA0E;QAC1E,qEAAqE;QACrE,qBAAqB;QACrB,MAAM,IAAIC,MAAM,CAAC,+BAA+B,EAAEH,GAAG,EAAE,EAAEE,KAAK;IAChE;IAEA,IAAI,CAACU,OAAOX,IAAIG,UAAU,EAAE;QAC1B,OAAOH;IACT;IAEA,OAAOK,WAAWL,KAAKM,SAASN,MAAM;AACxC;AAEAS,gBAAgBG,OAAO,GAAG,CACxBb,IACAc;IAIA,OAAOC,QAAQF,OAAO,CAACb,IAAIc;AAC7B;AACAN,iBAAiBQ,CAAC,GAAGN","ignoreList":[0]}},
{"offset": {"line": 585, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared-node/node-externals-utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\ndeclare var RUNTIME_PUBLIC_PATH: string\ndeclare var RELATIVE_ROOT_PATH: string\ndeclare var ASSET_PREFIX: string\n\nconst path = require('path')\n\nconst relativePathToRuntimeRoot = path.relative(RUNTIME_PUBLIC_PATH, '.')\n// Compute the relative path to the `distDir`.\nconst relativePathToDistRoot = path.join(\n relativePathToRuntimeRoot,\n RELATIVE_ROOT_PATH\n)\nconst RUNTIME_ROOT = path.resolve(__filename, relativePathToRuntimeRoot)\n// Compute the absolute path to the root, by stripping distDir from the absolute path to this file.\nconst ABSOLUTE_ROOT = path.resolve(__filename, relativePathToDistRoot)\n\n/**\n * Returns an absolute path to the given module path.\n * Module path should be relative, either path to a file or a directory.\n *\n * This fn allows to calculate an absolute path for some global static values, such as\n * `__dirname` or `import.meta.url` that Turbopack will not embeds in compile time.\n * See ImportMetaBinding::code_generation for the usage.\n */\nfunction resolveAbsolutePath(modulePath?: string): string {\n if (modulePath) {\n return path.join(ABSOLUTE_ROOT, modulePath)\n }\n return ABSOLUTE_ROOT\n}\nContext.prototype.P = resolveAbsolutePath\n"],"names":["path","require","relativePathToRuntimeRoot","relative","RUNTIME_PUBLIC_PATH","relativePathToDistRoot","join","RELATIVE_ROOT_PATH","RUNTIME_ROOT","resolve","__filename","ABSOLUTE_ROOT","resolveAbsolutePath","modulePath","Context","prototype","P"],"mappings":"AAAA,oDAAoD,GAMpD,MAAMA,OAAOC,QAAQ;AAErB,MAAMC,4BAA4BF,KAAKG,QAAQ,CAACC,qBAAqB;AACrE,8CAA8C;AAC9C,MAAMC,yBAAyBL,KAAKM,IAAI,CACtCJ,2BACAK;AAEF,MAAMC,eAAeR,KAAKS,OAAO,CAACC,YAAYR;AAC9C,mGAAmG;AACnG,MAAMS,gBAAgBX,KAAKS,OAAO,CAACC,YAAYL;AAE/C;;;;;;;CAOC,GACD,SAASO,oBAAoBC,UAAmB;IAC9C,IAAIA,YAAY;QACd,OAAOb,KAAKM,IAAI,CAACK,eAAeE;IAClC;IACA,OAAOF;AACT;AACAG,QAAQC,SAAS,CAACC,CAAC,GAAGJ","ignoreList":[0]}},
{"offset": {"line": 606, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/shared-node/node-wasm-utils.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../shared/runtime/runtime-utils.ts\" />\n\nfunction readWebAssemblyAsResponse(path: string) {\n const { createReadStream } = require('fs') as typeof import('fs')\n const { Readable } = require('stream') as typeof import('stream')\n\n const stream = createReadStream(path)\n\n // @ts-ignore unfortunately there's a slight type mismatch with the stream.\n return new Response(Readable.toWeb(stream), {\n headers: {\n 'content-type': 'application/wasm',\n },\n })\n}\n\nasync function compileWebAssemblyFromPath(\n path: string\n): Promise<WebAssembly.Module> {\n const response = readWebAssemblyAsResponse(path)\n\n return await WebAssembly.compileStreaming(response)\n}\n\nasync function instantiateWebAssemblyFromPath(\n path: string,\n importsObj: WebAssembly.Imports\n): Promise<Exports> {\n const response = readWebAssemblyAsResponse(path)\n\n const { instance } = await WebAssembly.instantiateStreaming(\n response,\n importsObj\n )\n\n return instance.exports\n}\n"],"names":["readWebAssemblyAsResponse","path","createReadStream","require","Readable","stream","Response","toWeb","headers","compileWebAssemblyFromPath","response","WebAssembly","compileStreaming","instantiateWebAssemblyFromPath","importsObj","instance","instantiateStreaming","exports"],"mappings":"AAAA,oDAAoD,GAEpD,2DAA2D;AAE3D,SAASA,0BAA0BC,IAAY;IAC7C,MAAM,EAAEC,gBAAgB,EAAE,GAAGC,QAAQ;IACrC,MAAM,EAAEC,QAAQ,EAAE,GAAGD,QAAQ;IAE7B,MAAME,SAASH,iBAAiBD;IAEhC,2EAA2E;IAC3E,OAAO,IAAIK,SAASF,SAASG,KAAK,CAACF,SAAS;QAC1CG,SAAS;YACP,gBAAgB;QAClB;IACF;AACF;AAEA,eAAeC,2BACbR,IAAY;IAEZ,MAAMS,WAAWV,0BAA0BC;IAE3C,OAAO,MAAMU,YAAYC,gBAAgB,CAACF;AAC5C;AAEA,eAAeG,+BACbZ,IAAY,EACZa,UAA+B;IAE/B,MAAMJ,WAAWV,0BAA0BC;IAE3C,MAAM,EAAEc,QAAQ,EAAE,GAAG,MAAMJ,YAAYK,oBAAoB,CACzDN,UACAI;IAGF,OAAOC,SAASE,OAAO;AACzB","ignoreList":[0]}},
{"offset": {"line": 627, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/nodejs/runtime/runtime-base.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../hmr-types.d.ts\" />\n/// <reference path=\"../../shared/runtime/runtime-utils.ts\" />\n/// <reference path=\"../../shared-node/base-externals-utils.ts\" />\n/// <reference path=\"../../shared-node/node-externals-utils.ts\" />\n/// <reference path=\"../../shared-node/node-wasm-utils.ts\" />\n\nenum SourceType {\n /**\n * The module was instantiated because it was included in an evaluated chunk's\n * runtime.\n * SourceData is a ChunkPath.\n */\n Runtime = 0,\n /**\n * The module was instantiated because a parent module imported it.\n * SourceData is a ModuleId.\n */\n Parent = 1,\n}\n\ntype SourceData = ChunkPath | ModuleId\n\nprocess.env.TURBOPACK = '1'\n\ninterface TurbopackNodeBuildContext extends TurbopackBaseContext<Module> {\n R: ResolvePathFromModule\n x: ExternalRequire\n y: ExternalImport\n q: ExportUrl\n}\n\nconst nodeContextPrototype = Context.prototype as TurbopackNodeBuildContext\n\ntype ModuleFactory = (\n this: Module['exports'],\n context: TurbopackNodeBuildContext\n) => unknown\n\nconst url = require('url') as typeof import('url')\n\nconst moduleFactories: ModuleFactories = new Map()\nnodeContextPrototype.M = moduleFactories\nconst moduleCache: ModuleCache<Module> = Object.create(null)\nnodeContextPrototype.c = moduleCache\n\n/**\n * Returns an absolute path to the given module's id.\n */\nfunction resolvePathFromModule(\n this: TurbopackBaseContext<Module>,\n moduleId: string\n): string {\n const exported = this.r(moduleId)\n const exportedPath = exported?.default ?? exported\n if (typeof exportedPath !== 'string') {\n return exported as any\n }\n\n const strippedAssetPrefix = exportedPath.slice(ASSET_PREFIX.length)\n const resolved = path.resolve(RUNTIME_ROOT, strippedAssetPrefix)\n\n return url.pathToFileURL(resolved).href\n}\nnodeContextPrototype.R = resolvePathFromModule\n\n/**\n * Exports a URL value. No suffix is added in Node.js runtime.\n */\nfunction exportUrl(\n this: TurbopackBaseContext<Module>,\n urlValue: string,\n id: ModuleId | undefined\n) {\n exportValue.call(this, urlValue, id)\n}\nnodeContextPrototype.q = exportUrl\n\nfunction loadRuntimeChunk(sourcePath: ChunkPath, chunkData: ChunkData): void {\n if (typeof chunkData === 'string') {\n loadRuntimeChunkPath(sourcePath, chunkData)\n } else {\n loadRuntimeChunkPath(sourcePath, chunkData.path)\n }\n}\n\nconst loadedChunks = new Set<ChunkPath>()\nconst unsupportedLoadChunk = Promise.resolve(undefined)\nconst loadedChunk: Promise<void> = Promise.resolve(undefined)\nconst chunkCache = new Map<ChunkPath, Promise<void>>()\n\nfunction clearChunkCache() {\n chunkCache.clear()\n}\n\nfunction loadRuntimeChunkPath(\n sourcePath: ChunkPath,\n chunkPath: ChunkPath\n): void {\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return\n }\n\n if (loadedChunks.has(chunkPath)) {\n return\n }\n\n try {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n const chunkModules: CompressedModuleFactories = require(resolved)\n installCompressedModuleFactories(chunkModules, 0, moduleFactories)\n loadedChunks.add(chunkPath)\n } catch (cause) {\n let errorMessage = `Failed to load chunk ${chunkPath}`\n\n if (sourcePath) {\n errorMessage += ` from runtime for chunk ${sourcePath}`\n }\n\n const error = new Error(errorMessage, { cause })\n error.name = 'ChunkLoadError'\n throw error\n }\n}\n\nfunction loadChunkAsync(\n this: TurbopackBaseContext<Module>,\n chunkData: ChunkData\n): Promise<void> {\n const chunkPath = typeof chunkData === 'string' ? chunkData : chunkData.path\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return unsupportedLoadChunk\n }\n\n let entry = chunkCache.get(chunkPath)\n if (entry === undefined) {\n try {\n // resolve to an absolute path to simplify `require` handling\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n // TODO: consider switching to `import()` to enable concurrent chunk loading and async file io\n // However this is incompatible with hot reloading (since `import` doesn't use the require cache)\n const chunkModules: CompressedModuleFactories = require(resolved)\n installCompressedModuleFactories(chunkModules, 0, moduleFactories)\n entry = loadedChunk\n } catch (cause) {\n const errorMessage = `Failed to load chunk ${chunkPath} from module ${this.m.id}`\n const error = new Error(errorMessage, { cause })\n error.name = 'ChunkLoadError'\n\n // Cache the failure promise, future requests will also get this same rejection\n entry = Promise.reject(error)\n }\n chunkCache.set(chunkPath, entry)\n }\n // TODO: Return an instrumented Promise that React can use instead of relying on referential equality.\n return entry\n}\ncontextPrototype.l = loadChunkAsync\n\nfunction loadChunkAsyncByUrl(\n this: TurbopackBaseContext<Module>,\n chunkUrl: string\n) {\n const path = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT)) as ChunkPath\n return loadChunkAsync.call(this, path)\n}\ncontextPrototype.L = loadChunkAsyncByUrl\n\nfunction loadWebAssembly(\n chunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n imports: WebAssembly.Imports\n) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n return instantiateWebAssemblyFromPath(resolved, imports)\n}\ncontextPrototype.w = loadWebAssembly\n\nfunction loadWebAssemblyModule(\n chunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n return compileWebAssemblyFromPath(resolved)\n}\ncontextPrototype.u = loadWebAssemblyModule\n\nfunction getWorkerURL(\n _entrypoint: ChunkPath,\n _moduleChunks: ChunkPath[],\n _shared: boolean\n): URL {\n throw new Error('Worker urls are not implemented yet for Node.js')\n}\n\nnodeContextPrototype.b = getWorkerURL\n\nfunction instantiateModule(\n id: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): Module {\n const moduleFactory = moduleFactories.get(id)\n if (typeof moduleFactory !== 'function') {\n // This can happen if modules incorrectly handle HMR disposes/updates,\n // e.g. when they keep a `setTimeout` around which still executes old code\n // and contains e.g. a `require(\"something\")` call.\n let instantiationReason: string\n switch (sourceType) {\n case SourceType.Runtime:\n instantiationReason = `as a runtime entry of chunk ${sourceData}`\n break\n case SourceType.Parent:\n instantiationReason = `because it was required from module ${sourceData}`\n break\n default:\n invariant(\n sourceType,\n (sourceType) => `Unknown source type: ${sourceType}`\n )\n }\n throw new Error(\n `Module ${id} was instantiated ${instantiationReason}, but the module factory is not available.`\n )\n }\n\n const module: Module = createModuleObject(id)\n const exports = module.exports\n moduleCache[id] = module\n\n const context = new (Context as any as ContextConstructor<Module>)(\n module,\n exports\n )\n // NOTE(alexkirsz) This can fail when the module encounters a runtime error.\n try {\n moduleFactory(context, module, exports)\n } catch (error) {\n module.error = error as any\n throw error\n }\n\n module.loaded = true\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject)\n }\n\n return module\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// @ts-ignore\nfunction getOrInstantiateModuleFromParent(\n id: ModuleId,\n sourceModule: Module\n): Module {\n const module = moduleCache[id]\n\n if (module) {\n if (module.error) {\n throw module.error\n }\n\n return module\n }\n\n return instantiateModule(id, SourceType.Parent, sourceModule.id)\n}\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module {\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.\n */\n// @ts-ignore TypeScript doesn't separate this module space from the browser runtime\nfunction getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): Module {\n const module = moduleCache[moduleId]\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n return instantiateRuntimeModule(chunkPath, moduleId)\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath)\n}\n\nfunction __turbopack_server_hmr_apply__(\n _update: NodeJsPartialHmrUpdate\n): boolean {\n // TODO: Implement actual HMR logic to update module factories\n // For now, just return true to indicate we \"accepted\" the update\n return true\n}\n\nglobalThis.__turbopack_server_hmr_apply__ = __turbopack_server_hmr_apply__\n\nmodule.exports = (sourcePath: ChunkPath) => ({\n m: (id: ModuleId) => getOrInstantiateRuntimeModule(sourcePath, id),\n c: (chunkData: ChunkData) => loadRuntimeChunk(sourcePath, chunkData),\n})\n"],"names":["SourceType","process","env","TURBOPACK","nodeContextPrototype","Context","prototype","url","require","moduleFactories","Map","M","moduleCache","Object","create","c","resolvePathFromModule","moduleId","exported","r","exportedPath","default","strippedAssetPrefix","slice","ASSET_PREFIX","length","resolved","path","resolve","RUNTIME_ROOT","pathToFileURL","href","R","exportUrl","urlValue","id","exportValue","call","q","loadRuntimeChunk","sourcePath","chunkData","loadRuntimeChunkPath","loadedChunks","Set","unsupportedLoadChunk","Promise","undefined","loadedChunk","chunkCache","clearChunkCache","clear","chunkPath","isJs","has","chunkModules","installCompressedModuleFactories","add","cause","errorMessage","error","Error","name","loadChunkAsync","entry","get","m","reject","set","contextPrototype","l","loadChunkAsyncByUrl","chunkUrl","path1","fileURLToPath","URL","L","loadWebAssembly","_edgeModule","imports","instantiateWebAssemblyFromPath","w","loadWebAssemblyModule","compileWebAssemblyFromPath","u","getWorkerURL","_entrypoint","_moduleChunks","_shared","b","instantiateModule","sourceType","sourceData","moduleFactory","instantiationReason","invariant","module1","createModuleObject","exports","context","loaded","namespaceObject","interopEsm","getOrInstantiateModuleFromParent","sourceModule","instantiateRuntimeModule","getOrInstantiateRuntimeModule","regexJsUrl","chunkUrlOrPath","test","__turbopack_server_hmr_apply__","_update","globalThis","module"],"mappings":"AAAA,oDAAoD,GAEpD,0CAA0C;AAC1C,8DAA8D;AAC9D,kEAAkE;AAClE,kEAAkE;AAClE,6DAA6D;AAE7D,IAAA,AAAKA,oCAAAA;IACH;;;;GAIC;IAED;;;GAGC;WAVEA;EAAAA;AAgBLC,QAAQC,GAAG,CAACC,SAAS,GAAG;AASxB,MAAMC,uBAAuBC,QAAQC,SAAS;AAO9C,MAAMC,MAAMC,QAAQ;AAEpB,MAAMC,kBAAmC,IAAIC;AAC7CN,qBAAqBO,CAAC,GAAGF;AACzB,MAAMG,cAAmCC,OAAOC,MAAM,CAAC;AACvDV,qBAAqBW,CAAC,GAAGH;AAEzB;;CAEC,GACD,SAASI,sBAEPC,QAAgB;IAEhB,MAAMC,WAAW,IAAI,CAACC,CAAC,CAACF;IACxB,MAAMG,eAAeF,UAAUG,WAAWH;IAC1C,IAAI,OAAOE,iBAAiB,UAAU;QACpC,OAAOF;IACT;IAEA,MAAMI,sBAAsBF,aAAaG,KAAK,CAACC,aAAaC,MAAM;IAClE,MAAMC,WAAWC,KAAKC,OAAO,CAACC,cAAcP;IAE5C,OAAOf,IAAIuB,aAAa,CAACJ,UAAUK,IAAI;AACzC;AACA3B,qBAAqB4B,CAAC,GAAGhB;AAEzB;;CAEC,GACD,SAASiB,UAEPC,QAAgB,EAChBC,EAAwB;IAExBC,YAAYC,IAAI,CAAC,IAAI,EAAEH,UAAUC;AACnC;AACA/B,qBAAqBkC,CAAC,GAAGL;AAEzB,SAASM,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BnC,QAAkB;IAElB,MAAM+E,UAASpF,WAAW,CAACK,SAAS;IACpC,IAAI+E,SAAQ;QACV,IAAIA,QAAOpC,KAAK,EAAE;YAChB,MAAMoC,QAAOpC,KAAK;QACpB;QACA,OAAOoC;IACT;IAEA,OAAOS,yBAAyBrD,WAAWnC;AAC7C;AAEA,MAAM0F,aAAa;AACnB;;CAEC,GACD,SAAStD,KAAKuD,cAAoC;IAChD,OAAOD,WAAWE,IAAI,CAACD;AACzB;AAEA,SAASE,+BACPC,OAA+B;IAE/B,8DAA8D;IAC9D,iEAAiE;IACjE,OAAO;AACT;AAEAC,WAAWF,8BAA8B,GAAGA;AAE5CG,OAAOf,OAAO,GAAG,CAAC1D,aAA0B,CAAC;QAC3C0B,GAAG,CAAC/B,KAAiBuE,8BAA8BlE,YAAYL;QAC/DpB,GAAG,CAAC0B,YAAyBF,iBAAiBC,YAAYC;IAC5D,CAAC","ignoreList":[0]}}]
{"offset": {"line": 627, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/nodejs/runtime/runtime-base.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"../../shared/runtime/runtime-utils.ts\" />\n/// <reference path=\"../../shared-node/base-externals-utils.ts\" />\n/// <reference path=\"../../shared-node/node-externals-utils.ts\" />\n/// <reference path=\"../../shared-node/node-wasm-utils.ts\" />\n/// <reference path=\"./nodejs-globals.d.ts\" />\n\n/**\n * Base Node.js runtime shared between production and development.\n * Contains chunk loading, module caching, and other non-HMR functionality.\n */\n\nprocess.env.TURBOPACK = '1'\n\nconst url = require('url') as typeof import('url')\n\n// Use global module factories and cache to persist across chunk reloads during HMR\n// This ensures that when Node.js clears the require cache for a chunk file,\n// we don't lose our granular HMR updates to individual modules\nif (!globalThis.__turbopack_module_factories__) {\n globalThis.__turbopack_module_factories__ = new Map()\n}\nif (!globalThis.__turbopack_module_cache__) {\n globalThis.__turbopack_module_cache__ = Object.create(null)\n}\n\nconst moduleFactories: ModuleFactories =\n globalThis.__turbopack_module_factories__\n\n// Module cache - typed as base Module, can be cast to HotModule in dev mode\nconst moduleCache: ModuleCache<Module> = globalThis.__turbopack_module_cache__\n\n/**\n * Returns an absolute path to the given module's id.\n */\nfunction resolvePathFromModule(\n this: TurbopackBaseContext<Module>,\n moduleId: string\n): string {\n const exported = this.r(moduleId)\n const exportedPath = exported?.default ?? exported\n if (typeof exportedPath !== 'string') {\n return exported as any\n }\n\n const strippedAssetPrefix = exportedPath.slice(ASSET_PREFIX.length)\n const resolved = path.resolve(RUNTIME_ROOT, strippedAssetPrefix)\n\n return url.pathToFileURL(resolved).href\n}\n\n/**\n * Exports a URL value. No suffix is added in Node.js runtime.\n */\nfunction exportUrl(\n this: TurbopackBaseContext<Module>,\n urlValue: string,\n id: ModuleId | undefined\n) {\n exportValue.call(this, urlValue, id)\n}\n\nfunction loadRuntimeChunk(sourcePath: ChunkPath, chunkData: ChunkData): void {\n if (typeof chunkData === 'string') {\n loadRuntimeChunkPath(sourcePath, chunkData)\n } else {\n loadRuntimeChunkPath(sourcePath, chunkData.path)\n }\n}\n\nconst loadedChunks = new Set<ChunkPath>()\nconst unsupportedLoadChunk = Promise.resolve(undefined)\nconst loadedChunk: Promise<void> = Promise.resolve(undefined)\nconst chunkCache = new Map<ChunkPath, Promise<void>>()\n\n/**\n * Clear all chunk and module state to force re-evaluation on next require.\n * Called by Next.js when server HMR is disabled to implement the \"reload everything\" behavior.\n */\nfunction clearChunkCache() {\n chunkCache.clear()\n loadedChunks.clear()\n moduleFactories.clear()\n for (const key in moduleCache) {\n delete moduleCache[key]\n }\n}\n\nfunction loadRuntimeChunkPath(\n sourcePath: ChunkPath,\n chunkPath: ChunkPath\n): void {\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return\n }\n\n if (loadedChunks.has(chunkPath)) {\n return\n }\n\n try {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n const chunkModules: CompressedModuleFactories = require(resolved)\n installCompressedModuleFactories(chunkModules, 0, moduleFactories)\n loadedChunks.add(chunkPath)\n } catch (cause) {\n let errorMessage = `Failed to load chunk ${chunkPath}`\n\n if (sourcePath) {\n errorMessage += ` from runtime for chunk ${sourcePath}`\n }\n\n const error = new Error(errorMessage, { cause })\n error.name = 'ChunkLoadError'\n throw error\n }\n}\n\nfunction loadChunkAsync(\n this: TurbopackBaseContext<any>,\n chunkData: ChunkData\n): Promise<void> {\n const chunkPath = typeof chunkData === 'string' ? chunkData : chunkData.path\n if (!isJs(chunkPath)) {\n // We only support loading JS chunks in Node.js.\n // This branch can be hit when trying to load a CSS chunk.\n return unsupportedLoadChunk\n }\n\n let entry = chunkCache.get(chunkPath)\n if (entry === undefined) {\n try {\n // resolve to an absolute path to simplify `require` handling\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n // TODO: consider switching to `import()` to enable concurrent chunk loading and async file io\n // However this is incompatible with hot reloading (since `import` doesn't use the require cache)\n const chunkModules: CompressedModuleFactories = require(resolved)\n installCompressedModuleFactories(chunkModules, 0, moduleFactories)\n entry = loadedChunk\n } catch (cause) {\n const errorMessage = `Failed to load chunk ${chunkPath} from module ${this.m.id}`\n const error = new Error(errorMessage, { cause })\n error.name = 'ChunkLoadError'\n\n // Cache the failure promise, future requests will also get this same rejection\n entry = Promise.reject(error)\n }\n chunkCache.set(chunkPath, entry)\n }\n // TODO: Return an instrumented Promise that React can use instead of relying on referential equality.\n return entry\n}\ncontextPrototype.l = loadChunkAsync\n\nfunction loadChunkAsyncByUrl(\n this: TurbopackBaseContext<any>,\n chunkUrl: string\n) {\n const path = url.fileURLToPath(new URL(chunkUrl, RUNTIME_ROOT)) as ChunkPath\n return loadChunkAsync.call(this, path)\n}\ncontextPrototype.L = loadChunkAsyncByUrl\n\nfunction loadWebAssembly(\n chunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module,\n imports: WebAssembly.Imports\n) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n return instantiateWebAssemblyFromPath(resolved, imports)\n}\ncontextPrototype.w = loadWebAssembly\n\nfunction loadWebAssemblyModule(\n chunkPath: ChunkPath,\n _edgeModule: () => WebAssembly.Module\n) {\n const resolved = path.resolve(RUNTIME_ROOT, chunkPath)\n\n return compileWebAssemblyFromPath(resolved)\n}\ncontextPrototype.u = loadWebAssemblyModule\n\nfunction getWorkerURL(\n _entrypoint: ChunkPath,\n _moduleChunks: ChunkPath[],\n _shared: boolean\n): URL {\n throw new Error('Worker urls are not implemented yet for Node.js')\n}\n\nconst regexJsUrl = /\\.js(?:\\?[^#]*)?(?:#.*)?$/\n/**\n * Checks if a given path/URL ends with .js, optionally followed by ?query or #fragment.\n */\nfunction isJs(chunkUrlOrPath: ChunkUrl | ChunkPath): boolean {\n return regexJsUrl.test(chunkUrlOrPath)\n}\n"],"names":["process","env","TURBOPACK","url","require","globalThis","__turbopack_module_factories__","Map","__turbopack_module_cache__","Object","create","moduleFactories","moduleCache","resolvePathFromModule","moduleId","exported","r","exportedPath","default","strippedAssetPrefix","slice","ASSET_PREFIX","length","resolved","path","resolve","RUNTIME_ROOT","pathToFileURL","href","exportUrl","urlValue","id","exportValue","call","loadRuntimeChunk","sourcePath","chunkData","loadRuntimeChunkPath","loadedChunks","Set","unsupportedLoadChunk","Promise","undefined","loadedChunk","chunkCache","clearChunkCache","clear","key","chunkPath","isJs","has","chunkModules","installCompressedModuleFactories","add","cause","errorMessage","error","Error","name","loadChunkAsync","entry","get","m","reject","set","contextPrototype","l","loadChunkAsyncByUrl","chunkUrl","path1","fileURLToPath","URL","L","loadWebAssembly","_edgeModule","imports","instantiateWebAssemblyFromPath","w","loadWebAssemblyModule","compileWebAssemblyFromPath","u","getWorkerURL","_entrypoint","_moduleChunks","_shared","regexJsUrl","chunkUrlOrPath","test"],"mappings":"AAAA,oDAAoD,GAEpD,8DAA8D;AAC9D,kEAAkE;AAClE,kEAAkE;AAClE,6DAA6D;AAC7D,8CAA8C;AAE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AED;YAAM;YAC9CE,MAAME,IAAI,GAAG;YAEb,+EAA+E;YAC/EE,QAAQnB,QAAQsB,MAAM,CAACP;QACzB;QACAZ,WAAWoB,GAAG,CAAChB,WAAWY;IAC5B;IACA,sGAAsG;IACtG,OAAOA;AACT;AACAK,iBAAiBC,CAAC,GAAGP;AAErB,SAASQ,oBAEPC,QAAgB;IAEhB,MAAMC,QAAOlE,IAAImE,aAAa,CAAC,IAAIC,IAAIH,UAAU1C;IACjD,OAAOiC,eAAe1B,IAAI,CAAC,IAAI,EAAEoC;AACnC;AACAJ,iBAAiBO,CAAC,GAAGL;AAErB,SAASM,gBACPzB,SAAoB,EACpB0B,WAAqC,EACrCC,OAA4B;IAE5B,MAAMpD,WAAWC,KAAKC,OAAO,CAACC,cAAcsB;IAE5C,OAAO4B,+BAA+BrD,UAAUoD;AAClD;AACAV,iBAAiBY,CAAC,GAAGJ;AAErB,SAASK,sBACP9B,SAAoB,EACpB0B,WAAqC;IAErC,MAAMnD,WAAWC,KAAKC,OAAO,CAACC,cAAcsB;IAE5C,OAAO+B,2BAA2BxD;AACpC;AACA0C,iBAAiBe,CAAC,GAAGF;AAErB,SAASG,aACPC,WAAsB,EACtBC,aAA0B,EAC1BC,OAAgB;IAEhB,MAAM,IAAI3B,MAAM;AAClB;AAEA,MAAM4B,aAAa;AACnB;;CAEC,GACD,SAASpC,KAAKqC,cAAoC;IAChD,OAAOD,WAAWE,IAAI,CAACD;AACzB","ignoreList":[0]}},
{"offset": {"line": 770, "column": 0}, "map": {"version":3,"sources":["turbopack:///[turbopack]/nodejs/runtime/build-base.ts"],"sourcesContent":["/* eslint-disable @typescript-eslint/no-unused-vars */\n\n/// <reference path=\"./runtime-base.ts\" />\n\n/**\n * Production Node.js runtime.\n * Uses ModuleWithDirection and simple module instantiation without HMR support.\n */\n\n// moduleCache and moduleFactories are declared in runtime-base.ts\n\ninterface TurbopackNodeBuildContext\n extends TurbopackBaseContext<ModuleWithDirection> {\n R: ResolvePathFromModule\n x: ExternalRequire\n y: ExternalImport\n C: typeof clearChunkCache\n}\n\nconst nodeContextPrototype = Context.prototype as TurbopackNodeBuildContext\n\nnodeContextPrototype.q = exportUrl\nnodeContextPrototype.M = moduleFactories\n// Cast moduleCache to ModuleWithDirection for production mode\nnodeContextPrototype.c = moduleCache as ModuleCache<ModuleWithDirection>\nnodeContextPrototype.R = resolvePathFromModule\nnodeContextPrototype.b = getWorkerURL\nnodeContextPrototype.C = clearChunkCache\n\nfunction instantiateModule(\n id: ModuleId,\n sourceType: SourceType,\n sourceData: SourceData\n): ModuleWithDirection {\n const moduleFactory = moduleFactories.get(id)\n if (typeof moduleFactory !== 'function') {\n // This can happen if modules incorrectly handle HMR disposes/updates,\n // e.g. when they keep a `setTimeout` around which still executes old code\n // and contains e.g. a `require(\"something\")` call.\n let instantiationReason: string\n switch (sourceType) {\n case SourceType.Runtime:\n instantiationReason = `as a runtime entry of chunk ${sourceData}`\n break\n case SourceType.Parent:\n instantiationReason = `because it was required from module ${sourceData}`\n break\n default:\n invariant(\n sourceType,\n (sourceType) => `Unknown source type: ${sourceType}`\n )\n }\n throw new Error(\n `Module ${id} was instantiated ${instantiationReason}, but the module factory is not available.`\n )\n }\n\n const module: ModuleWithDirection = createModuleWithDirection(id)\n const exports = module.exports\n moduleCache[id] = module\n\n const context =\n new (Context as any as ContextConstructor<ModuleWithDirection>)(\n module,\n exports\n )\n // NOTE(alexkirsz) This can fail when the module encounters a runtime error.\n try {\n moduleFactory(context, module, exports)\n } catch (error) {\n module.error = error as any\n throw error\n }\n\n ;(module as any).loaded = true\n if (module.namespaceObject && module.exports !== module.namespaceObject) {\n // in case of a circular dependency: cjs1 -> esm2 -> cjs1\n interopEsm(module.exports, module.namespaceObject)\n }\n\n return module\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it if it is not cached.\n */\n// @ts-ignore\nfunction getOrInstantiateModuleFromParent(\n id: ModuleId,\n sourceModule: ModuleWithDirection\n): ModuleWithDirection {\n const module = moduleCache[id]\n\n if (module) {\n if (module.error) {\n throw module.error\n }\n\n return module\n }\n\n return instantiateModule(id, SourceType.Parent, sourceModule.id)\n}\n\n/**\n * Instantiates a runtime module.\n */\nfunction instantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): ModuleWithDirection {\n return instantiateModule(moduleId, SourceType.Runtime, chunkPath)\n}\n\n/**\n * Retrieves a module from the cache, or instantiate it as a runtime module if it is not cached.\n */\n// @ts-ignore TypeScript doesn't separate this module space from the browser runtime\nfunction getOrInstantiateRuntimeModule(\n chunkPath: ChunkPath,\n moduleId: ModuleId\n): ModuleWithDirection {\n const module = moduleCache[moduleId]\n\n if (module) {\n if (module.error) {\n throw module.error\n }\n return module\n }\n\n return instantiateRuntimeModule(chunkPath, moduleId)\n}\n\nmodule.exports = (sourcePath: ChunkPath) => ({\n m: (id: ModuleId) => getOrInstantiateRuntimeModule(sourcePath, id),\n c: (chunkData: ChunkData) => loadRuntimeChunk(sourcePath, chunkData),\n})\n"],"names":["nodeContextPrototype","Context","prototype","q","exportUrl","M","moduleFactories","c","moduleCache","R","resolvePathFromModule","b","getWorkerURL","C","clearChunkCache","instantiateModule","id","sourceType","sourceData","moduleFactory","get","instantiationReason","SourceType","Runtime","Parent","invariant","Error","module1","createModuleWithDirection","exports","context","error","loaded","namespaceObject","interopEsm","getOrInstantiateModuleFromParent","sourceModule","instantiateRuntimeModule","chunkPath","moduleId","getOrInstantiateRuntimeModule","module","sourcePath","m","chunkData","loadRuntimeChunk"],"mappings":"AAAA,oDAAoD,GAEpD,0CAA0C;AAE1C;;;CAGC,GAED,kEAAkE;AAUlE,MAAMA,uBAAuBC,QAAQC,SAAS;AAE9CF,qBAAqBG,CAAC,GAAGC;AACzBJ,qBAAqBK,CAAC,GAAGC;AACzB,8DAA8D;AAC9DN,qBAAqBO,CAAC,GAAGC;AACzBR,qBAAqBS,CAAC,GAAGC;AACzBV,qBAAqBW,CAAC,GAAGC;AACzBZ,qBAAqBa,CAAC,GAAGC;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,MAAM,EAAEY,aAAapB,EAAE;AACjE;AAEA;;CAEC,GACD,SAASqB,yBACPC,SAAoB,EACpBC,QAAkB;IAElB,OAAOxB,kBAAkBwB,UAAUjB,WAAWC,OAAO,EAAEe;AACzD;AAEA;;CAEC,GACD,oFAAoF;AACpF,SAASE,8BACPF,SAAoB,EACpBC,QAAkB;IAElB,MAAMZ,UAASnB,WAAW,CAAC+B,SAAS;IAEpC,IAAIZ,SAAQ;QACV,IAAIA,QAAOI,KAAK,EAAE;YAChB,MAAMJ,QAAOI,KAAK;QACpB;QACA,OAAOJ;IACT;IAEA,OAAOU,yBAAyBC,WAAWC;AAC7C;AAEAE,OAAOZ,OAAO,GAAG,CAACa,aAA0B,CAAC;QAC3CC,GAAG,CAAC3B,KAAiBwB,8BAA8BE,YAAY1B;QAC/DT,GAAG,CAACqC,YAAyBC,iBAAiBH,YAAYE;IAC5D,CAAC","ignoreList":[0]}}]
}
\ No newline at end of file
......@@ -853,11 +853,11 @@ class UpdateApplyError extends Error {
*/ // eslint-disable-next-line @typescript-eslint/no-unused-vars
function trackModuleImport(parentModule, childModuleId, childModule) {
// Record that parent imports child
if (parentModule.children.indexOf(childModuleId) === -1) {
if (parentModule.children && parentModule.children.indexOf(childModuleId) === -1) {
parentModule.children.push(childModuleId);
}
// Record that child is imported by parent
if (childModule && childModule.parents.indexOf(parentModule.id) === -1) {
if (childModule && childModule.parents && childModule.parents.indexOf(parentModule.id) === -1) {
childModule.parents.push(parentModule.id);
}
}
......@@ -869,11 +869,10 @@ function formatDependencyChain(dependencyChain) {
* Returns information about whether the update can be accepted and which
* modules need to be invalidated.
*
* Copied directly from browser implementation.
*
* @param moduleId - The module to check for effects
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function getAffectedModuleEffects(moduleId, autoAcceptRootModules) {
* @param moduleId - The module that changed
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept().
* This is used for server-side HMR where pages auto-accept at the top level.
*/ function getAffectedModuleEffects(moduleId, autoAcceptAtRoot) {
const outdatedModules = new Set();
const queue = [
{
......@@ -883,20 +882,29 @@ function formatDependencyChain(dependencyChain) {
];
let nextItem;
while(nextItem = queue.shift()){
const { moduleId: currentModuleId, dependencyChain } = nextItem;
const { moduleId, dependencyChain } = nextItem;
if (moduleId != null) {
if (outdatedModules.has(moduleId)) {
continue;
}
outdatedModules.add(moduleId);
}
// We've arrived at the runtime of the chunk, which means that nothing
// else above can accept this update.
if (currentModuleId === undefined) {
if (moduleId === undefined) {
if (autoAcceptAtRoot) {
return {
type: 'accepted',
moduleId,
outdatedModules
};
}
return {
type: 'unaccepted',
dependencyChain
};
}
if (outdatedModules.has(currentModuleId)) {
continue;
}
outdatedModules.add(currentModuleId);
const module = devModuleCache[currentModuleId];
const module = devModuleCache[moduleId];
const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before.
......@@ -907,15 +915,18 @@ function formatDependencyChain(dependencyChain) {
return {
type: 'self-declined',
dependencyChain,
moduleId: currentModuleId
moduleId
};
}
if (runtimeModules.has(currentModuleId)) {
if (runtimeModules.has(moduleId)) {
if (autoAcceptAtRoot) {
continue;
}
queue.push({
moduleId: undefined,
dependencyChain: [
...dependencyChain,
currentModuleId
moduleId
]
});
continue;
......@@ -931,10 +942,14 @@ function formatDependencyChain(dependencyChain) {
moduleId: parentId,
dependencyChain: [
...dependencyChain,
currentModuleId
moduleId
]
});
}
// If no parents and we're at a root module, auto-accept if configured
if (module.parents.length === 0 && autoAcceptAtRoot) {
continue;
}
}
return {
type: 'accepted',
......@@ -945,14 +960,12 @@ function formatDependencyChain(dependencyChain) {
/**
* Computes all modules that need to be invalidated based on which modules changed.
*
* Copied directly from browser implementation.
*
* @param invalidated - The modules to check for invalidation
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computedInvalidatedModules(invalidated, autoAcceptRootModules) {
* @param invalidated - The modules that have been invalidated
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computedInvalidatedModules(invalidated, autoAcceptAtRoot) {
const outdatedModules = new Set();
for (const moduleId of invalidated){
const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules);
const effect = getAffectedModuleEffects(moduleId, autoAcceptAtRoot);
switch(effect.type){
case 'unaccepted':
throw new UpdateApplyError(`cannot apply update: unaccepted module. ${formatDependencyChain(effect.dependencyChain)}.`, effect.dependencyChain);
......@@ -1040,11 +1053,11 @@ function formatDependencyChain(dependencyChain) {
* Processes queued invalidated modules and adds them to the outdated modules set.
* Modules that call module.hot.invalidate() are queued and processed here.
*
* @param outdatedModules - The set of already outdated modules
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInvalidatedModules(outdatedModules, autoAcceptRootModules) {
* @param outdatedModules - The current set of outdated modules
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInvalidatedModules(outdatedModules, autoAcceptAtRoot) {
if (queuedInvalidatedModules.size > 0) {
computedInvalidatedModules(queuedInvalidatedModules, autoAcceptRootModules).forEach((moduleId)=>{
computedInvalidatedModules(queuedInvalidatedModules, autoAcceptAtRoot).forEach((moduleId)=>{
outdatedModules.add(moduleId);
});
queuedInvalidatedModules.clear();
......@@ -1245,7 +1258,7 @@ function formatDependencyChain(dependencyChain) {
break;
}
default:
throw new Error(`Unknown merged chunk update`);
throw new Error('Unknown merged chunk update type');
}
}
// If a module was added from one chunk and deleted from another in the same update,
......@@ -1281,8 +1294,8 @@ function formatDependencyChain(dependencyChain) {
* @param added - Map of added modules
* @param modified - Map of modified modules
* @param evalModuleEntry - Function to compile module code
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptRootModules) {
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot) {
const newModuleFactories = new Map();
// Compile added modules
for (const [moduleId, entry] of added){
......@@ -1291,7 +1304,8 @@ function formatDependencyChain(dependencyChain) {
}
}
// Walk dependency tree to find all modules affected by modifications
const outdatedModules = computedInvalidatedModules(modified.keys(), autoAcceptRootModules);
const outdatedModules = computedInvalidatedModules(modified.keys(), autoAcceptAtRoot);
// Compile modified modules
for (const [moduleId, entry] of modified){
newModuleFactories.set(moduleId, evalModuleEntry(entry));
}
......@@ -1336,9 +1350,9 @@ function formatDependencyChain(dependencyChain) {
* Internal implementation that orchestrates the full HMR update flow:
* invalidation, disposal, and application of new modules.
*
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules) {
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptRootModules);
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot) {
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptAtRoot);
// Find self-accepted modules to re-instantiate
const outdatedSelfAcceptedModules = computeOutdatedSelfAcceptedModules(outdatedModules);
// Run dispose handlers, save hot.data, clear caches
......@@ -1353,16 +1367,20 @@ function formatDependencyChain(dependencyChain) {
}
// Recursively apply any queued invalidations from new module execution
if (queuedInvalidatedModules.size > 0) {
applyInternal(new Set(), [], new Map(), moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules);
applyInternal(new Set(), [], new Map(), moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot);
}
}
/**
* Main entry point for applying an ECMAScript merged update.
* This is called by both browser and Node.js runtimes with platform-specific callbacks.
*
* @param options.autoAcceptAtRoot - If true, root modules auto-accept updates without explicit
* module.hot.accept(). Used for server-side HMR where pages
* auto-accept at the top level.
*/ function applyEcmascriptMergedUpdateShared(options) {
const { added, modified, disposedModules, evalModuleEntry, instantiateModuleFn, applyModuleFactoryNameFn, moduleFactories, devModuleCache, autoAcceptRootModules } = options;
const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptRootModules);
applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules);
const { added, modified, disposedModules, evalModuleEntry, instantiateModule, applyModuleFactoryName, moduleFactories, devModuleCache, autoAcceptAtRoot } = options;
const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot);
applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModule, applyModuleFactoryName, autoAcceptAtRoot);
}
/// <reference path="../../../shared/runtime/dev-globals.d.ts" />
/// <reference path="../../../shared/runtime/dev-protocol.d.ts" />
......@@ -1601,11 +1619,12 @@ function applyEcmascriptMergedUpdate(update) {
modified,
disposedModules,
evalModuleEntry: _eval,
instantiateModuleFn: instantiateModule,
applyModuleFactoryNameFn: applyModuleFactoryName,
instantiateModule,
applyModuleFactoryName,
moduleFactories,
devModuleCache,
autoAcceptRootModules: false
runtimeModules,
autoAcceptAtRoot: false
});
}
function handleApply(chunkListPath, update) {
......
......@@ -853,11 +853,11 @@ class UpdateApplyError extends Error {
*/ // eslint-disable-next-line @typescript-eslint/no-unused-vars
function trackModuleImport(parentModule, childModuleId, childModule) {
// Record that parent imports child
if (parentModule.children.indexOf(childModuleId) === -1) {
if (parentModule.children && parentModule.children.indexOf(childModuleId) === -1) {
parentModule.children.push(childModuleId);
}
// Record that child is imported by parent
if (childModule && childModule.parents.indexOf(parentModule.id) === -1) {
if (childModule && childModule.parents && childModule.parents.indexOf(parentModule.id) === -1) {
childModule.parents.push(parentModule.id);
}
}
......@@ -869,11 +869,10 @@ function formatDependencyChain(dependencyChain) {
* Returns information about whether the update can be accepted and which
* modules need to be invalidated.
*
* Copied directly from browser implementation.
*
* @param moduleId - The module to check for effects
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function getAffectedModuleEffects(moduleId, autoAcceptRootModules) {
* @param moduleId - The module that changed
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept().
* This is used for server-side HMR where pages auto-accept at the top level.
*/ function getAffectedModuleEffects(moduleId, autoAcceptAtRoot) {
const outdatedModules = new Set();
const queue = [
{
......@@ -883,20 +882,29 @@ function formatDependencyChain(dependencyChain) {
];
let nextItem;
while(nextItem = queue.shift()){
const { moduleId: currentModuleId, dependencyChain } = nextItem;
const { moduleId, dependencyChain } = nextItem;
if (moduleId != null) {
if (outdatedModules.has(moduleId)) {
continue;
}
outdatedModules.add(moduleId);
}
// We've arrived at the runtime of the chunk, which means that nothing
// else above can accept this update.
if (currentModuleId === undefined) {
if (moduleId === undefined) {
if (autoAcceptAtRoot) {
return {
type: 'accepted',
moduleId,
outdatedModules
};
}
return {
type: 'unaccepted',
dependencyChain
};
}
if (outdatedModules.has(currentModuleId)) {
continue;
}
outdatedModules.add(currentModuleId);
const module = devModuleCache[currentModuleId];
const module = devModuleCache[moduleId];
const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before.
......@@ -907,15 +915,18 @@ function formatDependencyChain(dependencyChain) {
return {
type: 'self-declined',
dependencyChain,
moduleId: currentModuleId
moduleId
};
}
if (runtimeModules.has(currentModuleId)) {
if (runtimeModules.has(moduleId)) {
if (autoAcceptAtRoot) {
continue;
}
queue.push({
moduleId: undefined,
dependencyChain: [
...dependencyChain,
currentModuleId
moduleId
]
});
continue;
......@@ -931,10 +942,14 @@ function formatDependencyChain(dependencyChain) {
moduleId: parentId,
dependencyChain: [
...dependencyChain,
currentModuleId
moduleId
]
});
}
// If no parents and we're at a root module, auto-accept if configured
if (module.parents.length === 0 && autoAcceptAtRoot) {
continue;
}
}
return {
type: 'accepted',
......@@ -945,14 +960,12 @@ function formatDependencyChain(dependencyChain) {
/**
* Computes all modules that need to be invalidated based on which modules changed.
*
* Copied directly from browser implementation.
*
* @param invalidated - The modules to check for invalidation
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computedInvalidatedModules(invalidated, autoAcceptRootModules) {
* @param invalidated - The modules that have been invalidated
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computedInvalidatedModules(invalidated, autoAcceptAtRoot) {
const outdatedModules = new Set();
for (const moduleId of invalidated){
const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules);
const effect = getAffectedModuleEffects(moduleId, autoAcceptAtRoot);
switch(effect.type){
case 'unaccepted':
throw new UpdateApplyError(`cannot apply update: unaccepted module. ${formatDependencyChain(effect.dependencyChain)}.`, effect.dependencyChain);
......@@ -1040,11 +1053,11 @@ function formatDependencyChain(dependencyChain) {
* Processes queued invalidated modules and adds them to the outdated modules set.
* Modules that call module.hot.invalidate() are queued and processed here.
*
* @param outdatedModules - The set of already outdated modules
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInvalidatedModules(outdatedModules, autoAcceptRootModules) {
* @param outdatedModules - The current set of outdated modules
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInvalidatedModules(outdatedModules, autoAcceptAtRoot) {
if (queuedInvalidatedModules.size > 0) {
computedInvalidatedModules(queuedInvalidatedModules, autoAcceptRootModules).forEach((moduleId)=>{
computedInvalidatedModules(queuedInvalidatedModules, autoAcceptAtRoot).forEach((moduleId)=>{
outdatedModules.add(moduleId);
});
queuedInvalidatedModules.clear();
......@@ -1245,7 +1258,7 @@ function formatDependencyChain(dependencyChain) {
break;
}
default:
throw new Error(`Unknown merged chunk update`);
throw new Error('Unknown merged chunk update type');
}
}
// If a module was added from one chunk and deleted from another in the same update,
......@@ -1281,8 +1294,8 @@ function formatDependencyChain(dependencyChain) {
* @param added - Map of added modules
* @param modified - Map of modified modules
* @param evalModuleEntry - Function to compile module code
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptRootModules) {
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot) {
const newModuleFactories = new Map();
// Compile added modules
for (const [moduleId, entry] of added){
......@@ -1291,7 +1304,8 @@ function formatDependencyChain(dependencyChain) {
}
}
// Walk dependency tree to find all modules affected by modifications
const outdatedModules = computedInvalidatedModules(modified.keys(), autoAcceptRootModules);
const outdatedModules = computedInvalidatedModules(modified.keys(), autoAcceptAtRoot);
// Compile modified modules
for (const [moduleId, entry] of modified){
newModuleFactories.set(moduleId, evalModuleEntry(entry));
}
......@@ -1336,9 +1350,9 @@ function formatDependencyChain(dependencyChain) {
* Internal implementation that orchestrates the full HMR update flow:
* invalidation, disposal, and application of new modules.
*
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules) {
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptRootModules);
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot) {
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptAtRoot);
// Find self-accepted modules to re-instantiate
const outdatedSelfAcceptedModules = computeOutdatedSelfAcceptedModules(outdatedModules);
// Run dispose handlers, save hot.data, clear caches
......@@ -1353,16 +1367,20 @@ function formatDependencyChain(dependencyChain) {
}
// Recursively apply any queued invalidations from new module execution
if (queuedInvalidatedModules.size > 0) {
applyInternal(new Set(), [], new Map(), moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules);
applyInternal(new Set(), [], new Map(), moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot);
}
}
/**
* Main entry point for applying an ECMAScript merged update.
* This is called by both browser and Node.js runtimes with platform-specific callbacks.
*
* @param options.autoAcceptAtRoot - If true, root modules auto-accept updates without explicit
* module.hot.accept(). Used for server-side HMR where pages
* auto-accept at the top level.
*/ function applyEcmascriptMergedUpdateShared(options) {
const { added, modified, disposedModules, evalModuleEntry, instantiateModuleFn, applyModuleFactoryNameFn, moduleFactories, devModuleCache, autoAcceptRootModules } = options;
const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptRootModules);
applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules);
const { added, modified, disposedModules, evalModuleEntry, instantiateModule, applyModuleFactoryName, moduleFactories, devModuleCache, autoAcceptAtRoot } = options;
const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot);
applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModule, applyModuleFactoryName, autoAcceptAtRoot);
}
/// <reference path="../../../shared/runtime/dev-globals.d.ts" />
/// <reference path="../../../shared/runtime/dev-protocol.d.ts" />
......@@ -1601,11 +1619,12 @@ function applyEcmascriptMergedUpdate(update) {
modified,
disposedModules,
evalModuleEntry: _eval,
instantiateModuleFn: instantiateModule,
applyModuleFactoryNameFn: applyModuleFactoryName,
instantiateModule,
applyModuleFactoryName,
moduleFactories,
devModuleCache,
autoAcceptRootModules: false
runtimeModules,
autoAcceptAtRoot: false
});
}
function handleApply(chunkListPath, update) {
......
......@@ -853,11 +853,11 @@ class UpdateApplyError extends Error {
*/ // eslint-disable-next-line @typescript-eslint/no-unused-vars
function trackModuleImport(parentModule, childModuleId, childModule) {
// Record that parent imports child
if (parentModule.children.indexOf(childModuleId) === -1) {
if (parentModule.children && parentModule.children.indexOf(childModuleId) === -1) {
parentModule.children.push(childModuleId);
}
// Record that child is imported by parent
if (childModule && childModule.parents.indexOf(parentModule.id) === -1) {
if (childModule && childModule.parents && childModule.parents.indexOf(parentModule.id) === -1) {
childModule.parents.push(parentModule.id);
}
}
......@@ -869,11 +869,10 @@ function formatDependencyChain(dependencyChain) {
* Returns information about whether the update can be accepted and which
* modules need to be invalidated.
*
* Copied directly from browser implementation.
*
* @param moduleId - The module to check for effects
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function getAffectedModuleEffects(moduleId, autoAcceptRootModules) {
* @param moduleId - The module that changed
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept().
* This is used for server-side HMR where pages auto-accept at the top level.
*/ function getAffectedModuleEffects(moduleId, autoAcceptAtRoot) {
const outdatedModules = new Set();
const queue = [
{
......@@ -883,20 +882,29 @@ function formatDependencyChain(dependencyChain) {
];
let nextItem;
while(nextItem = queue.shift()){
const { moduleId: currentModuleId, dependencyChain } = nextItem;
const { moduleId, dependencyChain } = nextItem;
if (moduleId != null) {
if (outdatedModules.has(moduleId)) {
continue;
}
outdatedModules.add(moduleId);
}
// We've arrived at the runtime of the chunk, which means that nothing
// else above can accept this update.
if (currentModuleId === undefined) {
if (moduleId === undefined) {
if (autoAcceptAtRoot) {
return {
type: 'accepted',
moduleId,
outdatedModules
};
}
return {
type: 'unaccepted',
dependencyChain
};
}
if (outdatedModules.has(currentModuleId)) {
continue;
}
outdatedModules.add(currentModuleId);
const module = devModuleCache[currentModuleId];
const module = devModuleCache[moduleId];
const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before.
......@@ -907,15 +915,18 @@ function formatDependencyChain(dependencyChain) {
return {
type: 'self-declined',
dependencyChain,
moduleId: currentModuleId
moduleId
};
}
if (runtimeModules.has(currentModuleId)) {
if (runtimeModules.has(moduleId)) {
if (autoAcceptAtRoot) {
continue;
}
queue.push({
moduleId: undefined,
dependencyChain: [
...dependencyChain,
currentModuleId
moduleId
]
});
continue;
......@@ -931,10 +942,14 @@ function formatDependencyChain(dependencyChain) {
moduleId: parentId,
dependencyChain: [
...dependencyChain,
currentModuleId
moduleId
]
});
}
// If no parents and we're at a root module, auto-accept if configured
if (module.parents.length === 0 && autoAcceptAtRoot) {
continue;
}
}
return {
type: 'accepted',
......@@ -945,14 +960,12 @@ function formatDependencyChain(dependencyChain) {
/**
* Computes all modules that need to be invalidated based on which modules changed.
*
* Copied directly from browser implementation.
*
* @param invalidated - The modules to check for invalidation
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computedInvalidatedModules(invalidated, autoAcceptRootModules) {
* @param invalidated - The modules that have been invalidated
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computedInvalidatedModules(invalidated, autoAcceptAtRoot) {
const outdatedModules = new Set();
for (const moduleId of invalidated){
const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules);
const effect = getAffectedModuleEffects(moduleId, autoAcceptAtRoot);
switch(effect.type){
case 'unaccepted':
throw new UpdateApplyError(`cannot apply update: unaccepted module. ${formatDependencyChain(effect.dependencyChain)}.`, effect.dependencyChain);
......@@ -1040,11 +1053,11 @@ function formatDependencyChain(dependencyChain) {
* Processes queued invalidated modules and adds them to the outdated modules set.
* Modules that call module.hot.invalidate() are queued and processed here.
*
* @param outdatedModules - The set of already outdated modules
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInvalidatedModules(outdatedModules, autoAcceptRootModules) {
* @param outdatedModules - The current set of outdated modules
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInvalidatedModules(outdatedModules, autoAcceptAtRoot) {
if (queuedInvalidatedModules.size > 0) {
computedInvalidatedModules(queuedInvalidatedModules, autoAcceptRootModules).forEach((moduleId)=>{
computedInvalidatedModules(queuedInvalidatedModules, autoAcceptAtRoot).forEach((moduleId)=>{
outdatedModules.add(moduleId);
});
queuedInvalidatedModules.clear();
......@@ -1245,7 +1258,7 @@ function formatDependencyChain(dependencyChain) {
break;
}
default:
throw new Error(`Unknown merged chunk update`);
throw new Error('Unknown merged chunk update type');
}
}
// If a module was added from one chunk and deleted from another in the same update,
......@@ -1281,8 +1294,8 @@ function formatDependencyChain(dependencyChain) {
* @param added - Map of added modules
* @param modified - Map of modified modules
* @param evalModuleEntry - Function to compile module code
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptRootModules) {
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot) {
const newModuleFactories = new Map();
// Compile added modules
for (const [moduleId, entry] of added){
......@@ -1291,7 +1304,8 @@ function formatDependencyChain(dependencyChain) {
}
}
// Walk dependency tree to find all modules affected by modifications
const outdatedModules = computedInvalidatedModules(modified.keys(), autoAcceptRootModules);
const outdatedModules = computedInvalidatedModules(modified.keys(), autoAcceptAtRoot);
// Compile modified modules
for (const [moduleId, entry] of modified){
newModuleFactories.set(moduleId, evalModuleEntry(entry));
}
......@@ -1336,9 +1350,9 @@ function formatDependencyChain(dependencyChain) {
* Internal implementation that orchestrates the full HMR update flow:
* invalidation, disposal, and application of new modules.
*
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules) {
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptRootModules);
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot) {
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptAtRoot);
// Find self-accepted modules to re-instantiate
const outdatedSelfAcceptedModules = computeOutdatedSelfAcceptedModules(outdatedModules);
// Run dispose handlers, save hot.data, clear caches
......@@ -1353,16 +1367,20 @@ function formatDependencyChain(dependencyChain) {
}
// Recursively apply any queued invalidations from new module execution
if (queuedInvalidatedModules.size > 0) {
applyInternal(new Set(), [], new Map(), moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules);
applyInternal(new Set(), [], new Map(), moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot);
}
}
/**
* Main entry point for applying an ECMAScript merged update.
* This is called by both browser and Node.js runtimes with platform-specific callbacks.
*
* @param options.autoAcceptAtRoot - If true, root modules auto-accept updates without explicit
* module.hot.accept(). Used for server-side HMR where pages
* auto-accept at the top level.
*/ function applyEcmascriptMergedUpdateShared(options) {
const { added, modified, disposedModules, evalModuleEntry, instantiateModuleFn, applyModuleFactoryNameFn, moduleFactories, devModuleCache, autoAcceptRootModules } = options;
const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptRootModules);
applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules);
const { added, modified, disposedModules, evalModuleEntry, instantiateModule, applyModuleFactoryName, moduleFactories, devModuleCache, autoAcceptAtRoot } = options;
const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot);
applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModule, applyModuleFactoryName, autoAcceptAtRoot);
}
/// <reference path="../../../shared/runtime/dev-globals.d.ts" />
/// <reference path="../../../shared/runtime/dev-protocol.d.ts" />
......@@ -1601,11 +1619,12 @@ function applyEcmascriptMergedUpdate(update) {
modified,
disposedModules,
evalModuleEntry: _eval,
instantiateModuleFn: instantiateModule,
applyModuleFactoryNameFn: applyModuleFactoryName,
instantiateModule,
applyModuleFactoryName,
moduleFactories,
devModuleCache,
autoAcceptRootModules: false
runtimeModules,
autoAcceptAtRoot: false
});
}
function handleApply(chunkListPath, update) {
......
......@@ -853,11 +853,11 @@ class UpdateApplyError extends Error {
*/ // eslint-disable-next-line @typescript-eslint/no-unused-vars
function trackModuleImport(parentModule, childModuleId, childModule) {
// Record that parent imports child
if (parentModule.children.indexOf(childModuleId) === -1) {
if (parentModule.children && parentModule.children.indexOf(childModuleId) === -1) {
parentModule.children.push(childModuleId);
}
// Record that child is imported by parent
if (childModule && childModule.parents.indexOf(parentModule.id) === -1) {
if (childModule && childModule.parents && childModule.parents.indexOf(parentModule.id) === -1) {
childModule.parents.push(parentModule.id);
}
}
......@@ -869,11 +869,10 @@ function formatDependencyChain(dependencyChain) {
* Returns information about whether the update can be accepted and which
* modules need to be invalidated.
*
* Copied directly from browser implementation.
*
* @param moduleId - The module to check for effects
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function getAffectedModuleEffects(moduleId, autoAcceptRootModules) {
* @param moduleId - The module that changed
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept().
* This is used for server-side HMR where pages auto-accept at the top level.
*/ function getAffectedModuleEffects(moduleId, autoAcceptAtRoot) {
const outdatedModules = new Set();
const queue = [
{
......@@ -883,20 +882,29 @@ function formatDependencyChain(dependencyChain) {
];
let nextItem;
while(nextItem = queue.shift()){
const { moduleId: currentModuleId, dependencyChain } = nextItem;
const { moduleId, dependencyChain } = nextItem;
if (moduleId != null) {
if (outdatedModules.has(moduleId)) {
continue;
}
outdatedModules.add(moduleId);
}
// We've arrived at the runtime of the chunk, which means that nothing
// else above can accept this update.
if (currentModuleId === undefined) {
if (moduleId === undefined) {
if (autoAcceptAtRoot) {
return {
type: 'accepted',
moduleId,
outdatedModules
};
}
return {
type: 'unaccepted',
dependencyChain
};
}
if (outdatedModules.has(currentModuleId)) {
continue;
}
outdatedModules.add(currentModuleId);
const module = devModuleCache[currentModuleId];
const module = devModuleCache[moduleId];
const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before.
......@@ -907,15 +915,18 @@ function formatDependencyChain(dependencyChain) {
return {
type: 'self-declined',
dependencyChain,
moduleId: currentModuleId
moduleId
};
}
if (runtimeModules.has(currentModuleId)) {
if (runtimeModules.has(moduleId)) {
if (autoAcceptAtRoot) {
continue;
}
queue.push({
moduleId: undefined,
dependencyChain: [
...dependencyChain,
currentModuleId
moduleId
]
});
continue;
......@@ -931,10 +942,14 @@ function formatDependencyChain(dependencyChain) {
moduleId: parentId,
dependencyChain: [
...dependencyChain,
currentModuleId
moduleId
]
});
}
// If no parents and we're at a root module, auto-accept if configured
if (module.parents.length === 0 && autoAcceptAtRoot) {
continue;
}
}
return {
type: 'accepted',
......@@ -945,14 +960,12 @@ function formatDependencyChain(dependencyChain) {
/**
* Computes all modules that need to be invalidated based on which modules changed.
*
* Copied directly from browser implementation.
*
* @param invalidated - The modules to check for invalidation
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computedInvalidatedModules(invalidated, autoAcceptRootModules) {
* @param invalidated - The modules that have been invalidated
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computedInvalidatedModules(invalidated, autoAcceptAtRoot) {
const outdatedModules = new Set();
for (const moduleId of invalidated){
const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules);
const effect = getAffectedModuleEffects(moduleId, autoAcceptAtRoot);
switch(effect.type){
case 'unaccepted':
throw new UpdateApplyError(`cannot apply update: unaccepted module. ${formatDependencyChain(effect.dependencyChain)}.`, effect.dependencyChain);
......@@ -1040,11 +1053,11 @@ function formatDependencyChain(dependencyChain) {
* Processes queued invalidated modules and adds them to the outdated modules set.
* Modules that call module.hot.invalidate() are queued and processed here.
*
* @param outdatedModules - The set of already outdated modules
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInvalidatedModules(outdatedModules, autoAcceptRootModules) {
* @param outdatedModules - The current set of outdated modules
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInvalidatedModules(outdatedModules, autoAcceptAtRoot) {
if (queuedInvalidatedModules.size > 0) {
computedInvalidatedModules(queuedInvalidatedModules, autoAcceptRootModules).forEach((moduleId)=>{
computedInvalidatedModules(queuedInvalidatedModules, autoAcceptAtRoot).forEach((moduleId)=>{
outdatedModules.add(moduleId);
});
queuedInvalidatedModules.clear();
......@@ -1245,7 +1258,7 @@ function formatDependencyChain(dependencyChain) {
break;
}
default:
throw new Error(`Unknown merged chunk update`);
throw new Error('Unknown merged chunk update type');
}
}
// If a module was added from one chunk and deleted from another in the same update,
......@@ -1281,8 +1294,8 @@ function formatDependencyChain(dependencyChain) {
* @param added - Map of added modules
* @param modified - Map of modified modules
* @param evalModuleEntry - Function to compile module code
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptRootModules) {
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot) {
const newModuleFactories = new Map();
// Compile added modules
for (const [moduleId, entry] of added){
......@@ -1291,7 +1304,8 @@ function formatDependencyChain(dependencyChain) {
}
}
// Walk dependency tree to find all modules affected by modifications
const outdatedModules = computedInvalidatedModules(modified.keys(), autoAcceptRootModules);
const outdatedModules = computedInvalidatedModules(modified.keys(), autoAcceptAtRoot);
// Compile modified modules
for (const [moduleId, entry] of modified){
newModuleFactories.set(moduleId, evalModuleEntry(entry));
}
......@@ -1336,9 +1350,9 @@ function formatDependencyChain(dependencyChain) {
* Internal implementation that orchestrates the full HMR update flow:
* invalidation, disposal, and application of new modules.
*
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules) {
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptRootModules);
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot) {
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptAtRoot);
// Find self-accepted modules to re-instantiate
const outdatedSelfAcceptedModules = computeOutdatedSelfAcceptedModules(outdatedModules);
// Run dispose handlers, save hot.data, clear caches
......@@ -1353,16 +1367,20 @@ function formatDependencyChain(dependencyChain) {
}
// Recursively apply any queued invalidations from new module execution
if (queuedInvalidatedModules.size > 0) {
applyInternal(new Set(), [], new Map(), moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules);
applyInternal(new Set(), [], new Map(), moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot);
}
}
/**
* Main entry point for applying an ECMAScript merged update.
* This is called by both browser and Node.js runtimes with platform-specific callbacks.
*
* @param options.autoAcceptAtRoot - If true, root modules auto-accept updates without explicit
* module.hot.accept(). Used for server-side HMR where pages
* auto-accept at the top level.
*/ function applyEcmascriptMergedUpdateShared(options) {
const { added, modified, disposedModules, evalModuleEntry, instantiateModuleFn, applyModuleFactoryNameFn, moduleFactories, devModuleCache, autoAcceptRootModules } = options;
const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptRootModules);
applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules);
const { added, modified, disposedModules, evalModuleEntry, instantiateModule, applyModuleFactoryName, moduleFactories, devModuleCache, autoAcceptAtRoot } = options;
const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot);
applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModule, applyModuleFactoryName, autoAcceptAtRoot);
}
/// <reference path="../../../shared/runtime/dev-globals.d.ts" />
/// <reference path="../../../shared/runtime/dev-protocol.d.ts" />
......@@ -1601,11 +1619,12 @@ function applyEcmascriptMergedUpdate(update) {
modified,
disposedModules,
evalModuleEntry: _eval,
instantiateModuleFn: instantiateModule,
applyModuleFactoryNameFn: applyModuleFactoryName,
instantiateModule,
applyModuleFactoryName,
moduleFactories,
devModuleCache,
autoAcceptRootModules: false
runtimeModules,
autoAcceptAtRoot: false
});
}
function handleApply(chunkListPath, update) {
......
......@@ -853,11 +853,11 @@ class UpdateApplyError extends Error {
*/ // eslint-disable-next-line @typescript-eslint/no-unused-vars
function trackModuleImport(parentModule, childModuleId, childModule) {
// Record that parent imports child
if (parentModule.children.indexOf(childModuleId) === -1) {
if (parentModule.children && parentModule.children.indexOf(childModuleId) === -1) {
parentModule.children.push(childModuleId);
}
// Record that child is imported by parent
if (childModule && childModule.parents.indexOf(parentModule.id) === -1) {
if (childModule && childModule.parents && childModule.parents.indexOf(parentModule.id) === -1) {
childModule.parents.push(parentModule.id);
}
}
......@@ -869,11 +869,10 @@ function formatDependencyChain(dependencyChain) {
* Returns information about whether the update can be accepted and which
* modules need to be invalidated.
*
* Copied directly from browser implementation.
*
* @param moduleId - The module to check for effects
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function getAffectedModuleEffects(moduleId, autoAcceptRootModules) {
* @param moduleId - The module that changed
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept().
* This is used for server-side HMR where pages auto-accept at the top level.
*/ function getAffectedModuleEffects(moduleId, autoAcceptAtRoot) {
const outdatedModules = new Set();
const queue = [
{
......@@ -883,20 +882,29 @@ function formatDependencyChain(dependencyChain) {
];
let nextItem;
while(nextItem = queue.shift()){
const { moduleId: currentModuleId, dependencyChain } = nextItem;
const { moduleId, dependencyChain } = nextItem;
if (moduleId != null) {
if (outdatedModules.has(moduleId)) {
continue;
}
outdatedModules.add(moduleId);
}
// We've arrived at the runtime of the chunk, which means that nothing
// else above can accept this update.
if (currentModuleId === undefined) {
if (moduleId === undefined) {
if (autoAcceptAtRoot) {
return {
type: 'accepted',
moduleId,
outdatedModules
};
}
return {
type: 'unaccepted',
dependencyChain
};
}
if (outdatedModules.has(currentModuleId)) {
continue;
}
outdatedModules.add(currentModuleId);
const module = devModuleCache[currentModuleId];
const module = devModuleCache[moduleId];
const hotState = moduleHotState.get(module);
if (// The module is not in the cache. Since this is a "modified" update,
// it means that the module was never instantiated before.
......@@ -907,15 +915,18 @@ function formatDependencyChain(dependencyChain) {
return {
type: 'self-declined',
dependencyChain,
moduleId: currentModuleId
moduleId
};
}
if (runtimeModules.has(currentModuleId)) {
if (runtimeModules.has(moduleId)) {
if (autoAcceptAtRoot) {
continue;
}
queue.push({
moduleId: undefined,
dependencyChain: [
...dependencyChain,
currentModuleId
moduleId
]
});
continue;
......@@ -931,10 +942,14 @@ function formatDependencyChain(dependencyChain) {
moduleId: parentId,
dependencyChain: [
...dependencyChain,
currentModuleId
moduleId
]
});
}
// If no parents and we're at a root module, auto-accept if configured
if (module.parents.length === 0 && autoAcceptAtRoot) {
continue;
}
}
return {
type: 'accepted',
......@@ -945,14 +960,12 @@ function formatDependencyChain(dependencyChain) {
/**
* Computes all modules that need to be invalidated based on which modules changed.
*
* Copied directly from browser implementation.
*
* @param invalidated - The modules to check for invalidation
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computedInvalidatedModules(invalidated, autoAcceptRootModules) {
* @param invalidated - The modules that have been invalidated
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computedInvalidatedModules(invalidated, autoAcceptAtRoot) {
const outdatedModules = new Set();
for (const moduleId of invalidated){
const effect = getAffectedModuleEffects(moduleId, autoAcceptRootModules);
const effect = getAffectedModuleEffects(moduleId, autoAcceptAtRoot);
switch(effect.type){
case 'unaccepted':
throw new UpdateApplyError(`cannot apply update: unaccepted module. ${formatDependencyChain(effect.dependencyChain)}.`, effect.dependencyChain);
......@@ -1040,11 +1053,11 @@ function formatDependencyChain(dependencyChain) {
* Processes queued invalidated modules and adds them to the outdated modules set.
* Modules that call module.hot.invalidate() are queued and processed here.
*
* @param outdatedModules - The set of already outdated modules
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInvalidatedModules(outdatedModules, autoAcceptRootModules) {
* @param outdatedModules - The current set of outdated modules
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInvalidatedModules(outdatedModules, autoAcceptAtRoot) {
if (queuedInvalidatedModules.size > 0) {
computedInvalidatedModules(queuedInvalidatedModules, autoAcceptRootModules).forEach((moduleId)=>{
computedInvalidatedModules(queuedInvalidatedModules, autoAcceptAtRoot).forEach((moduleId)=>{
outdatedModules.add(moduleId);
});
queuedInvalidatedModules.clear();
......@@ -1245,7 +1258,7 @@ function formatDependencyChain(dependencyChain) {
break;
}
default:
throw new Error(`Unknown merged chunk update`);
throw new Error('Unknown merged chunk update type');
}
}
// If a module was added from one chunk and deleted from another in the same update,
......@@ -1281,8 +1294,8 @@ function formatDependencyChain(dependencyChain) {
* @param added - Map of added modules
* @param modified - Map of modified modules
* @param evalModuleEntry - Function to compile module code
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptRootModules) {
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot) {
const newModuleFactories = new Map();
// Compile added modules
for (const [moduleId, entry] of added){
......@@ -1291,7 +1304,8 @@ function formatDependencyChain(dependencyChain) {
}
}
// Walk dependency tree to find all modules affected by modifications
const outdatedModules = computedInvalidatedModules(modified.keys(), autoAcceptRootModules);
const outdatedModules = computedInvalidatedModules(modified.keys(), autoAcceptAtRoot);
// Compile modified modules
for (const [moduleId, entry] of modified){
newModuleFactories.set(moduleId, evalModuleEntry(entry));
}
......@@ -1336,9 +1350,9 @@ function formatDependencyChain(dependencyChain) {
* Internal implementation that orchestrates the full HMR update flow:
* invalidation, disposal, and application of new modules.
*
* @param autoAcceptRootModules - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules) {
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptRootModules);
* @param autoAcceptAtRoot - If true, root modules auto-accept updates without explicit module.hot.accept()
*/ function applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot) {
outdatedModules = applyInvalidatedModules(outdatedModules, autoAcceptAtRoot);
// Find self-accepted modules to re-instantiate
const outdatedSelfAcceptedModules = computeOutdatedSelfAcceptedModules(outdatedModules);
// Run dispose handlers, save hot.data, clear caches
......@@ -1353,16 +1367,20 @@ function formatDependencyChain(dependencyChain) {
}
// Recursively apply any queued invalidations from new module execution
if (queuedInvalidatedModules.size > 0) {
applyInternal(new Set(), [], new Map(), moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules);
applyInternal(new Set(), [], new Map(), moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptAtRoot);
}
}
/**
* Main entry point for applying an ECMAScript merged update.
* This is called by both browser and Node.js runtimes with platform-specific callbacks.
*
* @param options.autoAcceptAtRoot - If true, root modules auto-accept updates without explicit
* module.hot.accept(). Used for server-side HMR where pages
* auto-accept at the top level.
*/ function applyEcmascriptMergedUpdateShared(options) {
const { added, modified, disposedModules, evalModuleEntry, instantiateModuleFn, applyModuleFactoryNameFn, moduleFactories, devModuleCache, autoAcceptRootModules } = options;
const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptRootModules);
applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModuleFn, applyModuleFactoryNameFn, autoAcceptRootModules);
const { added, modified, disposedModules, evalModuleEntry, instantiateModule, applyModuleFactoryName, moduleFactories, devModuleCache, autoAcceptAtRoot } = options;
const { outdatedModules, newModuleFactories } = computeOutdatedModules(added, modified, evalModuleEntry, autoAcceptAtRoot);
applyInternal(outdatedModules, disposedModules, newModuleFactories, moduleFactories, devModuleCache, instantiateModule, applyModuleFactoryName, autoAcceptAtRoot);
}
/// <reference path="../../../shared/runtime/dev-globals.d.ts" />
/// <reference path="../../../shared/runtime/dev-protocol.d.ts" />
......@@ -1601,11 +1619,12 @@ function applyEcmascriptMergedUpdate(update) {
modified,
disposedModules,
evalModuleEntry: _eval,
instantiateModuleFn: instantiateModule,
applyModuleFactoryNameFn: applyModuleFactoryName,
instantiateModule,
applyModuleFactoryName,
moduleFactories,
devModuleCache,
autoAcceptRootModules: false
runtimeModules,
autoAcceptAtRoot: false
});
}
function handleApply(chunkListPath, update) {
......
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