@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.6 → 3.5.0-ultramodern.75

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 (179) hide show
  1. package/dist/cjs/contract-gate-snapshot-normalization.js +122 -0
  2. package/dist/cjs/contract-gate-snapshot-store/file-store.js +102 -0
  3. package/dist/cjs/contract-gate-snapshot-store/http-store.js +133 -0
  4. package/dist/cjs/contract-gate-snapshot-store/index.js +58 -0
  5. package/dist/cjs/contract-gate-snapshot-store/resolve.js +124 -0
  6. package/dist/cjs/contract-gate-snapshot-store/types.js +44 -0
  7. package/dist/cjs/contractGateAutopilot.js +22 -70
  8. package/dist/cjs/index.js +6 -25
  9. package/dist/cjs/mfCache.js +2 -2
  10. package/dist/cjs/module-federation-css/collector.js +79 -0
  11. package/dist/cjs/module-federation-css/index.js +55 -0
  12. package/dist/cjs/module-federation-css/manifest.js +129 -0
  13. package/dist/cjs/module-federation-css/plugin.js +71 -0
  14. package/dist/cjs/module-federation-css/remote.js +133 -0
  15. package/dist/cjs/runtime-fallback-signal/index.js +93 -0
  16. package/dist/cjs/runtime-fallback-signal/model.js +157 -0
  17. package/dist/cjs/runtime-fallback-signal/resolver.js +163 -0
  18. package/dist/cjs/runtime-fallback-signal/store.js +83 -0
  19. package/dist/cjs/runtimeFallbackSignal.js +32 -281
  20. package/dist/cjs/telemetry/canary.js +180 -0
  21. package/dist/cjs/telemetry/canaryEvaluation.js +79 -0
  22. package/dist/cjs/telemetry/canarySetup.js +107 -0
  23. package/dist/cjs/telemetry/envelope.js +223 -0
  24. package/dist/cjs/telemetry/exporters.js +148 -0
  25. package/dist/cjs/telemetry/lifecycle.js +98 -0
  26. package/dist/cjs/telemetry/metrics.js +115 -0
  27. package/dist/cjs/telemetry/plugin.js +185 -0
  28. package/dist/cjs/telemetry/registry.js +296 -0
  29. package/dist/cjs/telemetry/registryTypes.js +46 -0
  30. package/dist/cjs/telemetry/runtimeEndpoints.js +135 -0
  31. package/dist/cjs/telemetry.js +32 -343
  32. package/dist/cjs/telemetryCore.js +14 -767
  33. package/dist/esm/contract-gate-snapshot-normalization.mjs +81 -0
  34. package/dist/esm/contract-gate-snapshot-store/file-store.mjs +51 -0
  35. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +92 -0
  36. package/dist/esm/contract-gate-snapshot-store/index.mjs +4 -0
  37. package/dist/esm/contract-gate-snapshot-store/resolve.mjs +70 -0
  38. package/dist/esm/contract-gate-snapshot-store/types.mjs +3 -0
  39. package/dist/esm/contractGateAutopilot.mjs +21 -69
  40. package/dist/esm/index.mjs +1 -2
  41. package/dist/esm/mfCache.mjs +2 -2
  42. package/dist/esm/module-federation-css/collector.mjs +38 -0
  43. package/dist/esm/module-federation-css/index.mjs +4 -0
  44. package/dist/esm/module-federation-css/manifest.mjs +69 -0
  45. package/dist/esm/module-federation-css/plugin.mjs +33 -0
  46. package/dist/esm/module-federation-css/remote.mjs +92 -0
  47. package/dist/esm/runtime-fallback-signal/index.mjs +3 -0
  48. package/dist/esm/runtime-fallback-signal/model.mjs +73 -0
  49. package/dist/esm/runtime-fallback-signal/resolver.mjs +107 -0
  50. package/dist/esm/runtime-fallback-signal/store.mjs +39 -0
  51. package/dist/esm/runtimeFallbackSignal.mjs +1 -222
  52. package/dist/esm/telemetry/canary.mjs +142 -0
  53. package/dist/esm/telemetry/canaryEvaluation.mjs +41 -0
  54. package/dist/esm/telemetry/canarySetup.mjs +69 -0
  55. package/dist/esm/telemetry/envelope.mjs +164 -0
  56. package/dist/esm/telemetry/exporters.mjs +104 -0
  57. package/dist/esm/telemetry/lifecycle.mjs +60 -0
  58. package/dist/esm/telemetry/metrics.mjs +77 -0
  59. package/dist/esm/telemetry/plugin.mjs +87 -0
  60. package/dist/esm/telemetry/registry.mjs +258 -0
  61. package/dist/esm/telemetry/registryTypes.mjs +8 -0
  62. package/dist/esm/telemetry/runtimeEndpoints.mjs +94 -0
  63. package/dist/esm/telemetry.mjs +1 -275
  64. package/dist/esm/telemetryCore.mjs +6 -759
  65. package/dist/esm-node/contract-gate-snapshot-normalization.mjs +82 -0
  66. package/dist/esm-node/contract-gate-snapshot-store/file-store.mjs +52 -0
  67. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +93 -0
  68. package/dist/esm-node/contract-gate-snapshot-store/index.mjs +5 -0
  69. package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +71 -0
  70. package/dist/esm-node/contract-gate-snapshot-store/types.mjs +4 -0
  71. package/dist/esm-node/contractGateAutopilot.mjs +21 -69
  72. package/dist/esm-node/index.mjs +1 -2
  73. package/dist/esm-node/mfCache.mjs +2 -2
  74. package/dist/esm-node/module-federation-css/collector.mjs +39 -0
  75. package/dist/esm-node/module-federation-css/index.mjs +5 -0
  76. package/dist/esm-node/module-federation-css/manifest.mjs +70 -0
  77. package/dist/esm-node/module-federation-css/plugin.mjs +34 -0
  78. package/dist/esm-node/module-federation-css/remote.mjs +93 -0
  79. package/dist/esm-node/runtime-fallback-signal/index.mjs +4 -0
  80. package/dist/esm-node/runtime-fallback-signal/model.mjs +74 -0
  81. package/dist/esm-node/runtime-fallback-signal/resolver.mjs +108 -0
  82. package/dist/esm-node/runtime-fallback-signal/store.mjs +40 -0
  83. package/dist/esm-node/runtimeFallbackSignal.mjs +1 -222
  84. package/dist/esm-node/telemetry/canary.mjs +143 -0
  85. package/dist/esm-node/telemetry/canaryEvaluation.mjs +42 -0
  86. package/dist/esm-node/telemetry/canarySetup.mjs +70 -0
  87. package/dist/esm-node/telemetry/envelope.mjs +165 -0
  88. package/dist/esm-node/telemetry/exporters.mjs +105 -0
  89. package/dist/esm-node/telemetry/lifecycle.mjs +61 -0
  90. package/dist/esm-node/telemetry/metrics.mjs +78 -0
  91. package/dist/esm-node/telemetry/plugin.mjs +88 -0
  92. package/dist/esm-node/telemetry/registry.mjs +259 -0
  93. package/dist/esm-node/telemetry/registryTypes.mjs +9 -0
  94. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +95 -0
  95. package/dist/esm-node/telemetry.mjs +1 -275
  96. package/dist/esm-node/telemetryCore.mjs +6 -759
  97. package/dist/types/contract-gate-snapshot-normalization.d.ts +15 -0
  98. package/dist/types/contract-gate-snapshot-store/file-store.d.ts +3 -0
  99. package/dist/types/contract-gate-snapshot-store/http-store.d.ts +5 -0
  100. package/dist/types/contract-gate-snapshot-store/index.d.ts +5 -0
  101. package/dist/types/contract-gate-snapshot-store/resolve.d.ts +9 -0
  102. package/dist/types/{contractGateSnapshotStore.d.ts → contract-gate-snapshot-store/types.d.ts} +1 -11
  103. package/dist/types/contractGateAutopilot.d.ts +3 -6
  104. package/dist/types/index.d.ts +1 -2
  105. package/dist/types/module-federation-css/collector.d.ts +25 -0
  106. package/dist/types/module-federation-css/index.d.ts +8 -0
  107. package/dist/types/module-federation-css/manifest.d.ts +28 -0
  108. package/dist/types/module-federation-css/plugin.d.ts +23 -0
  109. package/dist/types/module-federation-css/remote.d.ts +20 -0
  110. package/dist/types/runtime-fallback-signal/index.d.ts +4 -0
  111. package/dist/types/runtime-fallback-signal/model.d.ts +70 -0
  112. package/dist/types/runtime-fallback-signal/resolver.d.ts +29 -0
  113. package/dist/types/runtime-fallback-signal/store.d.ts +4 -0
  114. package/dist/types/runtimeFallbackSignal.d.ts +1 -94
  115. package/dist/types/telemetry/canary.d.ts +85 -0
  116. package/dist/types/telemetry/canaryEvaluation.d.ts +20 -0
  117. package/dist/types/telemetry/canarySetup.d.ts +17 -0
  118. package/dist/types/telemetry/envelope.d.ts +55 -0
  119. package/dist/types/telemetry/exporters.d.ts +12 -0
  120. package/dist/types/telemetry/lifecycle.d.ts +18 -0
  121. package/dist/types/telemetry/metrics.d.ts +3 -0
  122. package/dist/types/telemetry/plugin.d.ts +12 -0
  123. package/dist/types/telemetry/registry.d.ts +69 -0
  124. package/dist/types/telemetry/registryTypes.d.ts +50 -0
  125. package/dist/types/telemetry/runtimeEndpoints.d.ts +35 -0
  126. package/dist/types/telemetry.d.ts +1 -12
  127. package/dist/types/telemetryCore.d.ts +6 -257
  128. package/package.json +11 -13
  129. package/src/contract-gate-snapshot-normalization.ts +155 -0
  130. package/src/contract-gate-snapshot-store/file-store.ts +83 -0
  131. package/src/contract-gate-snapshot-store/http-store.ts +159 -0
  132. package/src/contract-gate-snapshot-store/index.ts +20 -0
  133. package/src/contract-gate-snapshot-store/resolve.ts +179 -0
  134. package/src/contract-gate-snapshot-store/types.ts +64 -0
  135. package/src/contractGateAutopilot.ts +39 -131
  136. package/src/index.ts +1 -17
  137. package/src/mfCache.ts +3 -1
  138. package/src/module-federation-css/collector.ts +82 -0
  139. package/src/module-federation-css/index.ts +14 -0
  140. package/src/module-federation-css/manifest.ts +163 -0
  141. package/src/module-federation-css/plugin.ts +86 -0
  142. package/src/module-federation-css/remote.ts +165 -0
  143. package/src/runtime-fallback-signal/index.ts +34 -0
  144. package/src/runtime-fallback-signal/model.ts +230 -0
  145. package/src/runtime-fallback-signal/resolver.ts +304 -0
  146. package/src/runtime-fallback-signal/store.ts +78 -0
  147. package/src/runtimeFallbackSignal.ts +1 -584
  148. package/src/telemetry/canary.ts +291 -0
  149. package/src/telemetry/canaryEvaluation.ts +83 -0
  150. package/src/telemetry/canarySetup.ts +160 -0
  151. package/src/telemetry/envelope.ts +277 -0
  152. package/src/telemetry/exporters.ts +165 -0
  153. package/src/telemetry/lifecycle.ts +138 -0
  154. package/src/telemetry/metrics.ts +141 -0
  155. package/src/telemetry/plugin.ts +197 -0
  156. package/src/telemetry/registry.ts +424 -0
  157. package/src/telemetry/registryTypes.ts +63 -0
  158. package/src/telemetry/runtimeEndpoints.ts +172 -0
  159. package/src/telemetry.ts +1 -554
  160. package/src/telemetryCore.ts +34 -1332
  161. package/tests/contractGateAutopilot.test.ts +205 -0
  162. package/tests/contractGateSnapshotStore.test.ts +54 -1
  163. package/tests/helpers.ts +1 -0
  164. package/tests/moduleFederationCss.test.ts +1 -1
  165. package/tests/registration.test.ts +1 -1
  166. package/tests/telemetry.test.ts +51 -0
  167. package/tests/telemetryAutopilot.test.ts +141 -0
  168. package/tests/telemetryCanaryOrchestrator.test.ts +225 -0
  169. package/tests/telemetryLifecycle.test.ts +253 -2
  170. package/tests/telemetryRegistryQueueMatrix.test.ts +227 -0
  171. package/dist/cjs/contractGateSnapshotStore.js +0 -253
  172. package/dist/cjs/moduleFederationCss.js +0 -285
  173. package/dist/esm/contractGateSnapshotStore.mjs +0 -190
  174. package/dist/esm/moduleFederationCss.mjs +0 -225
  175. package/dist/esm-node/contractGateSnapshotStore.mjs +0 -192
  176. package/dist/esm-node/moduleFederationCss.mjs +0 -226
  177. package/dist/types/moduleFederationCss.d.ts +0 -87
  178. package/src/contractGateSnapshotStore.ts +0 -420
  179. package/src/moduleFederationCss.ts +0 -473
@@ -1,9 +1,12 @@
1
1
  import {
2
- type ContractGateSnapshotStore,
3
- createFileContractGateSnapshotStore,
4
- type GateSnapshot,
5
- type GateSnapshotGateValue,
6
- } from './contractGateSnapshotStore';
2
+ getSnapshotGateNames,
3
+ normalizeSnapshot,
4
+ } from './contract-gate-snapshot-normalization';
5
+ import { createFileContractGateSnapshotStore } from './contract-gate-snapshot-store/file-store';
6
+ import type {
7
+ ContractGateSnapshotStore,
8
+ GateSnapshot,
9
+ } from './contract-gate-snapshot-store/types';
7
10
  import type { TelemetryCanaryOrchestrator } from './telemetryCore';
8
11
 
9
12
  const DEFAULT_POLL_INTERVAL_MS = 15_000;
@@ -23,14 +26,6 @@ export type ContractGateAutopilotOptions = {
23
26
  logger?: LoggerLike;
24
27
  };
25
28
 
26
- type NormalizedGate = {
27
- name: string;
28
- passed: boolean;
29
- reason?: string;
30
- updatedAt: number;
31
- expiresAt?: number;
32
- };
33
-
34
29
  export class ContractGateAutopilot {
35
30
  private readonly orchestrator: TelemetryCanaryOrchestrator;
36
31
  private readonly gateSnapshotStore: ContractGateSnapshotStore;
@@ -39,7 +34,7 @@ export class ContractGateAutopilot {
39
34
  private readonly gateStaleAfterMs: number;
40
35
  private readonly logger?: LoggerLike;
41
36
  private poller?: ReturnType<typeof setInterval>;
42
- private lastSnapshotFingerprint?: string;
37
+ private syncGeneration = 0;
43
38
  private readonly appliedGateFingerprints = new Map<string, string>();
44
39
 
45
40
  constructor(options: ContractGateAutopilotOptions) {
@@ -87,13 +82,23 @@ export class ContractGateAutopilot {
87
82
  }
88
83
 
89
84
  async syncOnce() {
85
+ const syncGeneration = ++this.syncGeneration;
90
86
  const snapshot = await this.loadSnapshot();
87
+ if (syncGeneration !== this.syncGeneration) {
88
+ return 0;
89
+ }
91
90
  if (!snapshot) {
92
91
  return 0;
93
92
  }
94
93
 
95
- const gates = this.normalizeSnapshot(snapshot);
96
- let updatedCount = 0;
94
+ const snapshotGateNames = getSnapshotGateNames(snapshot);
95
+ const gates = normalizeSnapshot(snapshot, {
96
+ now: Date.now(),
97
+ gateStaleAfterMs: this.gateStaleAfterMs,
98
+ });
99
+ let updatedCount = snapshotGateNames
100
+ ? this.clearOmittedGates(snapshotGateNames)
101
+ : 0;
97
102
  for (const gate of gates) {
98
103
  this.orchestrator.addRequiredContractGate(gate.name);
99
104
  const fingerprint = `${gate.passed ? '1' : '0'}:${gate.reason || ''}`;
@@ -112,6 +117,24 @@ export class ContractGateAutopilot {
112
117
  return updatedCount;
113
118
  }
114
119
 
120
+ private clearOmittedGates(snapshotGateNames: ReadonlySet<string>) {
121
+ let updatedCount = 0;
122
+ for (const gateName of Array.from(this.appliedGateFingerprints.keys())) {
123
+ if (snapshotGateNames.has(gateName)) {
124
+ continue;
125
+ }
126
+
127
+ this.orchestrator.setContractGate(gateName, true);
128
+ this.appliedGateFingerprints.delete(gateName);
129
+ updatedCount += 1;
130
+ this.logger?.info?.(
131
+ `[telemetry.canary.autopilot] gate=${gateName} passed=true reason=omitted`,
132
+ );
133
+ }
134
+
135
+ return updatedCount;
136
+ }
137
+
115
138
  private async loadSnapshot() {
116
139
  try {
117
140
  const snapshot = await this.gateSnapshotStore.readSnapshot();
@@ -119,12 +142,6 @@ export class ContractGateAutopilot {
119
142
  return undefined;
120
143
  }
121
144
 
122
- const fingerprint = JSON.stringify(snapshot);
123
- if (fingerprint === this.lastSnapshotFingerprint) {
124
- return undefined;
125
- }
126
- this.lastSnapshotFingerprint = fingerprint;
127
-
128
145
  return snapshot;
129
146
  } catch (error) {
130
147
  const source =
@@ -135,113 +152,4 @@ export class ContractGateAutopilot {
135
152
  return undefined;
136
153
  }
137
154
  }
138
-
139
- private normalizeSnapshot(snapshot: GateSnapshot) {
140
- const now = Date.now();
141
- const output: NormalizedGate[] = [];
142
- const gates = snapshot.gates;
143
- if (!gates || typeof gates !== 'object') {
144
- return output;
145
- }
146
-
147
- for (const [name, value] of Object.entries(gates)) {
148
- const normalizedName = name.trim();
149
- if (!normalizedName) {
150
- continue;
151
- }
152
-
153
- const gate = this.normalizeGateValue(value, snapshot.updatedAt, now);
154
- if (!gate) {
155
- continue;
156
- }
157
-
158
- if (
159
- typeof gate.expiresAt === 'number' &&
160
- Number.isFinite(gate.expiresAt) &&
161
- gate.expiresAt > 0 &&
162
- now >= gate.expiresAt
163
- ) {
164
- output.push({
165
- name: normalizedName,
166
- passed: true,
167
- reason: undefined,
168
- updatedAt: gate.updatedAt,
169
- expiresAt: gate.expiresAt,
170
- });
171
- continue;
172
- }
173
-
174
- const isStale =
175
- this.gateStaleAfterMs > 0 &&
176
- now - gate.updatedAt > this.gateStaleAfterMs;
177
- if (isStale) {
178
- output.push({
179
- name: normalizedName,
180
- passed: false,
181
- reason: gate.reason || 'Gate snapshot is stale',
182
- updatedAt: gate.updatedAt,
183
- });
184
- continue;
185
- }
186
-
187
- output.push({
188
- name: normalizedName,
189
- passed: gate.passed,
190
- reason: gate.reason,
191
- updatedAt: gate.updatedAt,
192
- });
193
- }
194
-
195
- return output;
196
- }
197
-
198
- private normalizeGateValue(
199
- value: GateSnapshotGateValue,
200
- snapshotUpdatedAt: number | undefined,
201
- now: number,
202
- ) {
203
- if (typeof value === 'boolean') {
204
- return {
205
- passed: value,
206
- updatedAt: this.normalizeUpdatedAt(snapshotUpdatedAt, now),
207
- };
208
- }
209
-
210
- if (!value || typeof value !== 'object') {
211
- return undefined;
212
- }
213
-
214
- const hasPassed = typeof value.passed === 'boolean';
215
- const passed = value.passed === true;
216
- let reason =
217
- typeof value.reason === 'string' && value.reason.trim().length > 0
218
- ? value.reason
219
- : undefined;
220
- if (!hasPassed) {
221
- reason = reason || 'Gate snapshot record is missing "passed" boolean';
222
- }
223
- return {
224
- passed,
225
- reason,
226
- updatedAt: this.normalizeUpdatedAt(
227
- value.updatedAt ?? snapshotUpdatedAt,
228
- now,
229
- ),
230
- expiresAt: this.normalizeExpiresAt(value.expiresAt),
231
- };
232
- }
233
-
234
- private normalizeUpdatedAt(value: number | undefined, fallback: number) {
235
- if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
236
- return value;
237
- }
238
- return fallback;
239
- }
240
-
241
- private normalizeExpiresAt(value: number | undefined) {
242
- if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
243
- return value;
244
- }
245
- return undefined;
246
- }
247
155
  }
package/src/index.ts CHANGED
@@ -2,22 +2,6 @@ export {
2
2
  ContractGateAutopilot,
3
3
  type ContractGateAutopilotOptions,
4
4
  } from './contractGateAutopilot';
5
- export {
6
- CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
7
- type ContractGateSnapshotHttpStoreOptions,
8
- type ContractGateSnapshotStore,
9
- type ContractGateSnapshotStoreFactory,
10
- type ContractGateSnapshotStoreFactoryContext,
11
- type ContractGateSnapshotStoreModule,
12
- type ContractGateSnapshotStoreUserConfig,
13
- createFileContractGateSnapshotStore,
14
- createHttpContractGateSnapshotStore,
15
- DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH,
16
- type GateSnapshot,
17
- type GateSnapshotGateValue,
18
- resolveContractGateSnapshotPath,
19
- resolveContractGateSnapshotStore,
20
- } from './contractGateSnapshotStore';
21
5
  export {
22
6
  DEFAULT_ENVIRONMENT_NAME,
23
7
  parseServerRuntimeExtensionsEnv,
@@ -41,7 +25,7 @@ export {
41
25
  type ModuleFederationCssPluginOptions,
42
26
  type ModuleFederationManifest,
43
27
  type RemoteModuleFederationCssCollection,
44
- } from './moduleFederationCss';
28
+ } from './module-federation-css';
45
29
  export {
46
30
  createOtlpTelemetryExporter,
47
31
  createRuntimeFallbackSignalRuntimeState,
package/src/mfCache.ts CHANGED
@@ -4,7 +4,8 @@ import type {
4
4
  ServerPlugin,
5
5
  } from '@modern-js/server-core';
6
6
 
7
- const REMOTE_ENTRY_REGEXP = /(^|\/)remoteEntry(?:\.[a-zA-Z0-9_-]+)?\.js$/;
7
+ const REMOTE_ENTRY_REGEXP =
8
+ /(^|\/)(?:backendRemoteEntry\.cjs|remoteEntry(?:\.[a-zA-Z0-9_-]+)?\.js)$/;
8
9
 
9
10
  function firstQueryValue(value: unknown): string | undefined {
10
11
  if (Array.isArray(value)) {
@@ -26,6 +27,7 @@ export function getRequestPathname(url: string) {
26
27
 
27
28
  export function isMfManifestAsset(pathname: string) {
28
29
  return (
30
+ pathname.endsWith('/backend-mf-manifest.json') ||
29
31
  pathname.endsWith('/mf-manifest.json') ||
30
32
  pathname.endsWith('/mf-stats.json')
31
33
  );
@@ -0,0 +1,82 @@
1
+ import type { Monitors } from '@modern-js/types';
2
+
3
+ import type { CollectDirectRemoteModuleFederationCssOptions } from './remote';
4
+
5
+ import { collectDirectRemoteModuleFederationCssWithMeta } from './remote';
6
+
7
+ export type ModuleFederationCssCollectorOptions =
8
+ CollectDirectRemoteModuleFederationCssOptions & {
9
+ /**
10
+ * How long a successful remote CSS collection may be served from cache.
11
+ * `0` disables caching (beyond in-flight request coalescing).
12
+ */
13
+ ttlMs?: number;
14
+ /** Clock override for tests. */
15
+ now?: () => number;
16
+ };
17
+
18
+ /**
19
+ * TTL cache around remote MF CSS collection. Remote manifests mutate
20
+ * independently of the host (that is the point of module federation), so the
21
+ * collection must expire: a boot-time-forever cache serves stale or broken
22
+ * CSS links after any remote redeploy.
23
+ *
24
+ * Error handling: a collection where any remote fetch failed is never cached.
25
+ * The last known-good asset list is served instead (stale-on-error) and the
26
+ * next request retries the collection.
27
+ */
28
+ export const createModuleFederationCssCollector = (
29
+ pwd: string,
30
+ options: ModuleFederationCssCollectorOptions = {},
31
+ ) => {
32
+ const { ttlMs = 0, now = Date.now, ...collectOptions } = options;
33
+ const normalizedTtlMs = Math.max(0, ttlMs);
34
+
35
+ let cached: { assets: string[]; expiresAt: number } | undefined;
36
+ let lastGoodAssets: string[] | undefined;
37
+ let inflight: Promise<string[]> | undefined;
38
+
39
+ const refresh = (monitors?: Monitors) => {
40
+ const promise = collectDirectRemoteModuleFederationCssWithMeta(pwd, {
41
+ ...collectOptions,
42
+ monitors: monitors ?? collectOptions.monitors,
43
+ })
44
+ .then(result => {
45
+ if (!result.errored) {
46
+ lastGoodAssets = result.assets;
47
+ cached = {
48
+ assets: result.assets,
49
+ expiresAt: now() + normalizedTtlMs,
50
+ };
51
+ return result.assets;
52
+ }
53
+
54
+ // Error path: invalidate so the next request retries, and serve the
55
+ // last known-good list when one exists.
56
+ cached = undefined;
57
+ return lastGoodAssets ?? result.assets;
58
+ })
59
+ .finally(() => {
60
+ if (inflight === promise) {
61
+ inflight = undefined;
62
+ }
63
+ });
64
+
65
+ inflight = promise;
66
+ return promise;
67
+ };
68
+
69
+ return {
70
+ collect(monitors?: Monitors): Promise<string[]> {
71
+ if (cached && now() < cached.expiresAt) {
72
+ return Promise.resolve(cached.assets);
73
+ }
74
+ if (inflight) {
75
+ return inflight;
76
+ }
77
+ return refresh(monitors);
78
+ },
79
+ };
80
+ };
81
+
82
+ export const DEFAULT_REMOTE_CSS_CACHE_TTL_MS = 30_000;
@@ -0,0 +1,14 @@
1
+ export type { ModuleFederationCssCollectorOptions } from './collector';
2
+ export { createModuleFederationCssCollector } from './collector';
3
+ export type { ModuleFederationManifest } from './manifest';
4
+ export { collectModuleFederationManifestCss } from './manifest';
5
+ export type { ModuleFederationCssPluginOptions } from './plugin';
6
+ export { injectModuleFederationCssPlugin } from './plugin';
7
+ export type {
8
+ CollectDirectRemoteModuleFederationCssOptions,
9
+ RemoteModuleFederationCssCollection,
10
+ } from './remote';
11
+ export {
12
+ collectDirectRemoteModuleFederationCss,
13
+ collectDirectRemoteModuleFederationCssWithMeta,
14
+ } from './remote';
@@ -0,0 +1,163 @@
1
+ import path from 'node:path';
2
+ import { fileReader } from '@modern-js/runtime-utils/fileReader';
3
+ import type { Monitors } from '@modern-js/types';
4
+ import { fs } from '@modern-js/utils';
5
+
6
+ const MODULE_FEDERATION_MANIFEST_FILE = 'mf-manifest.json';
7
+
8
+ type ModuleFederationAssets = {
9
+ css?: {
10
+ sync?: string[];
11
+ async?: string[];
12
+ };
13
+ };
14
+
15
+ export type ModuleFederationManifest = {
16
+ metaData?: {
17
+ publicPath?: string;
18
+ };
19
+ shared?: Array<{
20
+ assets?: ModuleFederationAssets;
21
+ }>;
22
+ remotes?: Array<{
23
+ entry?: string;
24
+ assets?: ModuleFederationAssets;
25
+ }>;
26
+ exposes?: Array<{
27
+ assets?: ModuleFederationAssets;
28
+ }>;
29
+ };
30
+
31
+ export const warn = (
32
+ monitors: Monitors | undefined,
33
+ message: string,
34
+ ...args: unknown[]
35
+ ) => {
36
+ if (monitors) {
37
+ monitors.warn(message, ...args);
38
+ return;
39
+ }
40
+
41
+ console.warn(message, ...args);
42
+ };
43
+
44
+ export const ensureTrailingSlash = (value: string) =>
45
+ value.endsWith('/') ? value : `${value}/`;
46
+
47
+ const tryResolveUrl = (value: string, base: string) => {
48
+ try {
49
+ return new URL(value, base).toString();
50
+ } catch {
51
+ return undefined;
52
+ }
53
+ };
54
+
55
+ export const normalizeRemoteEntry = (entry: string) => {
56
+ const value = entry.trim();
57
+ if (!value) {
58
+ return undefined;
59
+ }
60
+
61
+ const atIndex = value.lastIndexOf('@');
62
+ return atIndex >= 0 ? value.slice(atIndex + 1) : value;
63
+ };
64
+
65
+ const getCssAssets = (assets?: ModuleFederationAssets) => [
66
+ ...(assets?.css?.sync || []),
67
+ ...(assets?.css?.async || []),
68
+ ];
69
+
70
+ const getManifestFallbackBase = (manifestUrl: string) => {
71
+ try {
72
+ return new URL('.', manifestUrl).toString();
73
+ } catch {
74
+ return ensureTrailingSlash(manifestUrl);
75
+ }
76
+ };
77
+
78
+ const getManifestPublicPathBase = (
79
+ publicPath: string | undefined,
80
+ manifestUrl: string,
81
+ ) => {
82
+ if (!publicPath || publicPath === 'auto') {
83
+ return getManifestFallbackBase(manifestUrl);
84
+ }
85
+
86
+ const base = tryResolveUrl(ensureTrailingSlash(publicPath), manifestUrl);
87
+ return base || getManifestFallbackBase(manifestUrl);
88
+ };
89
+
90
+ const appendResolvedCssAssets = (
91
+ result: string[],
92
+ seen: Set<string>,
93
+ assets: string[],
94
+ base: string,
95
+ ) => {
96
+ for (const asset of assets) {
97
+ if (!asset) {
98
+ continue;
99
+ }
100
+
101
+ const resolved = tryResolveUrl(asset, base);
102
+
103
+ if (resolved && !seen.has(resolved)) {
104
+ seen.add(resolved);
105
+ result.push(resolved);
106
+ }
107
+ }
108
+ };
109
+
110
+ export const collectModuleFederationManifestCss = (
111
+ manifest: ModuleFederationManifest,
112
+ manifestUrl: string,
113
+ ) => {
114
+ const base = getManifestPublicPathBase(
115
+ manifest.metaData?.publicPath,
116
+ manifestUrl,
117
+ );
118
+ const result: string[] = [];
119
+ const seen = new Set<string>();
120
+
121
+ for (const item of manifest.shared || []) {
122
+ appendResolvedCssAssets(result, seen, getCssAssets(item.assets), base);
123
+ }
124
+
125
+ for (const item of manifest.exposes || []) {
126
+ appendResolvedCssAssets(result, seen, getCssAssets(item.assets), base);
127
+ }
128
+
129
+ return result;
130
+ };
131
+
132
+ export const getHostManifest = async (
133
+ pwd: string,
134
+ monitors?: Monitors,
135
+ ): Promise<ModuleFederationManifest | undefined> => {
136
+ const manifestPath = path.join(pwd, MODULE_FEDERATION_MANIFEST_FILE);
137
+
138
+ if (!(await fs.pathExists(manifestPath))) {
139
+ return undefined;
140
+ }
141
+
142
+ const manifestBuffer = await fileReader.readFileFromSystem(
143
+ manifestPath,
144
+ 'buffer',
145
+ );
146
+
147
+ if (manifestBuffer === null) {
148
+ return undefined;
149
+ }
150
+
151
+ try {
152
+ return JSON.parse(
153
+ manifestBuffer.toString('utf-8'),
154
+ ) as ModuleFederationManifest;
155
+ } catch (error) {
156
+ warn(
157
+ monitors,
158
+ 'Parse module federation manifest failed, error = %s',
159
+ error instanceof Error ? error.message : error,
160
+ );
161
+ return undefined;
162
+ }
163
+ };
@@ -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
+ });