@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.5 → 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,225 +0,0 @@
1
- import { fileReader } from "@modern-js/runtime-utils/fileReader";
2
- import { fs, isProd } from "@modern-js/utils";
3
- import path from "path";
4
- const MODULE_FEDERATION_MANIFEST_FILE = 'mf-manifest.json';
5
- const DEFAULT_REMOTE_MANIFEST_TIMEOUT = 1500;
6
- const warn = (monitors, message, ...args)=>{
7
- if (monitors) return void monitors.warn(message, ...args);
8
- console.warn(message, ...args);
9
- };
10
- const ensureTrailingSlash = (value)=>value.endsWith('/') ? value : `${value}/`;
11
- const tryResolveUrl = (value, base)=>{
12
- try {
13
- return new URL(value, base).toString();
14
- } catch {
15
- return;
16
- }
17
- };
18
- const normalizeRemoteEntry = (entry)=>{
19
- const value = entry.trim();
20
- if (!value) return;
21
- const atIndex = value.lastIndexOf('@');
22
- return atIndex >= 0 ? value.slice(atIndex + 1) : value;
23
- };
24
- const getCssAssets = (assets)=>[
25
- ...assets?.css?.sync || [],
26
- ...assets?.css?.async || []
27
- ];
28
- const getManifestFallbackBase = (manifestUrl)=>{
29
- try {
30
- return new URL('.', manifestUrl).toString();
31
- } catch {
32
- return ensureTrailingSlash(manifestUrl);
33
- }
34
- };
35
- const getManifestPublicPathBase = (publicPath, manifestUrl)=>{
36
- if (!publicPath || 'auto' === publicPath) return getManifestFallbackBase(manifestUrl);
37
- const base = tryResolveUrl(ensureTrailingSlash(publicPath), manifestUrl);
38
- return base || getManifestFallbackBase(manifestUrl);
39
- };
40
- const appendResolvedCssAssets = (result, seen, assets, base)=>{
41
- for (const asset of assets){
42
- if (!asset) continue;
43
- const resolved = tryResolveUrl(asset, base);
44
- if (resolved && !seen.has(resolved)) {
45
- seen.add(resolved);
46
- result.push(resolved);
47
- }
48
- }
49
- };
50
- const collectModuleFederationManifestCss = (manifest, manifestUrl)=>{
51
- const base = getManifestPublicPathBase(manifest.metaData?.publicPath, manifestUrl);
52
- const result = [];
53
- const seen = new Set();
54
- for (const item of manifest.shared || [])appendResolvedCssAssets(result, seen, getCssAssets(item.assets), base);
55
- for (const item of manifest.exposes || [])appendResolvedCssAssets(result, seen, getCssAssets(item.assets), base);
56
- return result;
57
- };
58
- const fetchJsonWithTimeout = async (url, fetcher, timeout)=>{
59
- const controller = new AbortController();
60
- let timeoutId;
61
- try {
62
- const response = await Promise.race([
63
- fetcher(url, {
64
- signal: controller.signal
65
- }),
66
- new Promise((_, reject)=>{
67
- timeoutId = setTimeout(()=>{
68
- controller.abort();
69
- reject(new Error(`Request timed out after ${timeout}ms`));
70
- }, timeout);
71
- })
72
- ]);
73
- if (!response.ok) throw new Error(`Unexpected status ${response.status}`);
74
- return await response.json();
75
- } finally{
76
- if (timeoutId) clearTimeout(timeoutId);
77
- }
78
- };
79
- const getHostManifest = async (pwd, monitors)=>{
80
- const manifestPath = path.join(pwd, MODULE_FEDERATION_MANIFEST_FILE);
81
- if (!await fs.pathExists(manifestPath)) return;
82
- const manifestBuffer = await fileReader.readFileFromSystem(manifestPath, 'buffer');
83
- if (null === manifestBuffer) return;
84
- try {
85
- return JSON.parse(manifestBuffer.toString('utf-8'));
86
- } catch (error) {
87
- warn(monitors, 'Parse module federation manifest failed, error = %s', error instanceof Error ? error.message : error);
88
- return;
89
- }
90
- };
91
- const collectDirectRemoteModuleFederationCssWithMeta = async (pwd, options = {})=>{
92
- const hostManifest = await getHostManifest(pwd, options.monitors);
93
- if (!hostManifest) return {
94
- assets: [],
95
- errored: false
96
- };
97
- const fetcher = options.fetcher || globalThis.fetch?.bind(globalThis);
98
- if (!fetcher) {
99
- warn(options.monitors, 'Skip module federation remote CSS collection because fetch is unavailable.');
100
- return {
101
- assets: [],
102
- errored: false
103
- };
104
- }
105
- const timeout = options.timeout ?? DEFAULT_REMOTE_MANIFEST_TIMEOUT;
106
- const remoteResults = await Promise.all((hostManifest.remotes || []).map(async (remote)=>{
107
- if (!remote.entry) return {
108
- assets: [],
109
- errored: false
110
- };
111
- const remoteEntry = normalizeRemoteEntry(remote.entry);
112
- if (!remoteEntry) return {
113
- assets: [],
114
- errored: false
115
- };
116
- let remoteManifestUrl;
117
- try {
118
- remoteManifestUrl = new URL(remoteEntry).toString();
119
- } catch {
120
- warn(options.monitors, 'Skip module federation remote CSS collection for non-absolute manifest URL %s', remoteEntry);
121
- return {
122
- assets: [],
123
- errored: false
124
- };
125
- }
126
- try {
127
- const remoteManifest = await fetchJsonWithTimeout(remoteManifestUrl, fetcher, timeout);
128
- return {
129
- assets: collectModuleFederationManifestCss(remoteManifest, remoteManifestUrl),
130
- errored: false
131
- };
132
- } catch (error) {
133
- warn(options.monitors, 'Load module federation remote manifest %s failed, error = %s', remoteManifestUrl, error instanceof Error ? error.message : error);
134
- return {
135
- assets: [],
136
- errored: true
137
- };
138
- }
139
- }));
140
- const cssAssets = [];
141
- const seen = new Set();
142
- let errored = false;
143
- for (const result of remoteResults){
144
- errored = errored || result.errored;
145
- for (const asset of result.assets)if (!seen.has(asset)) {
146
- seen.add(asset);
147
- cssAssets.push(asset);
148
- }
149
- }
150
- return {
151
- assets: cssAssets,
152
- errored
153
- };
154
- };
155
- const collectDirectRemoteModuleFederationCss = async (pwd, options = {})=>{
156
- const { assets } = await collectDirectRemoteModuleFederationCssWithMeta(pwd, options);
157
- return assets;
158
- };
159
- const createModuleFederationCssCollector = (pwd, options = {})=>{
160
- const { ttlMs = 0, now = Date.now, ...collectOptions } = options;
161
- const normalizedTtlMs = Math.max(0, ttlMs);
162
- let cached;
163
- let lastGoodAssets;
164
- let inflight;
165
- const refresh = (monitors)=>{
166
- const promise = collectDirectRemoteModuleFederationCssWithMeta(pwd, {
167
- ...collectOptions,
168
- monitors: monitors ?? collectOptions.monitors
169
- }).then((result)=>{
170
- if (!result.errored) {
171
- lastGoodAssets = result.assets;
172
- cached = {
173
- assets: result.assets,
174
- expiresAt: now() + normalizedTtlMs
175
- };
176
- return result.assets;
177
- }
178
- cached = void 0;
179
- return lastGoodAssets ?? result.assets;
180
- }).finally(()=>{
181
- if (inflight === promise) inflight = void 0;
182
- });
183
- inflight = promise;
184
- return promise;
185
- };
186
- return {
187
- collect (monitors) {
188
- if (cached && now() < cached.expiresAt) return Promise.resolve(cached.assets);
189
- if (inflight) return inflight;
190
- return refresh(monitors);
191
- }
192
- };
193
- };
194
- const DEFAULT_REMOTE_CSS_CACHE_TTL_MS = 30000;
195
- const injectModuleFederationCssPlugin = (options = {})=>({
196
- name: '@modern-js/inject-module-federation-css',
197
- setup (api) {
198
- api.onPrepare(()=>{
199
- const { middlewares, distDirectory: pwd } = api.getServerContext();
200
- if (!pwd) return;
201
- const ttlMs = Math.max(0, options.remoteCssCacheTtlMs ?? (isProd() ? DEFAULT_REMOTE_CSS_CACHE_TTL_MS : 0));
202
- const collector = createModuleFederationCssCollector(pwd, {
203
- ttlMs
204
- });
205
- if (isProd()) collector.collect().catch(()=>{});
206
- const handler = async (c, next)=>{
207
- const serverManifest = c.get('serverManifest');
208
- if (serverManifest && !serverManifest.moduleFederationCssAssets) {
209
- const monitors = c.get('monitors');
210
- const moduleFederationCssAssets = await collector.collect(monitors);
211
- c.set('serverManifest', {
212
- ...serverManifest,
213
- moduleFederationCssAssets
214
- });
215
- }
216
- await next();
217
- };
218
- middlewares.push({
219
- name: 'inject-module-federation-css',
220
- handler
221
- });
222
- });
223
- }
224
- });
225
- export { collectDirectRemoteModuleFederationCss, collectDirectRemoteModuleFederationCssWithMeta, collectModuleFederationManifestCss, createModuleFederationCssCollector, injectModuleFederationCssPlugin };
@@ -1,192 +0,0 @@
1
- import __rslib_shim_module__ from "node:module";
2
- const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(/*#__PURE__*/ (()=>import.meta.url)());
3
- import { createRequire } from "node:module";
4
- import { fs } from "@modern-js/utils";
5
- import { promises } from "fs";
6
- import path from "path";
7
- import { parseServerRuntimeExtensionsEnv } from "./env.mjs";
8
- const CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION = 1;
9
- const DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH = '.modern/contract-gates.json';
10
- const DEFAULT_HTTP_STORE_TIMEOUT_MS = 5000;
11
- const BUILTIN_HTTP_STATE_STORE_MODULES = new Set([
12
- 'http',
13
- '@modern-js/server-core/http',
14
- '@modern-js/server-core/contract-gate-http-store',
15
- '@modern-js/server-runtime-extensions/http',
16
- '@modern-js/server-runtime-extensions/contract-gate-http-store'
17
- ]);
18
- const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
19
- const normalizeSnapshot = (snapshot)=>{
20
- if (!isRecord(snapshot)) return;
21
- const schemaVersion = 'number' == typeof snapshot.schemaVersion ? snapshot.schemaVersion : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
22
- const updatedAt = 'number' == typeof snapshot.updatedAt ? snapshot.updatedAt : Date.now();
23
- const gates = isRecord(snapshot.gates) ? snapshot.gates : {};
24
- return {
25
- schemaVersion,
26
- updatedAt,
27
- gates
28
- };
29
- };
30
- const normalizeHttpStoreOptions = (options)=>{
31
- const endpoint = 'string' == typeof options?.endpoint ? options.endpoint.trim() : '';
32
- if (!endpoint) throw new Error('[telemetry.canary.autopilot] HTTP stateStore requires options.endpoint');
33
- const readMethod = 'string' == typeof options?.readMethod && options.readMethod.trim() ? options.readMethod.trim().toUpperCase() : 'GET';
34
- const writeMethod = 'string' == typeof options?.writeMethod && options.writeMethod.trim() ? options.writeMethod.trim().toUpperCase() : 'PUT';
35
- const timeoutMsRaw = Number(options?.timeoutMs);
36
- const timeoutMs = Number.isFinite(timeoutMsRaw) && timeoutMsRaw > 0 ? Math.floor(timeoutMsRaw) : DEFAULT_HTTP_STORE_TIMEOUT_MS;
37
- const headersRaw = options?.headers;
38
- const headers = {};
39
- if (headersRaw && 'object' == typeof headersRaw && !Array.isArray(headersRaw)) Object.entries(headersRaw).forEach(([key, value])=>{
40
- if ('string' == typeof key && key.trim().length > 0 && null != value) headers[key] = String(value);
41
- });
42
- return {
43
- endpoint,
44
- readMethod,
45
- writeMethod,
46
- headers,
47
- timeoutMs
48
- };
49
- };
50
- const withTimeoutAbort = (timeoutMs)=>{
51
- const controller = new AbortController();
52
- const timer = setTimeout(()=>controller.abort(), timeoutMs);
53
- return {
54
- signal: controller.signal,
55
- clear: ()=>clearTimeout(timer)
56
- };
57
- };
58
- const createHttpContractGateSnapshotStore = (options)=>{
59
- const normalized = normalizeHttpStoreOptions(options);
60
- const endpoint = normalized.endpoint;
61
- return {
62
- name: `http:${endpoint}`,
63
- async readSnapshot () {
64
- const { signal, clear } = withTimeoutAbort(normalized.timeoutMs || 5000);
65
- try {
66
- const response = await fetch(endpoint, {
67
- method: normalized.readMethod || 'GET',
68
- headers: {
69
- accept: 'application/json',
70
- ...normalized.headers || {}
71
- },
72
- signal
73
- });
74
- if (404 === response.status) return;
75
- if (!response.ok) throw new Error(`HTTP stateStore read failed with status ${String(response.status)}`);
76
- const payload = await response.json();
77
- return normalizeSnapshot(payload);
78
- } finally{
79
- clear();
80
- }
81
- },
82
- async writeSnapshot (snapshot) {
83
- const body = JSON.stringify(normalizeSnapshot(snapshot) || {
84
- schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
85
- updatedAt: Date.now(),
86
- gates: {}
87
- });
88
- const { signal, clear } = withTimeoutAbort(normalized.timeoutMs || 5000);
89
- try {
90
- const response = await fetch(endpoint, {
91
- method: normalized.writeMethod || 'PUT',
92
- headers: {
93
- 'content-type': 'application/json',
94
- ...normalized.headers || {}
95
- },
96
- body,
97
- signal
98
- });
99
- if (!response.ok) throw new Error(`HTTP stateStore write failed with status ${String(response.status)}`);
100
- } finally{
101
- clear();
102
- }
103
- }
104
- };
105
- };
106
- const tryResolveBuiltinSnapshotStore = (input)=>{
107
- const moduleName = input.stateStore.module.trim();
108
- if (!BUILTIN_HTTP_STATE_STORE_MODULES.has(moduleName)) return;
109
- return createHttpContractGateSnapshotStore(input.stateStore.options || {});
110
- };
111
- const pickStoreFactory = (mod)=>{
112
- if ('function' == typeof mod) return mod;
113
- if ('function' == typeof mod.createContractGateSnapshotStore) return mod.createContractGateSnapshotStore;
114
- if ('function' == typeof mod.default) return mod.default;
115
- if (mod.default && 'object' == typeof mod.default && 'function' == typeof mod.default.createContractGateSnapshotStore) return mod.default.createContractGateSnapshotStore;
116
- };
117
- const ensureStoreShape = (store, modulePath)=>{
118
- if (!store || 'object' != typeof store || 'function' != typeof store.readSnapshot || 'function' != typeof store.writeSnapshot) throw new Error(`Invalid contract gate snapshot store from "${modulePath}". Expected { readSnapshot(), writeSnapshot() }.`);
119
- };
120
- const resolveStoreModulePath = (appDirectory, modulePath)=>{
121
- const normalized = modulePath.trim();
122
- if (!normalized) throw new Error('Contract gate snapshot stateStore.module must be non-empty');
123
- if (path.isAbsolute(normalized)) return normalized;
124
- if (normalized.startsWith('.')) return path.resolve(appDirectory, normalized);
125
- const appRequire = createRequire(path.join(appDirectory, 'package.json'));
126
- try {
127
- return appRequire.resolve(normalized);
128
- } catch (_error) {
129
- return normalized;
130
- }
131
- };
132
- const resolveContractGateSnapshotPath = (appDirectory, configuredPath)=>{
133
- const rawPath = configuredPath || parseServerRuntimeExtensionsEnv().contractGatesFile || DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH;
134
- if (path.isAbsolute(rawPath)) return rawPath;
135
- return path.resolve(appDirectory, rawPath);
136
- };
137
- const createFileContractGateSnapshotStore = (gateSnapshotPath)=>{
138
- const resolvedPath = path.resolve(gateSnapshotPath);
139
- return {
140
- name: `file:${resolvedPath}`,
141
- async readSnapshot () {
142
- if (!await fs.pathExists(resolvedPath)) return;
143
- try {
144
- const raw = await promises.readFile(resolvedPath, 'utf8');
145
- return normalizeSnapshot(JSON.parse(raw));
146
- } catch (_error) {
147
- return;
148
- }
149
- },
150
- async writeSnapshot (snapshot) {
151
- const normalized = normalizeSnapshot(snapshot) || {
152
- schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
153
- updatedAt: Date.now(),
154
- gates: {}
155
- };
156
- await promises.mkdir(path.dirname(resolvedPath), {
157
- recursive: true
158
- });
159
- await promises.writeFile(resolvedPath, `${JSON.stringify(normalized, null, 2)}\n`);
160
- }
161
- };
162
- };
163
- const resolveContractGateSnapshotStore = async (input)=>{
164
- const { appDirectory, gateSnapshotPath, stateStore, logger } = input;
165
- if (!stateStore?.module) return createFileContractGateSnapshotStore(gateSnapshotPath);
166
- const builtinStore = tryResolveBuiltinSnapshotStore({
167
- stateStore
168
- });
169
- if (builtinStore) {
170
- logger?.info?.(`[telemetry.canary.autopilot] using built-in contract gate snapshot store "${builtinStore.name}"`);
171
- return builtinStore;
172
- }
173
- const modulePath = resolveStoreModulePath(appDirectory, stateStore.module);
174
- let mod;
175
- try {
176
- mod = require(modulePath);
177
- } catch (error) {
178
- throw new Error(`[telemetry.canary.autopilot] Failed to load stateStore.module "${stateStore.module}" (${modulePath}): ${error instanceof Error ? error.message : String(error)}`);
179
- }
180
- const factory = pickStoreFactory(mod);
181
- if (!factory) throw new Error(`[telemetry.canary.autopilot] stateStore.module "${stateStore.module}" does not export createContractGateSnapshotStore()`);
182
- const store = await factory({
183
- appDirectory,
184
- gateSnapshotPath,
185
- options: stateStore.options,
186
- logger
187
- });
188
- ensureStoreShape(store, modulePath);
189
- logger?.info?.(`[telemetry.canary.autopilot] using contract gate snapshot store "${store.name || modulePath}"`);
190
- return store;
191
- };
192
- export { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION, DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH, createFileContractGateSnapshotStore, createHttpContractGateSnapshotStore, resolveContractGateSnapshotPath, resolveContractGateSnapshotStore };
@@ -1,226 +0,0 @@
1
- import "node:module";
2
- import { fileReader } from "@modern-js/runtime-utils/fileReader";
3
- import { fs, isProd } from "@modern-js/utils";
4
- import path from "path";
5
- const MODULE_FEDERATION_MANIFEST_FILE = 'mf-manifest.json';
6
- const DEFAULT_REMOTE_MANIFEST_TIMEOUT = 1500;
7
- const warn = (monitors, message, ...args)=>{
8
- if (monitors) return void monitors.warn(message, ...args);
9
- console.warn(message, ...args);
10
- };
11
- const ensureTrailingSlash = (value)=>value.endsWith('/') ? value : `${value}/`;
12
- const tryResolveUrl = (value, base)=>{
13
- try {
14
- return new URL(value, base).toString();
15
- } catch {
16
- return;
17
- }
18
- };
19
- const normalizeRemoteEntry = (entry)=>{
20
- const value = entry.trim();
21
- if (!value) return;
22
- const atIndex = value.lastIndexOf('@');
23
- return atIndex >= 0 ? value.slice(atIndex + 1) : value;
24
- };
25
- const getCssAssets = (assets)=>[
26
- ...assets?.css?.sync || [],
27
- ...assets?.css?.async || []
28
- ];
29
- const getManifestFallbackBase = (manifestUrl)=>{
30
- try {
31
- return new URL('.', manifestUrl).toString();
32
- } catch {
33
- return ensureTrailingSlash(manifestUrl);
34
- }
35
- };
36
- const getManifestPublicPathBase = (publicPath, manifestUrl)=>{
37
- if (!publicPath || 'auto' === publicPath) return getManifestFallbackBase(manifestUrl);
38
- const base = tryResolveUrl(ensureTrailingSlash(publicPath), manifestUrl);
39
- return base || getManifestFallbackBase(manifestUrl);
40
- };
41
- const appendResolvedCssAssets = (result, seen, assets, base)=>{
42
- for (const asset of assets){
43
- if (!asset) continue;
44
- const resolved = tryResolveUrl(asset, base);
45
- if (resolved && !seen.has(resolved)) {
46
- seen.add(resolved);
47
- result.push(resolved);
48
- }
49
- }
50
- };
51
- const collectModuleFederationManifestCss = (manifest, manifestUrl)=>{
52
- const base = getManifestPublicPathBase(manifest.metaData?.publicPath, manifestUrl);
53
- const result = [];
54
- const seen = new Set();
55
- for (const item of manifest.shared || [])appendResolvedCssAssets(result, seen, getCssAssets(item.assets), base);
56
- for (const item of manifest.exposes || [])appendResolvedCssAssets(result, seen, getCssAssets(item.assets), base);
57
- return result;
58
- };
59
- const fetchJsonWithTimeout = async (url, fetcher, timeout)=>{
60
- const controller = new AbortController();
61
- let timeoutId;
62
- try {
63
- const response = await Promise.race([
64
- fetcher(url, {
65
- signal: controller.signal
66
- }),
67
- new Promise((_, reject)=>{
68
- timeoutId = setTimeout(()=>{
69
- controller.abort();
70
- reject(new Error(`Request timed out after ${timeout}ms`));
71
- }, timeout);
72
- })
73
- ]);
74
- if (!response.ok) throw new Error(`Unexpected status ${response.status}`);
75
- return await response.json();
76
- } finally{
77
- if (timeoutId) clearTimeout(timeoutId);
78
- }
79
- };
80
- const getHostManifest = async (pwd, monitors)=>{
81
- const manifestPath = path.join(pwd, MODULE_FEDERATION_MANIFEST_FILE);
82
- if (!await fs.pathExists(manifestPath)) return;
83
- const manifestBuffer = await fileReader.readFileFromSystem(manifestPath, 'buffer');
84
- if (null === manifestBuffer) return;
85
- try {
86
- return JSON.parse(manifestBuffer.toString('utf-8'));
87
- } catch (error) {
88
- warn(monitors, 'Parse module federation manifest failed, error = %s', error instanceof Error ? error.message : error);
89
- return;
90
- }
91
- };
92
- const collectDirectRemoteModuleFederationCssWithMeta = async (pwd, options = {})=>{
93
- const hostManifest = await getHostManifest(pwd, options.monitors);
94
- if (!hostManifest) return {
95
- assets: [],
96
- errored: false
97
- };
98
- const fetcher = options.fetcher || globalThis.fetch?.bind(globalThis);
99
- if (!fetcher) {
100
- warn(options.monitors, 'Skip module federation remote CSS collection because fetch is unavailable.');
101
- return {
102
- assets: [],
103
- errored: false
104
- };
105
- }
106
- const timeout = options.timeout ?? DEFAULT_REMOTE_MANIFEST_TIMEOUT;
107
- const remoteResults = await Promise.all((hostManifest.remotes || []).map(async (remote)=>{
108
- if (!remote.entry) return {
109
- assets: [],
110
- errored: false
111
- };
112
- const remoteEntry = normalizeRemoteEntry(remote.entry);
113
- if (!remoteEntry) return {
114
- assets: [],
115
- errored: false
116
- };
117
- let remoteManifestUrl;
118
- try {
119
- remoteManifestUrl = new URL(remoteEntry).toString();
120
- } catch {
121
- warn(options.monitors, 'Skip module federation remote CSS collection for non-absolute manifest URL %s', remoteEntry);
122
- return {
123
- assets: [],
124
- errored: false
125
- };
126
- }
127
- try {
128
- const remoteManifest = await fetchJsonWithTimeout(remoteManifestUrl, fetcher, timeout);
129
- return {
130
- assets: collectModuleFederationManifestCss(remoteManifest, remoteManifestUrl),
131
- errored: false
132
- };
133
- } catch (error) {
134
- warn(options.monitors, 'Load module federation remote manifest %s failed, error = %s', remoteManifestUrl, error instanceof Error ? error.message : error);
135
- return {
136
- assets: [],
137
- errored: true
138
- };
139
- }
140
- }));
141
- const cssAssets = [];
142
- const seen = new Set();
143
- let errored = false;
144
- for (const result of remoteResults){
145
- errored = errored || result.errored;
146
- for (const asset of result.assets)if (!seen.has(asset)) {
147
- seen.add(asset);
148
- cssAssets.push(asset);
149
- }
150
- }
151
- return {
152
- assets: cssAssets,
153
- errored
154
- };
155
- };
156
- const collectDirectRemoteModuleFederationCss = async (pwd, options = {})=>{
157
- const { assets } = await collectDirectRemoteModuleFederationCssWithMeta(pwd, options);
158
- return assets;
159
- };
160
- const createModuleFederationCssCollector = (pwd, options = {})=>{
161
- const { ttlMs = 0, now = Date.now, ...collectOptions } = options;
162
- const normalizedTtlMs = Math.max(0, ttlMs);
163
- let cached;
164
- let lastGoodAssets;
165
- let inflight;
166
- const refresh = (monitors)=>{
167
- const promise = collectDirectRemoteModuleFederationCssWithMeta(pwd, {
168
- ...collectOptions,
169
- monitors: monitors ?? collectOptions.monitors
170
- }).then((result)=>{
171
- if (!result.errored) {
172
- lastGoodAssets = result.assets;
173
- cached = {
174
- assets: result.assets,
175
- expiresAt: now() + normalizedTtlMs
176
- };
177
- return result.assets;
178
- }
179
- cached = void 0;
180
- return lastGoodAssets ?? result.assets;
181
- }).finally(()=>{
182
- if (inflight === promise) inflight = void 0;
183
- });
184
- inflight = promise;
185
- return promise;
186
- };
187
- return {
188
- collect (monitors) {
189
- if (cached && now() < cached.expiresAt) return Promise.resolve(cached.assets);
190
- if (inflight) return inflight;
191
- return refresh(monitors);
192
- }
193
- };
194
- };
195
- const DEFAULT_REMOTE_CSS_CACHE_TTL_MS = 30000;
196
- const injectModuleFederationCssPlugin = (options = {})=>({
197
- name: '@modern-js/inject-module-federation-css',
198
- setup (api) {
199
- api.onPrepare(()=>{
200
- const { middlewares, distDirectory: pwd } = api.getServerContext();
201
- if (!pwd) return;
202
- const ttlMs = Math.max(0, options.remoteCssCacheTtlMs ?? (isProd() ? DEFAULT_REMOTE_CSS_CACHE_TTL_MS : 0));
203
- const collector = createModuleFederationCssCollector(pwd, {
204
- ttlMs
205
- });
206
- if (isProd()) collector.collect().catch(()=>{});
207
- const handler = async (c, next)=>{
208
- const serverManifest = c.get('serverManifest');
209
- if (serverManifest && !serverManifest.moduleFederationCssAssets) {
210
- const monitors = c.get('monitors');
211
- const moduleFederationCssAssets = await collector.collect(monitors);
212
- c.set('serverManifest', {
213
- ...serverManifest,
214
- moduleFederationCssAssets
215
- });
216
- }
217
- await next();
218
- };
219
- middlewares.push({
220
- name: 'inject-module-federation-css',
221
- handler
222
- });
223
- });
224
- }
225
- });
226
- export { collectDirectRemoteModuleFederationCss, collectDirectRemoteModuleFederationCssWithMeta, collectModuleFederationManifestCss, createModuleFederationCssCollector, injectModuleFederationCssPlugin };