@bleedingdev/modern-js-server-core 3.9.3-ultramodern.9 → 3.11.3-ultramodern.1

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.
Files changed (45) hide show
  1. package/dist/cjs/adapters/node/node.js +63 -4
  2. package/dist/cjs/adapters/node/plugins/resource.js +38 -10
  3. package/dist/cjs/adapters/node/plugins/static.js +39 -21
  4. package/dist/cjs/adapters/node/plugins/staticCache.js +110 -0
  5. package/dist/cjs/plugins/monitors.js +4 -7
  6. package/dist/cjs/plugins/render/index.js +6 -8
  7. package/dist/cjs/plugins/render/render.js +6 -7
  8. package/dist/cjs/plugins/render/ssrCache.js +10 -1
  9. package/dist/cjs/plugins/render/ssrRender.js +0 -4
  10. package/dist/cjs/plugins/route.js +1 -1
  11. package/dist/cjs/serverBase.js +5 -1
  12. package/dist/cjs/utils/entry.js +7 -0
  13. package/dist/esm/adapters/node/node.mjs +64 -5
  14. package/dist/esm/adapters/node/plugins/resource.mjs +38 -10
  15. package/dist/esm/adapters/node/plugins/static.mjs +39 -21
  16. package/dist/esm/adapters/node/plugins/staticCache.mjs +56 -0
  17. package/dist/esm/plugins/monitors.mjs +4 -7
  18. package/dist/esm/plugins/render/index.mjs +7 -9
  19. package/dist/esm/plugins/render/render.mjs +7 -8
  20. package/dist/esm/plugins/render/ssrCache.mjs +10 -1
  21. package/dist/esm/plugins/render/ssrRender.mjs +1 -5
  22. package/dist/esm/plugins/route.mjs +2 -2
  23. package/dist/esm/serverBase.mjs +5 -1
  24. package/dist/esm/utils/entry.mjs +5 -1
  25. package/dist/esm-node/adapters/node/node.mjs +64 -5
  26. package/dist/esm-node/adapters/node/plugins/resource.mjs +38 -10
  27. package/dist/esm-node/adapters/node/plugins/static.mjs +39 -21
  28. package/dist/esm-node/adapters/node/plugins/staticCache.mjs +57 -0
  29. package/dist/esm-node/plugins/monitors.mjs +4 -7
  30. package/dist/esm-node/plugins/render/index.mjs +7 -9
  31. package/dist/esm-node/plugins/render/render.mjs +7 -8
  32. package/dist/esm-node/plugins/render/ssrCache.mjs +10 -1
  33. package/dist/esm-node/plugins/render/ssrRender.mjs +1 -5
  34. package/dist/esm-node/plugins/route.mjs +2 -2
  35. package/dist/esm-node/serverBase.mjs +5 -1
  36. package/dist/esm-node/utils/entry.mjs +5 -1
  37. package/dist/types/adapters/node/plugins/resource.d.ts +3 -1
  38. package/dist/types/adapters/node/plugins/static.d.ts +8 -3
  39. package/dist/types/adapters/node/plugins/staticCache.d.ts +27 -0
  40. package/dist/types/context.d.ts +5 -1
  41. package/dist/types/hono.d.ts +1 -1
  42. package/dist/types/serverBase.d.ts +1 -0
  43. package/dist/types/types/config/server.d.ts +17 -0
  44. package/dist/types/utils/entry.d.ts +1 -0
  45. package/package.json +6 -6
@@ -28,28 +28,51 @@ function injectTemplates(pwd, routes, htmlTemplatePromise) {
28
28
  await next();
29
29
  };
30
30
  }
31
- const loadBundle = async (filepath, monitors)=>{
32
- if (!await fs.pathExists(filepath)) return;
31
+ function reportBundleError(filepath, error, monitors) {
32
+ const detail = error instanceof Error ? error.stack || error.message : error;
33
+ if (monitors) monitors.error(`Load ${filepath} bundle failed, error = %s`, detail);
34
+ else console.error(`Load ${filepath} bundle failed, error = ${detail}`);
35
+ }
36
+ const loadBundle = async (filepath, monitors, { required = false, failOnError = false } = {})=>{
37
+ if (!required && !failOnError && !await fs.pathExists(filepath)) return;
33
38
  try {
39
+ if (!required && failOnError) try {
40
+ await fs.access(filepath);
41
+ } catch (e) {
42
+ const code = e?.code;
43
+ if ('ENOENT' === code || 'ENOTDIR' === code) return;
44
+ throw e;
45
+ }
34
46
  const module = await compatibleRequire(filepath, false);
35
47
  return module;
36
48
  } catch (e) {
37
- if (monitors) monitors.error(`Load ${filepath} bundle failed, error = %s`, e instanceof Error ? e.stack || e.message : e);
38
- else console.error(`Load ${filepath} bundle failed, error = ${e instanceof Error ? e.stack || e.message : e}`);
49
+ reportBundleError(filepath, e, monitors);
50
+ if (failOnError) throw e;
39
51
  return;
40
52
  }
41
53
  };
42
- async function getServerManifest(pwd, routes, monitors) {
54
+ async function getServerManifest(pwd, routes, monitors, { failOnError = false } = {}) {
43
55
  const loaderBundles = {};
44
56
  const renderBundles = {};
45
57
  await Promise.all(routes.filter((route)=>Boolean(route.bundle)).map(async (route)=>{
58
+ const failOnBundleError = failOnError && Boolean(route.isSSR);
46
59
  const entryName = route.entryName || MAIN_ENTRY_NAME;
47
60
  const renderBundlePath = path.join(pwd, route.bundle || '');
48
61
  const loaderBundlePath = path.join(pwd, SERVER_BUNDLE_DIRECTORY, `${entryName}-server-loaders.js`);
49
- const renderBundle = await loadBundle(renderBundlePath, monitors);
50
- const loaderBundle = await loadBundle(loaderBundlePath, monitors);
62
+ const renderBundle = await loadBundle(renderBundlePath, monitors, {
63
+ required: failOnBundleError,
64
+ failOnError: failOnBundleError
65
+ });
66
+ const loaderBundle = await loadBundle(loaderBundlePath, monitors, {
67
+ failOnError: failOnBundleError
68
+ });
51
69
  renderBundle && (renderBundles[entryName] = renderBundle);
52
- loaderBundle && (loaderBundles[entryName] = loaderBundle?.loadModules ? await loaderBundle?.loadModules() : loaderBundle);
70
+ if (loaderBundle) try {
71
+ loaderBundles[entryName] = loaderBundle.loadModules ? await loaderBundle.loadModules() : loaderBundle;
72
+ } catch (e) {
73
+ if (failOnBundleError) reportBundleError(loaderBundlePath, e, monitors);
74
+ throw e;
75
+ }
53
76
  }));
54
77
  const loadableUri = path.join(pwd, LOADABLE_STATS_FILE);
55
78
  const loadableStats = await compatibleRequire(loadableUri).catch((_)=>({}));
@@ -117,13 +140,18 @@ const injectRscManifestPlugin = (enableRsc)=>({
117
140
  const injectResourcePlugin = ()=>({
118
141
  name: '@modern-js/plugin-inject-resource',
119
142
  setup (api) {
120
- api.onPrepare(()=>{
143
+ api.onPrepare(async ()=>{
121
144
  const { middlewares, routes, distDirectory: pwd } = api.getServerContext();
122
145
  let htmlTemplatePromise;
123
146
  let manifestPromise;
124
147
  if (isProd()) {
125
- manifestPromise = getServerManifest(pwd, routes || [], void 0);
148
+ const warmupRoutes = routes || [];
149
+ const failOnError = warmupRoutes.some((route)=>route.isSSR && route.bundle) && !warmupRoutes.some((route)=>route.isRSC);
150
+ manifestPromise = getServerManifest(pwd, warmupRoutes, void 0, {
151
+ failOnError
152
+ });
126
153
  htmlTemplatePromise = getHtmlTemplates(pwd, routes || []);
154
+ if (failOnError) await manifestPromise;
127
155
  }
128
156
  middlewares.push({
129
157
  name: 'inject-server-manifest',
@@ -5,6 +5,7 @@ import { getMimeType } from "hono/utils/mime";
5
5
  import path from "path";
6
6
  import { sortRoutes } from "../../../utils/index.mjs";
7
7
  import { getPublicDirPatterns } from "../../../utils/publicDir.mjs";
8
+ import { createHashedAssetMatcher, resolveStaticCacheControl, setStaticFileHeaders } from "./staticCache.mjs";
8
9
  const isPathInside = (target, root)=>{
9
10
  const relative = path.relative(path.resolve(root), path.resolve(target));
10
11
  return '' === relative || !relative.startsWith(`..${path.sep}`) && '..' !== relative && !path.isAbsolute(relative);
@@ -29,24 +30,26 @@ async function serveStaticAsset(context, asset, respond) {
29
30
  } catch {
30
31
  return null;
31
32
  }
32
- if ('static' === kind && !await fs.pathExists(filename)) return null;
33
+ if ('static' === kind && !asset.realpath) {
34
+ const stat = await fs.stat(filename).catch(()=>null);
35
+ if (!stat?.isFile()) return null;
36
+ }
33
37
  if (respond) return respond(asset, (representation)=>serveStaticAsset(context, {
34
38
  ...asset,
35
39
  ...representation,
36
40
  filename: representation?.filename ?? asset.filename,
37
41
  mimeFilename: asset.mimeFilename ?? filename
38
42
  }));
39
- const mimeType = getMimeType(asset.mimeFilename ?? filename);
40
- if ('static' === kind && mimeType) context.header('Content-Type', mimeType);
41
- const size = 'static' === kind ? (await fs.lstat(filename)).size : void 0;
42
43
  const data = 'static' === kind ? await fileReader.readFileFromSystem(filename, 'buffer') : await fileReader.readFile(filename, 'buffer');
43
- if ('static' === kind && (asset.contentLength ?? true)) context.header('Content-Length', String(true === asset.contentLength && data ? data.byteLength : size));
44
44
  if (null === data) return null;
45
- if ('public' === kind && mimeType) context.header('Content-Type', mimeType);
45
+ const mimeType = getMimeType(asset.mimeFilename ?? filename);
46
+ if (mimeType) context.header('Content-Type', mimeType);
46
47
  Object.entries(asset.responseHeaders || {}).forEach(([key, value])=>{
47
48
  context.header(key, value);
48
49
  });
49
- if ('public' === kind && asset.contentLength) context.header('Content-Length', String(data.byteLength));
50
+ const notModified = setStaticFileHeaders(context, data, asset.cacheControl);
51
+ if (notModified && false !== asset.revalidate) return context.body(null, 304);
52
+ if (asset.contentLength ?? 'static' === kind) context.header('Content-Length', String(data.byteLength));
50
53
  const body = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
51
54
  return context.body(body, 200);
52
55
  }
@@ -72,14 +75,16 @@ const serverStaticPlugin = (options = {})=>({
72
75
  });
73
76
  }
74
77
  });
75
- function createPublicMiddleware({ pwd, routes, pathPrefix = '/', respondAsset, respondPublicFallback }) {
78
+ function createPublicMiddleware({ pwd, routes, pathPrefix = '/', cacheControl, respondAsset, respondPublicFallback }) {
79
+ const publicRoutes = routes.filter((route)=>!route.isSSR && route.entryPath?.startsWith('public')).sort(sortRoutes);
76
80
  return async (c, next)=>{
77
81
  const respondPublic = async ()=>{
78
- const route = matchPublicRoute(c.req, routes);
82
+ const route = matchPublicRoute(c.req, publicRoutes);
79
83
  if (!route) return null;
80
84
  const asset = {
81
85
  filename: path.join(pwd, route.entryPath),
82
86
  kind: 'public',
87
+ cacheControl: cacheControl?.unhashed,
83
88
  responseHeaders: route.responseHeaders
84
89
  };
85
90
  const serve = (representation)=>serveStaticAsset(c, {
@@ -101,8 +106,8 @@ function createPublicMiddleware({ pwd, routes, pathPrefix = '/', respondAsset, r
101
106
  return response ?? next();
102
107
  };
103
108
  }
104
- function matchPublicRoute(req, routes) {
105
- for (const route of routes.sort(sortRoutes))if (!route.isSSR && route.entryPath.startsWith('public') && req.path.startsWith(route.urlPath)) return route;
109
+ function matchPublicRoute(req, publicRoutes) {
110
+ return publicRoutes.find((route)=>req.path.startsWith(route.urlPath));
106
111
  }
107
112
  const extractPathname = (url)=>{
108
113
  try {
@@ -115,6 +120,7 @@ const extractPathname = (url)=>{
115
120
  };
116
121
  function createStaticMiddleware(options) {
117
122
  const { pwd, routes } = options;
123
+ const cacheControl = resolveStaticCacheControl(options.server.staticCacheControl);
118
124
  const prefix = options.output.assetPrefix || '/';
119
125
  const pathPrefix = extractPathname(prefix);
120
126
  const { distPath: { css: cssPath, js: jsPath, media: mediaPath } = {} } = options.output;
@@ -127,6 +133,11 @@ function createStaticMiddleware(options) {
127
133
  mediaPath
128
134
  ].filter((v)=>Boolean(v));
129
135
  const publicDirPatterns = getPublicDirPatterns(publicDir);
136
+ const isHashedAsset = createHashedAssetMatcher(staticFiles, [
137
+ 'public/',
138
+ 'upload/',
139
+ ...publicDirPatterns
140
+ ]);
130
141
  const staticReg = [
131
142
  'static/',
132
143
  'upload/',
@@ -143,25 +154,32 @@ function createStaticMiddleware(options) {
143
154
  ...staticReg,
144
155
  ...iconReg
145
156
  ].join('|')})`);
157
+ const publicMiddleware = createPublicMiddleware({
158
+ pwd,
159
+ routes: routes || [],
160
+ pathPrefix,
161
+ cacheControl,
162
+ respondAsset: options.respondAsset,
163
+ respondPublicFallback: options.respondPublicFallback
164
+ });
146
165
  return async (c, next)=>{
147
166
  const pageRoute = c.get('route');
148
167
  const pathname = c.req.path;
149
168
  if (pageRoute && '' === path.extname(pathname)) return next();
150
169
  const hit = staticPathRegExp.test(pathname);
151
- if (!hit) return createPublicMiddleware({
152
- pwd,
153
- routes: routes || [],
154
- pathPrefix,
155
- respondAsset: options.respondAsset,
156
- respondPublicFallback: options.respondPublicFallback
157
- })(c, next);
170
+ if (!hit) return publicMiddleware(c, next);
158
171
  else {
159
- const filepath = path.join(pwd, pathname.replace(pathPrefix, ()=>''));
172
+ const relativePath = pathname.replace(pathPrefix, ()=>'').replace(/^\/+/, '');
173
+ const filepath = path.join(pwd, relativePath);
160
174
  if (!isPathInside(filepath, pwd)) return next();
161
- if (!await fs.pathExists(filepath)) return next();
175
+ if (options.respondAsset) {
176
+ const stat = await fs.stat(filepath).catch(()=>null);
177
+ if (!stat?.isFile()) return next();
178
+ }
162
179
  const asset = {
163
180
  filename: filepath,
164
- kind: 'static'
181
+ kind: 'static',
182
+ cacheControl: cacheControl && (isHashedAsset(relativePath) ? cacheControl.hashed : cacheControl.unhashed)
165
183
  };
166
184
  const serve = (representation)=>serveStaticAsset(c, {
167
185
  ...asset,
@@ -0,0 +1,57 @@
1
+ import "node:module";
2
+ import { createHash } from "node:crypto";
3
+ import path from "path";
4
+ const DEFAULT_HASHED_CACHE_CONTROL = 'public, max-age=31536000, immutable';
5
+ const DEFAULT_UNHASHED_CACHE_CONTROL = 'no-cache';
6
+ const CONTENT_HASH_REGEX = /[.-][0-9a-f]{8,}\.[^./]+$/i;
7
+ function resolveStaticCacheControl(staticCacheControl) {
8
+ if (false === staticCacheControl) return;
9
+ if ('production' !== process.env.NODE_ENV) return {
10
+ hashed: 'no-cache',
11
+ unhashed: 'no-cache'
12
+ };
13
+ const options = 'object' == typeof staticCacheControl ? staticCacheControl : {};
14
+ return {
15
+ hashed: options.hashed ?? DEFAULT_HASHED_CACHE_CONTROL,
16
+ unhashed: options.unhashed ?? DEFAULT_UNHASHED_CACHE_CONTROL
17
+ };
18
+ }
19
+ const normalizeDir = (dir)=>{
20
+ const normalized = dir.replace(/^\.?\/?/, '').replace(/\/+$/, '');
21
+ return normalized ? `${normalized}/` : '';
22
+ };
23
+ function createHashedAssetMatcher(assetDirs, userDirs = []) {
24
+ const dirs = [
25
+ 'static/',
26
+ ...assetDirs.map(normalizeDir)
27
+ ];
28
+ const isInAssetDir = (relativePath)=>!userDirs.some((userDir)=>relativePath.startsWith(userDir)) && dirs.some((dir)=>!dir || relativePath.startsWith(dir));
29
+ return (relativePath)=>isInAssetDir(relativePath) && CONTENT_HASH_REGEX.test(path.basename(relativePath));
30
+ }
31
+ const etags = new WeakMap();
32
+ function getETag(data) {
33
+ let etag = etags.get(data);
34
+ if (!etag) {
35
+ const hash = createHash('sha1').update(data).digest('base64url');
36
+ etag = `W/"${data.byteLength.toString(16)}-${hash.slice(0, 22)}"`;
37
+ etags.set(data, etag);
38
+ }
39
+ return etag;
40
+ }
41
+ const stripWeak = (etag)=>etag.trim().replace(/^W\//, '');
42
+ const ENTITY_TAG_REGEX = /(?:W\/)?"[^"]*"/g;
43
+ function setStaticFileHeaders(c, data, cacheControl) {
44
+ const { headers } = c.res;
45
+ let etag = headers.get('ETag');
46
+ if (!etag) {
47
+ etag = getETag(data);
48
+ c.header('ETag', etag);
49
+ }
50
+ if (cacheControl && !headers.has('Cache-Control')) c.header('Cache-Control', cacheControl);
51
+ const { method } = c.req;
52
+ const ifNoneMatch = c.req.header('If-None-Match');
53
+ if ('GET' !== method && 'HEAD' !== method || !ifNoneMatch) return false;
54
+ const expected = stripWeak(etag);
55
+ return '*' === ifNoneMatch.trim() || (ifNoneMatch.match(ENTITY_TAG_REGEX) || []).some((value)=>stripWeak(value) === expected);
56
+ }
57
+ export { createHashedAssetMatcher, resolveStaticCacheControl, setStaticFileHeaders };
@@ -124,13 +124,10 @@ const injectServerTiming = ()=>({
124
124
  const monitors = c.get('monitors');
125
125
  monitors?.push(timingMonitor);
126
126
  await next();
127
- serverTimings.forEach((serverTiming)=>{
128
- const { name, desc, dur } = serverTiming;
129
- const _name = `bd-${metaName}-${name}`;
130
- const value = `${_name};${desc ? `decs="${desc}";` : ''} dur=${dur}`;
131
- c.header(SERVER_TIMING, value, {
132
- append: true
133
- });
127
+ if (0 === serverTimings.length) return;
128
+ const value = serverTimings.map(({ name, desc, dur })=>`bd-${metaName}-${name};${desc ? `decs="${desc}";` : ''} dur=${dur}`).join(', ');
129
+ c.header(SERVER_TIMING, value, {
130
+ append: true
134
131
  });
135
132
  }
136
133
  });
@@ -1,12 +1,8 @@
1
1
  import "node:module";
2
2
  import { getLoaderCtx } from "../../helper.mjs";
3
- import { sortRoutes } from "../../utils/index.mjs";
3
+ import { getRoutePath, sortRoutes } from "../../utils/index.mjs";
4
4
  import { requestLatencyMiddleware } from "../monitors.mjs";
5
5
  export * from "./inject.mjs";
6
- const DYNAMIC_ROUTE_REG = /\/:./;
7
- function escapeRegexSpecialChars(path) {
8
- return path.replace(/[()[\]{}*+?.^$|\\]/g, '\\$&');
9
- }
10
6
  const renderPlugin = ()=>({
11
7
  name: '@modern-js/plugin-render',
12
8
  setup (api) {
@@ -19,10 +15,12 @@ const renderPlugin = ()=>({
19
15
  handler: requestLatencyMiddleware()
20
16
  });
21
17
  for (const route of pageRoutes){
22
- const { urlPath: originUrlPath } = route;
23
- const isDynamic = DYNAMIC_ROUTE_REG.test(originUrlPath);
24
- const escapedPath = isDynamic ? originUrlPath : escapeRegexSpecialChars(originUrlPath);
25
- const urlPath = escapedPath.endsWith('/') ? `${escapedPath}*` : `${escapedPath}/*`;
18
+ const urlPath = getRoutePath(route);
19
+ if (route.isSSG && !urlPath.endsWith('/')) middlewares.push({
20
+ name: 'ssg-trailing-slash-redirect',
21
+ path: `${urlPath}/`,
22
+ handler: async (c)=>c.redirect(`${urlPath}${new URL(c.req.url).search}`, 308)
23
+ });
26
24
  renderMiddlewares?.forEach((m)=>{
27
25
  middlewares.push({
28
26
  name: m.name,
@@ -1,8 +1,9 @@
1
1
  import "node:module";
2
2
  import { cutNameByHyphen } from "@modern-js/utils/universal";
3
3
  import { TrieRouter } from "hono/router/trie-router";
4
+ import { getPath } from "hono/utils/url";
4
5
  import { X_MODERNJS_RENDER } from "../../constants.mjs";
5
- import { ErrorDigest, createErrorHtml, getPathname, getRuntimeEnv, parseHeaders, parseQuery, sortRoutes, uniqueKeyByRoute } from "../../utils/index.mjs";
6
+ import { ErrorDigest, createErrorHtml, getRoutePath, getRuntimeEnv, parseHeaders, parseQuery, sortRoutes, uniqueKeyByRoute } from "../../utils/index.mjs";
6
7
  import { csrRscRender } from "./csrRscRender.mjs";
7
8
  import { dataHandler } from "./dataHandler.mjs";
8
9
  import { renderRscHandler } from "./renderRscHandler.mjs";
@@ -24,8 +25,7 @@ function getRouter(routes) {
24
25
  ];
25
26
  const router = new TrieRouter();
26
27
  for (const route of finalRoutes){
27
- const { urlPath: originUrlPath } = route;
28
- const urlPath = originUrlPath.endsWith('/') ? `${originUrlPath}*` : `${originUrlPath}/*`;
28
+ const urlPath = getRoutePath(route);
29
29
  router.add('*', urlPath, route);
30
30
  }
31
31
  return router;
@@ -64,12 +64,12 @@ function getHeadersWithoutCookie(headers) {
64
64
  }
65
65
  async function createRender({ routes, pwd, metaName, staticGenerate, cacheConfig, forceCSR, forceCSRMap, config }) {
66
66
  const router = getRouter(routes);
67
+ const framework = cutNameByHyphen(metaName || 'modern-js');
68
+ const fallbackHeader = `x-${framework}-ssr-fallback`;
67
69
  return async (req, { monitors, nodeReq, templates, serverManifest, rscClientManifest, rscSSRManifest, rscServerManifest, locals, matchEntryName, matchPathname, loaderContext, serverContext, contextForceCSR, reporter })=>{
68
- const forMatchpathname = matchPathname ?? getPathname(req);
70
+ const forMatchpathname = matchPathname ?? getPath(req);
69
71
  const [routeInfo, params] = matchRoute(router, forMatchpathname, matchEntryName);
70
72
  serverContext?.set('renderRoute', routeInfo);
71
- const framework = cutNameByHyphen(metaName || 'modern-js');
72
- const fallbackHeader = `x-${framework}-ssr-fallback`;
73
73
  let fallbackReason = null;
74
74
  const fallbackWrapper = (reason)=>{
75
75
  fallbackReason = reason;
@@ -95,9 +95,8 @@ async function createRender({ routes, pwd, metaName, staticGenerate, cacheConfig
95
95
  });
96
96
  const finalForceCSR = routeInfo.entryName ? forceCSRMap?.get(routeInfo.entryName) ?? forceCSR : forceCSR;
97
97
  const renderMode = await getRenderMode(req, fallbackHeader, routeInfo.isSSR, finalForceCSR, nodeReq, fallbackWrapper, contextForceCSR);
98
- const headerData = parseHeaders(req);
99
98
  const onError = (e, key)=>{
100
- 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(headerData));
99
+ 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)));
101
100
  };
102
101
  const onTiming = (name, dur)=>{
103
102
  monitors?.timing(name, dur, 'SSR');
@@ -112,6 +112,15 @@ function shouldUseCache(request) {
112
112
  const hasLoaderQuery = url.searchParams.has('__loader');
113
113
  return !(hasRSCAction || hasRSCTree || hasLoaderQuery);
114
114
  }
115
+ const cacheKeyRegExps = new Map();
116
+ function getCacheKeyRegExp(key) {
117
+ let regExp = cacheKeyRegExps.get(key);
118
+ if (!regExp) {
119
+ regExp = new RegExp(key);
120
+ cacheKeyRegExps.set(key, regExp);
121
+ }
122
+ return regExp;
123
+ }
115
124
  function matchCacheControl(cacheOption, req) {
116
125
  if (!cacheOption || !req) return;
117
126
  else {
@@ -119,7 +128,7 @@ function matchCacheControl(cacheOption, req) {
119
128
  if (isCacheOptionProvider(cacheOption)) return cacheOption(req);
120
129
  const url = req.url;
121
130
  const options = Object.entries(cacheOption);
122
- for (const [key, option] of options)if ('*' === key || new RegExp(key).test(url)) if ('function' == typeof option) return option(req);
131
+ for (const [key, option] of options)if ('*' === key || getCacheKeyRegExp(key).test(url)) if ('function' == typeof option) return option(req);
123
132
  else return option;
124
133
  return;
125
134
  }
@@ -1,7 +1,7 @@
1
1
  import "node:module";
2
2
  import { MAIN_ENTRY_NAME } from "@modern-js/utils/universal/constants";
3
3
  import { X_MODERNJS_RENDER } from "../../constants.mjs";
4
- import { getPathname, parseHeaders } from "../../utils/index.mjs";
4
+ import { getPathname } from "../../utils/index.mjs";
5
5
  import { getCacheResult, matchCacheControl, shouldUseCache } from "./ssrCache.mjs";
6
6
  import { createRequestHandlerConfig } from "./utils.mjs";
7
7
  const SERVER_RUNTIME_ENTRY = 'requestHandler';
@@ -10,10 +10,6 @@ async function ssrRender(request, { routeInfo, html, config: userConfig, staticG
10
10
  const loadableStats = serverManifest.loadableStats || {};
11
11
  const routeManifest = serverManifest.routeManifest || {};
12
12
  const moduleFederationCssAssets = serverManifest.moduleFederationCssAssets || [];
13
- const headers = parseHeaders(request);
14
- if (nodeReq) {
15
- for(const key in nodeReq.headers)if (!headers[key]) headers[key] = nodeReq.headers[key];
16
- }
17
13
  const renderBundle = serverManifest.renderBundles?.[entryName || MAIN_ENTRY_NAME];
18
14
  if (!renderBundle) throw new Error(`Can't find renderBundle ${entryName || MAIN_ENTRY_NAME}`);
19
15
  const requestHandler = await renderBundle[SERVER_RUNTIME_ENTRY];
@@ -1,6 +1,6 @@
1
1
  import "node:module";
2
2
  import { MAIN_ENTRY_NAME } from "@modern-js/utils/universal/constants";
3
- import { sortRoutes } from "../utils/index.mjs";
3
+ import { getRoutePath, sortRoutes } from "../utils/index.mjs";
4
4
  function injectRoute(route) {
5
5
  return async (c, next)=>{
6
6
  if (route && !c.get('route')) c.set('route', route);
@@ -19,7 +19,7 @@ const injectRoutePlugin = ()=>({
19
19
  const pageRoutes = getPageRoutes(routes);
20
20
  for (const route of pageRoutes){
21
21
  const { urlPath: originUrlPath, entryName = MAIN_ENTRY_NAME } = route;
22
- const urlPath = originUrlPath.endsWith('/') ? `${originUrlPath}*` : `${originUrlPath}/*`;
22
+ const urlPath = getRoutePath(route);
23
23
  middlewares.push({
24
24
  name: 'inject-route-info',
25
25
  path: urlPath,
@@ -1,5 +1,6 @@
1
1
  import "node:module";
2
2
  import { server as server_server } from "@modern-js/plugin/server";
3
+ import { fileReader } from "@modern-js/runtime-utils/fileReader";
3
4
  import { logger } from "@modern-js/utils";
4
5
  import { Hono } from "hono";
5
6
  import { run } from "./context.mjs";
@@ -112,6 +113,7 @@ class ServerBase {
112
113
  }
113
114
  constructor(options){
114
115
  _class_private_method_init(this, _applyMiddlewares);
116
+ this.fileReader = fileReader;
115
117
  this.plugins = [
116
118
  {
117
119
  name: '@modern-js/server-lifecycle',
@@ -124,7 +126,9 @@ class ServerBase {
124
126
  this.serverContext = null;
125
127
  this.serverOptions = options;
126
128
  this.app = new Hono();
127
- this.app.use('*', run);
129
+ this.app.use('*', async (context, next)=>{
130
+ await run(context, next);
131
+ });
128
132
  }
129
133
  }
130
134
  function applyMiddlewares() {
@@ -1,4 +1,8 @@
1
1
  import "node:module";
2
2
  const sortRoutes = (route1, route2)=>route2.urlPath.length - route1.urlPath.length;
3
3
  const uniqueKeyByRoute = (route)=>`${route.entryName}-${route.urlPath}`;
4
- export { sortRoutes, uniqueKeyByRoute };
4
+ const getRoutePath = ({ urlPath, isSSG })=>{
5
+ if (isSSG) return urlPath;
6
+ return urlPath.endsWith('/') ? `${urlPath}*` : `${urlPath}/*`;
7
+ };
8
+ export { getRoutePath, sortRoutes, uniqueKeyByRoute };
@@ -2,7 +2,9 @@ import type { Monitors, ServerRoute } from '@modern-js/types';
2
2
  import type { Middleware, ServerEnv, ServerManifest, ServerPlugin } from '../../../types/index.js';
3
3
  export declare function getHtmlTemplates(pwd: string, routes: ServerRoute[]): Promise<Record<string, string>>;
4
4
  export declare function injectTemplates(pwd: string, routes?: ServerRoute[], htmlTemplatePromise?: ReturnType<typeof getHtmlTemplates>): Middleware<ServerEnv>;
5
- export declare function getServerManifest(pwd: string, routes: ServerRoute[], monitors?: Monitors): Promise<ServerManifest>;
5
+ export declare function getServerManifest(pwd: string, routes: ServerRoute[], monitors?: Monitors, { failOnError }?: {
6
+ failOnError?: boolean | undefined;
7
+ }): Promise<ServerManifest>;
6
8
  export declare function injectServerManifest(pwd: string, routes?: ServerRoute[], manifestPromise?: Promise<ServerManifest>): Middleware<ServerEnv>;
7
9
  export declare function getRscServerManifest(pwd: string): Promise<any>;
8
10
  export declare function getClientManifest(pwd: string): Promise<any>;
@@ -1,5 +1,6 @@
1
1
  import type { ServerRoute } from '@modern-js/types';
2
2
  import type { HtmlNormalizedConfig, Middleware, OutputNormalizedConfig, ServerNormalizedConfig, ServerPlugin } from '../../../types/index.js';
3
+ import { type ResolvedStaticCacheControl } from './staticCache.js';
3
4
  /** A selected file and the native response conventions to use for it. */
4
5
  export type StaticAsset = {
5
6
  filename: string;
@@ -7,8 +8,11 @@ export type StaticAsset = {
7
8
  /** An alternate representation retains the original resource's MIME type. */
8
9
  mimeFilename?: string;
9
10
  responseHeaders?: ServerRoute['responseHeaders'];
10
- /** True uses the served byte length; omitted preserves native length defaults. */
11
+ /** Controls whether to include the served byte length. */
11
12
  contentLength?: boolean;
13
+ cacheControl?: string;
14
+ /** Disable conditional responses when an extension will rewrite the body. */
15
+ revalidate?: boolean;
12
16
  /** Optional lexical containment boundary. Use real paths to contain symlinks. */
13
17
  root?: string;
14
18
  /** Resolve symlinks before checking root. Implies a regular file is required. */
@@ -19,7 +23,7 @@ export type StaticAssetRequest = {
19
23
  pathPrefix: string;
20
24
  };
21
25
  /** Native serving of the selected file, optionally choosing another representation. */
22
- export type ServeStaticAsset = (representation?: Partial<Pick<StaticAsset, 'filename' | 'contentLength'>>) => Promise<Response | null>;
26
+ export type ServeStaticAsset = (representation?: Partial<Pick<StaticAsset, 'filename' | 'contentLength' | 'revalidate'>>) => Promise<Response | null>;
23
27
  /**
24
28
  * Trusted server extension. Undefined uses the native file; null skips it.
25
29
  * A returned response is final. Exceptions use the normal server error handler.
@@ -42,8 +46,9 @@ export type PublicMiddlewareOptions = {
42
46
  pwd: string;
43
47
  routes: ServerRoute[];
44
48
  pathPrefix?: string;
49
+ cacheControl?: ResolvedStaticCacheControl;
45
50
  } & ServerStaticPluginOptions;
46
- export declare function createPublicMiddleware({ pwd, routes, pathPrefix, respondAsset, respondPublicFallback, }: PublicMiddlewareOptions): Middleware;
51
+ export declare function createPublicMiddleware({ pwd, routes, pathPrefix, cacheControl, respondAsset, respondPublicFallback, }: PublicMiddlewareOptions): Middleware;
47
52
  export interface ServerStaticOptions extends ServerStaticPluginOptions {
48
53
  pwd: string;
49
54
  output: OutputNormalizedConfig;
@@ -0,0 +1,27 @@
1
+ import type { Context } from 'hono';
2
+ import type { ServerNormalizedConfig } from '../../../types/index.js';
3
+ export type ResolvedStaticCacheControl = {
4
+ hashed: string;
5
+ unhashed: string;
6
+ };
7
+ /**
8
+ * Resolve `server.staticCacheControl`. During development every static file
9
+ * is revalidated, so an edited file is never served from the browser cache.
10
+ */
11
+ export declare function resolveStaticCacheControl(staticCacheControl: ServerNormalizedConfig['staticCacheControl']): ResolvedStaticCacheControl | undefined;
12
+ /**
13
+ * Build assets live in the build output directories and have a content hash
14
+ * in the file name. Requiring both keeps files like
15
+ * `upload/report.20261101.pdf` from being cached as immutable. Files in the
16
+ * directories holding user files (`userDirs`) are never build assets, even
17
+ * inside a build output directory. When assets are emitted to the output root,
18
+ * every other directory counts as a build output directory.
19
+ */
20
+ export declare function createHashedAssetMatcher(assetDirs: string[], userDirs?: string[]): (relativePath: string) => boolean;
21
+ /**
22
+ * Set `ETag` and `Cache-Control` of a static file, and return whether the
23
+ * request can be answered with `304 Not Modified`. Headers that are already
24
+ * set, e.g. by a middleware before `await next()` or by a public route, are
25
+ * kept, and an existing `ETag` is the one that is compared.
26
+ */
27
+ export declare function setStaticFileHeaders(c: Context, data: Buffer, cacheControl?: string): boolean;
@@ -1,3 +1,7 @@
1
1
  import type { Context } from 'hono';
2
- declare const run: <O>(context: Context<any, any, {}>, cb: () => O | Promise<O>) => Promise<O>, useHonoContext: () => Context<any, any, {}>;
2
+ declare const { run, useContext: useHonoContext }: {
3
+ run: <O>(context: Context<any, any, {}>, cb: () => O | Promise<O>) => Promise<O>;
4
+ useContext: () => Context<any, any, {}>;
5
+ useHonoContext: () => Context<any, any, {}>;
6
+ };
3
7
  export { run, useHonoContext };
@@ -1,3 +1,3 @@
1
1
  export type { Context, HonoRequest, MiddlewareHandler, MiddlewareHandler as Middleware, Next, } from 'hono';
2
- export { deleteCookie, getCookie, setCookie, } from 'hono/cookie';
2
+ export { deleteCookie, getCookie, setCookie } from 'hono/cookie';
3
3
  export { languageDetector } from 'hono/language';
@@ -9,6 +9,7 @@ export interface ServerBaseOptions extends ServerCreateOptions {
9
9
  }
10
10
  export declare class ServerBase<E extends Env = any> {
11
11
  #private;
12
+ readonly fileReader: import("@modern-js/runtime-utils/fileReader").FileReader;
12
13
  serverOptions: ServerBaseOptions;
13
14
  private app;
14
15
  private plugins;
@@ -27,6 +27,18 @@ export type SSR = boolean | {
27
27
  };
28
28
  export type SSRByEntries = Record<string, SSR>;
29
29
  type SSRPreload = Record<string, unknown>;
30
+ export type StaticCacheControlOptions = {
31
+ /**
32
+ * @description `Cache-Control` of build assets with a content hash in the file name
33
+ * @default 'public, max-age=31536000, immutable'
34
+ */
35
+ hashed?: string;
36
+ /**
37
+ * @description `Cache-Control` of other static files, such as files in `config/public` and `config/upload`
38
+ * @default 'no-cache'
39
+ */
40
+ unhashed?: string;
41
+ };
30
42
  export interface ServerUserConfig {
31
43
  publicDir?: string | string[];
32
44
  routes?: Routes;
@@ -53,6 +65,11 @@ export interface ServerUserConfig {
53
65
  */
54
66
  useJsonScript?: boolean;
55
67
  logger?: boolean | Record<string, unknown>;
68
+ /**
69
+ * @description set `Cache-Control` for static files served by the production server
70
+ * @default true
71
+ */
72
+ staticCacheControl?: boolean | StaticCacheControlOptions;
56
73
  /**
57
74
  * @description disable hook middleware for performance
58
75
  * @default false
@@ -1,3 +1,4 @@
1
1
  import type { ServerRoute } from '@modern-js/types';
2
2
  export declare const sortRoutes: (route1: ServerRoute, route2: ServerRoute) => number;
3
3
  export declare const uniqueKeyByRoute: (route: ServerRoute) => string;
4
+ export declare const getRoutePath: ({ urlPath, isSSG }: ServerRoute) => string;