-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathurls.ts
More file actions
111 lines (96 loc) · 2.02 KB
/
urls.ts
File metadata and controls
111 lines (96 loc) · 2.02 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
import url from 'url';
import net from 'net';
import address from 'address';
import { env } from './env';
export interface ServiceUrl {
url: string;
port: number;
host: string;
}
interface InternalServiceUrls {
local: ServiceUrl;
network: ServiceUrl;
}
export const DEFAULT_PORT = 3000;
/**
* Finds whether the port is available
*
* @param port the port to check
* @private
*/
/* c8 ignore next */
const _findPort = async (port: number) => {
return new Promise((resolve, reject) => {
const server = net.createConnection({ port });
/*
* If we can connect, port is not free
* If we cannot connect (i.e. on('error')), then port is free
*/
server
.on('connect', () => {
server.end();
reject();
})
.on('error', () => resolve(port));
});
};
/**
* Returns the default port
* @param port optional port parameter
*/
export const getDefaultPort = (port?: string): number => {
if (port) {
const numeric = parseInt(port, 10);
if (isNaN(numeric)) {
return DEFAULT_PORT;
}
return numeric;
}
return DEFAULT_PORT;
};
/**
* Finds the first available
*
* @param startPort
*/
/* c8 ignore next */
export const findPort = async (startPort: number = 3000): Promise<number> => {
try {
await Promise.all([_findPort(startPort)]);
return startPort;
} catch (e) {
return findPort(startPort + 1);
}
};
/**
* Returns the local and network urls
* @param port the port the server is running on
*/
export const getLocalAndNetworkUrls = (port: number): InternalServiceUrls => {
const protocol = env.isHTTPS() ? 'https' : 'http';
const localUrl = url.format({
protocol,
port,
hostname: 'localhost',
pathname: '/',
});
const networkUrl = url.format({
protocol,
port,
hostname: address.ip(),
pathname: '/',
});
return {
local: {
url: localUrl,
port,
host: '0.0.0.0',
},
network: {
url: networkUrl,
port,
host: address.ip(),
},
};
};
export default url;