@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.3 → 3.5.0-ultramodern.31

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 (207) hide show
  1. package/dist/cjs/contract-gate-snapshot-store/file-store.js +102 -0
  2. package/dist/cjs/contract-gate-snapshot-store/http-store.js +142 -0
  3. package/dist/cjs/contract-gate-snapshot-store/index.js +58 -0
  4. package/dist/cjs/contract-gate-snapshot-store/resolve.js +122 -0
  5. package/dist/cjs/contract-gate-snapshot-store/types.js +44 -0
  6. package/dist/cjs/contractGateAutopilot.js +27 -6
  7. package/dist/cjs/index.js +13 -13
  8. package/dist/cjs/module-federation-css/collector.js +79 -0
  9. package/dist/cjs/module-federation-css/index.js +55 -0
  10. package/dist/cjs/module-federation-css/manifest.js +144 -0
  11. package/dist/cjs/module-federation-css/plugin.js +71 -0
  12. package/dist/cjs/module-federation-css/remote.js +133 -0
  13. package/dist/cjs/runtime-fallback-signal/auth.js +87 -0
  14. package/dist/cjs/runtime-fallback-signal/constants.js +72 -0
  15. package/dist/cjs/runtime-fallback-signal/contract-gate.js +64 -0
  16. package/dist/cjs/runtime-fallback-signal/endpoint.js +50 -0
  17. package/dist/cjs/runtime-fallback-signal/errors.js +44 -0
  18. package/dist/cjs/runtime-fallback-signal/index.js +99 -0
  19. package/dist/cjs/runtime-fallback-signal/payload.js +72 -0
  20. package/dist/cjs/runtime-fallback-signal/source.js +66 -0
  21. package/dist/cjs/runtime-fallback-signal/state.js +57 -0
  22. package/dist/cjs/runtime-fallback-signal/status.js +47 -0
  23. package/dist/cjs/runtime-fallback-signal/trust-policy.js +108 -0
  24. package/dist/cjs/runtime-fallback-signal/types.js +18 -0
  25. package/dist/cjs/runtimeFallbackSignal.js +32 -281
  26. package/dist/cjs/telemetry/canary.js +180 -0
  27. package/dist/cjs/telemetry/canaryEvaluation.js +79 -0
  28. package/dist/cjs/telemetry/canarySetup.js +107 -0
  29. package/dist/cjs/telemetry/envelope.js +148 -0
  30. package/dist/cjs/telemetry/exporters.js +148 -0
  31. package/dist/cjs/telemetry/lifecycle.js +98 -0
  32. package/dist/cjs/telemetry/metrics.js +115 -0
  33. package/dist/cjs/telemetry/plugin.js +185 -0
  34. package/dist/cjs/telemetry/registry.js +348 -0
  35. package/dist/cjs/telemetry/registryTypes.js +46 -0
  36. package/dist/cjs/telemetry/runtimeEndpoints.js +135 -0
  37. package/dist/cjs/telemetry.js +32 -343
  38. package/dist/cjs/telemetryCore.js +14 -767
  39. package/dist/esm/contract-gate-snapshot-store/file-store.mjs +51 -0
  40. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +92 -0
  41. package/dist/esm/contract-gate-snapshot-store/index.mjs +4 -0
  42. package/dist/esm/contract-gate-snapshot-store/resolve.mjs +68 -0
  43. package/dist/esm/contract-gate-snapshot-store/types.mjs +3 -0
  44. package/dist/esm/contractGateAutopilot.mjs +26 -5
  45. package/dist/esm/index.mjs +2 -2
  46. package/dist/esm/module-federation-css/collector.mjs +38 -0
  47. package/dist/esm/module-federation-css/index.mjs +4 -0
  48. package/dist/esm/module-federation-css/manifest.mjs +69 -0
  49. package/dist/esm/module-federation-css/plugin.mjs +33 -0
  50. package/dist/esm/module-federation-css/remote.mjs +92 -0
  51. package/dist/esm/runtime-fallback-signal/auth.mjs +40 -0
  52. package/dist/esm/runtime-fallback-signal/constants.mjs +10 -0
  53. package/dist/esm/runtime-fallback-signal/contract-gate.mjs +26 -0
  54. package/dist/esm/runtime-fallback-signal/endpoint.mjs +12 -0
  55. package/dist/esm/runtime-fallback-signal/errors.mjs +6 -0
  56. package/dist/esm/runtime-fallback-signal/index.mjs +9 -0
  57. package/dist/esm/runtime-fallback-signal/payload.mjs +31 -0
  58. package/dist/esm/runtime-fallback-signal/source.mjs +22 -0
  59. package/dist/esm/runtime-fallback-signal/state.mjs +16 -0
  60. package/dist/esm/runtime-fallback-signal/status.mjs +9 -0
  61. package/dist/esm/runtime-fallback-signal/trust-policy.mjs +67 -0
  62. package/dist/esm/runtime-fallback-signal/types.mjs +0 -0
  63. package/dist/esm/runtimeFallbackSignal.mjs +1 -222
  64. package/dist/esm/telemetry/canary.mjs +142 -0
  65. package/dist/esm/telemetry/canaryEvaluation.mjs +41 -0
  66. package/dist/esm/telemetry/canarySetup.mjs +69 -0
  67. package/dist/esm/telemetry/envelope.mjs +101 -0
  68. package/dist/esm/telemetry/exporters.mjs +104 -0
  69. package/dist/esm/telemetry/lifecycle.mjs +60 -0
  70. package/dist/esm/telemetry/metrics.mjs +77 -0
  71. package/dist/esm/telemetry/plugin.mjs +87 -0
  72. package/dist/esm/telemetry/registry.mjs +310 -0
  73. package/dist/esm/telemetry/registryTypes.mjs +8 -0
  74. package/dist/esm/telemetry/runtimeEndpoints.mjs +94 -0
  75. package/dist/esm/telemetry.mjs +1 -275
  76. package/dist/esm/telemetryCore.mjs +6 -759
  77. package/dist/esm-node/contract-gate-snapshot-store/file-store.mjs +52 -0
  78. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +93 -0
  79. package/dist/esm-node/contract-gate-snapshot-store/index.mjs +5 -0
  80. package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +70 -0
  81. package/dist/esm-node/contract-gate-snapshot-store/types.mjs +4 -0
  82. package/dist/esm-node/contractGateAutopilot.mjs +26 -5
  83. package/dist/esm-node/index.mjs +2 -2
  84. package/dist/esm-node/module-federation-css/collector.mjs +39 -0
  85. package/dist/esm-node/module-federation-css/index.mjs +5 -0
  86. package/dist/esm-node/module-federation-css/manifest.mjs +70 -0
  87. package/dist/esm-node/module-federation-css/plugin.mjs +34 -0
  88. package/dist/esm-node/module-federation-css/remote.mjs +93 -0
  89. package/dist/esm-node/runtime-fallback-signal/auth.mjs +41 -0
  90. package/dist/esm-node/runtime-fallback-signal/constants.mjs +11 -0
  91. package/dist/esm-node/runtime-fallback-signal/contract-gate.mjs +27 -0
  92. package/dist/esm-node/runtime-fallback-signal/endpoint.mjs +13 -0
  93. package/dist/esm-node/runtime-fallback-signal/errors.mjs +7 -0
  94. package/dist/esm-node/runtime-fallback-signal/index.mjs +10 -0
  95. package/dist/esm-node/runtime-fallback-signal/payload.mjs +32 -0
  96. package/dist/esm-node/runtime-fallback-signal/source.mjs +23 -0
  97. package/dist/esm-node/runtime-fallback-signal/state.mjs +17 -0
  98. package/dist/esm-node/runtime-fallback-signal/status.mjs +10 -0
  99. package/dist/esm-node/runtime-fallback-signal/trust-policy.mjs +68 -0
  100. package/dist/esm-node/runtime-fallback-signal/types.mjs +1 -0
  101. package/dist/esm-node/runtimeFallbackSignal.mjs +1 -222
  102. package/dist/esm-node/telemetry/canary.mjs +143 -0
  103. package/dist/esm-node/telemetry/canaryEvaluation.mjs +42 -0
  104. package/dist/esm-node/telemetry/canarySetup.mjs +70 -0
  105. package/dist/esm-node/telemetry/envelope.mjs +102 -0
  106. package/dist/esm-node/telemetry/exporters.mjs +105 -0
  107. package/dist/esm-node/telemetry/lifecycle.mjs +61 -0
  108. package/dist/esm-node/telemetry/metrics.mjs +78 -0
  109. package/dist/esm-node/telemetry/plugin.mjs +88 -0
  110. package/dist/esm-node/telemetry/registry.mjs +311 -0
  111. package/dist/esm-node/telemetry/registryTypes.mjs +9 -0
  112. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +95 -0
  113. package/dist/esm-node/telemetry.mjs +1 -275
  114. package/dist/esm-node/telemetryCore.mjs +6 -759
  115. package/dist/types/contract-gate-snapshot-store/file-store.d.ts +3 -0
  116. package/dist/types/contract-gate-snapshot-store/http-store.d.ts +11 -0
  117. package/dist/types/contract-gate-snapshot-store/index.d.ts +5 -0
  118. package/dist/types/contract-gate-snapshot-store/resolve.d.ts +9 -0
  119. package/dist/types/{contractGateSnapshotStore.d.ts → contract-gate-snapshot-store/types.d.ts} +1 -11
  120. package/dist/types/contractGateAutopilot.d.ts +4 -2
  121. package/dist/types/index.d.ts +2 -2
  122. package/dist/types/module-federation-css/collector.d.ts +25 -0
  123. package/dist/types/module-federation-css/index.d.ts +8 -0
  124. package/dist/types/module-federation-css/manifest.d.ts +33 -0
  125. package/dist/types/module-federation-css/plugin.d.ts +23 -0
  126. package/dist/types/module-federation-css/remote.d.ts +20 -0
  127. package/dist/types/runtime-fallback-signal/auth.d.ts +18 -0
  128. package/dist/types/runtime-fallback-signal/constants.d.ts +9 -0
  129. package/dist/types/runtime-fallback-signal/contract-gate.d.ts +2 -0
  130. package/dist/types/runtime-fallback-signal/endpoint.d.ts +1 -0
  131. package/dist/types/runtime-fallback-signal/errors.d.ts +2 -0
  132. package/dist/types/runtime-fallback-signal/index.d.ts +10 -0
  133. package/dist/types/runtime-fallback-signal/payload.d.ts +6 -0
  134. package/dist/types/runtime-fallback-signal/source.d.ts +3 -0
  135. package/dist/types/runtime-fallback-signal/state.d.ts +3 -0
  136. package/dist/types/runtime-fallback-signal/status.d.ts +2 -0
  137. package/dist/types/runtime-fallback-signal/trust-policy.d.ts +13 -0
  138. package/dist/types/runtime-fallback-signal/types.d.ts +50 -0
  139. package/dist/types/runtimeFallbackSignal.d.ts +1 -94
  140. package/dist/types/telemetry/canary.d.ts +85 -0
  141. package/dist/types/telemetry/canaryEvaluation.d.ts +19 -0
  142. package/dist/types/telemetry/canarySetup.d.ts +17 -0
  143. package/dist/types/telemetry/envelope.d.ts +45 -0
  144. package/dist/types/telemetry/exporters.d.ts +12 -0
  145. package/dist/types/telemetry/lifecycle.d.ts +18 -0
  146. package/dist/types/telemetry/metrics.d.ts +3 -0
  147. package/dist/types/telemetry/plugin.d.ts +12 -0
  148. package/dist/types/telemetry/registry.d.ts +72 -0
  149. package/dist/types/telemetry/registryTypes.d.ts +50 -0
  150. package/dist/types/telemetry/runtimeEndpoints.d.ts +35 -0
  151. package/dist/types/telemetry.d.ts +1 -12
  152. package/dist/types/telemetryCore.d.ts +6 -257
  153. package/package.json +7 -7
  154. package/src/contract-gate-snapshot-store/file-store.ts +85 -0
  155. package/src/contract-gate-snapshot-store/http-store.ts +159 -0
  156. package/src/contract-gate-snapshot-store/index.ts +20 -0
  157. package/src/contract-gate-snapshot-store/resolve.ts +175 -0
  158. package/src/contract-gate-snapshot-store/types.ts +64 -0
  159. package/src/contractGateAutopilot.ts +45 -9
  160. package/src/index.ts +6 -6
  161. package/src/module-federation-css/collector.ts +82 -0
  162. package/src/module-federation-css/index.ts +14 -0
  163. package/src/module-federation-css/manifest.ts +166 -0
  164. package/src/module-federation-css/plugin.ts +86 -0
  165. package/src/module-federation-css/remote.ts +165 -0
  166. package/src/runtime-fallback-signal/auth.ts +117 -0
  167. package/src/runtime-fallback-signal/constants.ts +19 -0
  168. package/src/runtime-fallback-signal/contract-gate.ts +43 -0
  169. package/src/runtime-fallback-signal/endpoint.ts +22 -0
  170. package/src/runtime-fallback-signal/errors.ts +10 -0
  171. package/src/runtime-fallback-signal/index.ts +36 -0
  172. package/src/runtime-fallback-signal/payload.ts +79 -0
  173. package/src/runtime-fallback-signal/source.ts +49 -0
  174. package/src/runtime-fallback-signal/state.ts +34 -0
  175. package/src/runtime-fallback-signal/status.ts +22 -0
  176. package/src/runtime-fallback-signal/trust-policy.ts +179 -0
  177. package/src/runtime-fallback-signal/types.ts +66 -0
  178. package/src/runtimeFallbackSignal.ts +1 -584
  179. package/src/telemetry/canary.ts +291 -0
  180. package/src/telemetry/canaryEvaluation.ts +83 -0
  181. package/src/telemetry/canarySetup.ts +160 -0
  182. package/src/telemetry/envelope.ts +189 -0
  183. package/src/telemetry/exporters.ts +165 -0
  184. package/src/telemetry/lifecycle.ts +138 -0
  185. package/src/telemetry/metrics.ts +141 -0
  186. package/src/telemetry/plugin.ts +197 -0
  187. package/src/telemetry/registry.ts +467 -0
  188. package/src/telemetry/registryTypes.ts +63 -0
  189. package/src/telemetry/runtimeEndpoints.ts +172 -0
  190. package/src/telemetry.ts +1 -554
  191. package/src/telemetryCore.ts +34 -1332
  192. package/tests/contractGateAutopilot.test.ts +205 -0
  193. package/tests/contractGateSnapshotStore.test.ts +54 -1
  194. package/tests/helpers.ts +1 -0
  195. package/tests/moduleFederationCss.test.ts +1 -1
  196. package/tests/registration.test.ts +1 -1
  197. package/tests/telemetry.test.ts +40 -0
  198. package/tests/telemetryLifecycle.test.ts +253 -2
  199. package/dist/cjs/contractGateSnapshotStore.js +0 -253
  200. package/dist/cjs/moduleFederationCss.js +0 -285
  201. package/dist/esm/contractGateSnapshotStore.mjs +0 -190
  202. package/dist/esm/moduleFederationCss.mjs +0 -225
  203. package/dist/esm-node/contractGateSnapshotStore.mjs +0 -192
  204. package/dist/esm-node/moduleFederationCss.mjs +0 -226
  205. package/dist/types/moduleFederationCss.d.ts +0 -87
  206. package/src/contractGateSnapshotStore.ts +0 -420
  207. package/src/moduleFederationCss.ts +0 -473
@@ -0,0 +1,166 @@
1
+ import { fileReader } from '@modern-js/runtime-utils/fileReader';
2
+
3
+ import type { Monitors } from '@modern-js/types';
4
+
5
+ import { fs } from '@modern-js/utils';
6
+
7
+ import path from 'path';
8
+
9
+ const MODULE_FEDERATION_MANIFEST_FILE = 'mf-manifest.json';
10
+
11
+ type ModuleFederationAssets = {
12
+ css?: {
13
+ sync?: string[];
14
+ async?: string[];
15
+ };
16
+ };
17
+
18
+ export type ModuleFederationManifest = {
19
+ metaData?: {
20
+ publicPath?: string;
21
+ };
22
+ shared?: Array<{
23
+ assets?: ModuleFederationAssets;
24
+ }>;
25
+ remotes?: Array<{
26
+ entry?: string;
27
+ assets?: ModuleFederationAssets;
28
+ }>;
29
+ exposes?: Array<{
30
+ assets?: ModuleFederationAssets;
31
+ }>;
32
+ };
33
+
34
+ export const warn = (
35
+ monitors: Monitors | undefined,
36
+ message: string,
37
+ ...args: unknown[]
38
+ ) => {
39
+ if (monitors) {
40
+ monitors.warn(message, ...args);
41
+ return;
42
+ }
43
+
44
+ console.warn(message, ...args);
45
+ };
46
+
47
+ export const ensureTrailingSlash = (value: string) =>
48
+ value.endsWith('/') ? value : `${value}/`;
49
+
50
+ export const tryResolveUrl = (value: string, base: string) => {
51
+ try {
52
+ return new URL(value, base).toString();
53
+ } catch {
54
+ return undefined;
55
+ }
56
+ };
57
+
58
+ export const normalizeRemoteEntry = (entry: string) => {
59
+ const value = entry.trim();
60
+ if (!value) {
61
+ return undefined;
62
+ }
63
+
64
+ const atIndex = value.lastIndexOf('@');
65
+ return atIndex >= 0 ? value.slice(atIndex + 1) : value;
66
+ };
67
+
68
+ export const getCssAssets = (assets?: ModuleFederationAssets) => [
69
+ ...(assets?.css?.sync || []),
70
+ ...(assets?.css?.async || []),
71
+ ];
72
+
73
+ export const getManifestFallbackBase = (manifestUrl: string) => {
74
+ try {
75
+ return new URL('.', manifestUrl).toString();
76
+ } catch {
77
+ return ensureTrailingSlash(manifestUrl);
78
+ }
79
+ };
80
+
81
+ export const getManifestPublicPathBase = (
82
+ publicPath: string | undefined,
83
+ manifestUrl: string,
84
+ ) => {
85
+ if (!publicPath || publicPath === 'auto') {
86
+ return getManifestFallbackBase(manifestUrl);
87
+ }
88
+
89
+ const base = tryResolveUrl(ensureTrailingSlash(publicPath), manifestUrl);
90
+ return base || getManifestFallbackBase(manifestUrl);
91
+ };
92
+
93
+ export const appendResolvedCssAssets = (
94
+ result: string[],
95
+ seen: Set<string>,
96
+ assets: string[],
97
+ base: string,
98
+ ) => {
99
+ for (const asset of assets) {
100
+ if (!asset) {
101
+ continue;
102
+ }
103
+
104
+ const resolved = tryResolveUrl(asset, base);
105
+
106
+ if (resolved && !seen.has(resolved)) {
107
+ seen.add(resolved);
108
+ result.push(resolved);
109
+ }
110
+ }
111
+ };
112
+
113
+ export const collectModuleFederationManifestCss = (
114
+ manifest: ModuleFederationManifest,
115
+ manifestUrl: string,
116
+ ) => {
117
+ const base = getManifestPublicPathBase(
118
+ manifest.metaData?.publicPath,
119
+ manifestUrl,
120
+ );
121
+ const result: string[] = [];
122
+ const seen = new Set<string>();
123
+
124
+ for (const item of manifest.shared || []) {
125
+ appendResolvedCssAssets(result, seen, getCssAssets(item.assets), base);
126
+ }
127
+
128
+ for (const item of manifest.exposes || []) {
129
+ appendResolvedCssAssets(result, seen, getCssAssets(item.assets), base);
130
+ }
131
+
132
+ return result;
133
+ };
134
+
135
+ export const getHostManifest = async (
136
+ pwd: string,
137
+ monitors?: Monitors,
138
+ ): Promise<ModuleFederationManifest | undefined> => {
139
+ const manifestPath = path.join(pwd, MODULE_FEDERATION_MANIFEST_FILE);
140
+
141
+ if (!(await fs.pathExists(manifestPath))) {
142
+ return undefined;
143
+ }
144
+
145
+ const manifestBuffer = await fileReader.readFileFromSystem(
146
+ manifestPath,
147
+ 'buffer',
148
+ );
149
+
150
+ if (manifestBuffer === null) {
151
+ return undefined;
152
+ }
153
+
154
+ try {
155
+ return JSON.parse(
156
+ manifestBuffer.toString('utf-8'),
157
+ ) as ModuleFederationManifest;
158
+ } catch (error) {
159
+ warn(
160
+ monitors,
161
+ 'Parse module federation manifest failed, error = %s',
162
+ error instanceof Error ? error.message : error,
163
+ );
164
+ return undefined;
165
+ }
166
+ };
@@ -0,0 +1,86 @@
1
+ import type {
2
+ Middleware,
3
+ ServerEnv,
4
+ ServerPlugin,
5
+ } from '@modern-js/server-core';
6
+
7
+ import { isProd } from '@modern-js/utils';
8
+
9
+ import {
10
+ createModuleFederationCssCollector,
11
+ DEFAULT_REMOTE_CSS_CACHE_TTL_MS,
12
+ } from './collector';
13
+
14
+ export type ModuleFederationCssPluginOptions = {
15
+ /**
16
+ * TTL for the cached remote CSS collection in production.
17
+ *
18
+ * @default 30000 in production, 0 (no caching) otherwise
19
+ */
20
+ remoteCssCacheTtlMs?: number;
21
+ };
22
+
23
+ /**
24
+ * Enriches the request-scoped server manifest with CSS assets collected from
25
+ * direct module federation remotes, so SSR/CSR-RSC rendering can inline
26
+ * `<link>` tags for remote CSS.
27
+ *
28
+ * In production the collection is cached with a TTL (default 30s) instead of
29
+ * being pinned at boot: remote manifests change on every remote redeploy, and
30
+ * fetch failures must not pin an empty/partial list for the process lifetime.
31
+ *
32
+ * This plugin must be registered after `injectResourcePlugin()` (which sets
33
+ * `serverManifest` on the request context). @modern-js/prod-server wires it
34
+ * into its plugin assembly for both production and dev servers.
35
+ */
36
+ export const injectModuleFederationCssPlugin = (
37
+ options: ModuleFederationCssPluginOptions = {},
38
+ ): ServerPlugin => ({
39
+ name: '@modern-js/inject-module-federation-css',
40
+
41
+ setup(api) {
42
+ api.onPrepare(() => {
43
+ const { middlewares, distDirectory: pwd } = api.getServerContext();
44
+
45
+ if (!pwd) {
46
+ return;
47
+ }
48
+
49
+ const ttlMs = Math.max(
50
+ 0,
51
+ options.remoteCssCacheTtlMs ??
52
+ (isProd() ? DEFAULT_REMOTE_CSS_CACHE_TTL_MS : 0),
53
+ );
54
+ const collector = createModuleFederationCssCollector(pwd, { ttlMs });
55
+
56
+ if (isProd()) {
57
+ // Warm up the remote manifest fetch at prepare time, mirroring the
58
+ // server manifest warmup of injectResourcePlugin, so the first
59
+ // request does not pay the collection latency. Failures are retried
60
+ // on the next request instead of failing startup.
61
+ collector.collect().catch(() => {});
62
+ }
63
+
64
+ const handler: Middleware<ServerEnv> = async (c, next) => {
65
+ const serverManifest = c.get('serverManifest');
66
+
67
+ if (serverManifest && !serverManifest.moduleFederationCssAssets) {
68
+ const monitors = c.get('monitors');
69
+ const moduleFederationCssAssets = await collector.collect(monitors);
70
+
71
+ c.set('serverManifest', {
72
+ ...serverManifest,
73
+ moduleFederationCssAssets,
74
+ });
75
+ }
76
+
77
+ await next();
78
+ };
79
+
80
+ middlewares.push({
81
+ name: 'inject-module-federation-css',
82
+ handler,
83
+ });
84
+ });
85
+ },
86
+ });
@@ -0,0 +1,165 @@
1
+ import type { Monitors } from '@modern-js/types';
2
+
3
+ import type { ModuleFederationManifest } from './manifest';
4
+
5
+ import {
6
+ collectModuleFederationManifestCss,
7
+ getHostManifest,
8
+ normalizeRemoteEntry,
9
+ warn,
10
+ } from './manifest';
11
+
12
+ const DEFAULT_REMOTE_MANIFEST_TIMEOUT = 1500;
13
+
14
+ type FetchLike = (
15
+ input: string,
16
+ init?: {
17
+ signal?: AbortSignal;
18
+ },
19
+ ) => Promise<Response>;
20
+
21
+ export type CollectDirectRemoteModuleFederationCssOptions = {
22
+ fetcher?: FetchLike;
23
+ monitors?: Monitors;
24
+ timeout?: number;
25
+ };
26
+
27
+ const fetchJsonWithTimeout = async (
28
+ url: string,
29
+ fetcher: FetchLike,
30
+ timeout: number,
31
+ ) => {
32
+ const controller = new AbortController();
33
+ let timeoutId: ReturnType<typeof setTimeout> | undefined;
34
+
35
+ try {
36
+ const response = await Promise.race([
37
+ fetcher(url, { signal: controller.signal }),
38
+ new Promise<Response>((_, reject) => {
39
+ timeoutId = setTimeout(() => {
40
+ controller.abort();
41
+ reject(new Error(`Request timed out after ${timeout}ms`));
42
+ }, timeout);
43
+ }),
44
+ ]);
45
+
46
+ if (!response.ok) {
47
+ throw new Error(`Unexpected status ${response.status}`);
48
+ }
49
+
50
+ return (await response.json()) as ModuleFederationManifest;
51
+ } finally {
52
+ if (timeoutId) {
53
+ clearTimeout(timeoutId);
54
+ }
55
+ }
56
+ };
57
+
58
+ export type RemoteModuleFederationCssCollection = {
59
+ assets: string[];
60
+ /**
61
+ * True when at least one remote manifest fetch failed, i.e. `assets` may be
62
+ * incomplete and should not be cached long-term.
63
+ */
64
+ errored: boolean;
65
+ };
66
+
67
+ export const collectDirectRemoteModuleFederationCssWithMeta = async (
68
+ pwd: string,
69
+ options: CollectDirectRemoteModuleFederationCssOptions = {},
70
+ ): Promise<RemoteModuleFederationCssCollection> => {
71
+ const hostManifest = await getHostManifest(pwd, options.monitors);
72
+
73
+ if (!hostManifest) {
74
+ return { assets: [], errored: false };
75
+ }
76
+
77
+ const fetcher = options.fetcher || globalThis.fetch?.bind(globalThis);
78
+ if (!fetcher) {
79
+ warn(
80
+ options.monitors,
81
+ 'Skip module federation remote CSS collection because fetch is unavailable.',
82
+ );
83
+ return { assets: [], errored: false };
84
+ }
85
+
86
+ const timeout = options.timeout ?? DEFAULT_REMOTE_MANIFEST_TIMEOUT;
87
+
88
+ // Fetch all remote manifests in parallel so SSR latency is bounded by the
89
+ // slowest remote rather than the sum of all remotes.
90
+ const remoteResults = await Promise.all(
91
+ (hostManifest.remotes || []).map(
92
+ async (remote): Promise<{ assets: string[]; errored: boolean }> => {
93
+ if (!remote.entry) {
94
+ return { assets: [], errored: false };
95
+ }
96
+
97
+ const remoteEntry = normalizeRemoteEntry(remote.entry);
98
+ if (!remoteEntry) {
99
+ return { assets: [], errored: false };
100
+ }
101
+
102
+ let remoteManifestUrl: string;
103
+ try {
104
+ remoteManifestUrl = new URL(remoteEntry).toString();
105
+ } catch {
106
+ warn(
107
+ options.monitors,
108
+ 'Skip module federation remote CSS collection for non-absolute manifest URL %s',
109
+ remoteEntry,
110
+ );
111
+ return { assets: [], errored: false };
112
+ }
113
+
114
+ try {
115
+ const remoteManifest = await fetchJsonWithTimeout(
116
+ remoteManifestUrl,
117
+ fetcher,
118
+ timeout,
119
+ );
120
+ return {
121
+ assets: collectModuleFederationManifestCss(
122
+ remoteManifest,
123
+ remoteManifestUrl,
124
+ ),
125
+ errored: false,
126
+ };
127
+ } catch (error) {
128
+ warn(
129
+ options.monitors,
130
+ 'Load module federation remote manifest %s failed, error = %s',
131
+ remoteManifestUrl,
132
+ error instanceof Error ? error.message : error,
133
+ );
134
+ return { assets: [], errored: true };
135
+ }
136
+ },
137
+ ),
138
+ );
139
+
140
+ const cssAssets: string[] = [];
141
+ const seen = new Set<string>();
142
+ let errored = false;
143
+ for (const result of remoteResults) {
144
+ errored = errored || result.errored;
145
+ for (const asset of result.assets) {
146
+ if (!seen.has(asset)) {
147
+ seen.add(asset);
148
+ cssAssets.push(asset);
149
+ }
150
+ }
151
+ }
152
+
153
+ return { assets: cssAssets, errored };
154
+ };
155
+
156
+ export const collectDirectRemoteModuleFederationCss = async (
157
+ pwd: string,
158
+ options: CollectDirectRemoteModuleFederationCssOptions = {},
159
+ ) => {
160
+ const { assets } = await collectDirectRemoteModuleFederationCssWithMeta(
161
+ pwd,
162
+ options,
163
+ );
164
+ return assets;
165
+ };
@@ -0,0 +1,117 @@
1
+ import { createHash, timingSafeEqual } from 'node:crypto';
2
+ import type { Context, ServerEnv } from '@modern-js/server-core';
3
+ import { DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER } from './constants';
4
+ import { createRuntimeSignalError } from './errors';
5
+ import type {
6
+ RuntimeFallbackSignalAuthConfig,
7
+ RuntimeFallbackSignalConfig,
8
+ } from './types';
9
+
10
+ export function normalizeRuntimeFallbackSignalAuthConfig(
11
+ configured:
12
+ | {
13
+ enabled?: boolean;
14
+ headerName?: string;
15
+ expectedValue?: string;
16
+ expectedValueEnv?: string;
17
+ }
18
+ | undefined,
19
+ ): RuntimeFallbackSignalAuthConfig {
20
+ const headerName =
21
+ typeof configured?.headerName === 'string' && configured.headerName.trim()
22
+ ? configured.headerName.trim().toLowerCase()
23
+ : DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER;
24
+ const expectedFromEnv =
25
+ typeof configured?.expectedValueEnv === 'string' &&
26
+ configured.expectedValueEnv.trim().length > 0
27
+ ? process.env[configured.expectedValueEnv.trim()]
28
+ : undefined;
29
+ const expectedFromConfig =
30
+ typeof configured?.expectedValue === 'string' &&
31
+ configured.expectedValue.trim().length > 0
32
+ ? configured.expectedValue.trim()
33
+ : undefined;
34
+ const expectedValue = expectedFromConfig || expectedFromEnv;
35
+ const enabled = configured?.enabled === true;
36
+
37
+ if (enabled && !expectedValue) {
38
+ throw new Error(
39
+ '[telemetry.canary.autopilot.runtimeFallbackSignal] auth.enabled is true but no expected token is configured',
40
+ );
41
+ }
42
+
43
+ return {
44
+ enabled,
45
+ headerName,
46
+ expectedValue,
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Normalizes the auth config for the runtime fallback signal endpoint when the
52
+ * endpoint itself is enabled. The endpoint can persist failing contract gates
53
+ * (a canary kill switch), so it always requires a token: auth cannot be
54
+ * disabled and a token must be configured via `auth.expectedValue` or
55
+ * `auth.expectedValueEnv`.
56
+ */
57
+ export function normalizeRequiredRuntimeFallbackSignalAuthConfig(
58
+ configured: Parameters<typeof normalizeRuntimeFallbackSignalAuthConfig>[0],
59
+ ): RuntimeFallbackSignalAuthConfig {
60
+ if (configured?.enabled === false) {
61
+ throw new Error(
62
+ '[telemetry.canary.autopilot.runtimeFallbackSignal] the endpoint cannot be enabled with auth disabled; configure auth.expectedValue or auth.expectedValueEnv',
63
+ );
64
+ }
65
+
66
+ try {
67
+ return normalizeRuntimeFallbackSignalAuthConfig({
68
+ ...configured,
69
+ enabled: true,
70
+ });
71
+ } catch (_error) {
72
+ throw new Error(
73
+ '[telemetry.canary.autopilot.runtimeFallbackSignal] enabling the endpoint requires an auth token; configure auth.expectedValue or auth.expectedValueEnv',
74
+ );
75
+ }
76
+ }
77
+
78
+ /**
79
+ * Constant-time token comparison. Both sides are hashed first so neither the
80
+ * comparison time nor the early length check leaks information about the
81
+ * expected secret.
82
+ */
83
+ function safeTokenEquals(candidate: string, expected: string) {
84
+ const candidateDigest = createHash('sha256').update(candidate).digest();
85
+ const expectedDigest = createHash('sha256').update(expected).digest();
86
+ return timingSafeEqual(candidateDigest, expectedDigest);
87
+ }
88
+
89
+ export function enforceRuntimeFallbackSignalAuthToken(
90
+ token: string | undefined,
91
+ authConfig: RuntimeFallbackSignalAuthConfig,
92
+ ) {
93
+ if (!authConfig.enabled) {
94
+ return;
95
+ }
96
+
97
+ if (
98
+ !token ||
99
+ !authConfig.expectedValue ||
100
+ !safeTokenEquals(token, authConfig.expectedValue)
101
+ ) {
102
+ throw createRuntimeSignalError(
103
+ 'runtime fallback signal auth failed',
104
+ 'UNAUTHORIZED',
105
+ );
106
+ }
107
+ }
108
+
109
+ export function enforceRuntimeFallbackSignalAuth(
110
+ c: Context<ServerEnv>,
111
+ runtimeSignalConfig: RuntimeFallbackSignalConfig,
112
+ ) {
113
+ enforceRuntimeFallbackSignalAuthToken(
114
+ c.req.header(runtimeSignalConfig.auth.headerName),
115
+ runtimeSignalConfig.auth,
116
+ );
117
+ }
@@ -0,0 +1,19 @@
1
+ export const DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT =
2
+ '/_modern/contract-gates/runtime-fallback';
3
+
4
+ export const DEFAULT_RUNTIME_STATUS_ENDPOINT = '/_modern/runtime/status';
5
+
6
+ export const DEFAULT_RUNTIME_FALLBACK_GATE_NAME = 'runtime-mf-fallback-health';
7
+
8
+ export const DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS = 5 * 60_000;
9
+
10
+ export const DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES = 16 * 1024;
11
+
12
+ export const DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER =
13
+ 'x-modernjs-runtime-signal-token';
14
+
15
+ export const DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW = 30;
16
+
17
+ export const DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS = 60_000;
18
+
19
+ export const DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS = 10_000;
@@ -0,0 +1,43 @@
1
+ import type { GateSnapshot } from '../contract-gate-snapshot-store';
2
+ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from '../contract-gate-snapshot-store';
3
+ import type {
4
+ RuntimeFallbackSignalConfig,
5
+ RuntimeFallbackSignalSource,
6
+ } from './types';
7
+
8
+ export async function persistRuntimeFallbackContractGate(
9
+ payload: Record<string, unknown>,
10
+ runtimeSignalConfig: RuntimeFallbackSignalConfig,
11
+ ) {
12
+ const now = Date.now();
13
+ const gateSnapshotStore = await runtimeSignalConfig.gateSnapshotStore;
14
+ const snapshot: GateSnapshot = (await gateSnapshotStore.readSnapshot()) || {};
15
+ const existingGates =
16
+ snapshot.gates && typeof snapshot.gates === 'object' ? snapshot.gates : {};
17
+
18
+ const reason =
19
+ typeof payload.reason === 'string' ? payload.reason : 'runtime_fallback';
20
+ const phase = typeof payload.phase === 'string' ? payload.phase : 'unknown';
21
+ const appName =
22
+ typeof payload.appName === 'string' ? payload.appName : 'unknown';
23
+ const entry = typeof payload.entry === 'string' ? payload.entry : undefined;
24
+
25
+ snapshot.schemaVersion =
26
+ typeof snapshot.schemaVersion === 'number'
27
+ ? snapshot.schemaVersion
28
+ : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
29
+ snapshot.updatedAt = now;
30
+ snapshot.gates = {
31
+ ...existingGates,
32
+ [runtimeSignalConfig.gateName]: {
33
+ passed: false,
34
+ reason: `runtime_fallback:${reason} phase=${phase} app=${appName}${entry ? ` entry=${entry}` : ''}`,
35
+ updatedAt: now,
36
+ expiresAt: now + runtimeSignalConfig.failureHoldMs,
37
+ source: 'runtime-mf-fallback-signal',
38
+ metadata: payload,
39
+ },
40
+ };
41
+
42
+ await gateSnapshotStore.writeSnapshot(snapshot);
43
+ }
@@ -0,0 +1,22 @@
1
+ import { DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT } from './constants';
2
+
3
+ export function resolveRuntimeFallbackSignalEndpoint(
4
+ configuredEndpoint?: string,
5
+ ) {
6
+ const rawEndpoint = configuredEndpoint?.trim();
7
+ if (!rawEndpoint) {
8
+ return DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
9
+ }
10
+
11
+ if (rawEndpoint.startsWith('/')) {
12
+ return rawEndpoint;
13
+ }
14
+
15
+ try {
16
+ return (
17
+ new URL(rawEndpoint).pathname || DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT
18
+ );
19
+ } catch (_error) {
20
+ return `/${rawEndpoint.replace(/^\/+/, '')}`;
21
+ }
22
+ }
@@ -0,0 +1,10 @@
1
+ import type { RuntimeSignalError } from './types';
2
+
3
+ export function createRuntimeSignalError(
4
+ message: string,
5
+ code: RuntimeSignalError['code'],
6
+ ) {
7
+ const error = new Error(message) as RuntimeSignalError;
8
+ error.code = code;
9
+ return error;
10
+ }
@@ -0,0 +1,36 @@
1
+ export {
2
+ enforceRuntimeFallbackSignalAuth,
3
+ enforceRuntimeFallbackSignalAuthToken,
4
+ normalizeRequiredRuntimeFallbackSignalAuthConfig,
5
+ normalizeRuntimeFallbackSignalAuthConfig,
6
+ } from './auth';
7
+ export {
8
+ DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS,
9
+ DEFAULT_RUNTIME_FALLBACK_GATE_NAME,
10
+ DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES,
11
+ DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT,
12
+ DEFAULT_RUNTIME_STATUS_ENDPOINT,
13
+ } from './constants';
14
+ export { persistRuntimeFallbackContractGate } from './contract-gate';
15
+ export { resolveRuntimeFallbackSignalEndpoint } from './endpoint';
16
+ export { createRuntimeSignalError } from './errors';
17
+ export {
18
+ parseRuntimeFallbackSignalPayload,
19
+ parseRuntimeFallbackSignalPayloadFromRawBody,
20
+ } from './payload';
21
+ export { createRuntimeFallbackSignalRuntimeState } from './state';
22
+ export { getRuntimeSignalErrorStatusCode } from './status';
23
+ export {
24
+ enforceRuntimeFallbackSignalTrustPolicy,
25
+ normalizeRuntimeFallbackTrustPolicy,
26
+ } from './trust-policy';
27
+ export type {
28
+ RuntimeFallbackSignalAuthConfig,
29
+ RuntimeFallbackSignalConfig,
30
+ RuntimeFallbackSignalRuntimeState,
31
+ RuntimeFallbackSignalSource,
32
+ RuntimeFallbackSignalTrustContext,
33
+ RuntimeFallbackSignalTrustPolicy,
34
+ RuntimeSignalError,
35
+ RuntimeSignalErrorCode,
36
+ } from './types';