-
-
Notifications
You must be signed in to change notification settings - Fork 8.6k
Expand file tree
/
Copy pathclient.ts
More file actions
622 lines (572 loc) · 19.4 KB
/
Copy pathclient.ts
File metadata and controls
622 lines (572 loc) · 19.4 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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
import type { ErrorPayload, HotPayload } from '#types/hmrPayload'
import type { ViteHotContext } from '#types/hot'
import { HMRClient, HMRContext } from '../shared/hmr'
import {
createWebSocketModuleRunnerTransport,
normalizeModuleRunnerTransport,
} from '../shared/moduleRunnerTransport'
import { createHMRHandler } from '../shared/hmrHandler'
import { setupForwardConsoleHandler } from '../shared/forwardConsole'
import type { BundledDevHMRClient } from './bundledDevHmrClient'
import { ErrorOverlay, cspNonce, overlayId } from './overlay'
// @ts-expect-error internal virtual module
import '@vite/env'
// injected by the hmr plugin when served
declare const __BASE__: string
declare const __SERVER_HOST__: string
declare const __HMR_PROTOCOL__: string | null
declare const __HMR_HOSTNAME__: string | null
declare const __HMR_PORT__: number | null
declare const __HMR_DIRECT_TARGET__: string
declare const __HMR_BASE__: string
declare const __HMR_TIMEOUT__: number
declare const __HMR_ENABLE_OVERLAY__: boolean
declare const __WS_TOKEN__: string
declare const __SERVER_FORWARD_CONSOLE__: any
console.debug('[vite] connecting...')
const importMetaUrl = new URL(import.meta.url)
// use server configuration, then fallback to inference
const serverHost = __SERVER_HOST__
const socketProtocol =
__HMR_PROTOCOL__ || (importMetaUrl.protocol === 'https:' ? 'wss' : 'ws')
const hmrPort = __HMR_PORT__
const socketHost = `${__HMR_HOSTNAME__ || importMetaUrl.hostname}:${
hmrPort || importMetaUrl.port
}${__HMR_BASE__}`
const directSocketHost = __HMR_DIRECT_TARGET__
export const base = __BASE__ || '/'
const hmrTimeout = __HMR_TIMEOUT__
const wsToken = __WS_TOKEN__
const forwardConsole = __SERVER_FORWARD_CONSOLE__
export const transport = normalizeModuleRunnerTransport(
(() => {
let wsTransport = createWebSocketModuleRunnerTransport({
createConnection: () =>
new WebSocket(
`${socketProtocol}://${socketHost}?token=${wsToken}`,
'vite-hmr',
),
pingInterval: hmrTimeout,
})
return {
async connect(handlers) {
try {
await wsTransport.connect(handlers)
} catch (e) {
// only use fallback when port is inferred and was not connected before to prevent confusion
if (!hmrPort) {
wsTransport = createWebSocketModuleRunnerTransport({
createConnection: () =>
new WebSocket(
`${socketProtocol}://${directSocketHost}?token=${wsToken}`,
'vite-hmr',
),
pingInterval: hmrTimeout,
})
try {
await wsTransport.connect(handlers)
console.info(
'[vite] Direct websocket connection fallback. Check out https://vite.dev/config/server-options.html#server-hmr to remove the previous connection error.',
)
} catch (e) {
if (
e instanceof Error &&
e.message.includes('WebSocket closed without opened.')
) {
const currentScriptHostURL = new URL(import.meta.url)
const currentScriptHost =
currentScriptHostURL.host +
currentScriptHostURL.pathname.replace(/@vite\/client$/, '')
console.error(
'[vite] failed to connect to websocket.\n' +
'your current setup:\n' +
` (browser) ${currentScriptHost} <--[HTTP]--> ${serverHost} (server)\n` +
` (browser) ${socketHost} <--[WebSocket (failing)]--> ${directSocketHost} (server)\n` +
'Check out your Vite / network configuration and https://vite.dev/config/server-options.html#server-hmr .',
)
}
}
return
}
console.error(`[vite] failed to connect to websocket (${e}). `)
throw e
}
},
async disconnect() {
await wsTransport.disconnect()
},
send(data) {
wsTransport.send(data)
},
}
})(),
)
let willUnload = false
if (typeof window !== 'undefined') {
// window can be misleadingly defined in a worker if using define (see #19307)
window.addEventListener?.('beforeunload', () => {
willUnload = true
})
}
function cleanUrl(pathname: string): string {
const url = new URL(pathname, 'http://vite.dev')
url.searchParams.delete('direct')
return url.pathname + url.search
}
let isFirstUpdate = true
const outdatedLinkTags = new WeakSet<HTMLLinkElement>()
const debounceReload = (time: number) => {
let timer: ReturnType<typeof setTimeout> | null
return () => {
if (timer) {
clearTimeout(timer)
timer = null
}
timer = setTimeout(() => {
location.reload()
}, time)
}
}
export const pageReload = debounceReload(20)
const hmrClient = new HMRClient(
{
error: (err) => console.error('[vite]', err),
debug: (...msg) => console.debug('[vite]', ...msg),
},
transport,
async function importUpdatedModule({
acceptedPath,
timestamp,
explicitImportRequired,
isWithinCircularImport,
}) {
const [acceptedPathWithoutQuery, query] = acceptedPath.split(`?`)
const importPromise = import(
/* @vite-ignore */
base +
acceptedPathWithoutQuery.slice(1) +
`?${explicitImportRequired ? 'import&' : ''}t=${timestamp}${
query ? `&${query}` : ''
}`
)
if (isWithinCircularImport) {
importPromise.catch(() => {
console.info(
`[hmr] ${acceptedPath} failed to apply HMR as it's within a circular import. Reloading page to reset the execution order. ` +
`To debug and break the circular import, you can run \`vite --debug hmr\` to log the circular dependency path if a file change triggered it.`,
)
pageReload()
})
}
return await importPromise
},
)
// set by the full-bundle-mode entry (`bundledDevClient.ts`); the `import type` above keeps
// `BundledDevHMRClient` compile-time only, so `client.mjs` bundles no bundled-dev code
let bundledDevClient: BundledDevHMRClient | undefined
export function registerBundledDevClient(client: BundledDevHMRClient): void {
bundledDevClient = client
}
transport.connect!(createHMRHandler(handleMessage))
setupForwardConsoleHandler(transport, forwardConsole)
// if this is the first update and there's already an error overlay, it means the
// page opened with existing server compile error and the whole module script failed
// to load (since one of the nested imports is 500). in this case a normal update
// won't work and a full reload is needed.
export function clearOverlayOrReloadOnFirstUpdate(): 'reload' | 'continue' {
if (hasDocument) {
if (isFirstUpdate && hasErrorOverlay()) {
location.reload()
return 'reload'
}
if (enableOverlay) {
clearErrorOverlay()
}
isFirstUpdate = false
}
return 'continue'
}
async function handleMessage(payload: HotPayload) {
const activeHmrClient = bundledDevClient ?? hmrClient
switch (payload.type) {
case 'connected':
console.debug(`[vite] connected.`)
break
case 'bundled-dev-update':
bundledDevClient!.handlePush(payload)
break
case 'update':
await activeHmrClient.notifyListeners('vite:beforeUpdate', payload)
if (clearOverlayOrReloadOnFirstUpdate() === 'reload') {
return
}
await Promise.all(
payload.updates.map(async (update): Promise<void> => {
if (update.type === 'js-update') {
return hmrClient.queueUpdate(update)
}
// css-update
// this is only sent when a css file referenced with <link> is updated
const { path, timestamp } = update
const searchUrl = cleanUrl(path)
// can't use querySelector with `[href*=]` here since the link may be
// using relative paths so we need to use link.href to grab the full
// URL for the include check.
const el = Array.from(
document.querySelectorAll<HTMLLinkElement>('link'),
).find(
(e) =>
!outdatedLinkTags.has(e) && cleanUrl(e.href).includes(searchUrl),
)
if (!el) {
return
}
const newPath = `${base}${searchUrl.slice(1)}${
searchUrl.includes('?') ? '&' : '?'
}t=${timestamp}`
// rather than swapping the href on the existing tag, we will
// create a new link tag. Once the new stylesheet has loaded we
// will remove the existing link tag. This removes a Flash Of
// Unstyled Content that can occur when swapping out the tag href
// directly, as the new stylesheet has not yet been loaded.
return new Promise((resolve) => {
const newLinkTag = el.cloneNode() as HTMLLinkElement
newLinkTag.href = new URL(newPath, el.href).href
const removeOldEl = () => {
el.remove()
console.debug(`[vite] css hot updated: ${searchUrl}`)
resolve()
}
newLinkTag.addEventListener('load', removeOldEl)
newLinkTag.addEventListener('error', removeOldEl)
outdatedLinkTags.add(el)
el.after(newLinkTag)
})
}),
)
await activeHmrClient.notifyListeners('vite:afterUpdate', payload)
break
case 'custom': {
await activeHmrClient.notifyListeners(payload.event, payload.data)
if (payload.event === 'vite:ws:disconnect') {
if (hasDocument && !willUnload) {
console.log(`[vite] server connection lost. Polling for restart...`)
const socket = payload.data.webSocket as WebSocket
const url = new URL(socket.url)
url.search = '' // remove query string including `token`
await waitForSuccessfulPing(url.href)
location.reload()
}
}
break
}
case 'full-reload':
// `ifFallback` reloads are addressed only to the bundling-fallback page,
// which marks itself with this global (see `generateFallbackHtml`)
if (
payload.ifFallback &&
!(globalThis as any).__vite_is_fallback_page__
) {
break
}
await activeHmrClient.notifyListeners('vite:beforeFullReload', payload)
if (hasDocument) {
if (payload.path && payload.path.endsWith('.html')) {
// if html file is edited, only reload the page if the browser is
// currently on that page.
const pagePath = decodeURI(location.pathname)
const payloadPath = base + payload.path.slice(1)
if (
pagePath === payloadPath ||
payload.path === '/index.html' ||
(pagePath.endsWith('/') && pagePath + 'index.html' === payloadPath)
) {
pageReload()
}
return
} else {
pageReload()
}
}
break
case 'prune':
await activeHmrClient.notifyListeners('vite:beforePrune', payload)
await activeHmrClient.prunePaths(payload.paths)
break
case 'error': {
await activeHmrClient.notifyListeners('vite:error', payload)
if (hasDocument) {
const err = payload.err
if (enableOverlay) {
createErrorOverlay(err)
} else {
console.error(
`[vite] Internal Server Error\n${err.message}\n${err.stack}`,
)
}
}
break
}
case 'ping': // noop
break
default: {
const check: never = payload
return check
}
}
}
const enableOverlay = __HMR_ENABLE_OVERLAY__
const hasDocument = 'document' in globalThis
function createErrorOverlay(err: ErrorPayload['err']) {
clearErrorOverlay()
const { customElements } = globalThis
if (customElements) {
const ErrorOverlayConstructor = customElements.get(overlayId)!
document.body.appendChild(new ErrorOverlayConstructor(err))
}
}
function clearErrorOverlay() {
document.querySelectorAll<ErrorOverlay>(overlayId).forEach((n) => n.close())
}
function hasErrorOverlay() {
return document.querySelectorAll(overlayId).length
}
function waitForSuccessfulPing(socketUrl: string) {
if (typeof SharedWorker === 'undefined') {
const visibilityManager: VisibilityManager = {
currentState: document.visibilityState,
listeners: new Set(),
}
const onVisibilityChange = () => {
visibilityManager.currentState = document.visibilityState
for (const listener of visibilityManager.listeners) {
listener(visibilityManager.currentState)
}
}
document.addEventListener('visibilitychange', onVisibilityChange)
return waitForSuccessfulPingInternal(socketUrl, visibilityManager)
}
// needs to be inlined to
// - load the worker after the server is closed
// - make it work with backend integrations
const blob = new Blob(
[
'"use strict";',
`const waitForSuccessfulPingInternal = ${waitForSuccessfulPingInternal.toString()};`,
`const fn = ${pingWorkerContentMain.toString()};`,
`fn(${JSON.stringify(socketUrl)})`,
],
{ type: 'application/javascript' },
)
const objURL = URL.createObjectURL(blob)
const sharedWorker = new SharedWorker(objURL)
return new Promise<void>((resolve, reject) => {
const onVisibilityChange = () => {
sharedWorker.port.postMessage({ visibility: document.visibilityState })
}
document.addEventListener('visibilitychange', onVisibilityChange)
sharedWorker.port.addEventListener('message', (event) => {
document.removeEventListener('visibilitychange', onVisibilityChange)
sharedWorker.port.close()
const data: { type: 'success' } | { type: 'error'; error: Error } =
event.data
if (data.type === 'error') {
reject(data.error)
return
}
resolve()
})
onVisibilityChange()
sharedWorker.port.start()
})
}
type VisibilityManager = {
currentState: DocumentVisibilityState
listeners: Set<(newVisibility: DocumentVisibilityState) => void>
}
function pingWorkerContentMain(socketUrl: string) {
self.addEventListener('connect', (_event) => {
const event = _event as MessageEvent
const port = event.ports[0]
if (!socketUrl) {
port.postMessage({
type: 'error',
error: new Error('socketUrl not found'),
})
return
}
const visibilityManager: VisibilityManager = {
currentState: 'visible',
listeners: new Set(),
}
port.addEventListener('message', (event) => {
const { visibility } = event.data
visibilityManager.currentState = visibility
console.debug('[vite] new window visibility', visibility)
for (const listener of visibilityManager.listeners) {
listener(visibility)
}
})
port.start()
console.debug('[vite] connected from window')
waitForSuccessfulPingInternal(socketUrl, visibilityManager).then(
() => {
console.debug('[vite] ping successful')
try {
port.postMessage({ type: 'success' })
} catch (error) {
port.postMessage({ type: 'error', error })
}
},
(error) => {
console.debug('[vite] error happened', error)
try {
port.postMessage({ type: 'error', error })
} catch (error) {
port.postMessage({ type: 'error', error })
}
},
)
})
}
async function waitForSuccessfulPingInternal(
socketUrl: string,
visibilityManager: VisibilityManager,
ms = 1000,
) {
function wait(ms: number) {
return new Promise((resolve) => setTimeout(resolve, ms))
}
async function ping() {
try {
const socket = new WebSocket(socketUrl, 'vite-ping')
return new Promise<boolean>((resolve) => {
function onOpen() {
resolve(true)
close()
}
function onError() {
resolve(false)
close()
}
function close() {
socket.removeEventListener('open', onOpen)
socket.removeEventListener('error', onError)
socket.close()
}
socket.addEventListener('open', onOpen)
socket.addEventListener('error', onError)
})
} catch {
return false
}
}
function waitForWindowShow(visibilityManager: VisibilityManager) {
return new Promise<void>((resolve) => {
const onChange = (newVisibility: DocumentVisibilityState) => {
if (newVisibility === 'visible') {
resolve()
visibilityManager.listeners.delete(onChange)
}
}
visibilityManager.listeners.add(onChange)
})
}
if (await ping()) {
return
}
await wait(ms)
while (true) {
if (visibilityManager.currentState === 'visible') {
if (await ping()) {
break
}
await wait(ms)
} else {
await waitForWindowShow(visibilityManager)
}
}
}
const sheetsMap = new Map<string, HTMLStyleElement>()
const linkSheetsMap = new Map<string, HTMLLinkElement>()
// collect existing style elements that may have been inserted during SSR
// to avoid FOUC or duplicate styles
if ('document' in globalThis) {
document
.querySelectorAll<HTMLStyleElement>('style[data-vite-dev-id]')
.forEach((el) => {
sheetsMap.set(el.getAttribute('data-vite-dev-id')!, el)
})
document
.querySelectorAll<HTMLLinkElement>(
'link[rel="stylesheet"][data-vite-dev-id]',
)
.forEach((el) => {
linkSheetsMap.set(el.getAttribute('data-vite-dev-id')!, el)
})
}
// all css imports should be inserted at the same position
// because after build it will be a single css file
let lastInsertedStyle: HTMLStyleElement | undefined
export function updateStyle(id: string, content: string): void {
if (linkSheetsMap.has(id)) return
let style = sheetsMap.get(id)
if (!style) {
style = document.createElement('style')
style.setAttribute('type', 'text/css')
style.setAttribute('data-vite-dev-id', id)
style.textContent = content
if (cspNonce) {
style.setAttribute('nonce', cspNonce)
}
if (!lastInsertedStyle) {
document.head.appendChild(style)
// reset lastInsertedStyle after async
// because dynamically imported css will be split into a different file
setTimeout(() => {
lastInsertedStyle = undefined
}, 0)
} else {
lastInsertedStyle.insertAdjacentElement('afterend', style)
}
lastInsertedStyle = style
} else {
style.textContent = content
}
sheetsMap.set(id, style)
}
export function removeStyle(id: string): void {
if (linkSheetsMap.has(id)) {
// re-select elements since HMR can replace links
document
.querySelectorAll<HTMLLinkElement>(
`link[rel="stylesheet"][data-vite-dev-id="${CSS.escape(id)}"]`,
)
.forEach((el) => el.remove())
linkSheetsMap.delete(id)
}
const style = sheetsMap.get(id)
if (style) {
document.head.removeChild(style)
sheetsMap.delete(id)
}
}
export function createHotContext(ownerPath: string): ViteHotContext {
return new HMRContext(hmrClient, ownerPath)
}
/**
* urls here are dynamic import() urls that couldn't be statically analyzed
*/
export function injectQuery(url: string, queryToInject: string): string {
// skip urls that won't be handled by vite
if (url[0] !== '.' && url[0] !== '/') {
return url
}
// can't use pathname from URL since it may be relative like ../
const pathname = url.replace(/[?#].*$/, '')
const { search, hash } = new URL(url, 'http://vite.dev')
return `${pathname}?${queryToInject}${search ? `&` + search.slice(1) : ''}${
hash || ''
}`
}
export { ErrorOverlay }