Skip to content

Commit 27c559c

Browse files
authored
feat: allow defining timeout when waiting for port (#70)
1 parent 24ab04f commit 27c559c

File tree

1 file changed

+25
-2
lines changed

1 file changed

+25
-2
lines changed

src/ports.ts

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -93,21 +93,44 @@ export class Ports extends Disposable {
9393
* Wait for a port to be opened.
9494
*
9595
* @param port - The port to wait for.
96+
* @param options - Additional options
97+
* @param options.timeoutMs - Optional timeout in milliseconds. If specified, the promise will reject after this time if the port hasn't opened.
9698
* @returns A promise that resolves when the port is opened.
99+
* @throws {Error} If the timeout is reached before the port opens
97100
*/
98-
async waitForPort(port: number): Promise<PortInfo> {
101+
async waitForPort(
102+
port: number,
103+
options?: { timeoutMs?: number }
104+
): Promise<PortInfo> {
99105
await this.pitcherClient.clients.port.readyPromise;
100106

101-
return new Promise((resolve) => {
107+
return new Promise((resolve, reject) => {
108+
// Check if port is already open
102109
const portInfo = this.getOpenedPorts().find((p) => p.port === port);
103110
if (portInfo) {
104111
resolve(portInfo);
105112
return;
106113
}
107114

115+
// Set up timeout if specified
116+
let timeoutId: NodeJS.Timeout | undefined;
117+
if (options?.timeoutMs !== undefined) {
118+
timeoutId = setTimeout(() => {
119+
reject(
120+
new Error(
121+
`Timeout of ${options.timeoutMs}ms exceeded waiting for port ${port} to open`
122+
)
123+
);
124+
}, options.timeoutMs);
125+
}
126+
127+
// Listen for port open events
108128
const disposable = this.addDisposable(
109129
this.onDidPortOpen((portInfo) => {
110130
if (portInfo.port === port) {
131+
if (timeoutId !== undefined) {
132+
clearTimeout(timeoutId);
133+
}
111134
resolve(portInfo);
112135
disposable.dispose();
113136
}

0 commit comments

Comments
 (0)