| 219 | * @returns WebSocket connection |
| 220 | */ |
| 221 | export async function wsConnect( |
| 222 | projectId: string, |
| 223 | overleafAuth: OverleafAuthentication, |
| 224 | csrfToken: string, |
| 225 | ): Promise<WebSocket> { |
| 226 | // if (import.meta.env.DEV) { |
| 227 | // throw new Error("Development mode is not supported for wsConnect"); |
| 228 | // } |
| 229 | const currentDomain = window.location.hostname; |
| 230 | const baseUrl = import.meta.env.DEV ? "http://localhost:3000" : "https://" + currentDomain; |
| 231 | const res = await fetch(`${baseUrl}/socket.io/1/?projectId=${projectId}&t=${Date.now()}`, { |
| 232 | headers: { |
| 233 | Accept: "application/json", |
| 234 | "Content-Type": "application/json", |
| 235 | "X-Csrf-Token": csrfToken, |
| 236 | Cookie: `overleaf_session2=${overleafAuth.cookieOverleafSession2}; GCLB=${overleafAuth.cookieGCLB}`, |
| 237 | }, |
| 238 | }); |
| 239 | |
| 240 | if (res.status !== 200) { |
| 241 | throw new Error(`HTTP error when connecting ws: ${res.status}`); |
| 242 | } |
| 243 | |
| 244 | const wsUrl = import.meta.env.DEV ? "ws://localhost:3000" : "wss://" + currentDomain; |
| 245 | const data = await res.text(); |
| 246 | const sessionId = data.split(":")[0]; |
| 247 | |
| 248 | // Set cookies for WebSocket connection |
| 249 | document.cookie = `overleaf_session2=${overleafAuth.cookieOverleafSession2}; path=/; domain=${import.meta.env.DEV ? "localhost" : currentDomain}`; |
| 250 | document.cookie = `GCLB=${overleafAuth.cookieGCLB}; path=/; domain=${import.meta.env.DEV ? "localhost" : currentDomain}`; |
| 251 | |
| 252 | return new WebSocket(`${wsUrl}/socket.io/1/websocket/${sessionId}?projectId=${projectId}`); |
| 253 | } |