-
Notifications
You must be signed in to change notification settings - Fork 14
Expand file tree
/
Copy pathhmr-hot-update.test.ts
More file actions
276 lines (231 loc) · 7.99 KB
/
hmr-hot-update.test.ts
File metadata and controls
276 lines (231 loc) · 7.99 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
/**
* Tests for handleHotUpdate behavior (Issue #185).
*
* The plugin's handleHotUpdate hook must distinguish between:
* 1. Component resource files (templates/styles) → handled by custom fs.watch, return []
* 2. Non-component files (global CSS, etc.) → let Vite handle normally
*
* Previously, the plugin returned [] for ALL .css/.html files, which swallowed
* HMR updates for global stylesheets and prevented PostCSS/Tailwind from
* processing changes.
*/
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import type { Plugin, ModuleNode, HmrContext } from 'vite'
import { normalizePath } from 'vite'
import { afterAll, beforeAll, describe, it, expect, vi } from 'vitest'
import { angular } from '../vite-plugin/index.js'
let tempDir: string
let appDir: string
let templatePath: string
let stylePath: string
beforeAll(() => {
tempDir = mkdtempSync(join(tmpdir(), 'hmr-test-'))
appDir = join(tempDir, 'src', 'app')
mkdirSync(appDir, { recursive: true })
templatePath = join(appDir, 'app.component.html')
stylePath = join(appDir, 'app.component.css')
writeFileSync(templatePath, '<h1>Hello</h1>')
writeFileSync(stylePath, 'h1 { color: red; }')
})
afterAll(() => {
rmSync(tempDir, { recursive: true, force: true })
})
function getAngularPlugin() {
const plugin = angular({ liveReload: true }).find(
(candidate) => candidate.name === '@oxc-angular/vite',
)
if (!plugin) {
throw new Error('Failed to find @oxc-angular/vite plugin')
}
return plugin
}
function createMockServer() {
const wsMessages: any[] = []
const unwatchedFiles = new Set<string>()
return {
watcher: {
unwatch(file: string) {
unwatchedFiles.add(file)
},
on: vi.fn(),
emit: vi.fn(),
},
ws: {
send(msg: any) {
wsMessages.push(msg)
},
on: vi.fn(),
},
moduleGraph: {
getModuleById: vi.fn(() => null),
invalidateModule: vi.fn(),
},
middlewares: {
use: vi.fn(),
},
config: {
root: tempDir,
},
_wsMessages: wsMessages,
_unwatchedFiles: unwatchedFiles,
}
}
function createMockHmrContext(
file: string,
modules: Partial<ModuleNode>[] = [],
server?: any,
): HmrContext {
return {
file,
timestamp: Date.now(),
modules: modules as ModuleNode[],
read: async () => '',
server: server ?? createMockServer(),
} as HmrContext
}
async function callHandleHotUpdate(
plugin: Plugin,
ctx: HmrContext,
): Promise<ModuleNode[] | void | undefined> {
if (typeof plugin.handleHotUpdate === 'function') {
return (plugin.handleHotUpdate as Function).call(plugin, ctx)
}
return undefined
}
async function callPluginHook<TArgs extends unknown[], TResult>(
hook:
| {
handler: (...args: TArgs) => TResult
}
| ((...args: TArgs) => TResult)
| undefined,
...args: TArgs
): Promise<TResult | undefined> {
if (!hook) return undefined
if (typeof hook === 'function') return hook(...args)
return hook.handler(...args)
}
/**
* Set up a plugin through the full Vite lifecycle so that internal state
* (watchMode, viteServer, resourceToComponent, componentIds) is populated.
*/
async function setupPluginWithServer(plugin: Plugin) {
const mockServer = createMockServer()
// config() sets watchMode = true when command === 'serve'
await callPluginHook(
plugin.config as Plugin['config'],
{} as any,
{
command: 'serve',
mode: 'development',
} as any,
)
// configResolved() stores the resolved config
await callPluginHook(
plugin.configResolved as Plugin['configResolved'],
{
build: {},
isProduction: false,
} as any,
)
// configureServer() sets up the custom watcher and stores viteServer
if (typeof plugin.configureServer === 'function') {
await (plugin.configureServer as Function)(mockServer)
}
// Replace the real fs.watch-based watcher with a no-op to avoid EPERM
// errors on Windows when temp files are cleaned up. resourceToComponent
// is populated in transform *before* watchFn is called, so the map is
// still correctly populated for handleHotUpdate tests.
;(mockServer as any).__angularWatchTemplate = () => {}
return mockServer
}
/**
* Transform a component that references external template + style files,
* populating resourceToComponent and componentIds.
*/
async function transformComponent(plugin: Plugin) {
const componentFile = join(appDir, 'app.component.ts')
const componentSource = `
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css'],
})
export class AppComponent {}
`
if (!plugin.transform || typeof plugin.transform === 'function') {
throw new Error('Expected plugin transform handler')
}
await plugin.transform.handler.call(
{ error() {}, warn() {} } as any,
componentSource,
componentFile,
)
}
describe('handleHotUpdate - Issue #185', () => {
it('should let non-component CSS files pass through to Vite HMR', async () => {
const plugin = getAngularPlugin()
await setupPluginWithServer(plugin)
// A global CSS file (not referenced by any component's styleUrls)
const globalCssFile = normalizePath(join(tempDir, 'src', 'styles.css'))
const mockModules = [{ id: globalCssFile }]
const ctx = createMockHmrContext(globalCssFile, mockModules)
const result = await callHandleHotUpdate(plugin, ctx)
// Non-component CSS should NOT be swallowed — either undefined (pass through)
// or the original modules array, but NOT an empty array
if (result !== undefined) {
expect(result).toEqual(mockModules)
}
})
it('should return [] for component CSS files managed by custom watcher', async () => {
const plugin = getAngularPlugin()
const mockServer = await setupPluginWithServer(plugin)
await transformComponent(plugin)
// The component's CSS file IS in resourceToComponent
const componentCssFile = normalizePath(stylePath)
const mockModules = [{ id: componentCssFile }]
const ctx = createMockHmrContext(componentCssFile, mockModules, mockServer)
const result = await callHandleHotUpdate(plugin, ctx)
// Component resources MUST be swallowed (return [])
expect(result).toEqual([])
})
it('should return [] for component template HTML files managed by custom watcher', async () => {
const plugin = getAngularPlugin()
const mockServer = await setupPluginWithServer(plugin)
await transformComponent(plugin)
// The component's HTML template IS in resourceToComponent
const componentHtmlFile = normalizePath(templatePath)
const ctx = createMockHmrContext(componentHtmlFile, [{ id: componentHtmlFile }], mockServer)
const result = await callHandleHotUpdate(plugin, ctx)
// Component templates MUST be swallowed (return [])
expect(result).toEqual([])
})
it('should not swallow non-resource HTML files', async () => {
const plugin = getAngularPlugin()
await setupPluginWithServer(plugin)
// index.html is NOT a component template
const indexHtml = normalizePath(join(tempDir, 'index.html'))
const mockModules = [{ id: indexHtml }]
const ctx = createMockHmrContext(indexHtml, mockModules)
const result = await callHandleHotUpdate(plugin, ctx)
// Non-component HTML should pass through, not be swallowed
if (result !== undefined) {
expect(result).toEqual(mockModules)
}
})
it('should pass through non-style/template files unchanged', async () => {
const plugin = getAngularPlugin()
await setupPluginWithServer(plugin)
const utilFile = normalizePath(join(tempDir, 'src', 'utils.ts'))
const mockModules = [{ id: utilFile }]
const ctx = createMockHmrContext(utilFile, mockModules)
const result = await callHandleHotUpdate(plugin, ctx)
// Non-Angular .ts files should pass through with their modules
if (result !== undefined) {
expect(result).toEqual(mockModules)
}
})
})