Skip to content

Commit f1dd587

Browse files
authored
fix: support dev server on node 18 (#720)
1 parent 1240f92 commit f1dd587

File tree

2 files changed

+45
-7
lines changed

2 files changed

+45
-7
lines changed

src/core/utils/net.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ export async function validateDevServerConfig(url: string | undefined, timeout:
103103
const resolvedPortNumber = await isAcceptingTcpConnections({ port, host: hostname });
104104
if (resolvedPortNumber !== 0) {
105105
const spinner = ora();
106-
const waitOnOneOfResources = hostname === "localhost" ? [`tcp:127.0.0.1:${port}`, `tcp:[::1]:${port}`] : [`tcp:${hostname}:${port}`];
106+
let waitOnOneOfResources = hostname === "localhost" ? [`tcp:127.0.0.1:${port}`, `tcp:localhost:${port}`] : [`tcp:${hostname}:${port}`];
107107
spinner.start(`Waiting for ${chalk.green(url)} to be ready`);
108108

109109
let promises = waitOnOneOfResources.map((resource) => {
@@ -130,7 +130,7 @@ export async function validateDevServerConfig(url: string | undefined, timeout:
130130

131131
try {
132132
await Promise.any(promises);
133-
spinner.succeed(`Connected to ${url} successfully`);
133+
spinner.succeed(`${url} validated successfully`);
134134
spinner.clear();
135135
} catch {
136136
spinner.fail();

src/msha/middlewares/request.middleware.ts

Lines changed: 43 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@ import serveStatic from "serve-static";
99
import { DEFAULT_CONFIG } from "../../config";
1010
import { findSWAConfigFile, logger, logRequest } from "../../core";
1111
import { AUTH_STATUS, CUSTOM_URL_SCHEME, IS_APP_DEV_SERVER, SWA_PUBLIC_DIR } from "../../core/constants";
12+
import { parseUrl } from "../../core/utils/net";
13+
import waitOn from "wait-on";
1214
import { getAuthBlockResponse, handleAuthRequest, isAuthRequest, isLoginRequest, isLogoutRequest } from "../handlers/auth.handler";
1315
import { isDataApiRequest } from "../handlers/dab.handler";
1416
import { handleErrorPage } from "../handlers/error-page.handler";
@@ -67,7 +69,7 @@ export async function handleUserConfig(appLocation: string | undefined): Promise
6769
* @param proxyApp An `http-proxy` instance.
6870
* @param target The root folder of the static app (ie. `output_location`). Or, the HTTP host target, if connecting to a dev server, or
6971
*/
70-
function serveStaticOrProxyResponse(req: http.IncomingMessage, res: http.ServerResponse, proxyApp: httpProxy, target: string | undefined) {
72+
async function serveStaticOrProxyResponse(req: http.IncomingMessage, res: http.ServerResponse, proxyApp: httpProxy, target: string | undefined) {
7173
if ([301, 302].includes(res.statusCode)) {
7274
res.end();
7375
return;
@@ -100,6 +102,42 @@ function serveStaticOrProxyResponse(req: http.IncomingMessage, res: http.ServerR
100102
target = DEFAULT_CONFIG.outputLocation;
101103
logRequest(req, target);
102104

105+
let { protocol, hostname, port } = parseUrl(target);
106+
107+
if (hostname === "localhost") {
108+
let waitOnOneOfResources = [`tcp:127.0.0.1:${port}`, `tcp:localhost:${port}`];
109+
let promises = waitOnOneOfResources.map((resource) => {
110+
return waitOn({
111+
resources: [resource],
112+
delay: 1000, // initial delay in ms, default 0
113+
interval: 100, // poll interval in ms, default 250ms
114+
simultaneous: 1, // limit to 1 connection per resource at a time
115+
timeout: 60000, // timeout in ms, default Infinity
116+
tcpTimeout: 1000, // tcp timeout in ms, default 300ms
117+
window: 1000, // stabilization time in ms, default 750ms
118+
strictSSL: false,
119+
verbose: false, // force disable verbose logs even if SWA_CLI_DEBUG is enabled
120+
})
121+
.then(() => {
122+
logger.silly(`Connected to ${resource} successfully`);
123+
return resource;
124+
})
125+
.catch((err) => {
126+
logger.silly(`Could not connect to ${resource}`);
127+
logger.warn(err.message);
128+
throw err;
129+
});
130+
});
131+
132+
try {
133+
const availableUrl = await Promise.any(promises);
134+
logger.silly(`${target} validated successfully`);
135+
target = protocol + "//" + availableUrl.slice(4);
136+
} catch {
137+
logger.error(`Could not connect to "${target}". Is the server up and running?`);
138+
}
139+
}
140+
103141
proxyApp.web(
104142
req,
105143
res,
@@ -209,7 +247,7 @@ export async function requestMiddleware(
209247

210248
if (isWebsocketRequest(req)) {
211249
logger.silly(`websocket request detected`);
212-
return serveStaticOrProxyResponse(req, res, proxyApp, DEFAULT_CONFIG.outputLocation);
250+
return await serveStaticOrProxyResponse(req, res, proxyApp, DEFAULT_CONFIG.outputLocation);
213251
}
214252

215253
let target = DEFAULT_CONFIG.outputLocation;
@@ -224,7 +262,7 @@ export async function requestMiddleware(
224262
logger.silly(` - ${statusCodeToServe} code detected. Exit`);
225263

226264
handleErrorPage(req, res, statusCodeToServe, userConfig?.responseOverrides);
227-
return serveStaticOrProxyResponse(req, res, proxyApp, target);
265+
return await serveStaticOrProxyResponse(req, res, proxyApp, target);
228266
}
229267
}
230268

@@ -280,7 +318,7 @@ export async function requestMiddleware(
280318

281319
if (!isRouteRequiringUserRolesCheck(req, matchingRouteRule, isFunctionReq, authStatus)) {
282320
handleErrorPage(req, res, 401, userConfig?.responseOverrides);
283-
return serveStaticOrProxyResponse(req, res, proxyApp, target);
321+
return await serveStaticOrProxyResponse(req, res, proxyApp, target);
284322
}
285323

286324
if (authStatus != AUTH_STATUS.NoAuth && (authStatus != AUTH_STATUS.HostNameAuthLogin || !urlPathnameWithQueryParams)) {
@@ -295,6 +333,6 @@ export async function requestMiddleware(
295333
logger.silly(` - url: ${chalk.yellow(req.url)}`);
296334
logger.silly(` - target: ${chalk.yellow(target)}`);
297335

298-
serveStaticOrProxyResponse(req, res, proxyApp, target);
336+
await serveStaticOrProxyResponse(req, res, proxyApp, target);
299337
}
300338
}

0 commit comments

Comments
 (0)