Skip to content

Commit

Permalink
clarify conditions in normalized-asset-prefix helper + adjust types a…
Browse files Browse the repository at this point in the history
…nd returned prefix in getSocketUrl
  • Loading branch information
kjugi committed Jul 29, 2024
1 parent b1f7cc6 commit fe21ff8
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 11 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -11,16 +11,15 @@ function getSocketProtocol(assetPrefix: string): string {
return protocol === 'http:' ? 'ws' : 'wss'
}

export function getSocketUrl(assetPrefix: string): string {
export function getSocketUrl(assetPrefix: string | undefined): string {
const { hostname, port } = window.location
const protocol = getSocketProtocol(assetPrefix)
const protocol = getSocketProtocol(assetPrefix || '')
const prefix = normalizedAssetPrefix(assetPrefix)

let url = `${protocol}://${hostname}:${port}${prefix && prefix !== '' ? `/${prefix}` : ''}`

if (prefix.startsWith('http')) {
url = `${protocol}://${prefix.split('://', 2)[1]}`
// same check but on original assetPrefix value
if (assetPrefix?.replace(/^\/+/, '').startsWith('http')) {
return `${protocol}://${prefix}`
}

return url
return `${protocol}://${hostname}:${port}${prefix}`
}
15 changes: 11 additions & 4 deletions packages/next/src/shared/lib/normalized-asset-prefix.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,16 @@
export function normalizedAssetPrefix(assetPrefix: string): string {
const escapedAssetPrefix = assetPrefix.replace(/^\/+/, '')
export function normalizedAssetPrefix(assetPrefix: string | undefined): string {
const escapedAssetPrefix = assetPrefix?.replace(/^\/+/, '') || false

if (escapedAssetPrefix.startsWith('http')) {
// assetPrefix as a url
if (escapedAssetPrefix && escapedAssetPrefix.startsWith('http')) {
return escapedAssetPrefix.split('://', 2)[1]
}

return `${escapedAssetPrefix ? `/${escapedAssetPrefix}` : ''}`
// assetPrefix is set to `undefined` or '/'
if (!escapedAssetPrefix || escapedAssetPrefix === '') {
return ''
}

// assetPrefix is a common path but escaped so let's add one leading slash
return `/${escapedAssetPrefix}`
}

0 comments on commit fe21ff8

Please sign in to comment.