Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

hmr.ts

54 lines1.5 KB

1import * as http from 'node:http'
2​
3import { createFetchProxy } from 'remix/fetch-proxy'
4import { createHmrReadyFetch, run } from 'remix/node-hmr'
5import { createRequestListener } from 'remix/node-fetch-server'
6​
7function parsePort(value: string | undefined, fallback: number): number {
8 const port = value === undefined ? fallback : Number.parseInt(value, 10)
9 if (!Number.isInteger(port) || port < 1 || port > 65535) {
10 throw new Error(
11 `Port must be an integer from 1 to 65535 (got ${value ?? fallback})`,
12 )
13 }
14 return port
16​
17const hmrProxyPort = parsePort(process.env.PORT, 44100)
18const hmrEventPort = parsePort(process.env.HMR_PORT, hmrProxyPort + 1)
19const appPort = parsePort(process.env.APP_PORT, hmrEventPort + 1)
20​
21const hmrRunner = run('server.ts', {
22 env: {
23 ...process.env,
24 PORT: String(appPort),
25 HMR_PROXY_PORT: String(hmrProxyPort),
26 },
27 nodeArgs: ['--import', 'remix/node-tsx', '--import', 'remix/ui-hmr/node'],
28 browserHmrChannel: { port: hmrEventPort },
29})
30​
31const server = http.createServer(
32 createRequestListener(
33 createHmrReadyFetch(
34 hmrRunner,
35 createFetchProxy(`http://127.0.0.1:${appPort}`, {
36 xForwardedHeaders: true,
37 }),
38 ),
39 ),
41​
42server.listen(hmrProxyPort, '127.0.0.1')
43​
44let shuttingDown = false
45​
46function shutdown() {
47 if (shuttingDown) return
48 shuttingDown = true
49 server.close(() => hmrRunner.close().finally(() => process.exit(0)))
50 server.closeAllConnections()
52​
53process.on('SIGINT', shutdown)
54process.on('SIGTERM', shutdown)