@bleedingdev/modern-js-server-core 3.9.0-ultramodern.2 → 3.9.0-ultramodern.21

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 (65) hide show
  1. package/dist/cjs/adapters/node/hono.js +15 -5
  2. package/dist/cjs/adapters/node/index.js +4 -0
  3. package/dist/cjs/adapters/node/plugins/static.js +107 -29
  4. package/dist/cjs/helper.js +1 -1
  5. package/dist/cjs/index.js +10 -34
  6. package/dist/cjs/plugins/compat/index.js +1 -0
  7. package/dist/cjs/plugins/render/render.js +3 -4
  8. package/dist/cjs/plugins/render/ssrCache.js +63 -42
  9. package/dist/cjs/serverBase.js +60 -19
  10. package/dist/cjs/utils/error.js +0 -10
  11. package/dist/cjs/utils/transformStream.js +1 -1
  12. package/dist/esm/adapters/node/hono.mjs +15 -5
  13. package/dist/esm/adapters/node/index.mjs +1 -0
  14. package/dist/esm/adapters/node/plugins/static.mjs +107 -32
  15. package/dist/esm/helper.mjs +1 -1
  16. package/dist/esm/index.mjs +1 -1
  17. package/dist/esm/plugins/compat/index.mjs +1 -0
  18. package/dist/esm/plugins/render/render.mjs +4 -11
  19. package/dist/esm/plugins/render/ssrCache.mjs +63 -42
  20. package/dist/esm/serverBase.mjs +60 -19
  21. package/dist/esm/utils/error.mjs +0 -1
  22. package/dist/esm/utils/transformStream.mjs +1 -1
  23. package/dist/esm-node/adapters/node/hono.mjs +15 -5
  24. package/dist/esm-node/adapters/node/index.mjs +1 -0
  25. package/dist/esm-node/adapters/node/plugins/static.mjs +107 -32
  26. package/dist/esm-node/helper.mjs +1 -1
  27. package/dist/esm-node/index.mjs +1 -1
  28. package/dist/esm-node/plugins/compat/index.mjs +1 -0
  29. package/dist/esm-node/plugins/render/render.mjs +4 -11
  30. package/dist/esm-node/plugins/render/ssrCache.mjs +63 -42
  31. package/dist/esm-node/serverBase.mjs +60 -19
  32. package/dist/esm-node/utils/error.mjs +0 -1
  33. package/dist/esm-node/utils/transformStream.mjs +1 -1
  34. package/dist/types/adapters/node/index.d.ts +2 -0
  35. package/dist/types/adapters/node/plugins/static.d.ts +42 -4
  36. package/dist/types/index.d.ts +1 -2
  37. package/dist/types/serverBase.d.ts +6 -0
  38. package/dist/types/types/config/bff.d.ts +4 -15
  39. package/dist/types/types/config/server.d.ts +1 -3
  40. package/dist/types/types/plugins/plugin.d.ts +15 -1
  41. package/dist/types/types/requestHandler.d.ts +2 -3
  42. package/dist/types/utils/error.d.ts +0 -2
  43. package/package.json +9 -10
  44. package/dist/cjs/adapters/node/plugins/staticModuleFederation.js +0 -173
  45. package/dist/cjs/adapters/node/plugins/staticPrecompressed.js +0 -152
  46. package/dist/cjs/adapters/node/plugins/staticServing.js +0 -206
  47. package/dist/cjs/types/config/bffRuntime.js +0 -18
  48. package/dist/cjs/types/config/serverTelemetry.js +0 -18
  49. package/dist/esm/adapters/node/plugins/staticModuleFederation.mjs +0 -104
  50. package/dist/esm/adapters/node/plugins/staticPrecompressed.mjs +0 -111
  51. package/dist/esm/adapters/node/plugins/staticServing.mjs +0 -152
  52. package/dist/esm/rslib-runtime~1.mjs +0 -18
  53. package/dist/esm/types/config/bffRuntime.mjs +0 -0
  54. package/dist/esm/types/config/serverTelemetry.mjs +0 -0
  55. package/dist/esm-node/adapters/node/plugins/staticModuleFederation.mjs +0 -105
  56. package/dist/esm-node/adapters/node/plugins/staticPrecompressed.mjs +0 -112
  57. package/dist/esm-node/adapters/node/plugins/staticServing.mjs +0 -153
  58. package/dist/esm-node/rslib-runtime~0.mjs +0 -19
  59. package/dist/esm-node/types/config/bffRuntime.mjs +0 -1
  60. package/dist/esm-node/types/config/serverTelemetry.mjs +0 -1
  61. package/dist/types/adapters/node/plugins/staticModuleFederation.d.ts +0 -13
  62. package/dist/types/adapters/node/plugins/staticPrecompressed.d.ts +0 -13
  63. package/dist/types/adapters/node/plugins/staticServing.d.ts +0 -25
  64. package/dist/types/types/config/bffRuntime.d.ts +0 -116
  65. package/dist/types/types/config/serverTelemetry.d.ts +0 -319
@@ -1,152 +0,0 @@
1
- import { fileReader } from "@modern-js/runtime-utils/fileReader";
2
- import { fs } from "@modern-js/utils";
3
- import { getMimeType } from "hono/utils/mime";
4
- import path from "path";
5
- import { applyModuleFederationAssetHeaders, getModuleFederationAssetList, getModuleFederationRequestPath, isBackendModuleFederationManifestRequest, isModuleFederationManifestRequest, patchModuleFederationManifestPublicPath, patchModuleFederationRemoteEntryPublicPath } from "./staticModuleFederation.mjs";
6
- import { applyPreCompressedAssetHeaders, resolvePreCompressedAsset } from "./staticPrecompressed.mjs";
7
- const MODULE_FEDERATION_ASSET_REFRESH_INTERVAL_MS = 1000;
8
- const getStaticMimeType = (filename)=>getMimeType(filename) ?? ('.cjs' === path.extname(filename).toLowerCase() ? "text/javascript; charset=UTF-8" : void 0);
9
- const servePreCompressedPublicRouteAsset = async (c, pwd, route)=>{
10
- const { entryPath } = route;
11
- const originFilename = path.join(pwd, entryPath);
12
- const preCompressedAsset = await resolvePreCompressedAsset(c, originFilename);
13
- if (!preCompressedAsset.acceptable) {
14
- applyPreCompressedAssetHeaders(c, preCompressedAsset);
15
- return c.body(null, 406);
16
- }
17
- const filename = preCompressedAsset.selected?.filepath ?? originFilename;
18
- const data = await fileReader.readFile(filename, 'buffer');
19
- const mimeType = getStaticMimeType(originFilename);
20
- if (null === data) return null;
21
- const body = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
22
- if (mimeType) c.header('Content-Type', mimeType);
23
- Object.entries(route.responseHeaders || {}).forEach(([k, v])=>{
24
- c.header(k, v);
25
- });
26
- applyPreCompressedAssetHeaders(c, preCompressedAsset);
27
- c.header('Content-Length', String(data.byteLength));
28
- return c.body(body, 200);
29
- };
30
- const isPathInside = (target, root)=>{
31
- const relative = path.relative(path.resolve(root), path.resolve(target));
32
- return '' === relative || !relative.startsWith(`..${path.sep}`) && '..' !== relative && !path.isAbsolute(relative);
33
- };
34
- const resolvePublicDirectoryAsset = async (pwd, pathname)=>{
35
- let decodedPathname;
36
- try {
37
- decodedPathname = decodeURIComponent(pathname).replace(/\\/gu, '/');
38
- } catch {
39
- return null;
40
- }
41
- if (decodedPathname.includes('\0') || decodedPathname.split('/').includes('..')) return null;
42
- const publicDirectory = path.join(pwd, 'public');
43
- const filepath = path.resolve(publicDirectory, decodedPathname.replace(/^\/+/u, ''));
44
- if (!isPathInside(filepath, publicDirectory)) return null;
45
- try {
46
- const [realPublicDirectory, realFilepath, stat] = await Promise.all([
47
- fs.realpath(publicDirectory),
48
- fs.realpath(filepath),
49
- fs.stat(filepath)
50
- ]);
51
- if (!stat.isFile() || !isPathInside(realFilepath, realPublicDirectory)) return null;
52
- return realFilepath;
53
- } catch {
54
- return null;
55
- }
56
- };
57
- const servePublicDirectoryAsset = async (c, pwd)=>{
58
- const method = c.req.raw.method.toUpperCase();
59
- if ('GET' !== method && 'HEAD' !== method) return null;
60
- const originFilename = await resolvePublicDirectoryAsset(pwd, c.req.path);
61
- if (null === originFilename) return null;
62
- const preCompressedAsset = await resolvePreCompressedAsset(c, originFilename);
63
- if (!preCompressedAsset.acceptable) {
64
- applyPreCompressedAssetHeaders(c, preCompressedAsset);
65
- return c.body(null, 406);
66
- }
67
- const selectedFilename = preCompressedAsset.selected?.filepath ?? originFilename;
68
- const publicDirectory = await fs.realpath(path.join(pwd, 'public'));
69
- let realSelectedFilename;
70
- try {
71
- realSelectedFilename = await fs.realpath(selectedFilename);
72
- } catch {
73
- return null;
74
- }
75
- if (!isPathInside(realSelectedFilename, publicDirectory)) return null;
76
- const data = await fileReader.readFileFromSystem(realSelectedFilename, 'buffer');
77
- if (null === data) return null;
78
- const mimeType = getStaticMimeType(originFilename);
79
- if (mimeType) c.header('Content-Type', mimeType);
80
- applyPreCompressedAssetHeaders(c, preCompressedAsset);
81
- c.header('Content-Length', String(data.byteLength));
82
- if ('HEAD' === method) return c.body(null, 200);
83
- const body = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
84
- return c.body(body, 200);
85
- };
86
- const createModuleFederationStaticServing = ({ pwd, pathPrefix })=>{
87
- let moduleFederationAssets = null;
88
- let moduleFederationAssetsExpiresAt = 0;
89
- let moduleFederationAssetsRefresh = null;
90
- const getModuleFederationAssets = async ()=>{
91
- if (moduleFederationAssets && Date.now() < moduleFederationAssetsExpiresAt) return moduleFederationAssets;
92
- if (!moduleFederationAssetsRefresh) moduleFederationAssetsRefresh = getModuleFederationAssetList(pwd).then((assets)=>{
93
- moduleFederationAssets = assets;
94
- moduleFederationAssetsExpiresAt = Date.now() + MODULE_FEDERATION_ASSET_REFRESH_INTERVAL_MS;
95
- return assets;
96
- }).finally(()=>{
97
- moduleFederationAssetsRefresh = null;
98
- });
99
- return moduleFederationAssetsRefresh;
100
- };
101
- const resolveRequest = async (pathname)=>{
102
- const requestPath = getModuleFederationRequestPath(pathname, pathPrefix);
103
- if (requestPath.includes('..')) return null;
104
- const moduleFederationAssetMeta = await getModuleFederationAssets();
105
- return {
106
- requestPath,
107
- isModuleFederationAsset: moduleFederationAssetMeta.assets.has(requestPath),
108
- isModuleFederationRemoteEntry: moduleFederationAssetMeta.remoteEntries.has(requestPath)
109
- };
110
- };
111
- const serveFile = async (c, filepath, moduleFederationAsset = false, moduleFederationRemoteEntry = false, requestPath = '')=>{
112
- if (moduleFederationAsset) applyModuleFederationAssetHeaders(c);
113
- const mimeType = getStaticMimeType(filepath);
114
- if (mimeType) c.header('Content-Type', mimeType);
115
- const shouldPatchManifest = moduleFederationAsset && isModuleFederationManifestRequest(requestPath) && !isBackendModuleFederationManifestRequest(requestPath);
116
- const shouldPatchRemoteEntry = moduleFederationRemoteEntry;
117
- const canUsePreCompressed = !shouldPatchManifest && !shouldPatchRemoteEntry;
118
- const preCompressedAsset = canUsePreCompressed ? await resolvePreCompressedAsset(c, filepath) : {
119
- selected: null,
120
- hasVariant: false,
121
- acceptable: true
122
- };
123
- if (!preCompressedAsset.acceptable) {
124
- applyPreCompressedAssetHeaders(c, preCompressedAsset);
125
- return c.body(null, 406);
126
- }
127
- const targetFilepath = preCompressedAsset.selected?.filepath ?? filepath;
128
- const chunk = await fileReader.readFileFromSystem(targetFilepath, 'buffer');
129
- if (null === chunk) return null;
130
- const responseChunk = shouldPatchManifest ? patchModuleFederationManifestPublicPath(c, chunk, pathPrefix) : shouldPatchRemoteEntry ? patchModuleFederationRemoteEntryPublicPath(c, chunk, pathPrefix) : chunk;
131
- applyPreCompressedAssetHeaders(c, preCompressedAsset);
132
- c.header('Content-Length', String(responseChunk.byteLength));
133
- const body = new Uint8Array(responseChunk.buffer, responseChunk.byteOffset, responseChunk.byteLength);
134
- return c.body(body, 200);
135
- };
136
- const serveByPath = async (c, filepath, request, moduleFederationAsset = false, moduleFederationRemoteEntry = false)=>{
137
- if (!isPathInside(filepath, pwd)) return null;
138
- if (!await fs.pathExists(filepath)) return null;
139
- return serveFile(c, filepath, moduleFederationAsset, moduleFederationRemoteEntry, request.requestPath);
140
- };
141
- const serveStaticHit = (c, request)=>serveByPath(c, path.join(pwd, request.requestPath), request, request.isModuleFederationAsset, request.isModuleFederationRemoteEntry);
142
- const serveModuleFederationAsset = (c, request)=>{
143
- if (!request.isModuleFederationAsset) return null;
144
- return serveByPath(c, path.join(pwd, request.requestPath), request, true, request.isModuleFederationRemoteEntry);
145
- };
146
- return {
147
- resolveRequest,
148
- serveStaticHit,
149
- serveModuleFederationAsset
150
- };
151
- };
152
- export { createModuleFederationStaticServing, servePreCompressedPublicRouteAsset, servePublicDirectoryAsset };
@@ -1,18 +0,0 @@
1
- var __webpack_modules__ = {};
2
- var __webpack_module_cache__ = {};
3
- function __webpack_require__(moduleId) {
4
- var cachedModule = __webpack_module_cache__[moduleId];
5
- if (void 0 !== cachedModule) return cachedModule.exports;
6
- var module = __webpack_module_cache__[moduleId] = {
7
- exports: {}
8
- };
9
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
10
- return module.exports;
11
- }
12
- __webpack_require__.m = __webpack_modules__;
13
- (()=>{
14
- __webpack_require__.add = function(modules) {
15
- Object.assign(__webpack_require__.m, modules);
16
- };
17
- })();
18
- export { __webpack_require__ };
File without changes
File without changes
@@ -1,105 +0,0 @@
1
- import "node:module";
2
- import { fileReader } from "@modern-js/runtime-utils/fileReader";
3
- import { fs } from "@modern-js/utils";
4
- import path from "path";
5
- const MODULE_FEDERATION_MANIFEST_FILE = 'mf-manifest.json';
6
- const BACKEND_MODULE_FEDERATION_MANIFEST_FILE = 'backend-mf-manifest.json';
7
- const MODULE_FEDERATION_MANIFEST_FILES = [
8
- MODULE_FEDERATION_MANIFEST_FILE,
9
- BACKEND_MODULE_FEDERATION_MANIFEST_FILE
10
- ];
11
- const MODULE_FEDERATION_OPTIONAL_FILES = [
12
- 'mf-stats.json'
13
- ];
14
- const trimLeadingSlash = (value)=>value.replace(/^\/+/, '');
15
- const getModuleFederationRequestPath = (pathname, pathPrefix)=>{
16
- const normalizedPrefix = `/${trimLeadingSlash(pathPrefix)}`.replace(/\/+$/u, '');
17
- const requestPath = normalizedPrefix && (pathname === normalizedPrefix || pathname.startsWith(`${normalizedPrefix}/`)) ? pathname.slice(normalizedPrefix.length) : pathname;
18
- return trimLeadingSlash(requestPath);
19
- };
20
- const isModuleFederationManifestRequest = (requestPath)=>MODULE_FEDERATION_MANIFEST_FILES.includes(requestPath);
21
- const isBackendModuleFederationManifestRequest = (requestPath)=>requestPath === BACKEND_MODULE_FEDERATION_MANIFEST_FILE;
22
- const applyModuleFederationAssetHeaders = (c)=>{
23
- c.header('Access-Control-Allow-Origin', '*');
24
- c.header('Access-Control-Allow-Headers', '*');
25
- c.header('Access-Control-Allow-Methods', 'GET,HEAD,OPTIONS');
26
- };
27
- const joinModuleFederationAssetPath = (assetPath, assetName)=>{
28
- if (!assetName) return '';
29
- return trimLeadingSlash(path.posix.join(assetPath || '', assetName));
30
- };
31
- const appendModuleFederationAsset = (set, assetPath)=>{
32
- if (assetPath) set.add(trimLeadingSlash(assetPath));
33
- };
34
- const appendModuleFederationAssets = (set, assets)=>{
35
- assets?.js?.sync?.forEach((asset)=>appendModuleFederationAsset(set, asset));
36
- assets?.js?.async?.forEach((asset)=>appendModuleFederationAsset(set, asset));
37
- assets?.css?.sync?.forEach((asset)=>appendModuleFederationAsset(set, asset));
38
- assets?.css?.async?.forEach((asset)=>appendModuleFederationAsset(set, asset));
39
- };
40
- const hasAbsoluteProtocol = (value)=>/^https?:\/\//i.test(value) || value.startsWith('//');
41
- const ensureLeadingSlash = (value)=>{
42
- if ('' === value) return '/';
43
- return value.startsWith('/') ? value : `/${value}`;
44
- };
45
- const ensureTrailingSlash = (value)=>value.endsWith('/') ? value : `${value}/`;
46
- const patchModuleFederationManifestPublicPath = (c, manifestBuffer, pathPrefix)=>{
47
- try {
48
- const manifest = JSON.parse(manifestBuffer.toString('utf-8'));
49
- const publicPath = manifest.metaData?.publicPath;
50
- if (!publicPath || hasAbsoluteProtocol(publicPath)) return manifestBuffer;
51
- const requestURL = new URL(c.req.url);
52
- const prefixPath = ensureTrailingSlash(ensureLeadingSlash(pathPrefix || '/'));
53
- manifest.metaData = {
54
- ...manifest.metaData,
55
- publicPath: `${requestURL.origin}${prefixPath}`
56
- };
57
- return Buffer.from(JSON.stringify(manifest), 'utf-8');
58
- } catch {
59
- return manifestBuffer;
60
- }
61
- };
62
- const patchModuleFederationRemoteEntryPublicPath = (c, remoteEntryBuffer, pathPrefix)=>{
63
- const requestURL = new URL(c.req.url);
64
- const prefixPath = ensureTrailingSlash(ensureLeadingSlash(pathPrefix || '/'));
65
- const publicPath = `${requestURL.origin}${prefixPath}`;
66
- const source = remoteEntryBuffer.toString('utf-8');
67
- const patched = source.replace(/__webpack_require__\.p\s*=\s*(['"`])[^'"`]*\1;/, `__webpack_require__.p = ${JSON.stringify(publicPath)};`).replace(/__rspack_require__\.p\s*=\s*(['"`])[^'"`]*\1;/, `__rspack_require__.p = ${JSON.stringify(publicPath)};`);
68
- if (patched === source) return remoteEntryBuffer;
69
- return Buffer.from(patched, 'utf-8');
70
- };
71
- const getModuleFederationAssetList = async (pwd)=>{
72
- const assets = new Set();
73
- const remoteEntries = new Set();
74
- let manifestFound = false;
75
- for (const manifestFile of MODULE_FEDERATION_MANIFEST_FILES){
76
- const manifestPath = path.join(pwd, manifestFile);
77
- if (!await fs.pathExists(manifestPath)) continue;
78
- manifestFound = true;
79
- assets.add(manifestFile);
80
- const manifestBuffer = await fileReader.readFileFromSystem(manifestPath, 'buffer');
81
- if (null !== manifestBuffer) try {
82
- const manifest = JSON.parse(manifestBuffer.toString('utf-8'));
83
- const remoteEntry = joinModuleFederationAssetPath(manifest.metaData?.remoteEntry?.path, manifest.metaData?.remoteEntry?.name);
84
- const dtsZip = joinModuleFederationAssetPath(manifest.metaData?.types?.path, manifest.metaData?.types?.zip);
85
- const dtsApi = joinModuleFederationAssetPath(manifest.metaData?.types?.path, manifest.metaData?.types?.api);
86
- if (remoteEntry) {
87
- assets.add(remoteEntry);
88
- remoteEntries.add(remoteEntry);
89
- }
90
- appendModuleFederationAsset(assets, dtsZip);
91
- appendModuleFederationAsset(assets, dtsApi);
92
- manifest.shared?.forEach((item)=>appendModuleFederationAssets(assets, item.assets));
93
- manifest.remotes?.forEach((item)=>appendModuleFederationAssets(assets, item.assets));
94
- manifest.exposes?.forEach((item)=>appendModuleFederationAssets(assets, item.assets));
95
- } catch {}
96
- }
97
- if (manifestFound) {
98
- for (const filename of MODULE_FEDERATION_OPTIONAL_FILES)if (await fs.pathExists(path.join(pwd, filename))) assets.add(filename);
99
- }
100
- return {
101
- assets,
102
- remoteEntries
103
- };
104
- };
105
- export { MODULE_FEDERATION_MANIFEST_FILE, applyModuleFederationAssetHeaders, getModuleFederationAssetList, getModuleFederationRequestPath, isBackendModuleFederationManifestRequest, isModuleFederationManifestRequest, patchModuleFederationManifestPublicPath, patchModuleFederationRemoteEntryPublicPath };
@@ -1,112 +0,0 @@
1
- import "node:module";
2
- import { fs } from "@modern-js/utils";
3
- const PRE_COMPRESSED_ASSET_EXTENSIONS = {
4
- br: '.br',
5
- gzip: '.gz'
6
- };
7
- const PRE_COMPRESSED_SUPPORTED_ENCODINGS = [
8
- 'br',
9
- 'gzip'
10
- ];
11
- const QUALITY_VALUE_PATTERN = /^(?:0(?:\.\d{0,3})?|1(?:\.0{0,3})?)$/u;
12
- const parseAcceptEncoding = (value)=>value.split(',').map((item)=>item.trim()).filter(Boolean).map((item)=>{
13
- const [rawName, ...params] = item.split(';');
14
- const name = rawName.trim().toLowerCase();
15
- let q = 1;
16
- let qualitySeen = false;
17
- for (const param of params){
18
- const [key, rawValue] = param.split('=').map((v)=>v.trim());
19
- if ('q' === key.toLowerCase()) {
20
- if (qualitySeen || null == rawValue || !QUALITY_VALUE_PATTERN.test(rawValue)) {
21
- q = 0;
22
- break;
23
- }
24
- qualitySeen = true;
25
- q = Number(rawValue);
26
- }
27
- }
28
- return {
29
- name,
30
- q
31
- };
32
- });
33
- const getAcceptedRepresentations = (value)=>{
34
- if (!value) return [
35
- 'identity'
36
- ];
37
- const parsed = parseAcceptEncoding(value);
38
- const qualityByEncoding = new Map();
39
- let wildcardQuality;
40
- for (const { name, q } of parsed){
41
- if ('*' === name) {
42
- wildcardQuality = q;
43
- continue;
44
- }
45
- qualityByEncoding.set(name, q);
46
- }
47
- const getQuality = (encoding)=>{
48
- const explicit = qualityByEncoding.get(encoding);
49
- if (void 0 !== explicit) return explicit;
50
- return wildcardQuality ?? 0;
51
- };
52
- const identityQuality = qualityByEncoding.get('identity') ?? (0 === wildcardQuality ? 0 : 1);
53
- return [
54
- ...PRE_COMPRESSED_SUPPORTED_ENCODINGS.map((encoding)=>({
55
- encoding,
56
- quality: getQuality(encoding)
57
- })),
58
- {
59
- encoding: 'identity',
60
- quality: identityQuality
61
- }
62
- ].filter((item)=>item.quality > 0).sort((a, b)=>b.quality - a.quality).map((item)=>item.encoding);
63
- };
64
- const appendVaryHeader = (c, value)=>{
65
- const current = c.res.headers.get('Vary');
66
- if (!current) return void c.header('Vary', value);
67
- const values = current.split(',').map((item)=>item.trim().toLowerCase()).filter(Boolean);
68
- if (!values.includes(value.toLowerCase())) c.header('Vary', `${current}, ${value}`);
69
- };
70
- const resolvePreCompressedAsset = async (c, filepath)=>{
71
- const brPath = `${filepath}${PRE_COMPRESSED_ASSET_EXTENSIONS.br}`;
72
- const gzipPath = `${filepath}${PRE_COMPRESSED_ASSET_EXTENSIONS.gzip}`;
73
- const [hasBr, hasGzip] = await Promise.all([
74
- fs.pathExists(brPath),
75
- fs.pathExists(gzipPath)
76
- ]);
77
- const hasVariant = hasBr || hasGzip;
78
- const acceptedRepresentations = getAcceptedRepresentations(c.req.header('accept-encoding'));
79
- for (const encoding of acceptedRepresentations){
80
- if ('identity' === encoding) return {
81
- selected: null,
82
- hasVariant,
83
- acceptable: true
84
- };
85
- if ('br' === encoding && hasBr) return {
86
- selected: {
87
- filepath: brPath,
88
- encoding
89
- },
90
- hasVariant: true,
91
- acceptable: true
92
- };
93
- if ('gzip' === encoding && hasGzip) return {
94
- selected: {
95
- filepath: gzipPath,
96
- encoding
97
- },
98
- hasVariant: true,
99
- acceptable: true
100
- };
101
- }
102
- return {
103
- selected: null,
104
- hasVariant,
105
- acceptable: false
106
- };
107
- };
108
- const applyPreCompressedAssetHeaders = (c, preCompressedAsset)=>{
109
- if (preCompressedAsset.hasVariant || !preCompressedAsset.acceptable) appendVaryHeader(c, 'Accept-Encoding');
110
- if (preCompressedAsset.selected) c.header('Content-Encoding', preCompressedAsset.selected.encoding);
111
- };
112
- export { applyPreCompressedAssetHeaders, resolvePreCompressedAsset };
@@ -1,153 +0,0 @@
1
- import "node:module";
2
- import { fileReader } from "@modern-js/runtime-utils/fileReader";
3
- import { fs } from "@modern-js/utils";
4
- import { getMimeType } from "hono/utils/mime";
5
- import path from "path";
6
- import { applyModuleFederationAssetHeaders, getModuleFederationAssetList, getModuleFederationRequestPath, isBackendModuleFederationManifestRequest, isModuleFederationManifestRequest, patchModuleFederationManifestPublicPath, patchModuleFederationRemoteEntryPublicPath } from "./staticModuleFederation.mjs";
7
- import { applyPreCompressedAssetHeaders, resolvePreCompressedAsset } from "./staticPrecompressed.mjs";
8
- const MODULE_FEDERATION_ASSET_REFRESH_INTERVAL_MS = 1000;
9
- const getStaticMimeType = (filename)=>getMimeType(filename) ?? ('.cjs' === path.extname(filename).toLowerCase() ? "text/javascript; charset=UTF-8" : void 0);
10
- const servePreCompressedPublicRouteAsset = async (c, pwd, route)=>{
11
- const { entryPath } = route;
12
- const originFilename = path.join(pwd, entryPath);
13
- const preCompressedAsset = await resolvePreCompressedAsset(c, originFilename);
14
- if (!preCompressedAsset.acceptable) {
15
- applyPreCompressedAssetHeaders(c, preCompressedAsset);
16
- return c.body(null, 406);
17
- }
18
- const filename = preCompressedAsset.selected?.filepath ?? originFilename;
19
- const data = await fileReader.readFile(filename, 'buffer');
20
- const mimeType = getStaticMimeType(originFilename);
21
- if (null === data) return null;
22
- const body = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
23
- if (mimeType) c.header('Content-Type', mimeType);
24
- Object.entries(route.responseHeaders || {}).forEach(([k, v])=>{
25
- c.header(k, v);
26
- });
27
- applyPreCompressedAssetHeaders(c, preCompressedAsset);
28
- c.header('Content-Length', String(data.byteLength));
29
- return c.body(body, 200);
30
- };
31
- const isPathInside = (target, root)=>{
32
- const relative = path.relative(path.resolve(root), path.resolve(target));
33
- return '' === relative || !relative.startsWith(`..${path.sep}`) && '..' !== relative && !path.isAbsolute(relative);
34
- };
35
- const resolvePublicDirectoryAsset = async (pwd, pathname)=>{
36
- let decodedPathname;
37
- try {
38
- decodedPathname = decodeURIComponent(pathname).replace(/\\/gu, '/');
39
- } catch {
40
- return null;
41
- }
42
- if (decodedPathname.includes('\0') || decodedPathname.split('/').includes('..')) return null;
43
- const publicDirectory = path.join(pwd, 'public');
44
- const filepath = path.resolve(publicDirectory, decodedPathname.replace(/^\/+/u, ''));
45
- if (!isPathInside(filepath, publicDirectory)) return null;
46
- try {
47
- const [realPublicDirectory, realFilepath, stat] = await Promise.all([
48
- fs.realpath(publicDirectory),
49
- fs.realpath(filepath),
50
- fs.stat(filepath)
51
- ]);
52
- if (!stat.isFile() || !isPathInside(realFilepath, realPublicDirectory)) return null;
53
- return realFilepath;
54
- } catch {
55
- return null;
56
- }
57
- };
58
- const servePublicDirectoryAsset = async (c, pwd)=>{
59
- const method = c.req.raw.method.toUpperCase();
60
- if ('GET' !== method && 'HEAD' !== method) return null;
61
- const originFilename = await resolvePublicDirectoryAsset(pwd, c.req.path);
62
- if (null === originFilename) return null;
63
- const preCompressedAsset = await resolvePreCompressedAsset(c, originFilename);
64
- if (!preCompressedAsset.acceptable) {
65
- applyPreCompressedAssetHeaders(c, preCompressedAsset);
66
- return c.body(null, 406);
67
- }
68
- const selectedFilename = preCompressedAsset.selected?.filepath ?? originFilename;
69
- const publicDirectory = await fs.realpath(path.join(pwd, 'public'));
70
- let realSelectedFilename;
71
- try {
72
- realSelectedFilename = await fs.realpath(selectedFilename);
73
- } catch {
74
- return null;
75
- }
76
- if (!isPathInside(realSelectedFilename, publicDirectory)) return null;
77
- const data = await fileReader.readFileFromSystem(realSelectedFilename, 'buffer');
78
- if (null === data) return null;
79
- const mimeType = getStaticMimeType(originFilename);
80
- if (mimeType) c.header('Content-Type', mimeType);
81
- applyPreCompressedAssetHeaders(c, preCompressedAsset);
82
- c.header('Content-Length', String(data.byteLength));
83
- if ('HEAD' === method) return c.body(null, 200);
84
- const body = new Uint8Array(data.buffer, data.byteOffset, data.byteLength);
85
- return c.body(body, 200);
86
- };
87
- const createModuleFederationStaticServing = ({ pwd, pathPrefix })=>{
88
- let moduleFederationAssets = null;
89
- let moduleFederationAssetsExpiresAt = 0;
90
- let moduleFederationAssetsRefresh = null;
91
- const getModuleFederationAssets = async ()=>{
92
- if (moduleFederationAssets && Date.now() < moduleFederationAssetsExpiresAt) return moduleFederationAssets;
93
- if (!moduleFederationAssetsRefresh) moduleFederationAssetsRefresh = getModuleFederationAssetList(pwd).then((assets)=>{
94
- moduleFederationAssets = assets;
95
- moduleFederationAssetsExpiresAt = Date.now() + MODULE_FEDERATION_ASSET_REFRESH_INTERVAL_MS;
96
- return assets;
97
- }).finally(()=>{
98
- moduleFederationAssetsRefresh = null;
99
- });
100
- return moduleFederationAssetsRefresh;
101
- };
102
- const resolveRequest = async (pathname)=>{
103
- const requestPath = getModuleFederationRequestPath(pathname, pathPrefix);
104
- if (requestPath.includes('..')) return null;
105
- const moduleFederationAssetMeta = await getModuleFederationAssets();
106
- return {
107
- requestPath,
108
- isModuleFederationAsset: moduleFederationAssetMeta.assets.has(requestPath),
109
- isModuleFederationRemoteEntry: moduleFederationAssetMeta.remoteEntries.has(requestPath)
110
- };
111
- };
112
- const serveFile = async (c, filepath, moduleFederationAsset = false, moduleFederationRemoteEntry = false, requestPath = '')=>{
113
- if (moduleFederationAsset) applyModuleFederationAssetHeaders(c);
114
- const mimeType = getStaticMimeType(filepath);
115
- if (mimeType) c.header('Content-Type', mimeType);
116
- const shouldPatchManifest = moduleFederationAsset && isModuleFederationManifestRequest(requestPath) && !isBackendModuleFederationManifestRequest(requestPath);
117
- const shouldPatchRemoteEntry = moduleFederationRemoteEntry;
118
- const canUsePreCompressed = !shouldPatchManifest && !shouldPatchRemoteEntry;
119
- const preCompressedAsset = canUsePreCompressed ? await resolvePreCompressedAsset(c, filepath) : {
120
- selected: null,
121
- hasVariant: false,
122
- acceptable: true
123
- };
124
- if (!preCompressedAsset.acceptable) {
125
- applyPreCompressedAssetHeaders(c, preCompressedAsset);
126
- return c.body(null, 406);
127
- }
128
- const targetFilepath = preCompressedAsset.selected?.filepath ?? filepath;
129
- const chunk = await fileReader.readFileFromSystem(targetFilepath, 'buffer');
130
- if (null === chunk) return null;
131
- const responseChunk = shouldPatchManifest ? patchModuleFederationManifestPublicPath(c, chunk, pathPrefix) : shouldPatchRemoteEntry ? patchModuleFederationRemoteEntryPublicPath(c, chunk, pathPrefix) : chunk;
132
- applyPreCompressedAssetHeaders(c, preCompressedAsset);
133
- c.header('Content-Length', String(responseChunk.byteLength));
134
- const body = new Uint8Array(responseChunk.buffer, responseChunk.byteOffset, responseChunk.byteLength);
135
- return c.body(body, 200);
136
- };
137
- const serveByPath = async (c, filepath, request, moduleFederationAsset = false, moduleFederationRemoteEntry = false)=>{
138
- if (!isPathInside(filepath, pwd)) return null;
139
- if (!await fs.pathExists(filepath)) return null;
140
- return serveFile(c, filepath, moduleFederationAsset, moduleFederationRemoteEntry, request.requestPath);
141
- };
142
- const serveStaticHit = (c, request)=>serveByPath(c, path.join(pwd, request.requestPath), request, request.isModuleFederationAsset, request.isModuleFederationRemoteEntry);
143
- const serveModuleFederationAsset = (c, request)=>{
144
- if (!request.isModuleFederationAsset) return null;
145
- return serveByPath(c, path.join(pwd, request.requestPath), request, true, request.isModuleFederationRemoteEntry);
146
- };
147
- return {
148
- resolveRequest,
149
- serveStaticHit,
150
- serveModuleFederationAsset
151
- };
152
- };
153
- export { createModuleFederationStaticServing, servePreCompressedPublicRouteAsset, servePublicDirectoryAsset };
@@ -1,19 +0,0 @@
1
- import "node:module";
2
- var __webpack_modules__ = {};
3
- var __webpack_module_cache__ = {};
4
- function __webpack_require__(moduleId) {
5
- var cachedModule = __webpack_module_cache__[moduleId];
6
- if (void 0 !== cachedModule) return cachedModule.exports;
7
- var module = __webpack_module_cache__[moduleId] = {
8
- exports: {}
9
- };
10
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
11
- return module.exports;
12
- }
13
- __webpack_require__.m = __webpack_modules__;
14
- (()=>{
15
- __webpack_require__.add = function(modules) {
16
- Object.assign(__webpack_require__.m, modules);
17
- };
18
- })();
19
- export { __webpack_require__ };
@@ -1 +0,0 @@
1
- import "node:module";
@@ -1 +0,0 @@
1
- import "node:module";
@@ -1,13 +0,0 @@
1
- import type { Middleware } from '../../../types/index.js';
2
- export declare const MODULE_FEDERATION_MANIFEST_FILE = "mf-manifest.json";
3
- export type ModuleFederationServeAssets = {
4
- assets: Set<string>;
5
- remoteEntries: Set<string>;
6
- };
7
- export declare const getModuleFederationRequestPath: (pathname: string, pathPrefix: string) => string;
8
- export declare const isModuleFederationManifestRequest: (requestPath: string) => boolean;
9
- export declare const isBackendModuleFederationManifestRequest: (requestPath: string) => requestPath is "backend-mf-manifest.json";
10
- export declare const applyModuleFederationAssetHeaders: (c: Parameters<Middleware>[0]) => void;
11
- export declare const patchModuleFederationManifestPublicPath: (c: Parameters<Middleware>[0], manifestBuffer: Buffer, pathPrefix: string) => Buffer<ArrayBufferLike>;
12
- export declare const patchModuleFederationRemoteEntryPublicPath: (c: Parameters<Middleware>[0], remoteEntryBuffer: Buffer, pathPrefix: string) => Buffer<ArrayBufferLike>;
13
- export declare const getModuleFederationAssetList: (pwd: string) => Promise<ModuleFederationServeAssets>;
@@ -1,13 +0,0 @@
1
- import type { Middleware } from '../../../types/index.js';
2
- type SupportedEncoding = 'br' | 'gzip';
3
- type ResolvePreCompressedAssetResult = {
4
- selected: {
5
- filepath: string;
6
- encoding: SupportedEncoding;
7
- } | null;
8
- hasVariant: boolean;
9
- acceptable: boolean;
10
- };
11
- export declare const resolvePreCompressedAsset: (c: Parameters<Middleware>[0], filepath: string) => Promise<ResolvePreCompressedAssetResult>;
12
- export declare const applyPreCompressedAssetHeaders: (c: Parameters<Middleware>[0], preCompressedAsset: ResolvePreCompressedAssetResult) => void;
13
- export {};
@@ -1,25 +0,0 @@
1
- import type { ServerRoute } from '@modern-js/types';
2
- import type { Middleware } from '../../../types/index.js';
3
- type MiddlewareContext = Parameters<Middleware>[0];
4
- type StaticServingRequest = {
5
- requestPath: string;
6
- isModuleFederationAsset: boolean;
7
- isModuleFederationRemoteEntry: boolean;
8
- };
9
- type StaticServingOptions = {
10
- pwd: string;
11
- pathPrefix: string;
12
- };
13
- export declare const servePreCompressedPublicRouteAsset: (c: MiddlewareContext, pwd: string, route: ServerRoute) => Promise<(Response & import("hono").TypedResponse<null, 406, "body">) | (Response & import("hono").TypedResponse<Uint8Array<ArrayBuffer>, 200, "body">) | null>;
14
- /**
15
- * Serves post-build convention assets generated under dist/public at their
16
- * root URL. This is intentionally independent of config/public and route.json:
17
- * the generator runs after the route manifest is built.
18
- */
19
- export declare const servePublicDirectoryAsset: (c: MiddlewareContext, pwd: string) => Promise<(Response & import("hono").TypedResponse<null, 200, "body">) | (Response & import("hono").TypedResponse<null, 406, "body">) | (Response & import("hono").TypedResponse<Uint8Array<ArrayBuffer>, 200, "body">) | null>;
20
- export declare const createModuleFederationStaticServing: ({ pwd, pathPrefix, }: StaticServingOptions) => {
21
- resolveRequest: (pathname: string) => Promise<StaticServingRequest | null>;
22
- serveStaticHit: (c: MiddlewareContext, request: StaticServingRequest) => Promise<(Response & import("hono").TypedResponse<null, 406, "body">) | (Response & import("hono").TypedResponse<Uint8Array<ArrayBuffer>, 200, "body">) | null>;
23
- serveModuleFederationAsset: (c: MiddlewareContext, request: StaticServingRequest) => Promise<(Response & import("hono").TypedResponse<null, 406, "body">) | (Response & import("hono").TypedResponse<Uint8Array<ArrayBuffer>, 200, "body">) | null> | null;
24
- };
25
- export {};