Skip to content

Commit c721b8c

Browse files
committed
fix: normalize asset prefix for socket if start with http
refactor: use URL obj refactor: use URL canParse Co-authored-by: Sebastian Silbermann <silbermann.sebastian@gmail.com> refactor
1 parent dc1088a commit c721b8c

File tree

2 files changed

+18
-15
lines changed

2 files changed

+18
-15
lines changed

packages/next/src/client/components/react-dev-overlay/internal/helpers/get-socket-url.ts

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,19 +8,19 @@ function getSocketProtocol(assetPrefix: string): string {
88
protocol = new URL(assetPrefix).protocol
99
} catch {}
1010

11-
return protocol === 'http:' ? 'ws' : 'wss'
11+
return protocol === 'http:' ? 'ws:' : 'wss:'
1212
}
1313

1414
export function getSocketUrl(assetPrefix: string | undefined): string {
15-
const { hostname, port } = window.location
16-
const protocol = getSocketProtocol(assetPrefix || '')
1715
const prefix = normalizedAssetPrefix(assetPrefix)
16+
const protocol = getSocketProtocol(assetPrefix || '')
1817

19-
// if original assetPrefix is a full URL with protocol
20-
// we just update to use the correct `ws` protocol
21-
if (assetPrefix?.replace(/^\/+/, '').includes('://')) {
22-
return `${protocol}://${prefix}`
18+
if (URL.canParse(prefix)) {
19+
// since normalized asset prefix is ensured to be a URL format,
20+
// we can safely replace the protocol
21+
return prefix.replace(/^http/, 'ws')
2322
}
2423

25-
return `${protocol}://${hostname}:${port}${prefix}`
24+
const { hostname, port } = window.location
25+
return `${protocol}//${hostname}${port ? `:${port}` : ''}${prefix}`
2626
}
Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
export function normalizedAssetPrefix(assetPrefix: string | undefined): string {
2+
// remove all leading slashes
23
const escapedAssetPrefix = assetPrefix?.replace(/^\/+/, '') || false
34

4-
// assetPrefix as a url
5-
if (escapedAssetPrefix && escapedAssetPrefix.startsWith('://')) {
6-
return escapedAssetPrefix.split('://', 2)[1]
7-
}
8-
9-
// assetPrefix is set to `undefined` or '/'
5+
// if an assetPrefix was '/', we return empty string
6+
// because it could be an unnecessary trailing slash
107
if (!escapedAssetPrefix) {
118
return ''
129
}
1310

14-
// assetPrefix is a common path but escaped so let's add one leading slash
11+
if (URL.canParse(escapedAssetPrefix)) {
12+
const { hostname, port, protocol, pathname } = new URL(escapedAssetPrefix)
13+
return `${protocol}//${hostname}${port ? `:${port}` : ''}${pathname}`
14+
}
15+
16+
// assuming assetPrefix here is a pathname-style,
17+
// restore the leading slash
1518
return `/${escapedAssetPrefix}`
1619
}

0 commit comments

Comments
 (0)