46 lines
1.7 KiB
TypeScript
46 lines
1.7 KiB
TypeScript
/**
|
|
* Resolve a WebSocket base URL that prefers same-origin `/ws/...` (nginx :9080 / :9443).
|
|
* Avoids baking a public `:4001` host that browsers cannot reach on the VPS.
|
|
*/
|
|
|
|
export function resolveSameOriginWsUrl(pathname: string, explicitUrl?: string): string {
|
|
const explicit = explicitUrl?.replace(/\/$/, '') || undefined;
|
|
const normalizedPath = pathname.startsWith('/') ? pathname : `/${pathname}`;
|
|
|
|
if (typeof window !== 'undefined') {
|
|
const pageHost = window.location.host;
|
|
if (explicit) {
|
|
try {
|
|
const configured = new URL(explicit);
|
|
// Same host as the page (typical VPS nginx :9080 / :9443).
|
|
if (configured.host === pageHost) return explicit;
|
|
// Vite dev has no /ws/ proxy — keep explicit ws://localhost:4001/...
|
|
if (import.meta.env.DEV) return explicit;
|
|
} catch {
|
|
/* fall through to same-origin */
|
|
}
|
|
}
|
|
// Production / Docker web: same-origin /ws/ via nginx (never public :4001).
|
|
const u = new URL(window.location.origin);
|
|
u.protocol = u.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
u.pathname = normalizedPath;
|
|
u.search = '';
|
|
return u.toString().replace(/\/$/, '');
|
|
}
|
|
|
|
if (explicit) return explicit;
|
|
|
|
// Non-browser / SSR fallback for local tooling only.
|
|
const api = import.meta.env.VITE_API_BASE_URL || 'http://localhost:4000';
|
|
const url = new URL(api);
|
|
url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
|
|
url.port = import.meta.env.VITE_WS_PORT || '4001';
|
|
url.pathname = normalizedPath;
|
|
url.search = '';
|
|
return url.toString().replace(/\/$/, '');
|
|
}
|
|
|
|
export function isViteWsEnabled(): boolean {
|
|
return import.meta.env.VITE_WS_ENABLED === 'true';
|
|
}
|