| 1 | import type { BootstrapResponse } from "./types"; |
| 2 | |
| 3 | /** |
| 4 | * Fetch a short-lived token + the WebSocket path from the gateway's |
| 5 | * ``/webui/bootstrap`` endpoint. |
| 6 | */ |
| 7 | export async function fetchBootstrap( |
| 8 | baseUrl: string = "", |
| 9 | ): Promise<BootstrapResponse> { |
| 10 | const res = await fetch(`${baseUrl}/webui/bootstrap`, { |
| 11 | method: "GET", |
| 12 | credentials: "same-origin", |
| 13 | }); |
| 14 | if (!res.ok) { |
| 15 | throw new Error(`bootstrap failed: HTTP ${res.status}`); |
| 16 | } |
| 17 | const body = (await res.json()) as BootstrapResponse; |
| 18 | if (!body.token || !body.ws_path) { |
| 19 | throw new Error("bootstrap response missing token or ws_path"); |
| 20 | } |
| 21 | return body; |
| 22 | } |
| 23 | |
| 24 | /** Derive a WebSocket URL from the current window location and the server-provided path. |
| 25 | * |
| 26 | * Keeps the path segment exactly as the server registered it: the root ``/`` |
| 27 | * stays ``/`` and non-root paths are not given an extra trailing slash. This |
| 28 | * matters because some WS servers dispatch handshakes based on the literal |
| 29 | * path, not a normalised form. |
| 30 | */ |
| 31 | export function deriveWsUrl(wsPath: string, token: string): string { |
| 32 | const path = wsPath && wsPath.startsWith("/") ? wsPath : `/${wsPath || ""}`; |
| 33 | const params = new URLSearchParams({ token }); |
| 34 | const query = `?${params.toString()}`; |
| 35 | if (typeof window === "undefined") { |
| 36 | return `ws://127.0.0.1:8765${path}${query}`; |
| 37 | } |
| 38 | const scheme = window.location.protocol === "https:" ? "wss" : "ws"; |
| 39 | const host = import.meta.env.DEV ? "127.0.0.1:8765" : window.location.host; |
| 40 | return `${scheme}://${host}${path}${query}`; |
| 41 | } |
| 42 |