File size: 815 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { normalizedAssetPrefix } from '../../../shared/lib/normalized-asset-prefix'

function getSocketProtocol(assetPrefix: string): string {
  let protocol = window.location.protocol

  try {
    // assetPrefix is a url
    protocol = new URL(assetPrefix).protocol
  } catch {}

  return protocol === 'http:' ? 'ws:' : 'wss:'
}

export function getSocketUrl(assetPrefix: string | undefined): string {
  const prefix = normalizedAssetPrefix(assetPrefix)
  const protocol = getSocketProtocol(assetPrefix || '')

  if (URL.canParse(prefix)) {
    // since normalized asset prefix is ensured to be a URL format,
    // we can safely replace the protocol
    return prefix.replace(/^http/, 'ws')
  }

  const { hostname, port } = window.location
  return `${protocol}//${hostname}${port ? `:${port}` : ''}${prefix}`
}