Skip to content

Commit bfe4d9f

Browse files
committed
fix: make it harder to initialize OWWS
1 parent ecb2940 commit bfe4d9f

File tree

2 files changed

+17
-9
lines changed

2 files changed

+17
-9
lines changed

site/src/api/api.ts

Lines changed: 6 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -108,21 +108,19 @@ const getMissingParameters = (
108108
* (ServerSentEvent)
109109
*/
110110
export const watchAgentMetadata = (agentId: string): OneWayWebSocket => {
111-
const protocol = location.protocol === "https:" ? "wss:" : "ws:";
112-
return new OneWayWebSocket(
113-
`${protocol}//${location.host}/api/v2/workspaceagents/${agentId}/watch-metadata-ws`,
114-
);
111+
return new OneWayWebSocket({
112+
apiRoute: `/api/v2/workspaceagents/${agentId}/watch-metadata-ws`,
113+
});
115114
};
116115

117116
/**
118117
* @returns {EventSource} An EventSource that emits workspace event objects
119118
* (ServerSentEvent)
120119
*/
121120
export const watchWorkspace = (workspaceId: string): OneWayWebSocket => {
122-
const protocol = location.protocol === "https:" ? "wss:" : "ws:";
123-
return new OneWayWebSocket(
124-
`${protocol}//${location.host}/api/v2/workspaces/${workspaceId}/watch-ws`,
125-
);
121+
return new OneWayWebSocket({
122+
apiRoute: `/api/v2/workspaces/${workspaceId}/watch-ws`,
123+
});
126124
};
127125

128126
export const getURLWithSearchParams = (

site/src/utils/OneWayWebSocket.ts

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,13 +44,23 @@ interface OneWayWebSocketApi {
4444
close: (closeCode?: number, reason?: string) => void;
4545
}
4646

47+
type OneWayWebSocketInit = Readonly<{
48+
apiRoute: `/${string}`;
49+
location?: Location;
50+
protocols?: string | string[];
51+
}>;
52+
4753
// Implementing wrapper around the base WebSocket class instead of doing fancy
4854
// compile-time type-casts so that we have more runtime assurance that we won't
4955
// accidentally send a message from the client to the server
5056
export class OneWayWebSocket implements OneWayWebSocketApi {
5157
#socket: WebSocket;
5258

53-
constructor(url: string | URL, protocols?: string | string[]) {
59+
constructor(init: OneWayWebSocketInit) {
60+
const { apiRoute, protocols, location = window.location } = init;
61+
62+
const protocol = location.protocol === "https:" ? "wss:" : "ws:";
63+
const url = `${protocol}//${location.host}${apiRoute}`;
5464
this.#socket = new WebSocket(url, protocols);
5565
}
5666

0 commit comments

Comments
 (0)