@bleedingdev/modern-js-server-runtime-extensions 3.8.3-ultramodern.6 → 3.9.0-ultramodern.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (199) hide show
  1. package/README.md +5 -5
  2. package/dist/cjs/bff-policy/crossProjectPolicy.js +299 -0
  3. package/dist/cjs/bff-policy/index.js +62 -0
  4. package/dist/cjs/bff-policy/node.js +69 -0
  5. package/dist/cjs/bff-policy/operationContracts.js +182 -0
  6. package/dist/cjs/bff-policy/resolveCrossProjectPolicy.js +65 -0
  7. package/dist/cjs/contract-gate-snapshot-store/http-store.js +1 -8
  8. package/dist/cjs/errorResponsePlugin.js +57 -0
  9. package/dist/cjs/localisedLoaderPlugin.js +62 -0
  10. package/dist/cjs/mfCache.js +6 -0
  11. package/dist/cjs/module-federation-css/plugin.js +6 -0
  12. package/dist/cjs/serverConfig.js +18 -0
  13. package/dist/cjs/serverPlugin.js +74 -0
  14. package/dist/cjs/static-serving/plugin.js +57 -0
  15. package/dist/cjs/static-serving/responders.js +158 -0
  16. package/dist/cjs/static-serving/staticModuleFederation.js +173 -0
  17. package/dist/cjs/static-serving/staticPrecompressed.js +152 -0
  18. package/dist/cjs/telemetry/exporters.js +4 -4
  19. package/dist/cjs/telemetry/healthSetup.js +14 -14
  20. package/dist/cjs/telemetry/lifecycle.js +20 -21
  21. package/dist/cjs/telemetry/plugin.js +10 -4
  22. package/dist/cjs/telemetry/runtimeEndpoints.js +3 -2
  23. package/dist/cjs/telemetryCore.js +5 -5
  24. package/dist/esm/bff-policy/crossProjectPolicy.mjs +249 -0
  25. package/dist/esm/bff-policy/index.mjs +1 -0
  26. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +1 -8
  27. package/dist/esm/errorResponsePlugin.mjs +19 -0
  28. package/dist/esm/localisedLoaderPlugin.mjs +24 -0
  29. package/dist/esm/mfCache.mjs +6 -0
  30. package/dist/esm/module-federation-css/plugin.mjs +6 -0
  31. package/dist/esm/serverConfig.mjs +0 -0
  32. package/dist/esm/serverPlugin.mjs +34 -0
  33. package/dist/esm/telemetry/exporters.mjs +2 -2
  34. package/dist/esm/telemetry/healthSetup.mjs +14 -14
  35. package/dist/esm/telemetry/lifecycle.mjs +21 -22
  36. package/dist/esm/telemetry/plugin.mjs +9 -3
  37. package/dist/esm/telemetry/runtimeEndpoints.mjs +3 -2
  38. package/dist/esm/telemetryCore.mjs +1 -1
  39. package/dist/esm-node/bff-policy/crossProjectPolicy.mjs +250 -0
  40. package/dist/esm-node/bff-policy/index.mjs +2 -0
  41. package/dist/esm-node/bff-policy/node.mjs +3 -0
  42. package/dist/esm-node/bff-policy/operationContracts.mjs +129 -0
  43. package/dist/esm-node/bff-policy/resolveCrossProjectPolicy.mjs +28 -0
  44. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +1 -8
  45. package/dist/esm-node/errorResponsePlugin.mjs +20 -0
  46. package/dist/esm-node/localisedLoaderPlugin.mjs +25 -0
  47. package/dist/esm-node/mfCache.mjs +6 -0
  48. package/dist/esm-node/module-federation-css/plugin.mjs +6 -0
  49. package/dist/esm-node/serverConfig.mjs +1 -0
  50. package/dist/esm-node/serverPlugin.mjs +35 -0
  51. package/dist/esm-node/static-serving/plugin.mjs +18 -0
  52. package/dist/esm-node/static-serving/responders.mjs +111 -0
  53. package/dist/esm-node/static-serving/staticModuleFederation.mjs +105 -0
  54. package/dist/esm-node/static-serving/staticPrecompressed.mjs +112 -0
  55. package/dist/esm-node/telemetry/exporters.mjs +2 -2
  56. package/dist/esm-node/telemetry/healthSetup.mjs +14 -14
  57. package/dist/esm-node/telemetry/lifecycle.mjs +21 -22
  58. package/dist/esm-node/telemetry/plugin.mjs +9 -3
  59. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +3 -2
  60. package/dist/esm-node/telemetryCore.mjs +1 -1
  61. package/dist/types/backend-federation-security/node.d.ts +1 -1
  62. package/dist/types/bff-policy/crossProjectPolicy.d.ts +101 -0
  63. package/dist/types/bff-policy/index.d.ts +1 -0
  64. package/dist/types/bff-policy/node.d.ts +2 -0
  65. package/dist/types/bff-policy/operationContracts.d.ts +85 -0
  66. package/dist/types/bff-policy/resolveCrossProjectPolicy.d.ts +39 -0
  67. package/dist/types/contract-gate-snapshot-normalization.d.ts +1 -1
  68. package/dist/types/contract-gate-snapshot-store/file-store.d.ts +1 -1
  69. package/dist/types/contract-gate-snapshot-store/http-store.d.ts +1 -1
  70. package/dist/types/contract-gate-snapshot-store/index.d.ts +5 -5
  71. package/dist/types/contract-gate-snapshot-store/resolve.d.ts +1 -1
  72. package/dist/types/contractGateSnapshotObserver.d.ts +2 -2
  73. package/dist/types/errorResponsePlugin.d.ts +3 -0
  74. package/dist/types/index.d.ts +8 -7
  75. package/dist/types/localisedLoaderPlugin.d.ts +2 -0
  76. package/dist/types/mfCache.d.ts +2 -3
  77. package/dist/types/module-federation-css/collector.d.ts +1 -1
  78. package/dist/types/module-federation-css/index.d.ts +8 -8
  79. package/dist/types/module-federation-css/plugin.d.ts +2 -3
  80. package/dist/types/runtime-fallback-signal/index.d.ts +4 -4
  81. package/dist/types/runtime-fallback-signal/model.d.ts +1 -1
  82. package/dist/types/runtime-fallback-signal/resolver.d.ts +1 -1
  83. package/dist/types/runtime-fallback-signal/store.d.ts +1 -1
  84. package/dist/types/runtimeFallbackSignal.d.ts +1 -1
  85. package/dist/types/serverConfig.d.ts +17 -0
  86. package/dist/types/serverPlugin.d.ts +5 -0
  87. package/dist/types/static-serving/plugin.d.ts +3 -0
  88. package/dist/types/static-serving/responders.d.ts +2 -0
  89. package/dist/types/static-serving/staticModuleFederation.d.ts +13 -0
  90. package/dist/types/static-serving/staticPrecompressed.d.ts +13 -0
  91. package/dist/types/telemetry/exporters.d.ts +2 -2
  92. package/dist/types/telemetry/healthEvaluation.d.ts +2 -2
  93. package/dist/types/telemetry/healthMonitor.d.ts +2 -2
  94. package/dist/types/telemetry/healthSetup.d.ts +6 -6
  95. package/dist/types/telemetry/lifecycle.d.ts +6 -6
  96. package/dist/types/telemetry/metrics.d.ts +1 -1
  97. package/dist/types/telemetry/plugin.d.ts +5 -4
  98. package/dist/types/telemetry/registry.d.ts +2 -2
  99. package/dist/types/telemetry/runtimeEndpoints.d.ts +2 -2
  100. package/dist/types/telemetry.d.ts +1 -1
  101. package/dist/types/telemetryCore.d.ts +6 -6
  102. package/dist/types-esm/backend-federation-security/index.d.mts +68 -0
  103. package/dist/types-esm/backend-federation-security/node.d.mts +3 -0
  104. package/dist/types-esm/bff-policy/crossProjectPolicy.d.mts +101 -0
  105. package/dist/types-esm/bff-policy/index.d.mts +1 -0
  106. package/dist/types-esm/bff-policy/node.d.mts +2 -0
  107. package/dist/types-esm/bff-policy/operationContracts.d.mts +85 -0
  108. package/dist/types-esm/bff-policy/resolveCrossProjectPolicy.d.mts +39 -0
  109. package/dist/types-esm/contract-gate-snapshot-normalization.d.mts +15 -0
  110. package/dist/types-esm/contract-gate-snapshot-store/file-store.d.mts +3 -0
  111. package/dist/types-esm/contract-gate-snapshot-store/http-store.d.mts +5 -0
  112. package/dist/types-esm/contract-gate-snapshot-store/index.d.mts +5 -0
  113. package/dist/types-esm/contract-gate-snapshot-store/resolve.d.mts +9 -0
  114. package/dist/types-esm/contract-gate-snapshot-store/types.d.mts +47 -0
  115. package/dist/types-esm/contractGateSnapshotObserver.d.mts +33 -0
  116. package/dist/types-esm/env.d.mts +40 -0
  117. package/dist/types-esm/errorResponsePlugin.d.mts +3 -0
  118. package/dist/types-esm/index.d.mts +8 -0
  119. package/dist/types-esm/localisedLoaderPlugin.d.mts +2 -0
  120. package/dist/types-esm/mfCache.d.mts +26 -0
  121. package/dist/types-esm/module-federation-css/collector.d.mts +25 -0
  122. package/dist/types-esm/module-federation-css/index.d.mts +8 -0
  123. package/dist/types-esm/module-federation-css/manifest.d.mts +28 -0
  124. package/dist/types-esm/module-federation-css/plugin.d.mts +22 -0
  125. package/dist/types-esm/module-federation-css/remote.d.mts +20 -0
  126. package/dist/types-esm/runtime-fallback-signal/index.d.mts +4 -0
  127. package/dist/types-esm/runtime-fallback-signal/model.d.mts +70 -0
  128. package/dist/types-esm/runtime-fallback-signal/resolver.d.mts +29 -0
  129. package/dist/types-esm/runtime-fallback-signal/store.d.mts +4 -0
  130. package/dist/types-esm/runtimeFallbackSignal.d.mts +1 -0
  131. package/dist/types-esm/runtimeLifecycle.d.mts +10 -0
  132. package/dist/types-esm/serverConfig.d.mts +17 -0
  133. package/dist/types-esm/serverPlugin.d.mts +5 -0
  134. package/dist/types-esm/static-serving/plugin.d.mts +3 -0
  135. package/dist/types-esm/static-serving/responders.d.mts +2 -0
  136. package/dist/types-esm/static-serving/staticModuleFederation.d.mts +13 -0
  137. package/dist/types-esm/static-serving/staticPrecompressed.d.mts +13 -0
  138. package/dist/types-esm/telemetry/envelope.d.mts +55 -0
  139. package/dist/types-esm/telemetry/exporters.d.mts +12 -0
  140. package/dist/types-esm/telemetry/healthEvaluation.d.mts +20 -0
  141. package/dist/types-esm/telemetry/healthMonitor.d.mts +88 -0
  142. package/dist/types-esm/telemetry/healthSetup.d.mts +17 -0
  143. package/dist/types-esm/telemetry/lifecycle.d.mts +18 -0
  144. package/dist/types-esm/telemetry/metrics.d.mts +3 -0
  145. package/dist/types-esm/telemetry/plugin.d.mts +13 -0
  146. package/dist/types-esm/telemetry/registry.d.mts +69 -0
  147. package/dist/types-esm/telemetry/registryTypes.d.mts +50 -0
  148. package/dist/types-esm/telemetry/runtimeEndpoints.d.mts +35 -0
  149. package/dist/types-esm/telemetry.d.mts +1 -0
  150. package/dist/types-esm/telemetryCore.d.mts +6 -0
  151. package/package.json +160 -28
  152. package/rslib.config.mts +36 -2
  153. package/rstest.config.mts +11 -0
  154. package/src/bff-policy/crossProjectPolicy.ts +754 -0
  155. package/src/bff-policy/index.ts +1 -0
  156. package/src/bff-policy/node.ts +2 -0
  157. package/src/bff-policy/operationContracts.ts +298 -0
  158. package/src/bff-policy/resolveCrossProjectPolicy.ts +88 -0
  159. package/src/contract-gate-snapshot-store/http-store.ts +1 -11
  160. package/src/errorResponsePlugin.ts +21 -0
  161. package/src/index.ts +4 -0
  162. package/src/localisedLoaderPlugin.ts +34 -0
  163. package/src/mfCache.ts +4 -3
  164. package/src/module-federation-css/plugin.ts +4 -3
  165. package/src/serverConfig.ts +32 -0
  166. package/src/serverPlugin.ts +38 -0
  167. package/src/static-serving/plugin.ts +16 -0
  168. package/src/static-serving/responders.ts +208 -0
  169. package/src/static-serving/staticModuleFederation.ts +255 -0
  170. package/src/static-serving/staticPrecompressed.ts +193 -0
  171. package/src/telemetry/exporters.ts +1 -1
  172. package/src/telemetry/healthSetup.ts +17 -20
  173. package/src/telemetry/lifecycle.ts +27 -39
  174. package/src/telemetry/plugin.ts +6 -4
  175. package/src/telemetry/runtimeEndpoints.ts +3 -2
  176. package/src/telemetryCore.ts +1 -1
  177. package/tests/bff-policy/crossProjectPolicy.matrix.test.ts +450 -0
  178. package/tests/bff-policy/crossProjectPolicy.test.ts +197 -0
  179. package/tests/bff-policy/operationContracts.test.ts +221 -0
  180. package/tests/bff-policy/optionalZodPeer.test.ts +30 -0
  181. package/tests/bff-policy/resolveCrossProjectPolicy.test.ts +76 -0
  182. package/tests/contractGateSnapshotObserver.test.ts +0 -58
  183. package/tests/contractGateSnapshotStore.test.ts +0 -51
  184. package/tests/env.test.ts +45 -64
  185. package/tests/localisedLoader.test.ts +120 -0
  186. package/tests/mfCache.test.ts +1 -88
  187. package/tests/moduleFederationCss.test.ts +4 -48
  188. package/tests/nativeErrorResponse.test.ts +118 -0
  189. package/tests/nativeServerAssembly.test.ts +385 -0
  190. package/tests/runtimeLifecycle.test.ts +69 -17
  191. package/tests/static-serving/ordering.test.ts +214 -0
  192. package/tests/static-serving/static.test.ts +411 -0
  193. package/tests/telemetry.test.ts +35 -198
  194. package/tests/telemetryHealthMonitor.test.ts +0 -4
  195. package/tests/telemetryHealthObservation.test.ts +302 -0
  196. package/tests/telemetryLifecycle.test.ts +7 -303
  197. package/tests/telemetryRegistryQueueMatrix.test.ts +14 -111
  198. package/tests/registration.test.ts +0 -112
  199. package/tests/telemetryAutopilot.test.ts +0 -1134
@@ -0,0 +1,111 @@
1
+ import "node:module";
2
+ import node_path from "node:path";
3
+ import { serveStaticAsset } from "@modern-js/server-core/node";
4
+ import { applyModuleFederationAssetHeaders, getModuleFederationAssetList, getModuleFederationRequestPath, isBackendModuleFederationManifestRequest, isModuleFederationManifestRequest, patchModuleFederationManifestPublicPath, patchModuleFederationRemoteEntryPublicPath } from "./staticModuleFederation.mjs";
5
+ import { applyPreCompressedAssetHeaders, resolvePreCompressedAsset } from "./staticPrecompressed.mjs";
6
+ async function respondPrecompressedAsset(context, asset, serve) {
7
+ const selected = await resolvePreCompressedAsset(context, asset.filename);
8
+ const response = selected.acceptable ? await serve({
9
+ filename: selected.selected?.filepath,
10
+ contentLength: true
11
+ }) : new Response(null, {
12
+ status: 406
13
+ });
14
+ if (null === response) return null;
15
+ context.res = response;
16
+ applyPreCompressedAssetHeaders(context, selected);
17
+ if ('.cjs' === node_path.extname(asset.filename).toLowerCase()) context.res.headers.set('Content-Type', "text/javascript; charset=UTF-8");
18
+ return context.res;
19
+ }
20
+ function createStaticExtensionResponders() {
21
+ const caches = new Map();
22
+ const getAssets = (root)=>{
23
+ let cache = caches.get(root);
24
+ if (!cache) {
25
+ cache = {
26
+ assets: null,
27
+ expires: 0,
28
+ pending: null
29
+ };
30
+ caches.set(root, cache);
31
+ }
32
+ if (cache.assets && Date.now() < cache.expires) return Promise.resolve(cache.assets);
33
+ if (cache.pending) return cache.pending;
34
+ const current = cache;
35
+ const pending = getModuleFederationAssetList(root).then((assets)=>{
36
+ current.assets = assets;
37
+ current.expires = Date.now() + 1000;
38
+ return assets;
39
+ }).finally(()=>{
40
+ current.pending = null;
41
+ });
42
+ current.pending = pending;
43
+ return pending;
44
+ };
45
+ async function serveFederated(context, asset, serve, requestPath, pathPrefix, remoteEntry) {
46
+ applyModuleFederationAssetHeaders(context);
47
+ const patchManifest = isModuleFederationManifestRequest(requestPath) && !isBackendModuleFederationManifestRequest(requestPath);
48
+ if (!patchManifest && !remoteEntry) return respondPrecompressedAsset(context, asset, serve);
49
+ const response = await serve({
50
+ contentLength: true
51
+ });
52
+ if (!response) return null;
53
+ const bytes = Buffer.from(await response.arrayBuffer());
54
+ const patched = patchManifest ? patchModuleFederationManifestPublicPath(context, bytes, pathPrefix) : patchModuleFederationRemoteEntryPublicPath(context, bytes, pathPrefix);
55
+ response.headers.set('Content-Length', String(patched.byteLength));
56
+ if ('.cjs' === node_path.extname(asset.filename).toLowerCase()) response.headers.set('Content-Type', "text/javascript; charset=UTF-8");
57
+ return new Response(Uint8Array.from(patched), {
58
+ status: response.status,
59
+ headers: response.headers
60
+ });
61
+ }
62
+ async function serveGenerated(context, root) {
63
+ if (![
64
+ 'GET',
65
+ 'HEAD'
66
+ ].includes(context.req.raw.method.toUpperCase())) return null;
67
+ let pathname;
68
+ try {
69
+ pathname = decodeURIComponent(context.req.path).replace(/\\/gu, '/');
70
+ } catch {
71
+ return null;
72
+ }
73
+ if (pathname.includes('\0') || pathname.split('/').includes('..')) return null;
74
+ const publicRoot = node_path.join(root, 'public');
75
+ const response = await serveStaticAsset(context, {
76
+ filename: node_path.resolve(publicRoot, pathname.replace(/^\/+/, '')),
77
+ kind: 'static',
78
+ root: publicRoot,
79
+ realpath: true
80
+ }, (asset, serve)=>respondPrecompressedAsset(context, asset, serve));
81
+ if (response && 'HEAD' === context.req.raw.method.toUpperCase()) return new Response(null, {
82
+ status: response.status,
83
+ headers: response.headers
84
+ });
85
+ return response;
86
+ }
87
+ return {
88
+ async respondAsset (context, asset, serve, { root, pathPrefix }) {
89
+ const requestPath = getModuleFederationRequestPath(context.req.path, pathPrefix);
90
+ if (requestPath.includes('..')) return null;
91
+ const assets = await getAssets(root);
92
+ if ('static' === asset.kind && assets.assets.has(requestPath)) return serveFederated(context, asset, serve, requestPath, pathPrefix, assets.remoteEntries.has(requestPath));
93
+ return respondPrecompressedAsset(context, asset, serve);
94
+ },
95
+ async respondPublicFallback (context, respondPublic, { root, pathPrefix }) {
96
+ const requestPath = getModuleFederationRequestPath(context.req.path, pathPrefix);
97
+ if (requestPath.includes('..')) return null;
98
+ const assets = await getAssets(root);
99
+ if (assets.assets.has(requestPath)) {
100
+ const response = await serveStaticAsset(context, {
101
+ filename: node_path.join(root, requestPath),
102
+ kind: 'static',
103
+ root
104
+ }, (asset, serve)=>serveFederated(context, asset, serve, requestPath, pathPrefix, assets.remoteEntries.has(requestPath)));
105
+ if (null !== response) return response;
106
+ }
107
+ return await respondPublic() ?? serveGenerated(context, root);
108
+ }
109
+ };
110
+ }
111
+ export { createStaticExtensionResponders };
@@ -0,0 +1,105 @@
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 };
@@ -0,0 +1,112 @@
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') ?? wildcardQuality ?? 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 };
@@ -98,8 +98,8 @@ function createVictoriaMetricsTelemetryExporter(options = {}) {
98
98
  }
99
99
  };
100
100
  }
101
- function maybeWarnLegacyOtlpEndpoint(endpoint) {
101
+ function warnOnMetricsOtlpEndpoint(endpoint) {
102
102
  if (!endpoint || !endpoint.includes('/v1/metrics')) return;
103
103
  console.warn(`[telemetry] OTLP endpoint "${endpoint}" looks like a metrics path. UltraModern telemetry exporter expects log-style envelopes (default: ${DEFAULT_OTLP_ENDPOINT}).`);
104
104
  }
105
- export { createOtlpTelemetryExporter, createVictoriaMetricsTelemetryExporter, maybeWarnLegacyOtlpEndpoint };
105
+ export { createOtlpTelemetryExporter, createVictoriaMetricsTelemetryExporter, warnOnMetricsOtlpEndpoint };
@@ -16,17 +16,17 @@ function emitHealthTransitionMetric(registry, evaluation) {
16
16
  });
17
17
  } catch (_error) {}
18
18
  }
19
- const setupTelemetryHealthMonitoring = ({ registry, appDirectory, legacyHealthConfig })=>{
20
- if (!legacyHealthConfig?.enabled) return {};
21
- const contractGates = legacyHealthConfig.contractGates;
19
+ const setupTelemetryHealthMonitoring = ({ registry, appDirectory, healthConfig })=>{
20
+ if (!healthConfig?.enabled) return {};
21
+ const contractGates = healthConfig.contractGates;
22
22
  const healthMonitor = new TelemetryHealthMonitor({
23
23
  registry,
24
- evaluationIntervalMs: legacyHealthConfig.evaluationIntervalMs,
25
- minConsecutiveHealthyEvaluations: legacyHealthConfig.minConsecutiveHealthyEvaluations,
26
- minConsecutiveFailedEvaluations: legacyHealthConfig.rollbackConsecutiveFailures,
27
- maxQueueUtilization: legacyHealthConfig.maxQueueUtilization,
28
- maxTotalDropped: legacyHealthConfig.maxTotalDropped,
29
- maxUnhealthyExporters: legacyHealthConfig.maxUnhealthyExporters,
24
+ evaluationIntervalMs: healthConfig.evaluationIntervalMs,
25
+ minConsecutiveHealthyEvaluations: healthConfig.minConsecutiveHealthyEvaluations,
26
+ minConsecutiveFailedEvaluations: healthConfig.minConsecutiveFailedEvaluations,
27
+ maxQueueUtilization: healthConfig.maxQueueUtilization,
28
+ maxTotalDropped: healthConfig.maxTotalDropped,
29
+ maxUnhealthyExporters: healthConfig.maxUnhealthyExporters,
30
30
  requiredContractGates: Object.keys(contractGates || {}),
31
31
  onTransition: (evaluation)=>{
32
32
  emitHealthTransitionMetric(registry, evaluation);
@@ -35,15 +35,15 @@ const setupTelemetryHealthMonitoring = ({ registry, appDirectory, legacyHealthCo
35
35
  if (contractGates) healthMonitor.setContractGates(contractGates);
36
36
  let gateSnapshotStorePromise;
37
37
  let runtimeFallbackSignalConfig;
38
- const snapshotObservationEnabled = legacyHealthConfig.autopilot?.enabled ?? true;
38
+ const snapshotObservationEnabled = healthConfig.snapshotObservation?.enabled ?? true;
39
39
  if (snapshotObservationEnabled) {
40
- const gateSnapshotPath = resolveContractGateSnapshotPath(appDirectory, legacyHealthConfig.autopilot?.gateSnapshotPath);
40
+ const gateSnapshotPath = resolveContractGateSnapshotPath(appDirectory, healthConfig.snapshotObservation?.gateSnapshotPath);
41
41
  gateSnapshotStorePromise = resolveContractGateSnapshotStore({
42
42
  appDirectory,
43
43
  gateSnapshotPath: gateSnapshotPath || DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH,
44
- stateStore: legacyHealthConfig.autopilot?.stateStore
44
+ stateStore: healthConfig.snapshotObservation?.stateStore
45
45
  });
46
- const runtimeSignalConfig = legacyHealthConfig.autopilot?.runtimeFallbackSignal;
46
+ const runtimeSignalConfig = healthConfig.snapshotObservation?.runtimeFallbackSignal;
47
47
  if (runtimeSignalConfig?.enabled === true) runtimeFallbackSignalConfig = {
48
48
  endpoint: resolveRuntimeFallbackSignalEndpoint(runtimeSignalConfig.endpoint),
49
49
  gateName: runtimeSignalConfig.gateName?.trim() || DEFAULT_RUNTIME_FALLBACK_GATE_NAME,
@@ -55,7 +55,7 @@ const setupTelemetryHealthMonitoring = ({ registry, appDirectory, legacyHealthCo
55
55
  runtimeState: createRuntimeFallbackSignalRuntimeState()
56
56
  };
57
57
  }
58
- const runtimeStatusAuthConfig = runtimeFallbackSignalConfig?.auth ?? normalizeRuntimeFallbackSignalAuthConfig(legacyHealthConfig.autopilot?.runtimeFallbackSignal?.auth);
58
+ const runtimeStatusAuthConfig = runtimeFallbackSignalConfig?.auth ?? normalizeRuntimeFallbackSignalAuthConfig(healthConfig.snapshotObservation?.runtimeFallbackSignal?.auth);
59
59
  return {
60
60
  healthMonitor,
61
61
  gateSnapshotStorePromise,
@@ -1,7 +1,8 @@
1
1
  import "node:module";
2
+ import { logger } from "@modern-js/utils";
2
3
  import { resolveContractGateSnapshotPath } from "../contract-gate-snapshot-store/index.mjs";
3
4
  import { ContractGateSnapshotObserver } from "../contractGateSnapshotObserver.mjs";
4
- import { createOtlpTelemetryExporter, createVictoriaMetricsTelemetryExporter, maybeWarnLegacyOtlpEndpoint } from "../telemetryCore.mjs";
5
+ import { createOtlpTelemetryExporter, createVictoriaMetricsTelemetryExporter, warnOnMetricsOtlpEndpoint } from "../telemetryCore.mjs";
5
6
  const activeTelemetryLaneClosers = new Set();
6
7
  let telemetryBeforeExitHookInstalled = false;
7
8
  const ensureTelemetryBeforeExitHook = ()=>{
@@ -10,32 +11,30 @@ const ensureTelemetryBeforeExitHook = ()=>{
10
11
  process.on('beforeExit', ()=>{
11
12
  for (const close of [
12
13
  ...activeTelemetryLaneClosers
13
- ])close();
14
+ ])close().catch((error)=>logger.error(error));
14
15
  });
15
16
  };
16
- const registerTelemetryLifecycle = ({ api, registry, telemetryConfig, legacyHealthConfig, healthMonitor, gateSnapshotStorePromise, appDirectory })=>{
17
+ const registerTelemetryLifecycle = ({ api, registry, telemetryConfig, healthConfig, healthMonitor, gateSnapshotStorePromise, appDirectory })=>{
17
18
  let contractGateSnapshotObserver;
18
- let telemetryLaneClosed = false;
19
- const closeTelemetryLane = async ()=>{
20
- if (telemetryLaneClosed) return;
21
- telemetryLaneClosed = true;
22
- activeTelemetryLaneClosers.delete(closeTelemetryLane);
23
- contractGateSnapshotObserver?.stop();
24
- healthMonitor?.stop();
25
- await registry.shutdown();
19
+ let closePromise;
20
+ const closeTelemetryLane = ()=>{
21
+ closePromise ??= Promise.resolve().then(async ()=>{
22
+ activeTelemetryLaneClosers.delete(closeTelemetryLane);
23
+ contractGateSnapshotObserver?.stop();
24
+ healthMonitor?.stop();
25
+ await registry.shutdown();
26
+ });
27
+ return closePromise;
26
28
  };
29
+ api.onDispose(closeTelemetryLane);
30
+ activeTelemetryLaneClosers.add(closeTelemetryLane);
31
+ ensureTelemetryBeforeExitHook();
27
32
  let prepared = false;
28
33
  api.onPrepare(async ()=>{
29
- if (prepared) return;
34
+ if (prepared || closePromise) return;
30
35
  prepared = true;
31
- const { nodeServer } = api.getServerContext();
32
- if (nodeServer && 'function' == typeof nodeServer.once) nodeServer.once('close', ()=>{
33
- closeTelemetryLane();
34
- });
35
- activeTelemetryLaneClosers.add(closeTelemetryLane);
36
- ensureTelemetryBeforeExitHook();
37
36
  if (telemetryConfig.exporters?.otlp?.enabled) {
38
- maybeWarnLegacyOtlpEndpoint(telemetryConfig.exporters.otlp.endpoint);
37
+ warnOnMetricsOtlpEndpoint(telemetryConfig.exporters.otlp.endpoint);
39
38
  await registry.register(createOtlpTelemetryExporter(telemetryConfig.exporters.otlp));
40
39
  }
41
40
  if (telemetryConfig.exporters?.victoriaMetrics?.enabled) await registry.register(createVictoriaMetricsTelemetryExporter(telemetryConfig.exporters.victoriaMetrics));
@@ -48,10 +47,10 @@ const registerTelemetryLifecycle = ({ api, registry, telemetryConfig, legacyHeal
48
47
  const gateSnapshotStore = await gateSnapshotStorePromise;
49
48
  contractGateSnapshotObserver = new ContractGateSnapshotObserver({
50
49
  monitor: healthMonitor,
51
- gateSnapshotPath: resolveContractGateSnapshotPath(appDirectory, legacyHealthConfig?.autopilot?.gateSnapshotPath),
50
+ gateSnapshotPath: resolveContractGateSnapshotPath(appDirectory, healthConfig?.snapshotObservation?.gateSnapshotPath),
52
51
  gateSnapshotStore,
53
- pollIntervalMs: legacyHealthConfig?.autopilot?.pollIntervalMs,
54
- gateStaleAfterMs: legacyHealthConfig?.autopilot?.gateStaleAfterMs
52
+ pollIntervalMs: healthConfig?.snapshotObservation?.pollIntervalMs,
53
+ gateStaleAfterMs: healthConfig?.snapshotObservation?.gateStaleAfterMs
55
54
  });
56
55
  }
57
56
  if (contractGateSnapshotObserver) await contractGateSnapshotObserver.start();
@@ -1,5 +1,5 @@
1
1
  import "node:module";
2
- import { parseTraceparent } from "@modern-js/create-request/server";
2
+ import { parseTraceparent } from "@modern-js/runtime-extensions/request-context";
3
3
  import { logger } from "@modern-js/utils";
4
4
  import { parseServerRuntimeExtensionsEnv } from "../env.mjs";
5
5
  import { TelemetryHealthMonitor, TelemetryRegistry, TelemetryStartupHealthError, createOtlpTelemetryExporter, createTelemetryAwareMetrics, createVictoriaMetricsTelemetryExporter, toTelemetryEnvelope } from "../telemetryCore.mjs";
@@ -17,6 +17,12 @@ const resolveTelemetrySloOptions = (sloConfig, warnSink = (message)=>logger.warn
17
17
  });
18
18
  const injectTelemetryPlugin = ()=>({
19
19
  name: '@modern-js/inject-telemetry',
20
+ pre: [
21
+ '@modern-js/plugin-inject-route'
22
+ ],
23
+ post: [
24
+ '@modern-js/plugin-inject-config-middleware'
25
+ ],
20
26
  setup (api) {
21
27
  const serverConfig = api.getServerConfig();
22
28
  const telemetryConfig = serverConfig?.server?.telemetry;
@@ -40,7 +46,7 @@ const injectTelemetryPlugin = ()=>({
40
46
  const { healthMonitor, gateSnapshotStorePromise, runtimeFallbackSignalConfig, runtimeStatusAuthConfig } = setupTelemetryHealthMonitoring({
41
47
  registry,
42
48
  appDirectory,
43
- legacyHealthConfig: telemetryConfig.canary
49
+ healthConfig: telemetryConfig.health
44
50
  });
45
51
  if (runtimeFallbackSignalConfig) middlewares.push(createRuntimeFallbackSignalMiddleware(runtimeFallbackSignalConfig));
46
52
  middlewares.push(createRuntimeStatusMiddleware({
@@ -77,7 +83,7 @@ const injectTelemetryPlugin = ()=>({
77
83
  api,
78
84
  registry,
79
85
  telemetryConfig,
80
- legacyHealthConfig: telemetryConfig.canary,
86
+ healthConfig: telemetryConfig.health,
81
87
  healthMonitor,
82
88
  gateSnapshotStorePromise,
83
89
  appDirectory
@@ -47,6 +47,7 @@ const createRuntimeStatusMiddleware = ({ registry, healthMonitor, runtimeFallbac
47
47
  timestamp: Date.now()
48
48
  });
49
49
  enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeStatusAuthConfig.headerName), runtimeStatusAuthConfig);
50
+ const healthSnapshot = healthMonitor?.getStatusSnapshot();
50
51
  return c.json({
51
52
  ok: true,
52
53
  timestamp: Date.now(),
@@ -54,9 +55,9 @@ const createRuntimeStatusMiddleware = ({ registry, healthMonitor, runtimeFallbac
54
55
  queueStats: registry.getQueueStats(),
55
56
  exporterHealth: registry.getExporterHealth()
56
57
  },
57
- health: healthMonitor ? {
58
+ health: healthSnapshot ? {
58
59
  enabled: true,
59
- ...healthMonitor.getStatusSnapshot()
60
+ ...healthSnapshot
60
61
  } : {
61
62
  enabled: false
62
63
  },
@@ -1,6 +1,6 @@
1
1
  import "node:module";
2
2
  export { toTelemetryEnvelope } from "./telemetry/envelope.mjs";
3
- export { createOtlpTelemetryExporter, createVictoriaMetricsTelemetryExporter, maybeWarnLegacyOtlpEndpoint } from "./telemetry/exporters.mjs";
3
+ export { createOtlpTelemetryExporter, createVictoriaMetricsTelemetryExporter, warnOnMetricsOtlpEndpoint } from "./telemetry/exporters.mjs";
4
4
  export { TelemetryHealthMonitor } from "./telemetry/healthMonitor.mjs";
5
5
  export { createTelemetryAwareMetrics } from "./telemetry/metrics.mjs";
6
6
  export { TelemetryRegistry } from "./telemetry/registry.mjs";
@@ -1,3 +1,3 @@
1
- import { type BackendFederationCommonJsEvaluator, type BackendFederationEntryIntegrity } from './index';
1
+ import { type BackendFederationCommonJsEvaluator, type BackendFederationEntryIntegrity } from './index.js';
2
2
  export declare function createBackendFederationEntryIntegrity(value: string | Uint8Array): BackendFederationEntryIntegrity;
3
3
  export declare const evaluateNodeBackendFederationCommonJs: BackendFederationCommonJsEvaluator;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * Cross-project BFF policy evaluator.
3
+ *
4
+ * THREAT MODEL — read before relying on this module:
5
+ *
6
+ * Every header this evaluator inspects (envelope, operation id, operation
7
+ * context details) is constructed by the CLIENT from public, open-source
8
+ * formats. Without an out-of-band identity binding the checks below are a
9
+ * version-skew and misconfiguration gate, not an authentication or
10
+ * authorization boundary: any caller can echo an allowed `requestId` and a
11
+ * matching operation context.
12
+ *
13
+ * To use `allowedNamespaces`, supply
14
+ * {@link CrossProjectPolicyConfig.verifyProducerIdentity}: a server-side
15
+ * hook that derives the producer namespace from a VERIFIED channel (mTLS
16
+ * peer identity, gateway-authenticated JWT claims, service-mesh headers
17
+ * stripped at the edge, ...). Requests fail closed when a namespace allowlist
18
+ * is configured without this hook. When the hook is
19
+ * present, the client-asserted namespace must match the verified namespace
20
+ * and the allowlist is checked against the verified value.
21
+ *
22
+ * Client-side counterparts in `@modern-js/create-request` (identity binding,
23
+ * operation contract validation) are developer-experience aids that fail
24
+ * fast in well-behaved clients; they protect nothing against a malicious
25
+ * caller.
26
+ */
27
+ export declare const BFF_ENVELOPE_HEADER = "x-modernjs-bff-envelope";
28
+ export declare const BFF_OPERATION_CONTEXT_HEADER = "x-operation-id";
29
+ export declare const BFF_OPERATION_CONTEXT_DETAIL_HEADER = "x-modernjs-bff-operation-context";
30
+ export type CrossProjectOperationContract = {
31
+ schemaHash?: string;
32
+ operationVersion?: number;
33
+ operationId?: string;
34
+ };
35
+ /**
36
+ * Request facts observed by the server adapter rather than asserted by the
37
+ * client. `routePath` is the matched route template when the router exposes
38
+ * one (for example `/api/customers/:id`), not the client-provided detail.
39
+ */
40
+ export type CrossProjectRequestObservation = {
41
+ method: string;
42
+ routePath: string;
43
+ };
44
+ export type CrossProjectRequestTarget = {
45
+ method: string;
46
+ pathname: string;
47
+ };
48
+ export type CrossProjectPolicyViolationReason = 'missing_envelope' | 'invalid_envelope' | 'missing_request_id' | 'namespace_not_allowed' | 'missing_operation_context' | 'operation_context_mismatch' | 'missing_operation_context_details' | 'invalid_operation_context_details' | 'operation_context_details_request_id_mismatch' | 'missing_operation_schema_hash' | 'missing_operation_version' | 'unknown_operation_contract' | 'operation_schema_hash_mismatch' | 'operation_version_mismatch' | 'producer_identity_mismatch';
49
+ export type CrossProjectPolicyViolation = {
50
+ code: 'BFF_CROSS_PROJECT_POLICY_DENIED';
51
+ reason: CrossProjectPolicyViolationReason;
52
+ message: string;
53
+ status: number;
54
+ };
55
+ export interface CrossProjectPolicyConfig {
56
+ enabled?: boolean;
57
+ requireEnvelope?: boolean;
58
+ requireOperationContext?: boolean;
59
+ requireOperationContextDetails?: boolean;
60
+ requireOperationSchemaHash?: boolean;
61
+ requireOperationVersion?: boolean;
62
+ allowedNamespaces?: string[];
63
+ envelopeHeader?: string;
64
+ operationContextHeader?: string;
65
+ operationContextDetailHeader?: string;
66
+ expectedOperationContracts?: Record<string, CrossProjectOperationContract>;
67
+ allowUnknownOperations?: boolean;
68
+ denyStatus?: number;
69
+ /**
70
+ * Server-side hook binding producer namespace to VERIFIED identity
71
+ * channel (mTLS peer, gateway-authenticated JWT, mesh identity headers).
72
+ *
73
+ * When provided, the namespace asserted by the client envelope must match
74
+ * the namespace returned by this hook, and `allowedNamespaces` is checked
75
+ * against the verified value instead of the client-asserted one. Returning
76
+ * `undefined` (identity could not be verified) denies the request.
77
+ *
78
+ * By default, `allowedNamespaces` requires this hook and fails closed
79
+ * without it.
80
+ */
81
+ verifyProducerIdentity?: (headers: Record<string, unknown>) => string | undefined;
82
+ }
83
+ /** Serializable, fully-defaulted policy accepted by edge dispatchers. */
84
+ export type NormalizedCrossProjectPolicy = CrossProjectPolicyConfig & {
85
+ enabled: boolean;
86
+ requireEnvelope: boolean;
87
+ requireOperationContext: boolean;
88
+ requireOperationContextDetails: boolean;
89
+ requireOperationSchemaHash: boolean;
90
+ requireOperationVersion: boolean;
91
+ allowUnknownOperations: boolean;
92
+ expectedOperationContracts: Record<string, CrossProjectOperationContract>;
93
+ };
94
+ /**
95
+ * Resolves a concrete adapter request to the server-owned route template in
96
+ * the operation contract map. Effect receives requests after its BFF mount
97
+ * prefix has been stripped, so leading literal route segments may be mount
98
+ * prefixes. Ambiguous matches fail closed by retaining the concrete path.
99
+ */
100
+ export declare const resolveCrossProjectRequestObservation: (request: CrossProjectRequestTarget, policy: Pick<CrossProjectPolicyConfig, 'expectedOperationContracts'>) => CrossProjectRequestObservation | undefined;
101
+ export declare const evaluateCrossProjectPolicy: (headers: Record<string, unknown>, policy?: CrossProjectPolicyConfig, observedRequest?: CrossProjectRequestObservation) => CrossProjectPolicyViolation | null;
@@ -0,0 +1 @@
1
+ export * from './crossProjectPolicy.js';
@@ -0,0 +1,2 @@
1
+ export * from './operationContracts.js';
2
+ export * from './resolveCrossProjectPolicy.js';