-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
181 lines (159 loc) · 5.43 KB
/
index.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
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
'use strict';
const {
createReadableStreamFromReadable,
writeReadableStreamToWritable,
createRequestHandler: createRemixRequestHandler,
} = require('@remix-run/node');
const path = require('node:path');
const url = require('node:url');
/**
* Middleware function for integrating Remix with Express.
*
* @param {Object} options - Configuration options for Remix integration.
* @param {Object} options.build - Remix build instance.
* @param {Function} [options.getLoadContext] - Function to generate the load context.
* @param {string} options.mode - Application mode (e.g., development or production).
* @returns {Function} Express middleware function.
*/
const remixExpress =
({ build, getLoadContext, mode = process.env.NODE_ENV || 'development' }) =>
async (req, res, next) => {
try {
const remixRequestHandler = createRemixRequestHandler(build, mode);
const request = createRemixRequest(req, res);
const loadContext = getLoadContext ? getLoadContext(req, res) : {};
const response = await remixRequestHandler(request, loadContext);
await sendRemixResponse(res, response);
} catch (error) {
next(error);
}
};
/**
* Sends a Remix response using the given Express response object.
*
* @param {Object} res - Express response object.
* @param {Object} nodeResponse - Remix response object.
* @returns {Promise<void>}
*/
async function sendRemixResponse(res, nodeResponse) {
const { status, statusText, headers, body } = nodeResponse;
res.statusMessage = statusText;
res.status(status);
res.set(Object.fromEntries(headers));
const contentType = headers.get('Content-Type');
if (contentType?.toLowerCase().includes('text/event-stream')) {
res.flushHeaders();
}
if (body) {
await writeReadableStreamToWritable(body, res);
} else {
res.end();
}
}
/**
* Converts incoming request headers to a Remix Headers object.
*
* @param {Object} requestHeaders - Incoming request headers.
* @returns {Headers} Headers object for Remix.
*/
function createRemixHeaders(requestHeaders) {
return new Headers(
Object.entries(requestHeaders).flatMap(([key, values]) =>
values ? (Array.isArray(values) ? values.map((value) => [key, value]) : [[key, values]]) : []
)
);
}
/**
* Extracts the port number from the host header.
*
* @param {string} header - Host header value.
* @returns {string|undefined} Port number if available.
*/
const getPort = (header) => header?.split(':')?.[1];
/**
* Creates a Remix Request object from an Express request.
*
* @param {Object} req - Express request object.
* @param {Object} res - Express response object.
* @returns {Request} Remix Request object.
*/
function createRemixRequest(req, res) {
const port = getPort(req.get('X-Forwarded-Host')) || getPort(req.get('host'));
const host = `${req.hostname}${port ? `:${port}` : ''}`;
const url = new URL(`${req.protocol}://${host}${req.originalUrl}`);
const controller = new AbortController();
res.on('close', () => controller.abort());
const init = {
method: req.method,
headers: createRemixHeaders(req.headers),
signal: controller.signal,
};
if (!['GET', 'HEAD'].includes(req.method)) {
init.body = createReadableStreamFromReadable(req);
init.duplex = 'half';
}
return new Request(url.href, init);
}
/**
* Create a new express app with Remix SSR support.
*
* @param {Object} config - Configuration object for the app.
* @param {Function} [config.express=require('express')] - Express instance.
* @param {Object} [config.buildOptions] - Remix build options.
* @param {string} [config.buildOptions.buildDirectory='build'] - Build directory.
* @param {string} [config.buildOptions.clientDirectory='public'] - Client directory.
* @param {string} [config.buildOptions.serverDirectory='server'] - Server directory.
* @param {string} [config.buildOptions.serverBuildFile='index.js'] - Server build file.
* @param {string} [config.mode=process.env.NODE_ENV] - Node environment mode.
* @param {Object} [config.expressStaticOptions={}] - Express static options.
* @param {Object} [config.viteOptions={}] - Vite options.
* @returns {Promise<Function>} Express app.
*/
const createRemixExpressApp = async ({
express = require('express'),
buildOptions = {
buildDirectory: 'build',
clientDirectory: 'client',
serverDirectory: 'server',
serverBuildFile: 'index.js',
},
mode = process.env.NODE_ENV || 'development',
expressStaticOptions = {},
viteOptions = {},
}) => {
const app = express();
const cwd = process.cwd();
const clientDirectory = path.join(cwd, buildOptions.buildDirectory, buildOptions.clientDirectory);
const serverBuildUrl = url.pathToFileURL(
path.join(cwd, buildOptions.buildDirectory, buildOptions.serverDirectory, buildOptions.serverBuildFile)
).href;
let viteDevServer = undefined;
if (mode === 'development') {
const vite = await require('vite');
viteDevServer = await vite.createServer({
...viteOptions,
server: { middlewareMode: true, ...viteOptions?.server },
});
app.use(viteDevServer.middlewares);
} else {
app.use(
express.static(clientDirectory, {
...expressStaticOptions,
})
);
}
const build = viteDevServer
? () => viteDevServer.ssrLoadModule('virtual:remix/server-build')
: () => import(serverBuildUrl);
app.use(
remixExpress({
build,
mode,
})
);
return app;
};
module.exports = {
createRemixExpressApp,
remixExpress,
};