-
Notifications
You must be signed in to change notification settings - Fork 24.3k
/
ServerUtils.js
162 lines (153 loc) · 4.68 KB
/
ServerUtils.js
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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow strict-local
* @format
* @oncall react_native
*/
import type {JSONSerializable} from '../inspector-proxy/types';
import type {HandleFunction} from 'connect';
import {createDevMiddleware} from '../';
import connect from 'connect';
import http from 'http';
import https from 'https';
import * as selfsigned from 'selfsigned';
import url from 'url';
type CreateDevMiddlewareOptions = Parameters<typeof createDevMiddleware>[0];
type CreateServerOptions = {
...Omit<CreateDevMiddlewareOptions, 'serverBaseUrl'>,
secure?: boolean,
};
type ConnectApp = ReturnType<typeof connect>;
export function withServerForEachTest(options: CreateServerOptions): $ReadOnly<{
serverBaseUrl: string,
serverBaseWsUrl: string,
app: ConnectApp,
port: number,
}> {
const EAGER_ACCESS_ERROR_MESSAGE =
'The return value of withServerForEachTest is lazily initialized and can only be accessed in tests.';
const ref: {
serverBaseUrl: string,
serverBaseWsUrl: string,
app: ConnectApp,
port: number,
} = {
// $FlowIgnore[unsafe-getters-setters]
get serverBaseUrl() {
throw new Error(EAGER_ACCESS_ERROR_MESSAGE);
},
// $FlowIgnore[unsafe-getters-setters]
get serverBaseWsUrl() {
throw new Error(EAGER_ACCESS_ERROR_MESSAGE);
},
// $FlowIgnore[unsafe-getters-setters]
get app() {
throw new Error(EAGER_ACCESS_ERROR_MESSAGE);
},
// $FlowIgnore[unsafe-getters-setters]
get port() {
throw new Error(EAGER_ACCESS_ERROR_MESSAGE);
},
};
let server: http$Server | https$Server;
let app: ConnectApp;
beforeEach(async () => {
({server, app} = await createServer(options));
const serverBaseUrl = baseUrlForServer(
server,
options.secure ?? false ? 'https' : 'http',
);
const serverBaseWsUrl = baseUrlForServer(
server,
options.secure ?? false ? 'wss' : 'ws',
);
Object.defineProperty(ref, 'serverBaseUrl', {value: serverBaseUrl});
Object.defineProperty(ref, 'serverBaseWsUrl', {value: serverBaseWsUrl});
Object.defineProperty(ref, 'app', {value: app});
Object.defineProperty(ref, 'port', {value: server.address().port});
});
afterEach(done => {
server.close(() => done());
});
return ref;
}
export async function createServer(options: CreateServerOptions): Promise<{
server: http$Server | https$Server,
app: ReturnType<typeof connect>,
}> {
const app = connect();
const {secure = false, ...devMiddlewareOptions} = options;
let httpServer;
if (secure) {
const {cert, private: key} = selfsigned.generate(
[{name: 'commonName', value: 'localhost'}],
{days: 1},
);
httpServer = https.createServer(
{cert, key},
// $FlowFixMe[incompatible-call] The types for `connect` and `https` are subtly incompatible as written.
app,
);
} else {
httpServer = http.createServer(app);
}
return new Promise((resolve, reject) => {
httpServer.once('error', reject);
httpServer.listen(() => {
const {middleware, websocketEndpoints} = createDevMiddleware({
...devMiddlewareOptions,
serverBaseUrl: baseUrlForServer(httpServer, secure ? 'https' : 'http'),
});
app.use(middleware);
httpServer.on('upgrade', (request, socket, head) => {
const {pathname} = url.parse(request.url);
if (pathname != null && websocketEndpoints[pathname]) {
websocketEndpoints[pathname].handleUpgrade(
request,
socket,
head,
ws => {
websocketEndpoints[pathname].emit('connection', ws, request);
},
);
} else {
socket.destroy();
}
});
resolve({server: httpServer, app});
});
});
}
export function baseUrlForServer(
server: http$Server | https$Server,
scheme: string,
): string {
const address = server.address();
// Assumption: `server` is local and listening on `localhost`. We can't use
// the IP address because HTTPS requires a hostname.
return `${scheme}://localhost:${address.port}`;
}
export function serveStaticJson(json: JSONSerializable): HandleFunction {
return (req, res, next) => {
if (req.method !== 'GET') {
next();
return;
}
res.writeHead(200, {'Content-Type': 'application/json'});
res.end(JSON.stringify(json));
};
}
export function serveStaticText(text: string): HandleFunction {
return (req, res, next) => {
if (req.method !== 'GET') {
next();
return;
}
res.writeHead(200, {'Content-Type': 'text/plain'});
res.end(text);
};
}