Main menu
This commit is contained in:
+24
-4
@@ -20,10 +20,30 @@ export interface ServerAddress {
|
||||
// something went wrong in a way the player should see
|
||||
export class HandshakeError extends Error {}
|
||||
|
||||
export function server_address(page = new URL(location.href)): ServerAddress {
|
||||
// ?server=host:port, otherwise the server that served the page
|
||||
const host = page.searchParams.get("server") ?? page.host;
|
||||
const secure = page.protocol === "https:";
|
||||
// what the server field starts as: ?server=host:port, otherwise the server that served the page
|
||||
export function default_server(page = new URL(location.href)): string {
|
||||
return page.searchParams.get("server") ?? page.host;
|
||||
}
|
||||
|
||||
// what a player typed as the server: host:port, or a full http(s) or ws(s) url
|
||||
export function server_address(input: string, page = new URL(location.href)): ServerAddress {
|
||||
const text = input.trim();
|
||||
let host = text;
|
||||
// without a scheme it's as secure as the page, browsers block insecure sockets from secure pages anyway
|
||||
let secure = page.protocol === "https:";
|
||||
if (text.includes("://")) {
|
||||
let url: URL;
|
||||
try {
|
||||
url = new URL(text);
|
||||
} catch {
|
||||
throw new HandshakeError(`${text} isn't a server address`);
|
||||
}
|
||||
host = url.host;
|
||||
secure = url.protocol === "https:" || url.protocol === "wss:";
|
||||
}
|
||||
if (!host || /[\s/?#]/.test(host)) {
|
||||
throw new HandshakeError(`${text || "An empty address"} isn't a server address`);
|
||||
}
|
||||
const base = new URL(`${secure ? "https" : "http"}://${host}/`);
|
||||
return {
|
||||
ws_url: `${secure ? "wss" : "ws"}://${host}/ws`,
|
||||
|
||||
Reference in New Issue
Block a user