@bleedingdev/modern-js-server-core 3.9.3-ultramodern.9 → 3.11.3-ultramodern.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cjs/adapters/node/node.js +63 -4
- package/dist/cjs/adapters/node/plugins/resource.js +38 -10
- package/dist/cjs/adapters/node/plugins/static.js +39 -21
- package/dist/cjs/adapters/node/plugins/staticCache.js +110 -0
- package/dist/cjs/constants.js +2 -3
- package/dist/cjs/helper.js +2 -2
- package/dist/cjs/plugins/compat/hooks.js +4 -4
- package/dist/cjs/plugins/monitors.js +4 -7
- package/dist/cjs/plugins/render/index.js +6 -8
- package/dist/cjs/plugins/render/render.js +6 -7
- package/dist/cjs/plugins/render/ssrCache.js +10 -1
- package/dist/cjs/plugins/render/ssrRender.js +0 -4
- package/dist/cjs/plugins/render/utils.js +2 -2
- package/dist/cjs/plugins/route.js +1 -1
- package/dist/cjs/serverBase.js +5 -1
- package/dist/cjs/utils/entry.js +7 -0
- package/dist/cjs/utils/request.js +6 -6
- package/dist/cjs/utils/transformStream.js +3 -3
- package/dist/cjs/utils/warmup.js +2 -2
- package/dist/esm/adapters/node/node.mjs +64 -5
- package/dist/esm/adapters/node/plugins/resource.mjs +38 -10
- package/dist/esm/adapters/node/plugins/static.mjs +39 -21
- package/dist/esm/adapters/node/plugins/staticCache.mjs +56 -0
- package/dist/esm/context.mjs +1 -1
- package/dist/esm/plugins/monitors.mjs +4 -7
- package/dist/esm/plugins/render/index.mjs +7 -9
- package/dist/esm/plugins/render/render.mjs +7 -8
- package/dist/esm/plugins/render/ssrCache.mjs +10 -1
- package/dist/esm/plugins/render/ssrRender.mjs +1 -5
- package/dist/esm/plugins/route.mjs +2 -2
- package/dist/esm/serverBase.mjs +5 -1
- package/dist/esm/utils/entry.mjs +5 -1
- package/dist/esm-node/adapters/node/node.mjs +64 -5
- package/dist/esm-node/adapters/node/plugins/resource.mjs +38 -10
- package/dist/esm-node/adapters/node/plugins/static.mjs +39 -21
- package/dist/esm-node/adapters/node/plugins/staticCache.mjs +57 -0
- package/dist/esm-node/context.mjs +1 -1
- package/dist/esm-node/plugins/monitors.mjs +4 -7
- package/dist/esm-node/plugins/render/index.mjs +7 -9
- package/dist/esm-node/plugins/render/render.mjs +7 -8
- package/dist/esm-node/plugins/render/ssrCache.mjs +10 -1
- package/dist/esm-node/plugins/render/ssrRender.mjs +1 -5
- package/dist/esm-node/plugins/route.mjs +2 -2
- package/dist/esm-node/serverBase.mjs +5 -1
- package/dist/esm-node/utils/entry.mjs +5 -1
- package/dist/types/adapters/node/plugins/resource.d.ts +3 -1
- package/dist/types/adapters/node/plugins/static.d.ts +8 -3
- package/dist/types/adapters/node/plugins/staticCache.d.ts +27 -0
- package/dist/types/context.d.ts +5 -1
- package/dist/types/hono.d.ts +1 -1
- package/dist/types/serverBase.d.ts +1 -0
- package/dist/types/types/config/server.d.ts +17 -0
- package/dist/types/utils/entry.d.ts +1 -0
- package/package.json +11 -11
|
@@ -66,12 +66,12 @@ function parseCookie(req) {
|
|
|
66
66
|
});
|
|
67
67
|
return cookie;
|
|
68
68
|
}
|
|
69
|
-
__webpack_require__.d(__webpack_exports__, {
|
|
70
|
-
getHost:
|
|
71
|
-
getPathname:
|
|
72
|
-
parseCookie:
|
|
73
|
-
parseHeaders:
|
|
74
|
-
parseQuery:
|
|
69
|
+
__webpack_require__.d(__webpack_exports__, {}, {
|
|
70
|
+
getHost: getHost,
|
|
71
|
+
getPathname: getPathname,
|
|
72
|
+
parseCookie: parseCookie,
|
|
73
|
+
parseHeaders: parseHeaders,
|
|
74
|
+
parseQuery: parseQuery
|
|
75
75
|
});
|
|
76
76
|
exports.getHost = __webpack_exports__.getHost;
|
|
77
77
|
exports.getPathname = __webpack_exports__.getPathname;
|
|
@@ -54,9 +54,9 @@ function transformResponse(response, transformCb) {
|
|
|
54
54
|
statusText: response.statusText
|
|
55
55
|
});
|
|
56
56
|
}
|
|
57
|
-
__webpack_require__.d(__webpack_exports__, {
|
|
58
|
-
createTransformStream:
|
|
59
|
-
transformResponse:
|
|
57
|
+
__webpack_require__.d(__webpack_exports__, {}, {
|
|
58
|
+
createTransformStream: createTransformStream,
|
|
59
|
+
transformResponse: transformResponse
|
|
60
60
|
});
|
|
61
61
|
exports.createTransformStream = __webpack_exports__.createTransformStream;
|
|
62
62
|
exports.transformResponse = __webpack_exports__.transformResponse;
|
package/dist/cjs/utils/warmup.js
CHANGED
|
@@ -32,8 +32,8 @@ function warmup(bundles) {
|
|
|
32
32
|
bundle && import(bundle).catch((_)=>{});
|
|
33
33
|
});
|
|
34
34
|
}
|
|
35
|
-
__webpack_require__.d(__webpack_exports__, {
|
|
36
|
-
warmup:
|
|
35
|
+
__webpack_require__.d(__webpack_exports__, {}, {
|
|
36
|
+
warmup: warmup
|
|
37
37
|
});
|
|
38
38
|
exports.warmup = __webpack_exports__.warmup;
|
|
39
39
|
for(var __rspack_i in __webpack_exports__)if (-1 === [
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { ServerResponse } from "node:http";
|
|
2
|
-
import { Readable
|
|
2
|
+
import { Readable } from "node:stream";
|
|
3
3
|
import cloneable_readable from "cloneable-readable";
|
|
4
4
|
import { isResFinalized } from "./helper/index.mjs";
|
|
5
5
|
const createWebRequest = (req, res, body)=>{
|
|
@@ -67,6 +67,67 @@ const createWebRequest = (req, res, body)=>{
|
|
|
67
67
|
}
|
|
68
68
|
return originalRequest;
|
|
69
69
|
};
|
|
70
|
+
const noop = ()=>{};
|
|
71
|
+
const isDestroyed = (res)=>'stream' in res ? res.stream.destroyed : res.destroyed;
|
|
72
|
+
const createAbortError = ()=>Object.assign(new Error('The operation was aborted'), {
|
|
73
|
+
name: 'AbortError',
|
|
74
|
+
code: 'ABORT_ERR'
|
|
75
|
+
});
|
|
76
|
+
const writeBody = async (body, res)=>{
|
|
77
|
+
const reader = body.getReader();
|
|
78
|
+
let abortError;
|
|
79
|
+
let cancelled;
|
|
80
|
+
let resume;
|
|
81
|
+
let waitsForDrain = false;
|
|
82
|
+
const onDrain = ()=>resume?.();
|
|
83
|
+
const abort = (error)=>{
|
|
84
|
+
if (cancelled) return;
|
|
85
|
+
abortError = error;
|
|
86
|
+
cancelled = reader.cancel(error);
|
|
87
|
+
cancelled.catch(noop);
|
|
88
|
+
resume?.();
|
|
89
|
+
};
|
|
90
|
+
const onClose = ()=>abort(createAbortError());
|
|
91
|
+
res.on('close', onClose);
|
|
92
|
+
res.on('error', abort);
|
|
93
|
+
try {
|
|
94
|
+
if (isDestroyed(res)) onClose();
|
|
95
|
+
while(!cancelled){
|
|
96
|
+
let result;
|
|
97
|
+
try {
|
|
98
|
+
result = await reader.read();
|
|
99
|
+
} catch (error) {
|
|
100
|
+
res.destroy(error);
|
|
101
|
+
throw error;
|
|
102
|
+
}
|
|
103
|
+
if (result.done || cancelled) break;
|
|
104
|
+
try {
|
|
105
|
+
if (!res.write(result.value) && !cancelled) {
|
|
106
|
+
if (!waitsForDrain) {
|
|
107
|
+
waitsForDrain = true;
|
|
108
|
+
res.on('drain', onDrain);
|
|
109
|
+
}
|
|
110
|
+
await new Promise((resolve)=>{
|
|
111
|
+
resume = resolve;
|
|
112
|
+
});
|
|
113
|
+
resume = void 0;
|
|
114
|
+
}
|
|
115
|
+
} catch (error) {
|
|
116
|
+
abort(error);
|
|
117
|
+
}
|
|
118
|
+
}
|
|
119
|
+
if (cancelled) {
|
|
120
|
+
await cancelled;
|
|
121
|
+
throw abortError;
|
|
122
|
+
}
|
|
123
|
+
res.end();
|
|
124
|
+
} finally{
|
|
125
|
+
res.off('close', onClose);
|
|
126
|
+
res.off('error', abort);
|
|
127
|
+
if (waitsForDrain) res.off('drain', onDrain);
|
|
128
|
+
reader.releaseLock();
|
|
129
|
+
}
|
|
130
|
+
};
|
|
70
131
|
const sendResponse = async (response, res)=>{
|
|
71
132
|
res.statusMessage = response.statusText;
|
|
72
133
|
res.statusCode = response.status;
|
|
@@ -75,10 +136,8 @@ const sendResponse = async (response, res)=>{
|
|
|
75
136
|
else res.setHeader(key, value);
|
|
76
137
|
if (cookies.length > 0) res.setHeader('set-cookie', cookies);
|
|
77
138
|
if (response.headers.get('Content-Type')?.match(/text\/event-stream/i) && res instanceof ServerResponse) res.flushHeaders();
|
|
78
|
-
if (response.body)
|
|
79
|
-
|
|
80
|
-
await response.body.pipeTo(writable);
|
|
81
|
-
} else res.end();
|
|
139
|
+
if (response.body) await writeBody(response.body, res);
|
|
140
|
+
else res.end();
|
|
82
141
|
};
|
|
83
142
|
const handleResponseError = (e, res)=>{
|
|
84
143
|
const err = e instanceof Error ? e : new Error('unknown error', {
|
|
@@ -27,28 +27,51 @@ function injectTemplates(pwd, routes, htmlTemplatePromise) {
|
|
|
27
27
|
await next();
|
|
28
28
|
};
|
|
29
29
|
}
|
|
30
|
-
|
|
31
|
-
|
|
30
|
+
function reportBundleError(filepath, error, monitors) {
|
|
31
|
+
const detail = error instanceof Error ? error.stack || error.message : error;
|
|
32
|
+
if (monitors) monitors.error(`Load ${filepath} bundle failed, error = %s`, detail);
|
|
33
|
+
else console.error(`Load ${filepath} bundle failed, error = ${detail}`);
|
|
34
|
+
}
|
|
35
|
+
const loadBundle = async (filepath, monitors, { required = false, failOnError = false } = {})=>{
|
|
36
|
+
if (!required && !failOnError && !await fs.pathExists(filepath)) return;
|
|
32
37
|
try {
|
|
38
|
+
if (!required && failOnError) try {
|
|
39
|
+
await fs.access(filepath);
|
|
40
|
+
} catch (e) {
|
|
41
|
+
const code = e?.code;
|
|
42
|
+
if ('ENOENT' === code || 'ENOTDIR' === code) return;
|
|
43
|
+
throw e;
|
|
44
|
+
}
|
|
33
45
|
const module = await compatibleRequire(filepath, false);
|
|
34
46
|
return module;
|
|
35
47
|
} catch (e) {
|
|
36
|
-
|
|
37
|
-
|
|
48
|
+
reportBundleError(filepath, e, monitors);
|
|
49
|
+
if (failOnError) throw e;
|
|
38
50
|
return;
|
|
39
51
|
}
|
|
40
52
|
};
|
|
41
|
-
async function getServerManifest(pwd, routes, monitors) {
|
|
53
|
+
async function getServerManifest(pwd, routes, monitors, { failOnError = false } = {}) {
|
|
42
54
|
const loaderBundles = {};
|
|
43
55
|
const renderBundles = {};
|
|
44
56
|
await Promise.all(routes.filter((route)=>Boolean(route.bundle)).map(async (route)=>{
|
|
57
|
+
const failOnBundleError = failOnError && Boolean(route.isSSR);
|
|
45
58
|
const entryName = route.entryName || MAIN_ENTRY_NAME;
|
|
46
59
|
const renderBundlePath = path.join(pwd, route.bundle || '');
|
|
47
60
|
const loaderBundlePath = path.join(pwd, SERVER_BUNDLE_DIRECTORY, `${entryName}-server-loaders.js`);
|
|
48
|
-
const renderBundle = await loadBundle(renderBundlePath, monitors
|
|
49
|
-
|
|
61
|
+
const renderBundle = await loadBundle(renderBundlePath, monitors, {
|
|
62
|
+
required: failOnBundleError,
|
|
63
|
+
failOnError: failOnBundleError
|
|
64
|
+
});
|
|
65
|
+
const loaderBundle = await loadBundle(loaderBundlePath, monitors, {
|
|
66
|
+
failOnError: failOnBundleError
|
|
67
|
+
});
|
|
50
68
|
renderBundle && (renderBundles[entryName] = renderBundle);
|
|
51
|
-
|
|
69
|
+
if (loaderBundle) try {
|
|
70
|
+
loaderBundles[entryName] = loaderBundle.loadModules ? await loaderBundle.loadModules() : loaderBundle;
|
|
71
|
+
} catch (e) {
|
|
72
|
+
if (failOnBundleError) reportBundleError(loaderBundlePath, e, monitors);
|
|
73
|
+
throw e;
|
|
74
|
+
}
|
|
52
75
|
}));
|
|
53
76
|
const loadableUri = path.join(pwd, LOADABLE_STATS_FILE);
|
|
54
77
|
const loadableStats = await compatibleRequire(loadableUri).catch((_)=>({}));
|
|
@@ -116,13 +139,18 @@ const injectRscManifestPlugin = (enableRsc)=>({
|
|
|
116
139
|
const injectResourcePlugin = ()=>({
|
|
117
140
|
name: '@modern-js/plugin-inject-resource',
|
|
118
141
|
setup (api) {
|
|
119
|
-
api.onPrepare(()=>{
|
|
142
|
+
api.onPrepare(async ()=>{
|
|
120
143
|
const { middlewares, routes, distDirectory: pwd } = api.getServerContext();
|
|
121
144
|
let htmlTemplatePromise;
|
|
122
145
|
let manifestPromise;
|
|
123
146
|
if (isProd()) {
|
|
124
|
-
|
|
147
|
+
const warmupRoutes = routes || [];
|
|
148
|
+
const failOnError = warmupRoutes.some((route)=>route.isSSR && route.bundle) && !warmupRoutes.some((route)=>route.isRSC);
|
|
149
|
+
manifestPromise = getServerManifest(pwd, warmupRoutes, void 0, {
|
|
150
|
+
failOnError
|
|
151
|
+
});
|
|
125
152
|
htmlTemplatePromise = getHtmlTemplates(pwd, routes || []);
|
|
153
|
+
if (failOnError) await manifestPromise;
|
|
126
154
|
}
|
|
127
155
|
middlewares.push({
|
|
128
156
|
name: 'inject-server-manifest',
|
|
@@ -4,6 +4,7 @@ import { getMimeType } from "hono/utils/mime";
|
|
|
4
4
|
import path from "path";
|
|
5
5
|
import { sortRoutes } from "../../../utils/index.mjs";
|
|
6
6
|
import { getPublicDirPatterns } from "../../../utils/publicDir.mjs";
|
|
7
|
+
import { createHashedAssetMatcher, resolveStaticCacheControl, setStaticFileHeaders } from "./staticCache.mjs";
|
|
7
8
|
const isPathInside = (target, root)=>{
|
|
8
9
|
const relative = path.relative(path.resolve(root), path.resolve(target));
|
|
9
10
|
return '' === relative || !relative.startsWith(`..${path.sep}`) && '..' !== relative && !path.isAbsolute(relative);
|
|
@@ -28,24 +29,26 @@ async function serveStaticAsset(context, asset, respond) {
|
|
|
28
29
|
} catch {
|
|
29
30
|
return null;
|
|
30
31
|
}
|
|
31
|
-
if ('static' === kind && !
|
|
32
|
+
if ('static' === kind && !asset.realpath) {
|
|
33
|
+
const stat = await fs.stat(filename).catch(()=>null);
|
|
34
|
+
if (!stat?.isFile()) return null;
|
|
35
|
+
}
|
|
32
36
|
if (respond) return respond(asset, (representation)=>serveStaticAsset(context, {
|
|
33
37
|
...asset,
|
|
34
38
|
...representation,
|
|
35
39
|
filename: representation?.filename ?? asset.filename,
|
|
36
40
|
mimeFilename: asset.mimeFilename ?? filename
|
|
37
41
|
}));
|
|
38
|
-
const mimeType = getMimeType(asset.mimeFilename ?? filename);
|
|
39
|
-
if ('static' === kind && mimeType) context.header('Content-Type', mimeType);
|
|
40
|
-
const size = 'static' === kind ? (await fs.lstat(filename)).size : void 0;
|
|
41
42
|
const data = 'static' === kind ? await fileReader.readFileFromSystem(filename, 'buffer') : await fileReader.readFile(filename, 'buffer');
|
|
42
|
-
if ('static' === kind && (asset.contentLength ?? true)) context.header('Content-Length', String(true === asset.contentLength && data ? data.byteLength : size));
|
|
43
43
|
if (null === data) return null;
|
|
44
|
-
|
|
44
|
+
const mimeType = getMimeType(asset.mimeFilename ?? filename);
|
|
45
|
+
if (mimeType) context.header('Content-Type', mimeType);
|
|
45
46
|
Object.entries(asset.responseHeaders || {}).forEach(([key, value])=>{
|
|
46
47
|
context.header(key, value);
|
|
47
48
|
});
|
|
48
|
-
|
|
49
|
+
const notModified = setStaticFileHeaders(context, data, asset.cacheControl);
|
|
50
|
+
if (notModified && false !== asset.revalidate) return context.body(null, 304);
|
|
51
|
+
if (asset.contentLength ?? 'static' === kind) context.header('Content-Length', String(data.byteLength));
|
|
49
52
|
const body = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
|
|
50
53
|
return context.body(body, 200);
|
|
51
54
|
}
|
|
@@ -71,14 +74,16 @@ const serverStaticPlugin = (options = {})=>({
|
|
|
71
74
|
});
|
|
72
75
|
}
|
|
73
76
|
});
|
|
74
|
-
function createPublicMiddleware({ pwd, routes, pathPrefix = '/', respondAsset, respondPublicFallback }) {
|
|
77
|
+
function createPublicMiddleware({ pwd, routes, pathPrefix = '/', cacheControl, respondAsset, respondPublicFallback }) {
|
|
78
|
+
const publicRoutes = routes.filter((route)=>!route.isSSR && route.entryPath?.startsWith('public')).sort(sortRoutes);
|
|
75
79
|
return async (c, next)=>{
|
|
76
80
|
const respondPublic = async ()=>{
|
|
77
|
-
const route = matchPublicRoute(c.req,
|
|
81
|
+
const route = matchPublicRoute(c.req, publicRoutes);
|
|
78
82
|
if (!route) return null;
|
|
79
83
|
const asset = {
|
|
80
84
|
filename: path.join(pwd, route.entryPath),
|
|
81
85
|
kind: 'public',
|
|
86
|
+
cacheControl: cacheControl?.unhashed,
|
|
82
87
|
responseHeaders: route.responseHeaders
|
|
83
88
|
};
|
|
84
89
|
const serve = (representation)=>serveStaticAsset(c, {
|
|
@@ -100,8 +105,8 @@ function createPublicMiddleware({ pwd, routes, pathPrefix = '/', respondAsset, r
|
|
|
100
105
|
return response ?? next();
|
|
101
106
|
};
|
|
102
107
|
}
|
|
103
|
-
function matchPublicRoute(req,
|
|
104
|
-
|
|
108
|
+
function matchPublicRoute(req, publicRoutes) {
|
|
109
|
+
return publicRoutes.find((route)=>req.path.startsWith(route.urlPath));
|
|
105
110
|
}
|
|
106
111
|
const extractPathname = (url)=>{
|
|
107
112
|
try {
|
|
@@ -114,6 +119,7 @@ const extractPathname = (url)=>{
|
|
|
114
119
|
};
|
|
115
120
|
function createStaticMiddleware(options) {
|
|
116
121
|
const { pwd, routes } = options;
|
|
122
|
+
const cacheControl = resolveStaticCacheControl(options.server.staticCacheControl);
|
|
117
123
|
const prefix = options.output.assetPrefix || '/';
|
|
118
124
|
const pathPrefix = extractPathname(prefix);
|
|
119
125
|
const { distPath: { css: cssPath, js: jsPath, media: mediaPath } = {} } = options.output;
|
|
@@ -126,6 +132,11 @@ function createStaticMiddleware(options) {
|
|
|
126
132
|
mediaPath
|
|
127
133
|
].filter((v)=>Boolean(v));
|
|
128
134
|
const publicDirPatterns = getPublicDirPatterns(publicDir);
|
|
135
|
+
const isHashedAsset = createHashedAssetMatcher(staticFiles, [
|
|
136
|
+
'public/',
|
|
137
|
+
'upload/',
|
|
138
|
+
...publicDirPatterns
|
|
139
|
+
]);
|
|
129
140
|
const staticReg = [
|
|
130
141
|
'static/',
|
|
131
142
|
'upload/',
|
|
@@ -142,25 +153,32 @@ function createStaticMiddleware(options) {
|
|
|
142
153
|
...staticReg,
|
|
143
154
|
...iconReg
|
|
144
155
|
].join('|')})`);
|
|
156
|
+
const publicMiddleware = createPublicMiddleware({
|
|
157
|
+
pwd,
|
|
158
|
+
routes: routes || [],
|
|
159
|
+
pathPrefix,
|
|
160
|
+
cacheControl,
|
|
161
|
+
respondAsset: options.respondAsset,
|
|
162
|
+
respondPublicFallback: options.respondPublicFallback
|
|
163
|
+
});
|
|
145
164
|
return async (c, next)=>{
|
|
146
165
|
const pageRoute = c.get('route');
|
|
147
166
|
const pathname = c.req.path;
|
|
148
167
|
if (pageRoute && '' === path.extname(pathname)) return next();
|
|
149
168
|
const hit = staticPathRegExp.test(pathname);
|
|
150
|
-
if (!hit) return
|
|
151
|
-
pwd,
|
|
152
|
-
routes: routes || [],
|
|
153
|
-
pathPrefix,
|
|
154
|
-
respondAsset: options.respondAsset,
|
|
155
|
-
respondPublicFallback: options.respondPublicFallback
|
|
156
|
-
})(c, next);
|
|
169
|
+
if (!hit) return publicMiddleware(c, next);
|
|
157
170
|
else {
|
|
158
|
-
const
|
|
171
|
+
const relativePath = pathname.replace(pathPrefix, ()=>'').replace(/^\/+/, '');
|
|
172
|
+
const filepath = path.join(pwd, relativePath);
|
|
159
173
|
if (!isPathInside(filepath, pwd)) return next();
|
|
160
|
-
if (
|
|
174
|
+
if (options.respondAsset) {
|
|
175
|
+
const stat = await fs.stat(filepath).catch(()=>null);
|
|
176
|
+
if (!stat?.isFile()) return next();
|
|
177
|
+
}
|
|
161
178
|
const asset = {
|
|
162
179
|
filename: filepath,
|
|
163
|
-
kind: 'static'
|
|
180
|
+
kind: 'static',
|
|
181
|
+
cacheControl: cacheControl && (isHashedAsset(relativePath) ? cacheControl.hashed : cacheControl.unhashed)
|
|
164
182
|
};
|
|
165
183
|
const serve = (representation)=>serveStaticAsset(c, {
|
|
166
184
|
...asset,
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import path from "path";
|
|
3
|
+
const DEFAULT_HASHED_CACHE_CONTROL = 'public, max-age=31536000, immutable';
|
|
4
|
+
const DEFAULT_UNHASHED_CACHE_CONTROL = 'no-cache';
|
|
5
|
+
const CONTENT_HASH_REGEX = /[.-][0-9a-f]{8,}\.[^./]+$/i;
|
|
6
|
+
function resolveStaticCacheControl(staticCacheControl) {
|
|
7
|
+
if (false === staticCacheControl) return;
|
|
8
|
+
if ('production' !== process.env.NODE_ENV) return {
|
|
9
|
+
hashed: 'no-cache',
|
|
10
|
+
unhashed: 'no-cache'
|
|
11
|
+
};
|
|
12
|
+
const options = 'object' == typeof staticCacheControl ? staticCacheControl : {};
|
|
13
|
+
return {
|
|
14
|
+
hashed: options.hashed ?? DEFAULT_HASHED_CACHE_CONTROL,
|
|
15
|
+
unhashed: options.unhashed ?? DEFAULT_UNHASHED_CACHE_CONTROL
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
const normalizeDir = (dir)=>{
|
|
19
|
+
const normalized = dir.replace(/^\.?\/?/, '').replace(/\/+$/, '');
|
|
20
|
+
return normalized ? `${normalized}/` : '';
|
|
21
|
+
};
|
|
22
|
+
function createHashedAssetMatcher(assetDirs, userDirs = []) {
|
|
23
|
+
const dirs = [
|
|
24
|
+
'static/',
|
|
25
|
+
...assetDirs.map(normalizeDir)
|
|
26
|
+
];
|
|
27
|
+
const isInAssetDir = (relativePath)=>!userDirs.some((userDir)=>relativePath.startsWith(userDir)) && dirs.some((dir)=>!dir || relativePath.startsWith(dir));
|
|
28
|
+
return (relativePath)=>isInAssetDir(relativePath) && CONTENT_HASH_REGEX.test(path.basename(relativePath));
|
|
29
|
+
}
|
|
30
|
+
const etags = new WeakMap();
|
|
31
|
+
function getETag(data) {
|
|
32
|
+
let etag = etags.get(data);
|
|
33
|
+
if (!etag) {
|
|
34
|
+
const hash = createHash('sha1').update(data).digest('base64url');
|
|
35
|
+
etag = `W/"${data.byteLength.toString(16)}-${hash.slice(0, 22)}"`;
|
|
36
|
+
etags.set(data, etag);
|
|
37
|
+
}
|
|
38
|
+
return etag;
|
|
39
|
+
}
|
|
40
|
+
const stripWeak = (etag)=>etag.trim().replace(/^W\//, '');
|
|
41
|
+
const ENTITY_TAG_REGEX = /(?:W\/)?"[^"]*"/g;
|
|
42
|
+
function setStaticFileHeaders(c, data, cacheControl) {
|
|
43
|
+
const { headers } = c.res;
|
|
44
|
+
let etag = headers.get('ETag');
|
|
45
|
+
if (!etag) {
|
|
46
|
+
etag = getETag(data);
|
|
47
|
+
c.header('ETag', etag);
|
|
48
|
+
}
|
|
49
|
+
if (cacheControl && !headers.has('Cache-Control')) c.header('Cache-Control', cacheControl);
|
|
50
|
+
const { method } = c.req;
|
|
51
|
+
const ifNoneMatch = c.req.header('If-None-Match');
|
|
52
|
+
if ('GET' !== method && 'HEAD' !== method || !ifNoneMatch) return false;
|
|
53
|
+
const expected = stripWeak(etag);
|
|
54
|
+
return '*' === ifNoneMatch.trim() || (ifNoneMatch.match(ENTITY_TAG_REGEX) || []).some((value)=>stripWeak(value) === expected);
|
|
55
|
+
}
|
|
56
|
+
export { createHashedAssetMatcher, resolveStaticCacheControl, setStaticFileHeaders };
|
package/dist/esm/context.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import { createStorage } from "./utils/storage.mjs";
|
|
2
2
|
const kHonoContextStorage = Symbol.for('modernjs.server-core.honoContextStorage');
|
|
3
|
-
const { run
|
|
3
|
+
const { run, useContext: useHonoContext } = createStorage(kHonoContextStorage);
|
|
4
4
|
export { run, useHonoContext };
|
|
@@ -123,13 +123,10 @@ const injectServerTiming = ()=>({
|
|
|
123
123
|
const monitors = c.get('monitors');
|
|
124
124
|
monitors?.push(timingMonitor);
|
|
125
125
|
await next();
|
|
126
|
-
serverTimings.
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
c.header(SERVER_TIMING, value, {
|
|
131
|
-
append: true
|
|
132
|
-
});
|
|
126
|
+
if (0 === serverTimings.length) return;
|
|
127
|
+
const value = serverTimings.map(({ name, desc, dur })=>`bd-${metaName}-${name};${desc ? `decs="${desc}";` : ''} dur=${dur}`).join(', ');
|
|
128
|
+
c.header(SERVER_TIMING, value, {
|
|
129
|
+
append: true
|
|
133
130
|
});
|
|
134
131
|
}
|
|
135
132
|
});
|
|
@@ -1,11 +1,7 @@
|
|
|
1
1
|
import { getLoaderCtx } from "../../helper.mjs";
|
|
2
|
-
import { sortRoutes } from "../../utils/index.mjs";
|
|
2
|
+
import { getRoutePath, sortRoutes } from "../../utils/index.mjs";
|
|
3
3
|
import { requestLatencyMiddleware } from "../monitors.mjs";
|
|
4
4
|
export * from "./inject.mjs";
|
|
5
|
-
const DYNAMIC_ROUTE_REG = /\/:./;
|
|
6
|
-
function escapeRegexSpecialChars(path) {
|
|
7
|
-
return path.replace(/[()[\]{}*+?.^$|\\]/g, '\\$&');
|
|
8
|
-
}
|
|
9
5
|
const renderPlugin = ()=>({
|
|
10
6
|
name: '@modern-js/plugin-render',
|
|
11
7
|
setup (api) {
|
|
@@ -18,10 +14,12 @@ const renderPlugin = ()=>({
|
|
|
18
14
|
handler: requestLatencyMiddleware()
|
|
19
15
|
});
|
|
20
16
|
for (const route of pageRoutes){
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
17
|
+
const urlPath = getRoutePath(route);
|
|
18
|
+
if (route.isSSG && !urlPath.endsWith('/')) middlewares.push({
|
|
19
|
+
name: 'ssg-trailing-slash-redirect',
|
|
20
|
+
path: `${urlPath}/`,
|
|
21
|
+
handler: async (c)=>c.redirect(`${urlPath}${new URL(c.req.url).search}`, 308)
|
|
22
|
+
});
|
|
25
23
|
renderMiddlewares?.forEach((m)=>{
|
|
26
24
|
middlewares.push({
|
|
27
25
|
name: m.name,
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { cutNameByHyphen } from "@modern-js/utils/universal";
|
|
2
2
|
import { TrieRouter } from "hono/router/trie-router";
|
|
3
|
+
import { getPath } from "hono/utils/url";
|
|
3
4
|
import { X_MODERNJS_RENDER } from "../../constants.mjs";
|
|
4
|
-
import { ErrorDigest, createErrorHtml,
|
|
5
|
+
import { ErrorDigest, createErrorHtml, getRoutePath, getRuntimeEnv, parseHeaders, parseQuery, sortRoutes, uniqueKeyByRoute } from "../../utils/index.mjs";
|
|
5
6
|
import { csrRscRender } from "./csrRscRender.mjs";
|
|
6
7
|
import { dataHandler } from "./dataHandler.mjs";
|
|
7
8
|
import { renderRscHandler } from "./renderRscHandler.mjs";
|
|
@@ -21,8 +22,7 @@ function getRouter(routes) {
|
|
|
21
22
|
];
|
|
22
23
|
const router = new TrieRouter();
|
|
23
24
|
for (const route of finalRoutes){
|
|
24
|
-
const
|
|
25
|
-
const urlPath = originUrlPath.endsWith('/') ? `${originUrlPath}*` : `${originUrlPath}/*`;
|
|
25
|
+
const urlPath = getRoutePath(route);
|
|
26
26
|
router.add('*', urlPath, route);
|
|
27
27
|
}
|
|
28
28
|
return router;
|
|
@@ -61,12 +61,12 @@ function getHeadersWithoutCookie(headers) {
|
|
|
61
61
|
}
|
|
62
62
|
async function createRender({ routes, pwd, metaName, staticGenerate, cacheConfig, forceCSR, forceCSRMap, config }) {
|
|
63
63
|
const router = getRouter(routes);
|
|
64
|
+
const framework = cutNameByHyphen(metaName || 'modern-js');
|
|
65
|
+
const fallbackHeader = `x-${framework}-ssr-fallback`;
|
|
64
66
|
return async (req, { monitors, nodeReq, templates, serverManifest, rscClientManifest, rscSSRManifest, rscServerManifest, locals, matchEntryName, matchPathname, loaderContext, serverContext, contextForceCSR, reporter })=>{
|
|
65
|
-
const forMatchpathname = matchPathname ??
|
|
67
|
+
const forMatchpathname = matchPathname ?? getPath(req);
|
|
66
68
|
const [routeInfo, params] = matchRoute(router, forMatchpathname, matchEntryName);
|
|
67
69
|
serverContext?.set('renderRoute', routeInfo);
|
|
68
|
-
const framework = cutNameByHyphen(metaName || 'modern-js');
|
|
69
|
-
const fallbackHeader = `x-${framework}-ssr-fallback`;
|
|
70
70
|
let fallbackReason = null;
|
|
71
71
|
const fallbackWrapper = (reason)=>{
|
|
72
72
|
fallbackReason = reason;
|
|
@@ -92,9 +92,8 @@ async function createRender({ routes, pwd, metaName, staticGenerate, cacheConfig
|
|
|
92
92
|
});
|
|
93
93
|
const finalForceCSR = routeInfo.entryName ? forceCSRMap?.get(routeInfo.entryName) ?? forceCSR : forceCSR;
|
|
94
94
|
const renderMode = await getRenderMode(req, fallbackHeader, routeInfo.isSSR, finalForceCSR, nodeReq, fallbackWrapper, contextForceCSR);
|
|
95
|
-
const headerData = parseHeaders(req);
|
|
96
95
|
const onError = (e, key)=>{
|
|
97
|
-
monitors?.error(`SSR Error - ${key || (e instanceof Error ? e.name : e)}, error = %s, req.url = %s, req.headers = %o`, e instanceof Error ? e.stack || e.message : e, forMatchpathname, getHeadersWithoutCookie(
|
|
96
|
+
monitors?.error(`SSR Error - ${key || (e instanceof Error ? e.name : e)}, error = %s, req.url = %s, req.headers = %o`, e instanceof Error ? e.stack || e.message : e, forMatchpathname, getHeadersWithoutCookie(parseHeaders(req)));
|
|
98
97
|
};
|
|
99
98
|
const onTiming = (name, dur)=>{
|
|
100
99
|
monitors?.timing(name, dur, 'SSR');
|
|
@@ -111,6 +111,15 @@ function shouldUseCache(request) {
|
|
|
111
111
|
const hasLoaderQuery = url.searchParams.has('__loader');
|
|
112
112
|
return !(hasRSCAction || hasRSCTree || hasLoaderQuery);
|
|
113
113
|
}
|
|
114
|
+
const cacheKeyRegExps = new Map();
|
|
115
|
+
function getCacheKeyRegExp(key) {
|
|
116
|
+
let regExp = cacheKeyRegExps.get(key);
|
|
117
|
+
if (!regExp) {
|
|
118
|
+
regExp = new RegExp(key);
|
|
119
|
+
cacheKeyRegExps.set(key, regExp);
|
|
120
|
+
}
|
|
121
|
+
return regExp;
|
|
122
|
+
}
|
|
114
123
|
function matchCacheControl(cacheOption, req) {
|
|
115
124
|
if (!cacheOption || !req) return;
|
|
116
125
|
else {
|
|
@@ -118,7 +127,7 @@ function matchCacheControl(cacheOption, req) {
|
|
|
118
127
|
if (isCacheOptionProvider(cacheOption)) return cacheOption(req);
|
|
119
128
|
const url = req.url;
|
|
120
129
|
const options = Object.entries(cacheOption);
|
|
121
|
-
for (const [key, option] of options)if ('*' === key ||
|
|
130
|
+
for (const [key, option] of options)if ('*' === key || getCacheKeyRegExp(key).test(url)) if ('function' == typeof option) return option(req);
|
|
122
131
|
else return option;
|
|
123
132
|
return;
|
|
124
133
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { MAIN_ENTRY_NAME } from "@modern-js/utils/universal/constants";
|
|
2
2
|
import { X_MODERNJS_RENDER } from "../../constants.mjs";
|
|
3
|
-
import { getPathname
|
|
3
|
+
import { getPathname } from "../../utils/index.mjs";
|
|
4
4
|
import { getCacheResult, matchCacheControl, shouldUseCache } from "./ssrCache.mjs";
|
|
5
5
|
import { createRequestHandlerConfig } from "./utils.mjs";
|
|
6
6
|
const SERVER_RUNTIME_ENTRY = 'requestHandler';
|
|
@@ -9,10 +9,6 @@ async function ssrRender(request, { routeInfo, html, config: userConfig, staticG
|
|
|
9
9
|
const loadableStats = serverManifest.loadableStats || {};
|
|
10
10
|
const routeManifest = serverManifest.routeManifest || {};
|
|
11
11
|
const moduleFederationCssAssets = serverManifest.moduleFederationCssAssets || [];
|
|
12
|
-
const headers = parseHeaders(request);
|
|
13
|
-
if (nodeReq) {
|
|
14
|
-
for(const key in nodeReq.headers)if (!headers[key]) headers[key] = nodeReq.headers[key];
|
|
15
|
-
}
|
|
16
12
|
const renderBundle = serverManifest.renderBundles?.[entryName || MAIN_ENTRY_NAME];
|
|
17
13
|
if (!renderBundle) throw new Error(`Can't find renderBundle ${entryName || MAIN_ENTRY_NAME}`);
|
|
18
14
|
const requestHandler = await renderBundle[SERVER_RUNTIME_ENTRY];
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { MAIN_ENTRY_NAME } from "@modern-js/utils/universal/constants";
|
|
2
|
-
import { sortRoutes } from "../utils/index.mjs";
|
|
2
|
+
import { getRoutePath, sortRoutes } from "../utils/index.mjs";
|
|
3
3
|
function injectRoute(route) {
|
|
4
4
|
return async (c, next)=>{
|
|
5
5
|
if (route && !c.get('route')) c.set('route', route);
|
|
@@ -18,7 +18,7 @@ const injectRoutePlugin = ()=>({
|
|
|
18
18
|
const pageRoutes = getPageRoutes(routes);
|
|
19
19
|
for (const route of pageRoutes){
|
|
20
20
|
const { urlPath: originUrlPath, entryName = MAIN_ENTRY_NAME } = route;
|
|
21
|
-
const urlPath =
|
|
21
|
+
const urlPath = getRoutePath(route);
|
|
22
22
|
middlewares.push({
|
|
23
23
|
name: 'inject-route-info',
|
|
24
24
|
path: urlPath,
|
package/dist/esm/serverBase.mjs
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { server as server_server } from "@modern-js/plugin/server";
|
|
2
|
+
import { fileReader } from "@modern-js/runtime-utils/fileReader";
|
|
2
3
|
import { logger } from "@modern-js/utils";
|
|
3
4
|
import { Hono } from "hono";
|
|
4
5
|
import { run } from "./context.mjs";
|
|
@@ -111,6 +112,7 @@ class ServerBase {
|
|
|
111
112
|
}
|
|
112
113
|
constructor(options){
|
|
113
114
|
_class_private_method_init(this, _applyMiddlewares);
|
|
115
|
+
this.fileReader = fileReader;
|
|
114
116
|
this.plugins = [
|
|
115
117
|
{
|
|
116
118
|
name: '@modern-js/server-lifecycle',
|
|
@@ -123,7 +125,9 @@ class ServerBase {
|
|
|
123
125
|
this.serverContext = null;
|
|
124
126
|
this.serverOptions = options;
|
|
125
127
|
this.app = new Hono();
|
|
126
|
-
this.app.use('*',
|
|
128
|
+
this.app.use('*', async (context, next)=>{
|
|
129
|
+
await run(context, next);
|
|
130
|
+
});
|
|
127
131
|
}
|
|
128
132
|
}
|
|
129
133
|
function applyMiddlewares() {
|
package/dist/esm/utils/entry.mjs
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
1
|
const sortRoutes = (route1, route2)=>route2.urlPath.length - route1.urlPath.length;
|
|
2
2
|
const uniqueKeyByRoute = (route)=>`${route.entryName}-${route.urlPath}`;
|
|
3
|
-
|
|
3
|
+
const getRoutePath = ({ urlPath, isSSG })=>{
|
|
4
|
+
if (isSSG) return urlPath;
|
|
5
|
+
return urlPath.endsWith('/') ? `${urlPath}*` : `${urlPath}/*`;
|
|
6
|
+
};
|
|
7
|
+
export { getRoutePath, sortRoutes, uniqueKeyByRoute };
|