@bleedingdev/modern-js-server-core 3.9.3-ultramodern.8 → 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
@@ -111,6 +111,67 @@ const createWebRequest = (req, res, body)=>{
111
111
  }
112
112
  return originalRequest;
113
113
  };
114
+ const noop = ()=>{};
115
+ const isDestroyed = (res)=>'stream' in res ? res.stream.destroyed : res.destroyed;
116
+ const createAbortError = ()=>Object.assign(new Error('The operation was aborted'), {
117
+ name: 'AbortError',
118
+ code: 'ABORT_ERR'
119
+ });
120
+ const writeBody = async (body, res)=>{
121
+ const reader = body.getReader();
122
+ let abortError;
123
+ let cancelled;
124
+ let resume;
125
+ let waitsForDrain = false;
126
+ const onDrain = ()=>resume?.();
127
+ const abort = (error)=>{
128
+ if (cancelled) return;
129
+ abortError = error;
130
+ cancelled = reader.cancel(error);
131
+ cancelled.catch(noop);
132
+ resume?.();
133
+ };
134
+ const onClose = ()=>abort(createAbortError());
135
+ res.on('close', onClose);
136
+ res.on('error', abort);
137
+ try {
138
+ if (isDestroyed(res)) onClose();
139
+ while(!cancelled){
140
+ let result;
141
+ try {
142
+ result = await reader.read();
143
+ } catch (error) {
144
+ res.destroy(error);
145
+ throw error;
146
+ }
147
+ if (result.done || cancelled) break;
148
+ try {
149
+ if (!res.write(result.value) && !cancelled) {
150
+ if (!waitsForDrain) {
151
+ waitsForDrain = true;
152
+ res.on('drain', onDrain);
153
+ }
154
+ await new Promise((resolve)=>{
155
+ resume = resolve;
156
+ });
157
+ resume = void 0;
158
+ }
159
+ } catch (error) {
160
+ abort(error);
161
+ }
162
+ }
163
+ if (cancelled) {
164
+ await cancelled;
165
+ throw abortError;
166
+ }
167
+ res.end();
168
+ } finally{
169
+ res.off('close', onClose);
170
+ res.off('error', abort);
171
+ if (waitsForDrain) res.off('drain', onDrain);
172
+ reader.releaseLock();
173
+ }
174
+ };
114
175
  const sendResponse = async (response, res)=>{
115
176
  res.statusMessage = response.statusText;
116
177
  res.statusCode = response.status;
@@ -119,10 +180,8 @@ const sendResponse = async (response, res)=>{
119
180
  else res.setHeader(key, value);
120
181
  if (cookies.length > 0) res.setHeader('set-cookie', cookies);
121
182
  if (response.headers.get('Content-Type')?.match(/text\/event-stream/i) && res instanceof external_node_http_namespaceObject.ServerResponse) res.flushHeaders();
122
- if (response.body) {
123
- const writable = external_node_stream_namespaceObject.Writable.toWeb(res);
124
- await response.body.pipeTo(writable);
125
- } else res.end();
183
+ if (response.body) await writeBody(response.body, res);
184
+ else res.end();
126
185
  };
127
186
  const handleResponseError = (e, res)=>{
128
187
  const err = e instanceof Error ? e : new Error('unknown error', {
@@ -77,28 +77,51 @@ function injectTemplates(pwd, routes, htmlTemplatePromise) {
77
77
  await next();
78
78
  };
79
79
  }
80
- const loadBundle = async (filepath, monitors)=>{
81
- if (!await utils_namespaceObject.fs.pathExists(filepath)) return;
80
+ function reportBundleError(filepath, error, monitors) {
81
+ const detail = error instanceof Error ? error.stack || error.message : error;
82
+ if (monitors) monitors.error(`Load ${filepath} bundle failed, error = %s`, detail);
83
+ else console.error(`Load ${filepath} bundle failed, error = ${detail}`);
84
+ }
85
+ const loadBundle = async (filepath, monitors, { required = false, failOnError = false } = {})=>{
86
+ if (!required && !failOnError && !await utils_namespaceObject.fs.pathExists(filepath)) return;
82
87
  try {
88
+ if (!required && failOnError) try {
89
+ await utils_namespaceObject.fs.access(filepath);
90
+ } catch (e) {
91
+ const code = e?.code;
92
+ if ('ENOENT' === code || 'ENOTDIR' === code) return;
93
+ throw e;
94
+ }
83
95
  const module = await (0, utils_namespaceObject.compatibleRequire)(filepath, false);
84
96
  return module;
85
97
  } catch (e) {
86
- if (monitors) monitors.error(`Load ${filepath} bundle failed, error = %s`, e instanceof Error ? e.stack || e.message : e);
87
- else console.error(`Load ${filepath} bundle failed, error = ${e instanceof Error ? e.stack || e.message : e}`);
98
+ reportBundleError(filepath, e, monitors);
99
+ if (failOnError) throw e;
88
100
  return;
89
101
  }
90
102
  };
91
- async function getServerManifest(pwd, routes, monitors) {
103
+ async function getServerManifest(pwd, routes, monitors, { failOnError = false } = {}) {
92
104
  const loaderBundles = {};
93
105
  const renderBundles = {};
94
106
  await Promise.all(routes.filter((route)=>Boolean(route.bundle)).map(async (route)=>{
107
+ const failOnBundleError = failOnError && Boolean(route.isSSR);
95
108
  const entryName = route.entryName || utils_namespaceObject.MAIN_ENTRY_NAME;
96
109
  const renderBundlePath = external_path_default().join(pwd, route.bundle || '');
97
110
  const loaderBundlePath = external_path_default().join(pwd, utils_namespaceObject.SERVER_BUNDLE_DIRECTORY, `${entryName}-server-loaders.js`);
98
- const renderBundle = await loadBundle(renderBundlePath, monitors);
99
- const loaderBundle = await loadBundle(loaderBundlePath, monitors);
111
+ const renderBundle = await loadBundle(renderBundlePath, monitors, {
112
+ required: failOnBundleError,
113
+ failOnError: failOnBundleError
114
+ });
115
+ const loaderBundle = await loadBundle(loaderBundlePath, monitors, {
116
+ failOnError: failOnBundleError
117
+ });
100
118
  renderBundle && (renderBundles[entryName] = renderBundle);
101
- loaderBundle && (loaderBundles[entryName] = loaderBundle?.loadModules ? await loaderBundle?.loadModules() : loaderBundle);
119
+ if (loaderBundle) try {
120
+ loaderBundles[entryName] = loaderBundle.loadModules ? await loaderBundle.loadModules() : loaderBundle;
121
+ } catch (e) {
122
+ if (failOnBundleError) reportBundleError(loaderBundlePath, e, monitors);
123
+ throw e;
124
+ }
102
125
  }));
103
126
  const loadableUri = external_path_default().join(pwd, utils_namespaceObject.LOADABLE_STATS_FILE);
104
127
  const loadableStats = await (0, utils_namespaceObject.compatibleRequire)(loadableUri).catch((_)=>({}));
@@ -166,13 +189,18 @@ const injectRscManifestPlugin = (enableRsc)=>({
166
189
  const injectResourcePlugin = ()=>({
167
190
  name: '@modern-js/plugin-inject-resource',
168
191
  setup (api) {
169
- api.onPrepare(()=>{
192
+ api.onPrepare(async ()=>{
170
193
  const { middlewares, routes, distDirectory: pwd } = api.getServerContext();
171
194
  let htmlTemplatePromise;
172
195
  let manifestPromise;
173
196
  if ((0, utils_namespaceObject.isProd)()) {
174
- manifestPromise = getServerManifest(pwd, routes || [], void 0);
197
+ const warmupRoutes = routes || [];
198
+ const failOnError = warmupRoutes.some((route)=>route.isSSR && route.bundle) && !warmupRoutes.some((route)=>route.isRSC);
199
+ manifestPromise = getServerManifest(pwd, warmupRoutes, void 0, {
200
+ failOnError
201
+ });
175
202
  htmlTemplatePromise = getHtmlTemplates(pwd, routes || []);
203
+ if (failOnError) await manifestPromise;
176
204
  }
177
205
  middlewares.push({
178
206
  name: 'inject-server-manifest',
@@ -49,6 +49,7 @@ const external_path_namespaceObject = require("path");
49
49
  var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
50
50
  const index_js_namespaceObject = require("../../../utils/index.js");
51
51
  const publicDir_js_namespaceObject = require("../../../utils/publicDir.js");
52
+ const external_staticCache_js_namespaceObject = require("./staticCache.js");
52
53
  const isPathInside = (target, root)=>{
53
54
  const relative = external_path_default().relative(external_path_default().resolve(root), external_path_default().resolve(target));
54
55
  return '' === relative || !relative.startsWith(`..${external_path_default().sep}`) && '..' !== relative && !external_path_default().isAbsolute(relative);
@@ -73,24 +74,26 @@ async function serveStaticAsset(context, asset, respond) {
73
74
  } catch {
74
75
  return null;
75
76
  }
76
- if ('static' === kind && !await utils_namespaceObject.fs.pathExists(filename)) return null;
77
+ if ('static' === kind && !asset.realpath) {
78
+ const stat = await utils_namespaceObject.fs.stat(filename).catch(()=>null);
79
+ if (!stat?.isFile()) return null;
80
+ }
77
81
  if (respond) return respond(asset, (representation)=>serveStaticAsset(context, {
78
82
  ...asset,
79
83
  ...representation,
80
84
  filename: representation?.filename ?? asset.filename,
81
85
  mimeFilename: asset.mimeFilename ?? filename
82
86
  }));
83
- const mimeType = (0, mime_namespaceObject.getMimeType)(asset.mimeFilename ?? filename);
84
- if ('static' === kind && mimeType) context.header('Content-Type', mimeType);
85
- const size = 'static' === kind ? (await utils_namespaceObject.fs.lstat(filename)).size : void 0;
86
87
  const data = 'static' === kind ? await fileReader_namespaceObject.fileReader.readFileFromSystem(filename, 'buffer') : await fileReader_namespaceObject.fileReader.readFile(filename, 'buffer');
87
- if ('static' === kind && (asset.contentLength ?? true)) context.header('Content-Length', String(true === asset.contentLength && data ? data.byteLength : size));
88
88
  if (null === data) return null;
89
- if ('public' === kind && mimeType) context.header('Content-Type', mimeType);
89
+ const mimeType = (0, mime_namespaceObject.getMimeType)(asset.mimeFilename ?? filename);
90
+ if (mimeType) context.header('Content-Type', mimeType);
90
91
  Object.entries(asset.responseHeaders || {}).forEach(([key, value])=>{
91
92
  context.header(key, value);
92
93
  });
93
- if ('public' === kind && asset.contentLength) context.header('Content-Length', String(data.byteLength));
94
+ const notModified = (0, external_staticCache_js_namespaceObject.setStaticFileHeaders)(context, data, asset.cacheControl);
95
+ if (notModified && false !== asset.revalidate) return context.body(null, 304);
96
+ if (asset.contentLength ?? 'static' === kind) context.header('Content-Length', String(data.byteLength));
94
97
  const body = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
95
98
  return context.body(body, 200);
96
99
  }
@@ -116,14 +119,16 @@ const serverStaticPlugin = (options = {})=>({
116
119
  });
117
120
  }
118
121
  });
119
- function createPublicMiddleware({ pwd, routes, pathPrefix = '/', respondAsset, respondPublicFallback }) {
122
+ function createPublicMiddleware({ pwd, routes, pathPrefix = '/', cacheControl, respondAsset, respondPublicFallback }) {
123
+ const publicRoutes = routes.filter((route)=>!route.isSSR && route.entryPath?.startsWith('public')).sort(index_js_namespaceObject.sortRoutes);
120
124
  return async (c, next)=>{
121
125
  const respondPublic = async ()=>{
122
- const route = matchPublicRoute(c.req, routes);
126
+ const route = matchPublicRoute(c.req, publicRoutes);
123
127
  if (!route) return null;
124
128
  const asset = {
125
129
  filename: external_path_default().join(pwd, route.entryPath),
126
130
  kind: 'public',
131
+ cacheControl: cacheControl?.unhashed,
127
132
  responseHeaders: route.responseHeaders
128
133
  };
129
134
  const serve = (representation)=>serveStaticAsset(c, {
@@ -145,8 +150,8 @@ function createPublicMiddleware({ pwd, routes, pathPrefix = '/', respondAsset, r
145
150
  return response ?? next();
146
151
  };
147
152
  }
148
- function matchPublicRoute(req, routes) {
149
- for (const route of routes.sort(index_js_namespaceObject.sortRoutes))if (!route.isSSR && route.entryPath.startsWith('public') && req.path.startsWith(route.urlPath)) return route;
153
+ function matchPublicRoute(req, publicRoutes) {
154
+ return publicRoutes.find((route)=>req.path.startsWith(route.urlPath));
150
155
  }
151
156
  const extractPathname = (url)=>{
152
157
  try {
@@ -159,6 +164,7 @@ const extractPathname = (url)=>{
159
164
  };
160
165
  function createStaticMiddleware(options) {
161
166
  const { pwd, routes } = options;
167
+ const cacheControl = (0, external_staticCache_js_namespaceObject.resolveStaticCacheControl)(options.server.staticCacheControl);
162
168
  const prefix = options.output.assetPrefix || '/';
163
169
  const pathPrefix = extractPathname(prefix);
164
170
  const { distPath: { css: cssPath, js: jsPath, media: mediaPath } = {} } = options.output;
@@ -171,6 +177,11 @@ function createStaticMiddleware(options) {
171
177
  mediaPath
172
178
  ].filter((v)=>Boolean(v));
173
179
  const publicDirPatterns = (0, publicDir_js_namespaceObject.getPublicDirPatterns)(publicDir);
180
+ const isHashedAsset = (0, external_staticCache_js_namespaceObject.createHashedAssetMatcher)(staticFiles, [
181
+ 'public/',
182
+ 'upload/',
183
+ ...publicDirPatterns
184
+ ]);
174
185
  const staticReg = [
175
186
  'static/',
176
187
  'upload/',
@@ -187,25 +198,32 @@ function createStaticMiddleware(options) {
187
198
  ...staticReg,
188
199
  ...iconReg
189
200
  ].join('|')})`);
201
+ const publicMiddleware = createPublicMiddleware({
202
+ pwd,
203
+ routes: routes || [],
204
+ pathPrefix,
205
+ cacheControl,
206
+ respondAsset: options.respondAsset,
207
+ respondPublicFallback: options.respondPublicFallback
208
+ });
190
209
  return async (c, next)=>{
191
210
  const pageRoute = c.get('route');
192
211
  const pathname = c.req.path;
193
212
  if (pageRoute && '' === external_path_default().extname(pathname)) return next();
194
213
  const hit = staticPathRegExp.test(pathname);
195
- if (!hit) return createPublicMiddleware({
196
- pwd,
197
- routes: routes || [],
198
- pathPrefix,
199
- respondAsset: options.respondAsset,
200
- respondPublicFallback: options.respondPublicFallback
201
- })(c, next);
214
+ if (!hit) return publicMiddleware(c, next);
202
215
  else {
203
- const filepath = external_path_default().join(pwd, pathname.replace(pathPrefix, ()=>''));
216
+ const relativePath = pathname.replace(pathPrefix, ()=>'').replace(/^\/+/, '');
217
+ const filepath = external_path_default().join(pwd, relativePath);
204
218
  if (!isPathInside(filepath, pwd)) return next();
205
- if (!await utils_namespaceObject.fs.pathExists(filepath)) return next();
219
+ if (options.respondAsset) {
220
+ const stat = await utils_namespaceObject.fs.stat(filepath).catch(()=>null);
221
+ if (!stat?.isFile()) return next();
222
+ }
206
223
  const asset = {
207
224
  filename: filepath,
208
- kind: 'static'
225
+ kind: 'static',
226
+ cacheControl: cacheControl && (isHashedAsset(relativePath) ? cacheControl.hashed : cacheControl.unhashed)
209
227
  };
210
228
  const serve = (representation)=>serveStaticAsset(c, {
211
229
  ...asset,
@@ -0,0 +1,110 @@
1
+ "use strict";
2
+ var __webpack_require__ = {};
3
+ (()=>{
4
+ __webpack_require__.n = (module)=>{
5
+ var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
6
+ __webpack_require__.d(getter, {
7
+ a: getter
8
+ });
9
+ return getter;
10
+ };
11
+ })();
12
+ (()=>{
13
+ __webpack_require__.d = (exports1, getters, values)=>{
14
+ var define = (defs, kind)=>{
15
+ for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
16
+ enumerable: true,
17
+ [kind]: defs[key]
18
+ });
19
+ };
20
+ define(getters, "get");
21
+ define(values, "value");
22
+ };
23
+ })();
24
+ (()=>{
25
+ __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
26
+ })();
27
+ (()=>{
28
+ __webpack_require__.r = (exports1)=>{
29
+ if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
30
+ value: 'Module'
31
+ });
32
+ Object.defineProperty(exports1, '__esModule', {
33
+ value: true
34
+ });
35
+ };
36
+ })();
37
+ var __webpack_exports__ = {};
38
+ __webpack_require__.r(__webpack_exports__);
39
+ __webpack_require__.d(__webpack_exports__, {
40
+ createHashedAssetMatcher: ()=>createHashedAssetMatcher,
41
+ resolveStaticCacheControl: ()=>resolveStaticCacheControl,
42
+ setStaticFileHeaders: ()=>setStaticFileHeaders
43
+ });
44
+ const external_node_crypto_namespaceObject = require("node:crypto");
45
+ const external_path_namespaceObject = require("path");
46
+ var external_path_default = /*#__PURE__*/ __webpack_require__.n(external_path_namespaceObject);
47
+ const DEFAULT_HASHED_CACHE_CONTROL = 'public, max-age=31536000, immutable';
48
+ const DEFAULT_UNHASHED_CACHE_CONTROL = 'no-cache';
49
+ const CONTENT_HASH_REGEX = /[.-][0-9a-f]{8,}\.[^./]+$/i;
50
+ function resolveStaticCacheControl(staticCacheControl) {
51
+ if (false === staticCacheControl) return;
52
+ if ('production' !== process.env.NODE_ENV) return {
53
+ hashed: 'no-cache',
54
+ unhashed: 'no-cache'
55
+ };
56
+ const options = 'object' == typeof staticCacheControl ? staticCacheControl : {};
57
+ return {
58
+ hashed: options.hashed ?? DEFAULT_HASHED_CACHE_CONTROL,
59
+ unhashed: options.unhashed ?? DEFAULT_UNHASHED_CACHE_CONTROL
60
+ };
61
+ }
62
+ const normalizeDir = (dir)=>{
63
+ const normalized = dir.replace(/^\.?\/?/, '').replace(/\/+$/, '');
64
+ return normalized ? `${normalized}/` : '';
65
+ };
66
+ function createHashedAssetMatcher(assetDirs, userDirs = []) {
67
+ const dirs = [
68
+ 'static/',
69
+ ...assetDirs.map(normalizeDir)
70
+ ];
71
+ const isInAssetDir = (relativePath)=>!userDirs.some((userDir)=>relativePath.startsWith(userDir)) && dirs.some((dir)=>!dir || relativePath.startsWith(dir));
72
+ return (relativePath)=>isInAssetDir(relativePath) && CONTENT_HASH_REGEX.test(external_path_default().basename(relativePath));
73
+ }
74
+ const etags = new WeakMap();
75
+ function getETag(data) {
76
+ let etag = etags.get(data);
77
+ if (!etag) {
78
+ const hash = (0, external_node_crypto_namespaceObject.createHash)('sha1').update(data).digest('base64url');
79
+ etag = `W/"${data.byteLength.toString(16)}-${hash.slice(0, 22)}"`;
80
+ etags.set(data, etag);
81
+ }
82
+ return etag;
83
+ }
84
+ const stripWeak = (etag)=>etag.trim().replace(/^W\//, '');
85
+ const ENTITY_TAG_REGEX = /(?:W\/)?"[^"]*"/g;
86
+ function setStaticFileHeaders(c, data, cacheControl) {
87
+ const { headers } = c.res;
88
+ let etag = headers.get('ETag');
89
+ if (!etag) {
90
+ etag = getETag(data);
91
+ c.header('ETag', etag);
92
+ }
93
+ if (cacheControl && !headers.has('Cache-Control')) c.header('Cache-Control', cacheControl);
94
+ const { method } = c.req;
95
+ const ifNoneMatch = c.req.header('If-None-Match');
96
+ if ('GET' !== method && 'HEAD' !== method || !ifNoneMatch) return false;
97
+ const expected = stripWeak(etag);
98
+ return '*' === ifNoneMatch.trim() || (ifNoneMatch.match(ENTITY_TAG_REGEX) || []).some((value)=>stripWeak(value) === expected);
99
+ }
100
+ exports.createHashedAssetMatcher = __webpack_exports__.createHashedAssetMatcher;
101
+ exports.resolveStaticCacheControl = __webpack_exports__.resolveStaticCacheControl;
102
+ exports.setStaticFileHeaders = __webpack_exports__.setStaticFileHeaders;
103
+ for(var __rspack_i in __webpack_exports__)if (-1 === [
104
+ "createHashedAssetMatcher",
105
+ "resolveStaticCacheControl",
106
+ "setStaticFileHeaders"
107
+ ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
108
+ Object.defineProperty(exports, '__esModule', {
109
+ value: true
110
+ });
@@ -158,13 +158,10 @@ const injectServerTiming = ()=>({
158
158
  const monitors = c.get('monitors');
159
159
  monitors?.push(timingMonitor);
160
160
  await next();
161
- serverTimings.forEach((serverTiming)=>{
162
- const { name, desc, dur } = serverTiming;
163
- const _name = `bd-${metaName}-${name}`;
164
- const value = `${_name};${desc ? `decs="${desc}";` : ''} dur=${dur}`;
165
- c.header(external_constants_js_namespaceObject.SERVER_TIMING, value, {
166
- append: true
167
- });
161
+ if (0 === serverTimings.length) return;
162
+ const value = serverTimings.map(({ name, desc, dur })=>`bd-${metaName}-${name};${desc ? `decs="${desc}";` : ''} dur=${dur}`).join(', ');
163
+ c.header(external_constants_js_namespaceObject.SERVER_TIMING, value, {
164
+ append: true
168
165
  });
169
166
  }
170
167
  });
@@ -70,10 +70,6 @@ var __webpack_exports__ = {};
70
70
  "default"
71
71
  ].indexOf(__rspack_import_key) < 0) __rspack_reexport[__rspack_import_key] = ()=>_inject__rspack_import_3[__rspack_import_key];
72
72
  __webpack_require__.d(__webpack_exports__, __rspack_reexport);
73
- const DYNAMIC_ROUTE_REG = /\/:./;
74
- function escapeRegexSpecialChars(path) {
75
- return path.replace(/[()[\]{}*+?.^$|\\]/g, '\\$&');
76
- }
77
73
  const renderPlugin = ()=>({
78
74
  name: '@modern-js/plugin-render',
79
75
  setup (api) {
@@ -86,10 +82,12 @@ var __webpack_exports__ = {};
86
82
  handler: (0, _monitors__rspack_import_2.requestLatencyMiddleware)()
87
83
  });
88
84
  for (const route of pageRoutes){
89
- const { urlPath: originUrlPath } = route;
90
- const isDynamic = DYNAMIC_ROUTE_REG.test(originUrlPath);
91
- const escapedPath = isDynamic ? originUrlPath : escapeRegexSpecialChars(originUrlPath);
92
- const urlPath = escapedPath.endsWith('/') ? `${escapedPath}*` : `${escapedPath}/*`;
85
+ const urlPath = (0, _utils__rspack_import_1.getRoutePath)(route);
86
+ if (route.isSSG && !urlPath.endsWith('/')) middlewares.push({
87
+ name: 'ssg-trailing-slash-redirect',
88
+ path: `${urlPath}/`,
89
+ handler: async (c)=>c.redirect(`${urlPath}${new URL(c.req.url).search}`, 308)
90
+ });
93
91
  renderMiddlewares?.forEach((m)=>{
94
92
  middlewares.push({
95
93
  name: m.name,
@@ -48,6 +48,7 @@ var __webpack_exports__ = {};
48
48
  });
49
49
  const universal_namespaceObject = require("@modern-js/utils/universal");
50
50
  const trie_router_namespaceObject = require("hono/router/trie-router");
51
+ const url_namespaceObject = require("hono/utils/url");
51
52
  const external_constants_js_namespaceObject = require("../../constants.js");
52
53
  const index_js_namespaceObject = require("../../utils/index.js");
53
54
  const external_csrRscRender_js_namespaceObject = require("./csrRscRender.js");
@@ -69,8 +70,7 @@ var __webpack_exports__ = {};
69
70
  ];
70
71
  const router = new trie_router_namespaceObject.TrieRouter();
71
72
  for (const route of finalRoutes){
72
- const { urlPath: originUrlPath } = route;
73
- const urlPath = originUrlPath.endsWith('/') ? `${originUrlPath}*` : `${originUrlPath}/*`;
73
+ const urlPath = (0, index_js_namespaceObject.getRoutePath)(route);
74
74
  router.add('*', urlPath, route);
75
75
  }
76
76
  return router;
@@ -109,12 +109,12 @@ var __webpack_exports__ = {};
109
109
  }
110
110
  async function createRender({ routes, pwd, metaName, staticGenerate, cacheConfig, forceCSR, forceCSRMap, config }) {
111
111
  const router = getRouter(routes);
112
+ const framework = (0, universal_namespaceObject.cutNameByHyphen)(metaName || 'modern-js');
113
+ const fallbackHeader = `x-${framework}-ssr-fallback`;
112
114
  return async (req, { monitors, nodeReq, templates, serverManifest, rscClientManifest, rscSSRManifest, rscServerManifest, locals, matchEntryName, matchPathname, loaderContext, serverContext, contextForceCSR, reporter })=>{
113
- const forMatchpathname = matchPathname ?? (0, index_js_namespaceObject.getPathname)(req);
115
+ const forMatchpathname = matchPathname ?? (0, url_namespaceObject.getPath)(req);
114
116
  const [routeInfo, params] = matchRoute(router, forMatchpathname, matchEntryName);
115
117
  serverContext?.set('renderRoute', routeInfo);
116
- const framework = (0, universal_namespaceObject.cutNameByHyphen)(metaName || 'modern-js');
117
- const fallbackHeader = `x-${framework}-ssr-fallback`;
118
118
  let fallbackReason = null;
119
119
  const fallbackWrapper = (reason)=>{
120
120
  fallbackReason = reason;
@@ -140,9 +140,8 @@ var __webpack_exports__ = {};
140
140
  });
141
141
  const finalForceCSR = routeInfo.entryName ? forceCSRMap?.get(routeInfo.entryName) ?? forceCSR : forceCSR;
142
142
  const renderMode = await getRenderMode(req, fallbackHeader, routeInfo.isSSR, finalForceCSR, nodeReq, fallbackWrapper, contextForceCSR);
143
- const headerData = (0, index_js_namespaceObject.parseHeaders)(req);
144
143
  const onError = (e, key)=>{
145
- 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));
144
+ 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((0, index_js_namespaceObject.parseHeaders)(req)));
146
145
  };
147
146
  const onTiming = (name, dur)=>{
148
147
  monitors?.timing(name, dur, 'SSR');
@@ -145,6 +145,15 @@ function shouldUseCache(request) {
145
145
  const hasLoaderQuery = url.searchParams.has('__loader');
146
146
  return !(hasRSCAction || hasRSCTree || hasLoaderQuery);
147
147
  }
148
+ const cacheKeyRegExps = new Map();
149
+ function getCacheKeyRegExp(key) {
150
+ let regExp = cacheKeyRegExps.get(key);
151
+ if (!regExp) {
152
+ regExp = new RegExp(key);
153
+ cacheKeyRegExps.set(key, regExp);
154
+ }
155
+ return regExp;
156
+ }
148
157
  function matchCacheControl(cacheOption, req) {
149
158
  if (!cacheOption || !req) return;
150
159
  else {
@@ -152,7 +161,7 @@ function matchCacheControl(cacheOption, req) {
152
161
  if (isCacheOptionProvider(cacheOption)) return cacheOption(req);
153
162
  const url = req.url;
154
163
  const options = Object.entries(cacheOption);
155
- for (const [key, option] of options)if ('*' === key || new RegExp(key).test(url)) if ('function' == typeof option) return option(req);
164
+ for (const [key, option] of options)if ('*' === key || getCacheKeyRegExp(key).test(url)) if ('function' == typeof option) return option(req);
156
165
  else return option;
157
166
  return;
158
167
  }
@@ -41,10 +41,6 @@ async function ssrRender(request, { routeInfo, html, config: userConfig, staticG
41
41
  const loadableStats = serverManifest.loadableStats || {};
42
42
  const routeManifest = serverManifest.routeManifest || {};
43
43
  const moduleFederationCssAssets = serverManifest.moduleFederationCssAssets || [];
44
- const headers = (0, index_js_namespaceObject.parseHeaders)(request);
45
- if (nodeReq) {
46
- for(const key in nodeReq.headers)if (!headers[key]) headers[key] = nodeReq.headers[key];
47
- }
48
44
  const renderBundle = serverManifest.renderBundles?.[entryName || constants_namespaceObject.MAIN_ENTRY_NAME];
49
45
  if (!renderBundle) throw new Error(`Can't find renderBundle ${entryName || constants_namespaceObject.MAIN_ENTRY_NAME}`);
50
46
  const requestHandler = await renderBundle[SERVER_RUNTIME_ENTRY];
@@ -50,7 +50,7 @@ const injectRoutePlugin = ()=>({
50
50
  const pageRoutes = getPageRoutes(routes);
51
51
  for (const route of pageRoutes){
52
52
  const { urlPath: originUrlPath, entryName = constants_namespaceObject.MAIN_ENTRY_NAME } = route;
53
- const urlPath = originUrlPath.endsWith('/') ? `${originUrlPath}*` : `${originUrlPath}/*`;
53
+ const urlPath = (0, index_js_namespaceObject.getRoutePath)(route);
54
54
  middlewares.push({
55
55
  name: 'inject-route-info',
56
56
  path: urlPath,
@@ -32,6 +32,7 @@ __webpack_require__.d(__webpack_exports__, {
32
32
  createServerBase: ()=>createServerBase
33
33
  });
34
34
  const server_namespaceObject = require("@modern-js/plugin/server");
35
+ const fileReader_namespaceObject = require("@modern-js/runtime-utils/fileReader");
35
36
  const utils_namespaceObject = require("@modern-js/utils");
36
37
  const external_hono_namespaceObject = require("hono");
37
38
  const external_context_js_namespaceObject = require("./context.js");
@@ -144,6 +145,7 @@ class ServerBase {
144
145
  }
145
146
  constructor(options){
146
147
  _class_private_method_init(this, _applyMiddlewares);
148
+ this.fileReader = fileReader_namespaceObject.fileReader;
147
149
  this.plugins = [
148
150
  {
149
151
  name: '@modern-js/server-lifecycle',
@@ -156,7 +158,9 @@ class ServerBase {
156
158
  this.serverContext = null;
157
159
  this.serverOptions = options;
158
160
  this.app = new external_hono_namespaceObject.Hono();
159
- this.app.use('*', external_context_js_namespaceObject.run);
161
+ this.app.use('*', async (context, next)=>{
162
+ await (0, external_context_js_namespaceObject.run)(context, next);
163
+ });
160
164
  }
161
165
  }
162
166
  function applyMiddlewares() {
@@ -29,13 +29,20 @@ var __webpack_exports__ = {};
29
29
  __webpack_require__.r(__webpack_exports__);
30
30
  const sortRoutes = (route1, route2)=>route2.urlPath.length - route1.urlPath.length;
31
31
  const uniqueKeyByRoute = (route)=>`${route.entryName}-${route.urlPath}`;
32
+ const getRoutePath = ({ urlPath, isSSG })=>{
33
+ if (isSSG) return urlPath;
34
+ return urlPath.endsWith('/') ? `${urlPath}*` : `${urlPath}/*`;
35
+ };
32
36
  __webpack_require__.d(__webpack_exports__, {}, {
37
+ getRoutePath: getRoutePath,
33
38
  sortRoutes: sortRoutes,
34
39
  uniqueKeyByRoute: uniqueKeyByRoute
35
40
  });
41
+ exports.getRoutePath = __webpack_exports__.getRoutePath;
36
42
  exports.sortRoutes = __webpack_exports__.sortRoutes;
37
43
  exports.uniqueKeyByRoute = __webpack_exports__.uniqueKeyByRoute;
38
44
  for(var __rspack_i in __webpack_exports__)if (-1 === [
45
+ "getRoutePath",
39
46
  "sortRoutes",
40
47
  "uniqueKeyByRoute"
41
48
  ].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];