|
| 1 | +import { nanoid } from 'nanoid/non-secure' |
| 2 | +import type { DevRuntime as DevRuntimeType } from 'rolldown/experimental/runtime-types' |
| 3 | +import { |
| 4 | + BundledDevHMRClient, |
| 5 | + BundledDevHMRContext, |
| 6 | +} from './bundledDevHmrClient' |
| 7 | +import { |
| 8 | + base, |
| 9 | + clearOverlayOrReloadOnFirstUpdate, |
| 10 | + pageReload, |
| 11 | + registerBundledDevClient, |
| 12 | + removeStyle, |
| 13 | + transport, |
| 14 | + updateStyle, |
| 15 | +} from './client' |
| 16 | + |
| 17 | +// keep the same public exports as `client.ts`, which this entry replaces when inlined |
| 18 | +export { |
| 19 | + createHotContext, |
| 20 | + injectQuery, |
| 21 | + removeStyle, |
| 22 | + updateStyle, |
| 23 | + ErrorOverlay, |
| 24 | +} from './client' |
| 25 | + |
| 26 | +// injected by rolldown's hmr plugin into the bundle prelude, ahead of this client |
| 27 | +declare const DevRuntime: typeof DevRuntimeType |
| 28 | + |
| 29 | +if (typeof DevRuntime !== 'undefined') { |
| 30 | + class ViteDevRuntime extends DevRuntime { |
| 31 | + override createModuleHotContext(moduleId: string) { |
| 32 | + const ctx = new BundledDevHMRContext(bundledDevHmrClient, moduleId) |
| 33 | + // @ts-expect-error TODO: support CSS properly |
| 34 | + ctx._internal = { updateStyle, removeStyle } |
| 35 | + return ctx |
| 36 | + } |
| 37 | + } |
| 38 | + |
| 39 | + const clientId = nanoid() |
| 40 | + |
| 41 | + transport.send({ |
| 42 | + type: 'custom', |
| 43 | + event: 'vite:client-connected', |
| 44 | + data: { clientId }, |
| 45 | + }) |
| 46 | + |
| 47 | + const runtime = ((globalThis as any).__rolldown_runtime__ ??= |
| 48 | + new ViteDevRuntime(clientId)) |
| 49 | + |
| 50 | + const bundledDevHmrClient = new BundledDevHMRClient( |
| 51 | + { |
| 52 | + error: (err) => console.error('[vite]', err), |
| 53 | + debug: (...msg) => console.debug('[vite]', ...msg), |
| 54 | + }, |
| 55 | + transport, |
| 56 | + runtime, |
| 57 | + { |
| 58 | + base, |
| 59 | + beforeApply: clearOverlayOrReloadOnFirstUpdate, |
| 60 | + pageReload, |
| 61 | + }, |
| 62 | + ) |
| 63 | + registerBundledDevClient(bundledDevHmrClient) |
| 64 | + |
| 65 | + runtime.hooks = { |
| 66 | + createModuleHotContext: (id: string) => runtime.createModuleHotContext(id), |
| 67 | + onModuleCacheRemoval: (id: string) => |
| 68 | + bundledDevHmrClient.handleModuleCacheRemoval(id), |
| 69 | + } |
| 70 | +} |
0 commit comments