refactor: cleanup import path
[e-mobility-charging-stations-simulator.git] / src / charging-station / ui-server / UIServerUtils.ts
CommitLineData
66a7748d 1import type { IncomingMessage } from 'node:http'
8114d10e 2
66a7748d
JB
3import { Protocol, ProtocolVersion } from '../../types/index.js'
4import { logPrefix, logger } from '../../utils/index.js'
4198ad5c 5
66a7748d 6// eslint-disable-next-line @typescript-eslint/no-extraneous-class
ed3d2808 7export class UIServerUtils {
66a7748d 8 private constructor () {
d5bd1c00
JB
9 // This is intentional
10 }
11
1d6f2eb4 12 public static readonly handleProtocols = (
e7aeea18 13 protocols: Set<string>,
66a7748d 14 request: IncomingMessage
e7aeea18 15 ): string | false => {
66a7748d
JB
16 let protocol: Protocol | undefined
17 let version: ProtocolVersion | undefined
a92929f1 18 if (protocols.size === 0) {
66a7748d 19 return false
a92929f1 20 }
4198ad5c 21 for (const fullProtocol of protocols) {
66a7748d
JB
22 if (UIServerUtils.isProtocolAndVersionSupported(fullProtocol)) {
23 return fullProtocol
4198ad5c
JB
24 }
25 }
e7aeea18 26 logger.error(
9bf0ef23 27 `${logPrefix(
66a7748d
JB
28 ' UI WebSocket Server |'
29 )} Unsupported protocol: '${protocol}' or protocol version: '${version}'`
30 )
31 return false
32 }
d5bd1c00 33
1d6f2eb4 34 public static readonly isProtocolAndVersionSupported = (protocolStr: string): boolean => {
66a7748d 35 const [protocol, version] = UIServerUtils.getProtocolAndVersion(protocolStr)
7cb5b17f 36 return (
66a7748d
JB
37 Object.values(Protocol).includes(protocol) && Object.values(ProtocolVersion).includes(version)
38 )
39 }
1f7fa4de 40
1d6f2eb4
JB
41 public static readonly getProtocolAndVersion = (
42 protocolStr: string
43 ): [Protocol, ProtocolVersion] => {
66a7748d 44 const protocolIndex = protocolStr.indexOf(Protocol.UI)
a92929f1
JB
45 const protocol = protocolStr.substring(
46 protocolIndex,
66a7748d
JB
47 protocolIndex + Protocol.UI.length
48 ) as Protocol
49 const version = protocolStr.substring(protocolIndex + Protocol.UI.length) as ProtocolVersion
50 return [protocol, version]
51 }
a92929f1 52
66a7748d 53 public static isLoopback (address: string): boolean {
bbb339cc
JB
54 // eslint-disable-next-line no-useless-escape
55 return /^localhost$|^127(?:\.\d+){0,2}\.\d+$|^(?:0*\:)*?:?0*1$/i.test(address)
d5bd1c00 56 }
4198ad5c 57}