Skip to content

Commit

Permalink
refactor!: rename to HMRPayload to HotPayload and remove HMRBroadcaster
Browse files Browse the repository at this point in the history
  • Loading branch information
ArnaudBarre committed May 22, 2024
1 parent 4d03124 commit c568d1e
Show file tree
Hide file tree
Showing 18 changed files with 61 additions and 150 deletions.
4 changes: 2 additions & 2 deletions packages/vite/src/client/client.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ErrorPayload, HMRPayload } from 'types/hmrPayload'
import type { ErrorPayload, HotPayload } from 'types/hotPayload'
import type { ViteHotContext } from 'types/hot'
import type { InferCustomEventPayload } from 'types/customEvent'
import { HMRClient, HMRContext } from '../shared/hmr'
Expand Down Expand Up @@ -172,7 +172,7 @@ const hmrClient = new HMRClient(
},
)

async function handleMessage(payload: HMRPayload) {
async function handleMessage(payload: HotPayload) {
switch (payload.type) {
case 'connected':
console.debug(`[vite] connected.`)
Expand Down
2 changes: 1 addition & 1 deletion packages/vite/src/client/overlay.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ErrorPayload } from 'types/hmrPayload'
import type { ErrorPayload } from 'types/hotPayload'

// injected by the hmr plugin when served
declare const __BASE__: string
Expand Down
6 changes: 3 additions & 3 deletions packages/vite/src/module-runner/hmrHandler.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import type { HMRPayload } from 'types/hmrPayload'
import type { HotPayload } from 'types/hotPayload'
import { slash, unwrapId } from '../shared/utils'
import type { ModuleRunner } from './runner'

// updates to HMR should go one after another. It is possible to trigger another update during the invalidation for example.
export function createHMRHandler(
runner: ModuleRunner,
): (payload: HMRPayload) => Promise<void> {
): (payload: HotPayload) => Promise<void> {
const queue = new Queue()
return (payload) => queue.enqueue(() => handleHMRPayload(runner, payload))
}

export async function handleHMRPayload(
runner: ModuleRunner,
payload: HMRPayload,
payload: HotPayload,
): Promise<void> {
const hmrClient = runner.hmrClient
if (!hmrClient || runner.isDestroyed()) return
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/module-runner/types.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import type { ViteHotContext } from 'types/hot'
import type { HMRPayload } from 'types/hmrPayload'
import type { HotPayload } from 'types/hotPayload'
import type { HMRConnection, HMRLogger } from '../shared/hmr'
import type {
DefineImportMetadata,
Expand All @@ -24,7 +24,7 @@ export interface ModuleRunnerHMRConnection extends HMRConnection {
* Configure how HMR is handled when this connection triggers an update.
* This method expects that connection will start listening for HMR updates and call this callback when it's received.
*/
onUpdate(callback: (payload: HMRPayload) => void): void
onUpdate(callback: (payload: HotPayload) => void): void
}

export interface ModuleRunnerImportMeta extends ImportMeta {
Expand Down
7 changes: 3 additions & 4 deletions packages/vite/src/node/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,7 @@ export type {
export type { HmrOptions, HmrContext, HotUpdateContext } from './server/hmr'

export type {
HMRBroadcaster,
HMRChannel,
HotChannel,
ServerHMRChannel,
HMRBroadcasterClient,
} from './server/hmr'
Expand All @@ -164,15 +163,15 @@ export type { ServerModuleRunnerOptions } from './ssr/runtime/serverModuleRunner
export type { BindCLIShortcutsOptions, CLIShortcut } from './shortcuts'

export type {
HMRPayload,
HotPayload,
ConnectedPayload,
UpdatePayload,
Update,
FullReloadPayload,
CustomPayload,
PrunePayload,
ErrorPayload,
} from 'types/hmrPayload'
} from 'types/hotPayload'
export type {
CustomEventMap,
InferCustomEventPayload,
Expand Down
4 changes: 2 additions & 2 deletions packages/vite/src/node/plugins/esbuild.ts
Original file line number Diff line number Diff line change
Expand Up @@ -479,7 +479,7 @@ export async function reloadOnTsconfigChange(
// any json file in the tsconfig cache could have been used to compile ts
if (
path.basename(changedFile) === 'tsconfig.json' ||
changedFile.endsWith('.json') /*
changedFile.endsWith('.json') /*
TODO: the tsconfckCache?.clear() line will make this fail if there are several servers
we may need a cache per server if we don't want all servers to share the reset
leaving it commented for now because it should still work
Expand All @@ -500,7 +500,7 @@ export async function reloadOnTsconfigChange(
tsconfckCache?.clear()

// force full reload
server.hot.send({
server.ws.send({
type: 'full-reload',
path: '*',
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ async function getDevEnvironment(
// @ts-expect-error This plugin requires a ViteDevServer instance.
config.plugins = config.plugins.filter((p) => !p.name.includes('pre-alias'))

const environment = new DevEnvironment('client', config)
const environment = new DevEnvironment('client', config, { hot: false })
await environment.init()

return environment
Expand Down
24 changes: 12 additions & 12 deletions packages/vite/src/node/server/environment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import {
import { resolveEnvironmentPlugins } from '../plugin'
import type { DepsOptimizer } from '../optimizer'
import { EnvironmentModuleGraph } from './moduleGraph'
import type { HMRChannel } from './hmr'
import type { HotChannel } from './hmr'
import { createNoopHMRChannel, getShortName, updateModules } from './hmr'
import { transformRequest } from './transformRequest'
import type { TransformResult } from './transformRequest'
Expand All @@ -31,7 +31,7 @@ import type { RemoteEnvironmentTransport } from './environmentTransport'
import type { EnvironmentPluginContainer } from './pluginContainer'

export interface DevEnvironmentSetup {
hot?: false | HMRChannel
hot: false | HotChannel
watcher?: FSWatcher
options?: EnvironmentOptions
runner?: FetchModuleOptions & {
Expand Down Expand Up @@ -96,18 +96,18 @@ export class DevEnvironment extends Environment {
* @example
* environment.hot.send({ type: 'full-reload' })
*/
hot: HMRChannel
hot: HotChannel
constructor(
name: string,
config: ResolvedConfig,
setup?: DevEnvironmentSetup,
setup: DevEnvironmentSetup,
) {
let options =
config.environments[name] ?? getDefaultResolvedEnvironmentOptions(config)
if (setup?.options) {
if (setup.options) {
options = mergeConfig(
options,
setup?.options,
setup.options,
) as ResolvedEnvironmentOptions
}
super(name, config, options)
Expand All @@ -118,17 +118,17 @@ export class DevEnvironment extends Environment {
this.pluginContainer!.resolveId(url, undefined),
)

this.hot = setup?.hot || createNoopHMRChannel()
this.watcher = setup?.watcher
this.hot = setup.hot || createNoopHMRChannel()
this.watcher = setup.watcher

this._onCrawlEndCallbacks = []
this._crawlEndFinder = setupOnCrawlEnd(() => {
this._onCrawlEndCallbacks.forEach((cb) => cb())
})

const ssrRunnerOptions = setup?.runner || {}
const ssrRunnerOptions = setup.runner || {}
this._ssrRunnerOptions = ssrRunnerOptions
setup?.runner?.transport?.register(this)
setup.runner?.transport?.register(this)

this.hot.on('vite:invalidate', async ({ path, message }) => {
invalidateModule(this, {
Expand All @@ -138,8 +138,8 @@ export class DevEnvironment extends Environment {
})

const { optimizeDeps } = this.options.dev
if (setup?.depsOptimizer) {
this.depsOptimizer = setup?.depsOptimizer
if (setup.depsOptimizer) {
this.depsOptimizer = setup.depsOptimizer
} else if (
optimizeDeps?.noDiscovery &&
optimizeDeps?.include?.length === 0
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { asyncFunctionDeclarationPaddingLineCount } from '../../../shared/utils'
export function createNodeDevEnvironment(
name: string,
config: ResolvedConfig,
options?: DevEnvironmentSetup,
options: DevEnvironmentSetup,
): DevEnvironment {
return new DevEnvironment(name, config, {
...options,
Expand Down
83 changes: 7 additions & 76 deletions packages/vite/src/node/server/hmr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import path from 'node:path'
import type { Server } from 'node:http'
import { EventEmitter } from 'node:events'
import colors from 'picocolors'
import type { CustomPayload, HMRPayload, Update } from 'types/hmrPayload'
import type { CustomPayload, HotPayload, Update } from 'types/hotPayload'
import type { RollupError } from 'rollup'
import { CLIENT_DIR } from '../constants'
import type { Environment } from '../environment'
Expand Down Expand Up @@ -36,8 +36,6 @@ export interface HmrOptions {
timeout?: number
overlay?: boolean
server?: Server
/** @internal */
channels?: HMRChannel[]
}

export interface HotUpdateContext {
Expand Down Expand Up @@ -72,22 +70,18 @@ export interface HMRBroadcasterClient {
/**
* Send event to the client
*/
send(payload: HMRPayload): void
send(payload: HotPayload): void
/**
* Send custom event
*/
send(event: string, payload?: CustomPayload['data']): void
}

export interface HMRChannel {
/**
* Unique channel name
*/
name: string
export interface HotChannel {
/**
* Broadcast events to all clients
*/
send(payload: HMRPayload): void
send(payload: HotPayload): void
/**
* Send custom event
*/
Expand Down Expand Up @@ -118,18 +112,6 @@ export interface HMRChannel {
close(): void
}

export interface HMRBroadcaster extends Omit<HMRChannel, 'close' | 'name'> {
/**
* All registered channels. Always has websocket channel.
*/
readonly channels: HMRChannel[]
/**
* Add a new third-party channel.
*/
addChannel(connection: HMRChannel): HMRBroadcaster
close(): Promise<unknown[]>
}

export function getShortName(file: string, root: string): string {
return file.startsWith(withTrailingSlash(root))
? path.posix.relative(root, file)
Expand Down Expand Up @@ -816,56 +798,7 @@ async function readModifiedFile(file: string): Promise<string> {
}
}

export function createHMRBroadcaster(): HMRBroadcaster {
const channels: HMRChannel[] = []
const readyChannels = new WeakSet<HMRChannel>()
const broadcaster: HMRBroadcaster = {
get channels() {
return [...channels]
},
addChannel(channel) {
if (channels.some((c) => c.name === channel.name)) {
throw new Error(`HMR channel "${channel.name}" is already defined.`)
}
channels.push(channel)
return broadcaster
},
on(event: string, listener: (...args: any[]) => any) {
// emit connection event only when all channels are ready
if (event === 'connection') {
// make a copy so we don't wait for channels that might be added after this is triggered
const channels = this.channels
channels.forEach((channel) =>
channel.on('connection', () => {
readyChannels.add(channel)
if (channels.every((c) => readyChannels.has(c))) {
listener()
}
}),
)
return
}
channels.forEach((channel) => channel.on(event, listener))
return
},
off(event, listener) {
channels.forEach((channel) => channel.off(event, listener))
return
},
send(...args: any[]) {
channels.forEach((channel) => channel.send(...(args as [any])))
},
listen() {
channels.forEach((channel) => channel.listen())
},
close() {
return Promise.all(channels.map((channel) => channel.close()))
},
}
return broadcaster
}

export interface ServerHMRChannel extends HMRChannel {
export interface ServerHMRChannel extends HotChannel {
api: {
innerEmitter: EventEmitter
outsideEmitter: EventEmitter
Expand All @@ -877,9 +810,8 @@ export function createServerHMRChannel(): ServerHMRChannel {
const outsideEmitter = new EventEmitter()

return {
name: 'ssr',
send(...args: any[]) {
let payload: HMRPayload
let payload: HotPayload
if (typeof args[0] === 'string') {
payload = {
type: 'custom',
Expand Down Expand Up @@ -911,13 +843,12 @@ export function createServerHMRChannel(): ServerHMRChannel {
}
}

export function createNoopHMRChannel(): HMRChannel {
export function createNoopHMRChannel(): HotChannel {
function noop() {
// noop
}

return {
name: 'noop',
send: noop,
on: noop,
off: noop,
Expand Down
Loading

0 comments on commit c568d1e

Please sign in to comment.