@bleedingdev/modern-js-server-runtime-extensions 3.5.0-ultramodern.10 → 3.5.0-ultramodern.101

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 +10 -12
  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
@@ -0,0 +1,81 @@
1
+ const getSnapshotGateEntries = (snapshot)=>{
2
+ const gates = snapshot.gates;
3
+ if (!gates || 'object' != typeof gates) return;
4
+ const entries = [];
5
+ for (const [name, value] of Object.entries(gates)){
6
+ const normalizedName = name.trim();
7
+ if (normalizedName) entries.push([
8
+ normalizedName,
9
+ value
10
+ ]);
11
+ }
12
+ return entries;
13
+ };
14
+ const getSnapshotGateNames = (snapshot)=>{
15
+ const entries = getSnapshotGateEntries(snapshot);
16
+ if (!entries) return;
17
+ const names = new Set();
18
+ for (const [name] of entries)names.add(name);
19
+ return names;
20
+ };
21
+ const normalizeSnapshot = (snapshot, { now, gateStaleAfterMs })=>{
22
+ const output = [];
23
+ const entries = getSnapshotGateEntries(snapshot);
24
+ if (!entries) return output;
25
+ for (const [normalizedName, value] of entries){
26
+ const gate = normalizeGateValue(value, snapshot.updatedAt, now);
27
+ if (!gate) continue;
28
+ if ('number' == typeof gate.expiresAt && Number.isFinite(gate.expiresAt) && gate.expiresAt > 0 && now >= gate.expiresAt) {
29
+ output.push({
30
+ name: normalizedName,
31
+ passed: true,
32
+ reason: void 0,
33
+ updatedAt: gate.updatedAt,
34
+ expiresAt: gate.expiresAt
35
+ });
36
+ continue;
37
+ }
38
+ const isStale = gateStaleAfterMs > 0 && now - gate.updatedAt > gateStaleAfterMs;
39
+ if (isStale) {
40
+ output.push({
41
+ name: normalizedName,
42
+ passed: false,
43
+ reason: gate.reason || 'Gate snapshot is stale',
44
+ updatedAt: gate.updatedAt
45
+ });
46
+ continue;
47
+ }
48
+ output.push({
49
+ name: normalizedName,
50
+ passed: gate.passed,
51
+ reason: gate.reason,
52
+ updatedAt: gate.updatedAt
53
+ });
54
+ }
55
+ return output;
56
+ };
57
+ const normalizeGateValue = (value, snapshotUpdatedAt, now)=>{
58
+ if ('boolean' == typeof value) return {
59
+ passed: value,
60
+ updatedAt: normalizeUpdatedAt(snapshotUpdatedAt, now)
61
+ };
62
+ if (!value || 'object' != typeof value) return;
63
+ const hasPassed = 'boolean' == typeof value.passed;
64
+ const passed = true === value.passed;
65
+ let reason = 'string' == typeof value.reason && value.reason.trim().length > 0 ? value.reason : void 0;
66
+ if (!hasPassed) reason = reason || 'Gate snapshot record missing "passed" boolean';
67
+ return {
68
+ passed,
69
+ reason,
70
+ updatedAt: normalizeUpdatedAt(value.updatedAt ?? snapshotUpdatedAt, now),
71
+ expiresAt: normalizeExpiresAt(value.expiresAt)
72
+ };
73
+ };
74
+ const normalizeUpdatedAt = (value, fallback)=>{
75
+ if ('number' == typeof value && Number.isFinite(value) && value > 0) return value;
76
+ return fallback;
77
+ };
78
+ const normalizeExpiresAt = (value)=>{
79
+ if ('number' == typeof value && Number.isFinite(value) && value > 0) return value;
80
+ };
81
+ export { getSnapshotGateNames, normalizeSnapshot };
@@ -0,0 +1,51 @@
1
+ import { promises } from "node:fs";
2
+ import node_path from "node:path";
3
+ import { fs } from "@modern-js/utils";
4
+ import { parseServerRuntimeExtensionsEnv } from "../env.mjs";
5
+ import { normalizeSnapshot } from "./resolve.mjs";
6
+ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION, DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH } from "./types.mjs";
7
+ const resolveContractGateSnapshotPath = (appDirectory, configuredPath)=>{
8
+ const rawPath = configuredPath || parseServerRuntimeExtensionsEnv().contractGatesFile || DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH;
9
+ if (node_path.isAbsolute(rawPath)) return rawPath;
10
+ return node_path.resolve(appDirectory, rawPath);
11
+ };
12
+ const writeSnapshotFileAtomically = async (resolvedPath, contents)=>{
13
+ const directory = node_path.dirname(resolvedPath);
14
+ await promises.mkdir(directory, {
15
+ recursive: true
16
+ });
17
+ const temporaryPath = node_path.join(directory, `.${node_path.basename(resolvedPath)}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
18
+ try {
19
+ await promises.writeFile(temporaryPath, contents);
20
+ await promises.rename(temporaryPath, resolvedPath);
21
+ } catch (error) {
22
+ await promises.rm(temporaryPath, {
23
+ force: true
24
+ }).catch(()=>{});
25
+ throw error;
26
+ }
27
+ };
28
+ const createFileContractGateSnapshotStore = (gateSnapshotPath)=>{
29
+ const resolvedPath = node_path.resolve(gateSnapshotPath);
30
+ return {
31
+ name: `file:${resolvedPath}`,
32
+ async readSnapshot () {
33
+ if (!await fs.pathExists(resolvedPath)) return;
34
+ try {
35
+ const raw = await promises.readFile(resolvedPath, 'utf8');
36
+ return normalizeSnapshot(JSON.parse(raw));
37
+ } catch (_error) {
38
+ return;
39
+ }
40
+ },
41
+ async writeSnapshot (snapshot) {
42
+ const normalized = normalizeSnapshot(snapshot) || {
43
+ schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
44
+ updatedAt: Date.now(),
45
+ gates: {}
46
+ };
47
+ await writeSnapshotFileAtomically(resolvedPath, `${JSON.stringify(normalized, null, 2)}\n`);
48
+ }
49
+ };
50
+ };
51
+ export { createFileContractGateSnapshotStore, resolveContractGateSnapshotPath };
@@ -0,0 +1,92 @@
1
+ import { normalizeSnapshot } from "./resolve.mjs";
2
+ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from "./types.mjs";
3
+ const DEFAULT_HTTP_STORE_TIMEOUT_MS = 5000;
4
+ const BUILTIN_HTTP_STATE_STORE_MODULES = new Set([
5
+ 'http',
6
+ '@modern-js/server-core/http',
7
+ '@modern-js/server-core/contract-gate-http-store',
8
+ '@modern-js/server-runtime-extensions/http',
9
+ '@modern-js/server-runtime-extensions/contract-gate-http-store'
10
+ ]);
11
+ const normalizeHttpStoreOptions = (options)=>{
12
+ const endpoint = 'string' == typeof options?.endpoint ? options.endpoint.trim() : '';
13
+ if (!endpoint) throw new Error('[telemetry.canary.autopilot] HTTP stateStore requires options.endpoint');
14
+ const readMethod = 'string' == typeof options?.readMethod && options.readMethod.trim() ? options.readMethod.trim().toUpperCase() : 'GET';
15
+ const writeMethod = 'string' == typeof options?.writeMethod && options.writeMethod.trim() ? options.writeMethod.trim().toUpperCase() : 'PUT';
16
+ const timeoutMsRaw = Number(options?.timeoutMs);
17
+ const timeoutMs = Number.isFinite(timeoutMsRaw) && timeoutMsRaw > 0 ? Math.floor(timeoutMsRaw) : DEFAULT_HTTP_STORE_TIMEOUT_MS;
18
+ const headersRaw = options?.headers;
19
+ const headers = {};
20
+ if (headersRaw && 'object' == typeof headersRaw && !Array.isArray(headersRaw)) Object.entries(headersRaw).forEach(([key, value])=>{
21
+ if ('string' == typeof key && key.trim().length > 0 && null != value) headers[key] = String(value);
22
+ });
23
+ return {
24
+ endpoint,
25
+ readMethod,
26
+ writeMethod,
27
+ headers,
28
+ timeoutMs
29
+ };
30
+ };
31
+ const withTimeoutAbort = (timeoutMs)=>{
32
+ const controller = new AbortController();
33
+ const timer = setTimeout(()=>controller.abort(), timeoutMs);
34
+ return {
35
+ signal: controller.signal,
36
+ clear: ()=>clearTimeout(timer)
37
+ };
38
+ };
39
+ const createHttpContractGateSnapshotStore = (options)=>{
40
+ const normalized = normalizeHttpStoreOptions(options);
41
+ const endpoint = normalized.endpoint;
42
+ return {
43
+ name: `http:${endpoint}`,
44
+ async readSnapshot () {
45
+ const { signal, clear } = withTimeoutAbort(normalized.timeoutMs || 5000);
46
+ try {
47
+ const response = await fetch(endpoint, {
48
+ method: normalized.readMethod || 'GET',
49
+ headers: {
50
+ accept: 'application/json',
51
+ ...normalized.headers || {}
52
+ },
53
+ signal
54
+ });
55
+ if (404 === response.status) return;
56
+ if (!response.ok) throw new Error(`HTTP stateStore read failed with status ${String(response.status)}`);
57
+ const payload = await response.json();
58
+ return normalizeSnapshot(payload);
59
+ } finally{
60
+ clear();
61
+ }
62
+ },
63
+ async writeSnapshot (snapshot) {
64
+ const body = JSON.stringify(normalizeSnapshot(snapshot) || {
65
+ schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
66
+ updatedAt: Date.now(),
67
+ gates: {}
68
+ });
69
+ const { signal, clear } = withTimeoutAbort(normalized.timeoutMs || 5000);
70
+ try {
71
+ const response = await fetch(endpoint, {
72
+ method: normalized.writeMethod || 'PUT',
73
+ headers: {
74
+ 'content-type': 'application/json',
75
+ ...normalized.headers || {}
76
+ },
77
+ body,
78
+ signal
79
+ });
80
+ if (!response.ok) throw new Error(`HTTP stateStore write failed with status ${String(response.status)}`);
81
+ } finally{
82
+ clear();
83
+ }
84
+ }
85
+ };
86
+ };
87
+ const tryResolveBuiltinSnapshotStore = (input)=>{
88
+ const moduleName = input.stateStore.module.trim();
89
+ if (!BUILTIN_HTTP_STATE_STORE_MODULES.has(moduleName)) return;
90
+ return createHttpContractGateSnapshotStore(input.stateStore.options || {});
91
+ };
92
+ export { createHttpContractGateSnapshotStore, tryResolveBuiltinSnapshotStore };
@@ -0,0 +1,4 @@
1
+ export { createFileContractGateSnapshotStore, resolveContractGateSnapshotPath } from "./file-store.mjs";
2
+ export { createHttpContractGateSnapshotStore } from "./http-store.mjs";
3
+ export { resolveContractGateSnapshotStore } from "./resolve.mjs";
4
+ export { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION, DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH } from "./types.mjs";
@@ -0,0 +1,70 @@
1
+ import { createRequire } from "node:module";
2
+ import node_path from "node:path";
3
+ import { pathToFileURL } from "node:url";
4
+ import { createFileContractGateSnapshotStore } from "./file-store.mjs";
5
+ import { tryResolveBuiltinSnapshotStore } from "./http-store.mjs";
6
+ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from "./types.mjs";
7
+ const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
8
+ const normalizeSnapshot = (snapshot)=>{
9
+ if (!isRecord(snapshot)) return;
10
+ const schemaVersion = 'number' == typeof snapshot.schemaVersion ? snapshot.schemaVersion : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
11
+ const updatedAt = 'number' == typeof snapshot.updatedAt ? snapshot.updatedAt : Date.now();
12
+ const gates = isRecord(snapshot.gates) ? snapshot.gates : {};
13
+ return {
14
+ schemaVersion,
15
+ updatedAt,
16
+ gates
17
+ };
18
+ };
19
+ const pickStoreFactory = (mod)=>{
20
+ if ('function' == typeof mod) return mod;
21
+ if ('function' == typeof mod.createContractGateSnapshotStore) return mod.createContractGateSnapshotStore;
22
+ if ('function' == typeof mod.default) return mod.default;
23
+ if (mod.default && 'object' == typeof mod.default && 'function' == typeof mod.default.createContractGateSnapshotStore) return mod.default.createContractGateSnapshotStore;
24
+ };
25
+ const ensureStoreShape = (store, modulePath)=>{
26
+ 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() }.`);
27
+ };
28
+ const resolveStoreModulePath = (appDirectory, modulePath)=>{
29
+ const normalized = modulePath.trim();
30
+ if (!normalized) throw new Error('Contract gate snapshot stateStore.module must be non-empty');
31
+ if (node_path.isAbsolute(normalized)) return normalized;
32
+ if (normalized.startsWith('.')) return node_path.resolve(appDirectory, normalized);
33
+ const appRequire = createRequire(node_path.join(appDirectory, 'package.json'));
34
+ try {
35
+ return appRequire.resolve(normalized);
36
+ } catch (_error) {
37
+ return normalized;
38
+ }
39
+ };
40
+ const toStoreModuleImportSpecifier = (modulePath)=>node_path.isAbsolute(modulePath) ? pathToFileURL(modulePath).href : modulePath;
41
+ const resolveContractGateSnapshotStore = async (input)=>{
42
+ const { appDirectory, gateSnapshotPath, stateStore, logger } = input;
43
+ if (!stateStore?.module) return createFileContractGateSnapshotStore(gateSnapshotPath);
44
+ const builtinStore = tryResolveBuiltinSnapshotStore({
45
+ stateStore
46
+ });
47
+ if (builtinStore) {
48
+ logger?.info?.(`[telemetry.canary.autopilot] using built-in contract gate snapshot store "${builtinStore.name}"`);
49
+ return builtinStore;
50
+ }
51
+ const modulePath = resolveStoreModulePath(appDirectory, stateStore.module);
52
+ let mod;
53
+ try {
54
+ mod = await import(toStoreModuleImportSpecifier(modulePath));
55
+ } catch (error) {
56
+ throw new Error(`[telemetry.canary.autopilot] Failed to load stateStore.module "${stateStore.module}" (${modulePath}): ${error instanceof Error ? error.message : String(error)}`);
57
+ }
58
+ const factory = pickStoreFactory(mod);
59
+ if (!factory) throw new Error(`[telemetry.canary.autopilot] stateStore.module "${stateStore.module}" does not export createContractGateSnapshotStore()`);
60
+ const store = await factory({
61
+ appDirectory,
62
+ gateSnapshotPath,
63
+ options: stateStore.options,
64
+ logger
65
+ });
66
+ ensureStoreShape(store, modulePath);
67
+ logger?.info?.(`[telemetry.canary.autopilot] using contract gate snapshot store "${store.name || modulePath}"`);
68
+ return store;
69
+ };
70
+ export { isRecord, normalizeSnapshot, resolveContractGateSnapshotStore };
@@ -0,0 +1,3 @@
1
+ const CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION = 1;
2
+ const DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH = '.modern/contract-gates.json';
3
+ export { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION, DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH };
@@ -1,4 +1,5 @@
1
- import { createFileContractGateSnapshotStore } from "./contractGateSnapshotStore.mjs";
1
+ import { getSnapshotGateNames, normalizeSnapshot } from "./contract-gate-snapshot-normalization.mjs";
2
+ import { createFileContractGateSnapshotStore } from "./contract-gate-snapshot-store/file-store.mjs";
2
3
  const DEFAULT_POLL_INTERVAL_MS = 15000;
3
4
  const DEFAULT_GATE_STALE_AFTER_MS = 600000;
4
5
  class ContractGateAutopilot {
@@ -17,10 +18,16 @@ class ContractGateAutopilot {
17
18
  }
18
19
  }
19
20
  async syncOnce() {
21
+ const syncGeneration = ++this.syncGeneration;
20
22
  const snapshot = await this.loadSnapshot();
23
+ if (syncGeneration !== this.syncGeneration) return 0;
21
24
  if (!snapshot) return 0;
22
- const gates = this.normalizeSnapshot(snapshot);
23
- let updatedCount = 0;
25
+ const snapshotGateNames = getSnapshotGateNames(snapshot);
26
+ const gates = normalizeSnapshot(snapshot, {
27
+ now: Date.now(),
28
+ gateStaleAfterMs: this.gateStaleAfterMs
29
+ });
30
+ let updatedCount = snapshotGateNames ? this.clearOmittedGates(snapshotGateNames) : 0;
24
31
  for (const gate of gates){
25
32
  this.orchestrator.addRequiredContractGate(gate.name);
26
33
  const fingerprint = `${gate.passed ? '1' : '0'}:${gate.reason || ''}`;
@@ -33,13 +40,20 @@ class ContractGateAutopilot {
33
40
  }
34
41
  return updatedCount;
35
42
  }
43
+ clearOmittedGates(snapshotGateNames) {
44
+ let updatedCount = 0;
45
+ for (const gateName of Array.from(this.appliedGateFingerprints.keys()))if (!snapshotGateNames.has(gateName)) {
46
+ this.orchestrator.setContractGate(gateName, true);
47
+ this.appliedGateFingerprints.delete(gateName);
48
+ updatedCount += 1;
49
+ this.logger?.info?.(`[telemetry.canary.autopilot] gate=${gateName} passed=true reason=omitted`);
50
+ }
51
+ return updatedCount;
52
+ }
36
53
  async loadSnapshot() {
37
54
  try {
38
55
  const snapshot = await this.gateSnapshotStore.readSnapshot();
39
56
  if (!snapshot) return;
40
- const fingerprint = JSON.stringify(snapshot);
41
- if (fingerprint === this.lastSnapshotFingerprint) return;
42
- this.lastSnapshotFingerprint = fingerprint;
43
57
  return snapshot;
44
58
  } catch (error) {
45
59
  const source = this.gateSnapshotPath || this.gateSnapshotStore.name || 'stateStore';
@@ -47,70 +61,8 @@ class ContractGateAutopilot {
47
61
  return;
48
62
  }
49
63
  }
50
- normalizeSnapshot(snapshot) {
51
- const now = Date.now();
52
- const output = [];
53
- const gates = snapshot.gates;
54
- if (!gates || 'object' != typeof gates) return output;
55
- for (const [name, value] of Object.entries(gates)){
56
- const normalizedName = name.trim();
57
- if (!normalizedName) continue;
58
- const gate = this.normalizeGateValue(value, snapshot.updatedAt, now);
59
- if (!gate) continue;
60
- if ('number' == typeof gate.expiresAt && Number.isFinite(gate.expiresAt) && gate.expiresAt > 0 && now >= gate.expiresAt) {
61
- output.push({
62
- name: normalizedName,
63
- passed: true,
64
- reason: void 0,
65
- updatedAt: gate.updatedAt,
66
- expiresAt: gate.expiresAt
67
- });
68
- continue;
69
- }
70
- const isStale = this.gateStaleAfterMs > 0 && now - gate.updatedAt > this.gateStaleAfterMs;
71
- if (isStale) {
72
- output.push({
73
- name: normalizedName,
74
- passed: false,
75
- reason: gate.reason || 'Gate snapshot is stale',
76
- updatedAt: gate.updatedAt
77
- });
78
- continue;
79
- }
80
- output.push({
81
- name: normalizedName,
82
- passed: gate.passed,
83
- reason: gate.reason,
84
- updatedAt: gate.updatedAt
85
- });
86
- }
87
- return output;
88
- }
89
- normalizeGateValue(value, snapshotUpdatedAt, now) {
90
- if ('boolean' == typeof value) return {
91
- passed: value,
92
- updatedAt: this.normalizeUpdatedAt(snapshotUpdatedAt, now)
93
- };
94
- if (!value || 'object' != typeof value) return;
95
- const hasPassed = 'boolean' == typeof value.passed;
96
- const passed = true === value.passed;
97
- let reason = 'string' == typeof value.reason && value.reason.trim().length > 0 ? value.reason : void 0;
98
- if (!hasPassed) reason = reason || 'Gate snapshot record is missing "passed" boolean';
99
- return {
100
- passed,
101
- reason,
102
- updatedAt: this.normalizeUpdatedAt(value.updatedAt ?? snapshotUpdatedAt, now),
103
- expiresAt: this.normalizeExpiresAt(value.expiresAt)
104
- };
105
- }
106
- normalizeUpdatedAt(value, fallback) {
107
- if ('number' == typeof value && Number.isFinite(value) && value > 0) return value;
108
- return fallback;
109
- }
110
- normalizeExpiresAt(value) {
111
- if ('number' == typeof value && Number.isFinite(value) && value > 0) return value;
112
- }
113
64
  constructor(options){
65
+ this.syncGeneration = 0;
114
66
  this.appliedGateFingerprints = new Map();
115
67
  this.orchestrator = options.orchestrator;
116
68
  if (!options.gateSnapshotStore && !options.gateSnapshotPath) throw new Error('ContractGateAutopilot requires gateSnapshotPath or gateSnapshotStore');
@@ -1,6 +1,5 @@
1
1
  export { ContractGateAutopilot } from "./contractGateAutopilot.mjs";
2
- export { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION, DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH, createFileContractGateSnapshotStore, createHttpContractGateSnapshotStore, resolveContractGateSnapshotPath, resolveContractGateSnapshotStore } from "./contractGateSnapshotStore.mjs";
3
2
  export { DEFAULT_ENVIRONMENT_NAME, parseServerRuntimeExtensionsEnv } from "./env.mjs";
4
3
  export { getRequestPathname, injectMfAssetCacheHeadersPlugin, isMfManifestAsset, isMfRemoteEntryAsset, resolveMfAssetCacheHeaders } from "./mfCache.mjs";
5
- export { collectDirectRemoteModuleFederationCss, collectDirectRemoteModuleFederationCssWithMeta, collectModuleFederationManifestCss, createModuleFederationCssCollector, injectModuleFederationCssPlugin } from "./moduleFederationCss.mjs";
4
+ export { collectDirectRemoteModuleFederationCss, collectDirectRemoteModuleFederationCssWithMeta, collectModuleFederationManifestCss, createModuleFederationCssCollector, injectModuleFederationCssPlugin } from "./module-federation-css/index.mjs";
6
5
  export { DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, DEFAULT_RUNTIME_STATUS_ENDPOINT, TelemetryCanaryOrchestrator, TelemetryRegistry, TelemetryStartupHealthError, createOtlpTelemetryExporter, createRuntimeFallbackSignalRuntimeState, createRuntimeSignalError, createTelemetryAwareMetrics, createVictoriaMetricsTelemetryExporter, enforceRuntimeFallbackSignalAuthToken, enforceRuntimeFallbackSignalTrustPolicy, getRuntimeSignalErrorStatusCode, hasEnabledTelemetryExporters, injectTelemetryPlugin, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, parseRuntimeFallbackSignalPayloadFromRawBody, resolveRuntimeFallbackSignalEndpoint, resolveTelemetrySloOptions } from "./telemetry.mjs";
@@ -1,4 +1,4 @@
1
- const REMOTE_ENTRY_REGEXP = /(^|\/)remoteEntry(?:\.[a-zA-Z0-9_-]+)?\.js$/;
1
+ const REMOTE_ENTRY_REGEXP = /(^|\/)(?:backendRemoteEntry\.cjs|remoteEntry(?:\.[a-zA-Z0-9_-]+)?\.js)$/;
2
2
  function firstQueryValue(value) {
3
3
  if (Array.isArray(value)) return value.find((item)=>'string' == typeof item && item.length > 0);
4
4
  if ('string' == typeof value && value.length > 0) return value;
@@ -11,7 +11,7 @@ function getRequestPathname(url) {
11
11
  }
12
12
  }
13
13
  function isMfManifestAsset(pathname) {
14
- return pathname.endsWith('/mf-manifest.json') || pathname.endsWith('/mf-stats.json');
14
+ return pathname.endsWith('/backend-mf-manifest.json') || pathname.endsWith('/mf-manifest.json') || pathname.endsWith('/mf-stats.json');
15
15
  }
16
16
  function isMfRemoteEntryAsset(pathname) {
17
17
  return REMOTE_ENTRY_REGEXP.test(pathname);
@@ -0,0 +1,38 @@
1
+ import { collectDirectRemoteModuleFederationCssWithMeta } from "./remote.mjs";
2
+ const createModuleFederationCssCollector = (pwd, options = {})=>{
3
+ const { ttlMs = 0, now = Date.now, ...collectOptions } = options;
4
+ const normalizedTtlMs = Math.max(0, ttlMs);
5
+ let cached;
6
+ let lastGoodAssets;
7
+ let inflight;
8
+ const refresh = (monitors)=>{
9
+ const promise = collectDirectRemoteModuleFederationCssWithMeta(pwd, {
10
+ ...collectOptions,
11
+ monitors: monitors ?? collectOptions.monitors
12
+ }).then((result)=>{
13
+ if (!result.errored) {
14
+ lastGoodAssets = result.assets;
15
+ cached = {
16
+ assets: result.assets,
17
+ expiresAt: now() + normalizedTtlMs
18
+ };
19
+ return result.assets;
20
+ }
21
+ cached = void 0;
22
+ return lastGoodAssets ?? result.assets;
23
+ }).finally(()=>{
24
+ if (inflight === promise) inflight = void 0;
25
+ });
26
+ inflight = promise;
27
+ return promise;
28
+ };
29
+ return {
30
+ collect (monitors) {
31
+ if (cached && now() < cached.expiresAt) return Promise.resolve(cached.assets);
32
+ if (inflight) return inflight;
33
+ return refresh(monitors);
34
+ }
35
+ };
36
+ };
37
+ const DEFAULT_REMOTE_CSS_CACHE_TTL_MS = 30000;
38
+ export { DEFAULT_REMOTE_CSS_CACHE_TTL_MS, createModuleFederationCssCollector };
@@ -0,0 +1,4 @@
1
+ export { createModuleFederationCssCollector } from "./collector.mjs";
2
+ export { collectModuleFederationManifestCss } from "./manifest.mjs";
3
+ export { injectModuleFederationCssPlugin } from "./plugin.mjs";
4
+ export { collectDirectRemoteModuleFederationCss, collectDirectRemoteModuleFederationCssWithMeta } from "./remote.mjs";
@@ -0,0 +1,69 @@
1
+ import node_path from "node:path";
2
+ import { fileReader } from "@modern-js/runtime-utils/fileReader";
3
+ import { fs } from "@modern-js/utils";
4
+ const MODULE_FEDERATION_MANIFEST_FILE = 'mf-manifest.json';
5
+ const warn = (monitors, message, ...args)=>{
6
+ if (monitors) return void monitors.warn(message, ...args);
7
+ console.warn(message, ...args);
8
+ };
9
+ const ensureTrailingSlash = (value)=>value.endsWith('/') ? value : `${value}/`;
10
+ const tryResolveUrl = (value, base)=>{
11
+ try {
12
+ return new URL(value, base).toString();
13
+ } catch {
14
+ return;
15
+ }
16
+ };
17
+ const normalizeRemoteEntry = (entry)=>{
18
+ const value = entry.trim();
19
+ if (!value) return;
20
+ const atIndex = value.lastIndexOf('@');
21
+ return atIndex >= 0 ? value.slice(atIndex + 1) : value;
22
+ };
23
+ const getCssAssets = (assets)=>[
24
+ ...assets?.css?.sync || [],
25
+ ...assets?.css?.async || []
26
+ ];
27
+ const getManifestFallbackBase = (manifestUrl)=>{
28
+ try {
29
+ return new URL('.', manifestUrl).toString();
30
+ } catch {
31
+ return ensureTrailingSlash(manifestUrl);
32
+ }
33
+ };
34
+ const getManifestPublicPathBase = (publicPath, manifestUrl)=>{
35
+ if (!publicPath || 'auto' === publicPath) return getManifestFallbackBase(manifestUrl);
36
+ const base = tryResolveUrl(ensureTrailingSlash(publicPath), manifestUrl);
37
+ return base || getManifestFallbackBase(manifestUrl);
38
+ };
39
+ const appendResolvedCssAssets = (result, seen, assets, base)=>{
40
+ for (const asset of assets){
41
+ if (!asset) continue;
42
+ const resolved = tryResolveUrl(asset, base);
43
+ if (resolved && !seen.has(resolved)) {
44
+ seen.add(resolved);
45
+ result.push(resolved);
46
+ }
47
+ }
48
+ };
49
+ const collectModuleFederationManifestCss = (manifest, manifestUrl)=>{
50
+ const base = getManifestPublicPathBase(manifest.metaData?.publicPath, manifestUrl);
51
+ const result = [];
52
+ const seen = new Set();
53
+ for (const item of manifest.shared || [])appendResolvedCssAssets(result, seen, getCssAssets(item.assets), base);
54
+ for (const item of manifest.exposes || [])appendResolvedCssAssets(result, seen, getCssAssets(item.assets), base);
55
+ return result;
56
+ };
57
+ const getHostManifest = async (pwd, monitors)=>{
58
+ const manifestPath = node_path.join(pwd, MODULE_FEDERATION_MANIFEST_FILE);
59
+ if (!await fs.pathExists(manifestPath)) return;
60
+ const manifestBuffer = await fileReader.readFileFromSystem(manifestPath, 'buffer');
61
+ if (null === manifestBuffer) return;
62
+ try {
63
+ return JSON.parse(manifestBuffer.toString('utf-8'));
64
+ } catch (error) {
65
+ warn(monitors, 'Parse module federation manifest failed, error = %s', error instanceof Error ? error.message : error);
66
+ return;
67
+ }
68
+ };
69
+ export { collectModuleFederationManifestCss, ensureTrailingSlash, getHostManifest, normalizeRemoteEntry, warn };
@@ -0,0 +1,33 @@
1
+ import { isProd } from "@modern-js/utils";
2
+ import { DEFAULT_REMOTE_CSS_CACHE_TTL_MS, createModuleFederationCssCollector } from "./collector.mjs";
3
+ const injectModuleFederationCssPlugin = (options = {})=>({
4
+ name: '@modern-js/inject-module-federation-css',
5
+ setup (api) {
6
+ api.onPrepare(()=>{
7
+ const { middlewares, distDirectory: pwd } = api.getServerContext();
8
+ if (!pwd) return;
9
+ const ttlMs = Math.max(0, options.remoteCssCacheTtlMs ?? (isProd() ? DEFAULT_REMOTE_CSS_CACHE_TTL_MS : 0));
10
+ const collector = createModuleFederationCssCollector(pwd, {
11
+ ttlMs
12
+ });
13
+ if (isProd()) collector.collect().catch(()=>{});
14
+ const handler = async (c, next)=>{
15
+ const serverManifest = c.get('serverManifest');
16
+ if (serverManifest && !serverManifest.moduleFederationCssAssets) {
17
+ const monitors = c.get('monitors');
18
+ const moduleFederationCssAssets = await collector.collect(monitors);
19
+ c.set('serverManifest', {
20
+ ...serverManifest,
21
+ moduleFederationCssAssets
22
+ });
23
+ }
24
+ await next();
25
+ };
26
+ middlewares.push({
27
+ name: 'inject-module-federation-css',
28
+ handler
29
+ });
30
+ });
31
+ }
32
+ });
33
+ export { injectModuleFederationCssPlugin };