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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (207) hide show
  1. package/dist/cjs/contract-gate-snapshot-store/file-store.js +102 -0
  2. package/dist/cjs/contract-gate-snapshot-store/http-store.js +142 -0
  3. package/dist/cjs/contract-gate-snapshot-store/index.js +58 -0
  4. package/dist/cjs/contract-gate-snapshot-store/resolve.js +122 -0
  5. package/dist/cjs/contract-gate-snapshot-store/types.js +44 -0
  6. package/dist/cjs/contractGateAutopilot.js +27 -6
  7. package/dist/cjs/index.js +13 -13
  8. package/dist/cjs/module-federation-css/collector.js +79 -0
  9. package/dist/cjs/module-federation-css/index.js +55 -0
  10. package/dist/cjs/module-federation-css/manifest.js +144 -0
  11. package/dist/cjs/module-federation-css/plugin.js +71 -0
  12. package/dist/cjs/module-federation-css/remote.js +133 -0
  13. package/dist/cjs/runtime-fallback-signal/auth.js +87 -0
  14. package/dist/cjs/runtime-fallback-signal/constants.js +72 -0
  15. package/dist/cjs/runtime-fallback-signal/contract-gate.js +64 -0
  16. package/dist/cjs/runtime-fallback-signal/endpoint.js +50 -0
  17. package/dist/cjs/runtime-fallback-signal/errors.js +44 -0
  18. package/dist/cjs/runtime-fallback-signal/index.js +99 -0
  19. package/dist/cjs/runtime-fallback-signal/payload.js +72 -0
  20. package/dist/cjs/runtime-fallback-signal/source.js +66 -0
  21. package/dist/cjs/runtime-fallback-signal/state.js +57 -0
  22. package/dist/cjs/runtime-fallback-signal/status.js +47 -0
  23. package/dist/cjs/runtime-fallback-signal/trust-policy.js +108 -0
  24. package/dist/cjs/runtime-fallback-signal/types.js +18 -0
  25. package/dist/cjs/runtimeFallbackSignal.js +32 -281
  26. package/dist/cjs/telemetry/canary.js +180 -0
  27. package/dist/cjs/telemetry/canaryEvaluation.js +79 -0
  28. package/dist/cjs/telemetry/canarySetup.js +107 -0
  29. package/dist/cjs/telemetry/envelope.js +148 -0
  30. package/dist/cjs/telemetry/exporters.js +148 -0
  31. package/dist/cjs/telemetry/lifecycle.js +98 -0
  32. package/dist/cjs/telemetry/metrics.js +115 -0
  33. package/dist/cjs/telemetry/plugin.js +185 -0
  34. package/dist/cjs/telemetry/registry.js +348 -0
  35. package/dist/cjs/telemetry/registryTypes.js +46 -0
  36. package/dist/cjs/telemetry/runtimeEndpoints.js +135 -0
  37. package/dist/cjs/telemetry.js +32 -343
  38. package/dist/cjs/telemetryCore.js +14 -767
  39. package/dist/esm/contract-gate-snapshot-store/file-store.mjs +51 -0
  40. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +92 -0
  41. package/dist/esm/contract-gate-snapshot-store/index.mjs +4 -0
  42. package/dist/esm/contract-gate-snapshot-store/resolve.mjs +68 -0
  43. package/dist/esm/contract-gate-snapshot-store/types.mjs +3 -0
  44. package/dist/esm/contractGateAutopilot.mjs +26 -5
  45. package/dist/esm/index.mjs +2 -2
  46. package/dist/esm/module-federation-css/collector.mjs +38 -0
  47. package/dist/esm/module-federation-css/index.mjs +4 -0
  48. package/dist/esm/module-federation-css/manifest.mjs +69 -0
  49. package/dist/esm/module-federation-css/plugin.mjs +33 -0
  50. package/dist/esm/module-federation-css/remote.mjs +92 -0
  51. package/dist/esm/runtime-fallback-signal/auth.mjs +40 -0
  52. package/dist/esm/runtime-fallback-signal/constants.mjs +10 -0
  53. package/dist/esm/runtime-fallback-signal/contract-gate.mjs +26 -0
  54. package/dist/esm/runtime-fallback-signal/endpoint.mjs +12 -0
  55. package/dist/esm/runtime-fallback-signal/errors.mjs +6 -0
  56. package/dist/esm/runtime-fallback-signal/index.mjs +9 -0
  57. package/dist/esm/runtime-fallback-signal/payload.mjs +31 -0
  58. package/dist/esm/runtime-fallback-signal/source.mjs +22 -0
  59. package/dist/esm/runtime-fallback-signal/state.mjs +16 -0
  60. package/dist/esm/runtime-fallback-signal/status.mjs +9 -0
  61. package/dist/esm/runtime-fallback-signal/trust-policy.mjs +67 -0
  62. package/dist/esm/runtime-fallback-signal/types.mjs +0 -0
  63. package/dist/esm/runtimeFallbackSignal.mjs +1 -222
  64. package/dist/esm/telemetry/canary.mjs +142 -0
  65. package/dist/esm/telemetry/canaryEvaluation.mjs +41 -0
  66. package/dist/esm/telemetry/canarySetup.mjs +69 -0
  67. package/dist/esm/telemetry/envelope.mjs +101 -0
  68. package/dist/esm/telemetry/exporters.mjs +104 -0
  69. package/dist/esm/telemetry/lifecycle.mjs +60 -0
  70. package/dist/esm/telemetry/metrics.mjs +77 -0
  71. package/dist/esm/telemetry/plugin.mjs +87 -0
  72. package/dist/esm/telemetry/registry.mjs +310 -0
  73. package/dist/esm/telemetry/registryTypes.mjs +8 -0
  74. package/dist/esm/telemetry/runtimeEndpoints.mjs +94 -0
  75. package/dist/esm/telemetry.mjs +1 -275
  76. package/dist/esm/telemetryCore.mjs +6 -759
  77. package/dist/esm-node/contract-gate-snapshot-store/file-store.mjs +52 -0
  78. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +93 -0
  79. package/dist/esm-node/contract-gate-snapshot-store/index.mjs +5 -0
  80. package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +70 -0
  81. package/dist/esm-node/contract-gate-snapshot-store/types.mjs +4 -0
  82. package/dist/esm-node/contractGateAutopilot.mjs +26 -5
  83. package/dist/esm-node/index.mjs +2 -2
  84. package/dist/esm-node/module-federation-css/collector.mjs +39 -0
  85. package/dist/esm-node/module-federation-css/index.mjs +5 -0
  86. package/dist/esm-node/module-federation-css/manifest.mjs +70 -0
  87. package/dist/esm-node/module-federation-css/plugin.mjs +34 -0
  88. package/dist/esm-node/module-federation-css/remote.mjs +93 -0
  89. package/dist/esm-node/runtime-fallback-signal/auth.mjs +41 -0
  90. package/dist/esm-node/runtime-fallback-signal/constants.mjs +11 -0
  91. package/dist/esm-node/runtime-fallback-signal/contract-gate.mjs +27 -0
  92. package/dist/esm-node/runtime-fallback-signal/endpoint.mjs +13 -0
  93. package/dist/esm-node/runtime-fallback-signal/errors.mjs +7 -0
  94. package/dist/esm-node/runtime-fallback-signal/index.mjs +10 -0
  95. package/dist/esm-node/runtime-fallback-signal/payload.mjs +32 -0
  96. package/dist/esm-node/runtime-fallback-signal/source.mjs +23 -0
  97. package/dist/esm-node/runtime-fallback-signal/state.mjs +17 -0
  98. package/dist/esm-node/runtime-fallback-signal/status.mjs +10 -0
  99. package/dist/esm-node/runtime-fallback-signal/trust-policy.mjs +68 -0
  100. package/dist/esm-node/runtime-fallback-signal/types.mjs +1 -0
  101. package/dist/esm-node/runtimeFallbackSignal.mjs +1 -222
  102. package/dist/esm-node/telemetry/canary.mjs +143 -0
  103. package/dist/esm-node/telemetry/canaryEvaluation.mjs +42 -0
  104. package/dist/esm-node/telemetry/canarySetup.mjs +70 -0
  105. package/dist/esm-node/telemetry/envelope.mjs +102 -0
  106. package/dist/esm-node/telemetry/exporters.mjs +105 -0
  107. package/dist/esm-node/telemetry/lifecycle.mjs +61 -0
  108. package/dist/esm-node/telemetry/metrics.mjs +78 -0
  109. package/dist/esm-node/telemetry/plugin.mjs +88 -0
  110. package/dist/esm-node/telemetry/registry.mjs +311 -0
  111. package/dist/esm-node/telemetry/registryTypes.mjs +9 -0
  112. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +95 -0
  113. package/dist/esm-node/telemetry.mjs +1 -275
  114. package/dist/esm-node/telemetryCore.mjs +6 -759
  115. package/dist/types/contract-gate-snapshot-store/file-store.d.ts +3 -0
  116. package/dist/types/contract-gate-snapshot-store/http-store.d.ts +11 -0
  117. package/dist/types/contract-gate-snapshot-store/index.d.ts +5 -0
  118. package/dist/types/contract-gate-snapshot-store/resolve.d.ts +9 -0
  119. package/dist/types/{contractGateSnapshotStore.d.ts → contract-gate-snapshot-store/types.d.ts} +1 -11
  120. package/dist/types/contractGateAutopilot.d.ts +4 -2
  121. package/dist/types/index.d.ts +2 -2
  122. package/dist/types/module-federation-css/collector.d.ts +25 -0
  123. package/dist/types/module-federation-css/index.d.ts +8 -0
  124. package/dist/types/module-federation-css/manifest.d.ts +33 -0
  125. package/dist/types/module-federation-css/plugin.d.ts +23 -0
  126. package/dist/types/module-federation-css/remote.d.ts +20 -0
  127. package/dist/types/runtime-fallback-signal/auth.d.ts +18 -0
  128. package/dist/types/runtime-fallback-signal/constants.d.ts +9 -0
  129. package/dist/types/runtime-fallback-signal/contract-gate.d.ts +2 -0
  130. package/dist/types/runtime-fallback-signal/endpoint.d.ts +1 -0
  131. package/dist/types/runtime-fallback-signal/errors.d.ts +2 -0
  132. package/dist/types/runtime-fallback-signal/index.d.ts +10 -0
  133. package/dist/types/runtime-fallback-signal/payload.d.ts +6 -0
  134. package/dist/types/runtime-fallback-signal/source.d.ts +3 -0
  135. package/dist/types/runtime-fallback-signal/state.d.ts +3 -0
  136. package/dist/types/runtime-fallback-signal/status.d.ts +2 -0
  137. package/dist/types/runtime-fallback-signal/trust-policy.d.ts +13 -0
  138. package/dist/types/runtime-fallback-signal/types.d.ts +50 -0
  139. package/dist/types/runtimeFallbackSignal.d.ts +1 -94
  140. package/dist/types/telemetry/canary.d.ts +85 -0
  141. package/dist/types/telemetry/canaryEvaluation.d.ts +19 -0
  142. package/dist/types/telemetry/canarySetup.d.ts +17 -0
  143. package/dist/types/telemetry/envelope.d.ts +45 -0
  144. package/dist/types/telemetry/exporters.d.ts +12 -0
  145. package/dist/types/telemetry/lifecycle.d.ts +18 -0
  146. package/dist/types/telemetry/metrics.d.ts +3 -0
  147. package/dist/types/telemetry/plugin.d.ts +12 -0
  148. package/dist/types/telemetry/registry.d.ts +72 -0
  149. package/dist/types/telemetry/registryTypes.d.ts +50 -0
  150. package/dist/types/telemetry/runtimeEndpoints.d.ts +35 -0
  151. package/dist/types/telemetry.d.ts +1 -12
  152. package/dist/types/telemetryCore.d.ts +6 -257
  153. package/package.json +7 -7
  154. package/src/contract-gate-snapshot-store/file-store.ts +85 -0
  155. package/src/contract-gate-snapshot-store/http-store.ts +159 -0
  156. package/src/contract-gate-snapshot-store/index.ts +20 -0
  157. package/src/contract-gate-snapshot-store/resolve.ts +175 -0
  158. package/src/contract-gate-snapshot-store/types.ts +64 -0
  159. package/src/contractGateAutopilot.ts +45 -9
  160. package/src/index.ts +6 -6
  161. package/src/module-federation-css/collector.ts +82 -0
  162. package/src/module-federation-css/index.ts +14 -0
  163. package/src/module-federation-css/manifest.ts +166 -0
  164. package/src/module-federation-css/plugin.ts +86 -0
  165. package/src/module-federation-css/remote.ts +165 -0
  166. package/src/runtime-fallback-signal/auth.ts +117 -0
  167. package/src/runtime-fallback-signal/constants.ts +19 -0
  168. package/src/runtime-fallback-signal/contract-gate.ts +43 -0
  169. package/src/runtime-fallback-signal/endpoint.ts +22 -0
  170. package/src/runtime-fallback-signal/errors.ts +10 -0
  171. package/src/runtime-fallback-signal/index.ts +36 -0
  172. package/src/runtime-fallback-signal/payload.ts +79 -0
  173. package/src/runtime-fallback-signal/source.ts +49 -0
  174. package/src/runtime-fallback-signal/state.ts +34 -0
  175. package/src/runtime-fallback-signal/status.ts +22 -0
  176. package/src/runtime-fallback-signal/trust-policy.ts +179 -0
  177. package/src/runtime-fallback-signal/types.ts +66 -0
  178. package/src/runtimeFallbackSignal.ts +1 -584
  179. package/src/telemetry/canary.ts +291 -0
  180. package/src/telemetry/canaryEvaluation.ts +83 -0
  181. package/src/telemetry/canarySetup.ts +160 -0
  182. package/src/telemetry/envelope.ts +189 -0
  183. package/src/telemetry/exporters.ts +165 -0
  184. package/src/telemetry/lifecycle.ts +138 -0
  185. package/src/telemetry/metrics.ts +141 -0
  186. package/src/telemetry/plugin.ts +197 -0
  187. package/src/telemetry/registry.ts +467 -0
  188. package/src/telemetry/registryTypes.ts +63 -0
  189. package/src/telemetry/runtimeEndpoints.ts +172 -0
  190. package/src/telemetry.ts +1 -554
  191. package/src/telemetryCore.ts +34 -1332
  192. package/tests/contractGateAutopilot.test.ts +205 -0
  193. package/tests/contractGateSnapshotStore.test.ts +54 -1
  194. package/tests/helpers.ts +1 -0
  195. package/tests/moduleFederationCss.test.ts +1 -1
  196. package/tests/registration.test.ts +1 -1
  197. package/tests/telemetry.test.ts +40 -0
  198. package/tests/telemetryLifecycle.test.ts +253 -2
  199. package/dist/cjs/contractGateSnapshotStore.js +0 -253
  200. package/dist/cjs/moduleFederationCss.js +0 -285
  201. package/dist/esm/contractGateSnapshotStore.mjs +0 -190
  202. package/dist/esm/moduleFederationCss.mjs +0 -225
  203. package/dist/esm-node/contractGateSnapshotStore.mjs +0 -192
  204. package/dist/esm-node/moduleFederationCss.mjs +0 -226
  205. package/dist/types/moduleFederationCss.d.ts +0 -87
  206. package/src/contractGateSnapshotStore.ts +0 -420
  207. package/src/moduleFederationCss.ts +0 -473
@@ -0,0 +1,52 @@
1
+ import "node:module";
2
+ import { fs } from "@modern-js/utils";
3
+ import { promises } from "fs";
4
+ import path from "path";
5
+ import { parseServerRuntimeExtensionsEnv } from "../env.mjs";
6
+ import { normalizeSnapshot } from "./resolve.mjs";
7
+ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION, DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH } from "./types.mjs";
8
+ const resolveContractGateSnapshotPath = (appDirectory, configuredPath)=>{
9
+ const rawPath = configuredPath || parseServerRuntimeExtensionsEnv().contractGatesFile || DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH;
10
+ if (path.isAbsolute(rawPath)) return rawPath;
11
+ return path.resolve(appDirectory, rawPath);
12
+ };
13
+ const writeSnapshotFileAtomically = async (resolvedPath, contents)=>{
14
+ const directory = path.dirname(resolvedPath);
15
+ await promises.mkdir(directory, {
16
+ recursive: true
17
+ });
18
+ const temporaryPath = path.join(directory, `.${path.basename(resolvedPath)}.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}.tmp`);
19
+ try {
20
+ await promises.writeFile(temporaryPath, contents);
21
+ await promises.rename(temporaryPath, resolvedPath);
22
+ } catch (error) {
23
+ await promises.rm(temporaryPath, {
24
+ force: true
25
+ }).catch(()=>{});
26
+ throw error;
27
+ }
28
+ };
29
+ const createFileContractGateSnapshotStore = (gateSnapshotPath)=>{
30
+ const resolvedPath = path.resolve(gateSnapshotPath);
31
+ return {
32
+ name: `file:${resolvedPath}`,
33
+ async readSnapshot () {
34
+ if (!await fs.pathExists(resolvedPath)) return;
35
+ try {
36
+ const raw = await promises.readFile(resolvedPath, 'utf8');
37
+ return normalizeSnapshot(JSON.parse(raw));
38
+ } catch (_error) {
39
+ return;
40
+ }
41
+ },
42
+ async writeSnapshot (snapshot) {
43
+ const normalized = normalizeSnapshot(snapshot) || {
44
+ schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
45
+ updatedAt: Date.now(),
46
+ gates: {}
47
+ };
48
+ await writeSnapshotFileAtomically(resolvedPath, `${JSON.stringify(normalized, null, 2)}\n`);
49
+ }
50
+ };
51
+ };
52
+ export { createFileContractGateSnapshotStore, resolveContractGateSnapshotPath };
@@ -0,0 +1,93 @@
1
+ import "node:module";
2
+ import { normalizeSnapshot } from "./resolve.mjs";
3
+ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from "./types.mjs";
4
+ const DEFAULT_HTTP_STORE_TIMEOUT_MS = 5000;
5
+ const BUILTIN_HTTP_STATE_STORE_MODULES = new Set([
6
+ 'http',
7
+ '@modern-js/server-core/http',
8
+ '@modern-js/server-core/contract-gate-http-store',
9
+ '@modern-js/server-runtime-extensions/http',
10
+ '@modern-js/server-runtime-extensions/contract-gate-http-store'
11
+ ]);
12
+ const normalizeHttpStoreOptions = (options)=>{
13
+ const endpoint = 'string' == typeof options?.endpoint ? options.endpoint.trim() : '';
14
+ if (!endpoint) throw new Error('[telemetry.canary.autopilot] HTTP stateStore requires options.endpoint');
15
+ const readMethod = 'string' == typeof options?.readMethod && options.readMethod.trim() ? options.readMethod.trim().toUpperCase() : 'GET';
16
+ const writeMethod = 'string' == typeof options?.writeMethod && options.writeMethod.trim() ? options.writeMethod.trim().toUpperCase() : 'PUT';
17
+ const timeoutMsRaw = Number(options?.timeoutMs);
18
+ const timeoutMs = Number.isFinite(timeoutMsRaw) && timeoutMsRaw > 0 ? Math.floor(timeoutMsRaw) : DEFAULT_HTTP_STORE_TIMEOUT_MS;
19
+ const headersRaw = options?.headers;
20
+ const headers = {};
21
+ if (headersRaw && 'object' == typeof headersRaw && !Array.isArray(headersRaw)) Object.entries(headersRaw).forEach(([key, value])=>{
22
+ if ('string' == typeof key && key.trim().length > 0 && null != value) headers[key] = String(value);
23
+ });
24
+ return {
25
+ endpoint,
26
+ readMethod,
27
+ writeMethod,
28
+ headers,
29
+ timeoutMs
30
+ };
31
+ };
32
+ const withTimeoutAbort = (timeoutMs)=>{
33
+ const controller = new AbortController();
34
+ const timer = setTimeout(()=>controller.abort(), timeoutMs);
35
+ return {
36
+ signal: controller.signal,
37
+ clear: ()=>clearTimeout(timer)
38
+ };
39
+ };
40
+ const createHttpContractGateSnapshotStore = (options)=>{
41
+ const normalized = normalizeHttpStoreOptions(options);
42
+ const endpoint = normalized.endpoint;
43
+ return {
44
+ name: `http:${endpoint}`,
45
+ async readSnapshot () {
46
+ const { signal, clear } = withTimeoutAbort(normalized.timeoutMs || 5000);
47
+ try {
48
+ const response = await fetch(endpoint, {
49
+ method: normalized.readMethod || 'GET',
50
+ headers: {
51
+ accept: 'application/json',
52
+ ...normalized.headers || {}
53
+ },
54
+ signal
55
+ });
56
+ if (404 === response.status) return;
57
+ if (!response.ok) throw new Error(`HTTP stateStore read failed with status ${String(response.status)}`);
58
+ const payload = await response.json();
59
+ return normalizeSnapshot(payload);
60
+ } finally{
61
+ clear();
62
+ }
63
+ },
64
+ async writeSnapshot (snapshot) {
65
+ const body = JSON.stringify(normalizeSnapshot(snapshot) || {
66
+ schemaVersion: CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION,
67
+ updatedAt: Date.now(),
68
+ gates: {}
69
+ });
70
+ const { signal, clear } = withTimeoutAbort(normalized.timeoutMs || 5000);
71
+ try {
72
+ const response = await fetch(endpoint, {
73
+ method: normalized.writeMethod || 'PUT',
74
+ headers: {
75
+ 'content-type': 'application/json',
76
+ ...normalized.headers || {}
77
+ },
78
+ body,
79
+ signal
80
+ });
81
+ if (!response.ok) throw new Error(`HTTP stateStore write failed with status ${String(response.status)}`);
82
+ } finally{
83
+ clear();
84
+ }
85
+ }
86
+ };
87
+ };
88
+ const tryResolveBuiltinSnapshotStore = (input)=>{
89
+ const moduleName = input.stateStore.module.trim();
90
+ if (!BUILTIN_HTTP_STATE_STORE_MODULES.has(moduleName)) return;
91
+ return createHttpContractGateSnapshotStore(input.stateStore.options || {});
92
+ };
93
+ export { BUILTIN_HTTP_STATE_STORE_MODULES, createHttpContractGateSnapshotStore, normalizeHttpStoreOptions, tryResolveBuiltinSnapshotStore, withTimeoutAbort };
@@ -0,0 +1,5 @@
1
+ import "node:module";
2
+ export { createFileContractGateSnapshotStore, resolveContractGateSnapshotPath } from "./file-store.mjs";
3
+ export { createHttpContractGateSnapshotStore } from "./http-store.mjs";
4
+ export { resolveContractGateSnapshotStore } from "./resolve.mjs";
5
+ export { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION, DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH } from "./types.mjs";
@@ -0,0 +1,70 @@
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 path from "path";
5
+ import { createFileContractGateSnapshotStore } from "./file-store.mjs";
6
+ import { tryResolveBuiltinSnapshotStore } from "./http-store.mjs";
7
+ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from "./types.mjs";
8
+ const isRecord = (value)=>'object' == typeof value && null !== value && !Array.isArray(value);
9
+ const normalizeSnapshot = (snapshot)=>{
10
+ if (!isRecord(snapshot)) return;
11
+ const schemaVersion = 'number' == typeof snapshot.schemaVersion ? snapshot.schemaVersion : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
12
+ const updatedAt = 'number' == typeof snapshot.updatedAt ? snapshot.updatedAt : Date.now();
13
+ const gates = isRecord(snapshot.gates) ? snapshot.gates : {};
14
+ return {
15
+ schemaVersion,
16
+ updatedAt,
17
+ gates
18
+ };
19
+ };
20
+ const pickStoreFactory = (mod)=>{
21
+ if ('function' == typeof mod) return mod;
22
+ if ('function' == typeof mod.createContractGateSnapshotStore) return mod.createContractGateSnapshotStore;
23
+ if ('function' == typeof mod.default) return mod.default;
24
+ if (mod.default && 'object' == typeof mod.default && 'function' == typeof mod.default.createContractGateSnapshotStore) return mod.default.createContractGateSnapshotStore;
25
+ };
26
+ const ensureStoreShape = (store, modulePath)=>{
27
+ 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() }.`);
28
+ };
29
+ const resolveStoreModulePath = (appDirectory, modulePath)=>{
30
+ const normalized = modulePath.trim();
31
+ if (!normalized) throw new Error('Contract gate snapshot stateStore.module must be non-empty');
32
+ if (path.isAbsolute(normalized)) return normalized;
33
+ if (normalized.startsWith('.')) return path.resolve(appDirectory, normalized);
34
+ const appRequire = createRequire(path.join(appDirectory, 'package.json'));
35
+ try {
36
+ return appRequire.resolve(normalized);
37
+ } catch (_error) {
38
+ return normalized;
39
+ }
40
+ };
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 = require(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,4 @@
1
+ import "node:module";
2
+ const CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION = 1;
3
+ const DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH = '.modern/contract-gates.json';
4
+ export { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION, DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH };
@@ -1,5 +1,5 @@
1
1
  import "node:module";
2
- import { createFileContractGateSnapshotStore } from "./contractGateSnapshotStore.mjs";
2
+ import { createFileContractGateSnapshotStore } from "./contract-gate-snapshot-store/index.mjs";
3
3
  const DEFAULT_POLL_INTERVAL_MS = 15000;
4
4
  const DEFAULT_GATE_STALE_AFTER_MS = 600000;
5
5
  class ContractGateAutopilot {
@@ -18,10 +18,13 @@ class ContractGateAutopilot {
18
18
  }
19
19
  }
20
20
  async syncOnce() {
21
+ const syncGeneration = ++this.syncGeneration;
21
22
  const snapshot = await this.loadSnapshot();
23
+ if (syncGeneration !== this.syncGeneration) return 0;
22
24
  if (!snapshot) return 0;
25
+ const snapshotGateNames = this.getSnapshotGateNames(snapshot);
23
26
  const gates = this.normalizeSnapshot(snapshot);
24
- let updatedCount = 0;
27
+ let updatedCount = snapshotGateNames ? this.clearOmittedGates(snapshotGateNames) : 0;
25
28
  for (const gate of gates){
26
29
  this.orchestrator.addRequiredContractGate(gate.name);
27
30
  const fingerprint = `${gate.passed ? '1' : '0'}:${gate.reason || ''}`;
@@ -34,13 +37,30 @@ class ContractGateAutopilot {
34
37
  }
35
38
  return updatedCount;
36
39
  }
40
+ getSnapshotGateNames(snapshot) {
41
+ const gates = snapshot.gates;
42
+ if (!gates || 'object' != typeof gates) return;
43
+ const names = new Set();
44
+ for (const name of Object.keys(gates)){
45
+ const normalizedName = name.trim();
46
+ if (normalizedName) names.add(normalizedName);
47
+ }
48
+ return names;
49
+ }
50
+ clearOmittedGates(snapshotGateNames) {
51
+ let updatedCount = 0;
52
+ for (const gateName of Array.from(this.appliedGateFingerprints.keys()))if (!snapshotGateNames.has(gateName)) {
53
+ this.orchestrator.setContractGate(gateName, true);
54
+ this.appliedGateFingerprints.delete(gateName);
55
+ updatedCount += 1;
56
+ this.logger?.info?.(`[telemetry.canary.autopilot] gate=${gateName} passed=true reason=omitted`);
57
+ }
58
+ return updatedCount;
59
+ }
37
60
  async loadSnapshot() {
38
61
  try {
39
62
  const snapshot = await this.gateSnapshotStore.readSnapshot();
40
63
  if (!snapshot) return;
41
- const fingerprint = JSON.stringify(snapshot);
42
- if (fingerprint === this.lastSnapshotFingerprint) return;
43
- this.lastSnapshotFingerprint = fingerprint;
44
64
  return snapshot;
45
65
  } catch (error) {
46
66
  const source = this.gateSnapshotPath || this.gateSnapshotStore.name || 'stateStore';
@@ -112,6 +132,7 @@ class ContractGateAutopilot {
112
132
  if ('number' == typeof value && Number.isFinite(value) && value > 0) return value;
113
133
  }
114
134
  constructor(options){
135
+ this.syncGeneration = 0;
115
136
  this.appliedGateFingerprints = new Map();
116
137
  this.orchestrator = options.orchestrator;
117
138
  if (!options.gateSnapshotStore && !options.gateSnapshotPath) throw new Error('ContractGateAutopilot requires gateSnapshotPath or gateSnapshotStore');
@@ -1,7 +1,7 @@
1
1
  import "node:module";
2
+ export { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION, DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH, createFileContractGateSnapshotStore, createHttpContractGateSnapshotStore, resolveContractGateSnapshotPath, resolveContractGateSnapshotStore } from "./contract-gate-snapshot-store/index.mjs";
2
3
  export { ContractGateAutopilot } from "./contractGateAutopilot.mjs";
3
- export { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION, DEFAULT_CONTRACT_GATE_SNAPSHOT_PATH, createFileContractGateSnapshotStore, createHttpContractGateSnapshotStore, resolveContractGateSnapshotPath, resolveContractGateSnapshotStore } from "./contractGateSnapshotStore.mjs";
4
4
  export { DEFAULT_ENVIRONMENT_NAME, parseServerRuntimeExtensionsEnv } from "./env.mjs";
5
5
  export { getRequestPathname, injectMfAssetCacheHeadersPlugin, isMfManifestAsset, isMfRemoteEntryAsset, resolveMfAssetCacheHeaders } from "./mfCache.mjs";
6
- export { collectDirectRemoteModuleFederationCss, collectDirectRemoteModuleFederationCssWithMeta, collectModuleFederationManifestCss, createModuleFederationCssCollector, injectModuleFederationCssPlugin } from "./moduleFederationCss.mjs";
6
+ export { collectDirectRemoteModuleFederationCss, collectDirectRemoteModuleFederationCssWithMeta, collectModuleFederationManifestCss, createModuleFederationCssCollector, injectModuleFederationCssPlugin } from "./module-federation-css/index.mjs";
7
7
  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";
@@ -0,0 +1,39 @@
1
+ import "node:module";
2
+ import { collectDirectRemoteModuleFederationCssWithMeta } from "./remote.mjs";
3
+ const createModuleFederationCssCollector = (pwd, options = {})=>{
4
+ const { ttlMs = 0, now = Date.now, ...collectOptions } = options;
5
+ const normalizedTtlMs = Math.max(0, ttlMs);
6
+ let cached;
7
+ let lastGoodAssets;
8
+ let inflight;
9
+ const refresh = (monitors)=>{
10
+ const promise = collectDirectRemoteModuleFederationCssWithMeta(pwd, {
11
+ ...collectOptions,
12
+ monitors: monitors ?? collectOptions.monitors
13
+ }).then((result)=>{
14
+ if (!result.errored) {
15
+ lastGoodAssets = result.assets;
16
+ cached = {
17
+ assets: result.assets,
18
+ expiresAt: now() + normalizedTtlMs
19
+ };
20
+ return result.assets;
21
+ }
22
+ cached = void 0;
23
+ return lastGoodAssets ?? result.assets;
24
+ }).finally(()=>{
25
+ if (inflight === promise) inflight = void 0;
26
+ });
27
+ inflight = promise;
28
+ return promise;
29
+ };
30
+ return {
31
+ collect (monitors) {
32
+ if (cached && now() < cached.expiresAt) return Promise.resolve(cached.assets);
33
+ if (inflight) return inflight;
34
+ return refresh(monitors);
35
+ }
36
+ };
37
+ };
38
+ const DEFAULT_REMOTE_CSS_CACHE_TTL_MS = 30000;
39
+ export { DEFAULT_REMOTE_CSS_CACHE_TTL_MS, createModuleFederationCssCollector };
@@ -0,0 +1,5 @@
1
+ import "node:module";
2
+ export { createModuleFederationCssCollector } from "./collector.mjs";
3
+ export { collectModuleFederationManifestCss } from "./manifest.mjs";
4
+ export { injectModuleFederationCssPlugin } from "./plugin.mjs";
5
+ export { collectDirectRemoteModuleFederationCss, collectDirectRemoteModuleFederationCssWithMeta } from "./remote.mjs";
@@ -0,0 +1,70 @@
1
+ import "node:module";
2
+ import { fileReader } from "@modern-js/runtime-utils/fileReader";
3
+ import { fs } from "@modern-js/utils";
4
+ import path from "path";
5
+ const MODULE_FEDERATION_MANIFEST_FILE = 'mf-manifest.json';
6
+ const 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 getHostManifest = async (pwd, monitors)=>{
59
+ const manifestPath = path.join(pwd, MODULE_FEDERATION_MANIFEST_FILE);
60
+ if (!await fs.pathExists(manifestPath)) return;
61
+ const manifestBuffer = await fileReader.readFileFromSystem(manifestPath, 'buffer');
62
+ if (null === manifestBuffer) return;
63
+ try {
64
+ return JSON.parse(manifestBuffer.toString('utf-8'));
65
+ } catch (error) {
66
+ warn(monitors, 'Parse module federation manifest failed, error = %s', error instanceof Error ? error.message : error);
67
+ return;
68
+ }
69
+ };
70
+ export { appendResolvedCssAssets, collectModuleFederationManifestCss, ensureTrailingSlash, getCssAssets, getHostManifest, getManifestFallbackBase, getManifestPublicPathBase, normalizeRemoteEntry, tryResolveUrl, warn };
@@ -0,0 +1,34 @@
1
+ import "node:module";
2
+ import { isProd } from "@modern-js/utils";
3
+ import { DEFAULT_REMOTE_CSS_CACHE_TTL_MS, createModuleFederationCssCollector } from "./collector.mjs";
4
+ const injectModuleFederationCssPlugin = (options = {})=>({
5
+ name: '@modern-js/inject-module-federation-css',
6
+ setup (api) {
7
+ api.onPrepare(()=>{
8
+ const { middlewares, distDirectory: pwd } = api.getServerContext();
9
+ if (!pwd) return;
10
+ const ttlMs = Math.max(0, options.remoteCssCacheTtlMs ?? (isProd() ? DEFAULT_REMOTE_CSS_CACHE_TTL_MS : 0));
11
+ const collector = createModuleFederationCssCollector(pwd, {
12
+ ttlMs
13
+ });
14
+ if (isProd()) collector.collect().catch(()=>{});
15
+ const handler = async (c, next)=>{
16
+ const serverManifest = c.get('serverManifest');
17
+ if (serverManifest && !serverManifest.moduleFederationCssAssets) {
18
+ const monitors = c.get('monitors');
19
+ const moduleFederationCssAssets = await collector.collect(monitors);
20
+ c.set('serverManifest', {
21
+ ...serverManifest,
22
+ moduleFederationCssAssets
23
+ });
24
+ }
25
+ await next();
26
+ };
27
+ middlewares.push({
28
+ name: 'inject-module-federation-css',
29
+ handler
30
+ });
31
+ });
32
+ }
33
+ });
34
+ export { injectModuleFederationCssPlugin };
@@ -0,0 +1,93 @@
1
+ import "node:module";
2
+ import { collectModuleFederationManifestCss, getHostManifest, normalizeRemoteEntry, warn } from "./manifest.mjs";
3
+ const DEFAULT_REMOTE_MANIFEST_TIMEOUT = 1500;
4
+ const fetchJsonWithTimeout = async (url, fetcher, timeout)=>{
5
+ const controller = new AbortController();
6
+ let timeoutId;
7
+ try {
8
+ const response = await Promise.race([
9
+ fetcher(url, {
10
+ signal: controller.signal
11
+ }),
12
+ new Promise((_, reject)=>{
13
+ timeoutId = setTimeout(()=>{
14
+ controller.abort();
15
+ reject(new Error(`Request timed out after ${timeout}ms`));
16
+ }, timeout);
17
+ })
18
+ ]);
19
+ if (!response.ok) throw new Error(`Unexpected status ${response.status}`);
20
+ return await response.json();
21
+ } finally{
22
+ if (timeoutId) clearTimeout(timeoutId);
23
+ }
24
+ };
25
+ const collectDirectRemoteModuleFederationCssWithMeta = async (pwd, options = {})=>{
26
+ const hostManifest = await getHostManifest(pwd, options.monitors);
27
+ if (!hostManifest) return {
28
+ assets: [],
29
+ errored: false
30
+ };
31
+ const fetcher = options.fetcher || globalThis.fetch?.bind(globalThis);
32
+ if (!fetcher) {
33
+ warn(options.monitors, 'Skip module federation remote CSS collection because fetch is unavailable.');
34
+ return {
35
+ assets: [],
36
+ errored: false
37
+ };
38
+ }
39
+ const timeout = options.timeout ?? DEFAULT_REMOTE_MANIFEST_TIMEOUT;
40
+ const remoteResults = await Promise.all((hostManifest.remotes || []).map(async (remote)=>{
41
+ if (!remote.entry) return {
42
+ assets: [],
43
+ errored: false
44
+ };
45
+ const remoteEntry = normalizeRemoteEntry(remote.entry);
46
+ if (!remoteEntry) return {
47
+ assets: [],
48
+ errored: false
49
+ };
50
+ let remoteManifestUrl;
51
+ try {
52
+ remoteManifestUrl = new URL(remoteEntry).toString();
53
+ } catch {
54
+ warn(options.monitors, 'Skip module federation remote CSS collection for non-absolute manifest URL %s', remoteEntry);
55
+ return {
56
+ assets: [],
57
+ errored: false
58
+ };
59
+ }
60
+ try {
61
+ const remoteManifest = await fetchJsonWithTimeout(remoteManifestUrl, fetcher, timeout);
62
+ return {
63
+ assets: collectModuleFederationManifestCss(remoteManifest, remoteManifestUrl),
64
+ errored: false
65
+ };
66
+ } catch (error) {
67
+ warn(options.monitors, 'Load module federation remote manifest %s failed, error = %s', remoteManifestUrl, error instanceof Error ? error.message : error);
68
+ return {
69
+ assets: [],
70
+ errored: true
71
+ };
72
+ }
73
+ }));
74
+ const cssAssets = [];
75
+ const seen = new Set();
76
+ let errored = false;
77
+ for (const result of remoteResults){
78
+ errored = errored || result.errored;
79
+ for (const asset of result.assets)if (!seen.has(asset)) {
80
+ seen.add(asset);
81
+ cssAssets.push(asset);
82
+ }
83
+ }
84
+ return {
85
+ assets: cssAssets,
86
+ errored
87
+ };
88
+ };
89
+ const collectDirectRemoteModuleFederationCss = async (pwd, options = {})=>{
90
+ const { assets } = await collectDirectRemoteModuleFederationCssWithMeta(pwd, options);
91
+ return assets;
92
+ };
93
+ export { collectDirectRemoteModuleFederationCss, collectDirectRemoteModuleFederationCssWithMeta };
@@ -0,0 +1,41 @@
1
+ import "node:module";
2
+ import { createHash, timingSafeEqual } from "node:crypto";
3
+ import { DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER } from "./constants.mjs";
4
+ import { createRuntimeSignalError } from "./errors.mjs";
5
+ function normalizeRuntimeFallbackSignalAuthConfig(configured) {
6
+ const headerName = 'string' == typeof configured?.headerName && configured.headerName.trim() ? configured.headerName.trim().toLowerCase() : DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER;
7
+ const expectedFromEnv = 'string' == typeof configured?.expectedValueEnv && configured.expectedValueEnv.trim().length > 0 ? process.env[configured.expectedValueEnv.trim()] : void 0;
8
+ const expectedFromConfig = 'string' == typeof configured?.expectedValue && configured.expectedValue.trim().length > 0 ? configured.expectedValue.trim() : void 0;
9
+ const expectedValue = expectedFromConfig || expectedFromEnv;
10
+ const enabled = configured?.enabled === true;
11
+ if (enabled && !expectedValue) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] auth.enabled is true but no expected token is configured');
12
+ return {
13
+ enabled,
14
+ headerName,
15
+ expectedValue
16
+ };
17
+ }
18
+ function normalizeRequiredRuntimeFallbackSignalAuthConfig(configured) {
19
+ if (configured?.enabled === false) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] the endpoint cannot be enabled with auth disabled; configure auth.expectedValue or auth.expectedValueEnv');
20
+ try {
21
+ return normalizeRuntimeFallbackSignalAuthConfig({
22
+ ...configured,
23
+ enabled: true
24
+ });
25
+ } catch (_error) {
26
+ throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] enabling the endpoint requires an auth token; configure auth.expectedValue or auth.expectedValueEnv');
27
+ }
28
+ }
29
+ function safeTokenEquals(candidate, expected) {
30
+ const candidateDigest = createHash('sha256').update(candidate).digest();
31
+ const expectedDigest = createHash('sha256').update(expected).digest();
32
+ return timingSafeEqual(candidateDigest, expectedDigest);
33
+ }
34
+ function enforceRuntimeFallbackSignalAuthToken(token, authConfig) {
35
+ if (!authConfig.enabled) return;
36
+ if (!token || !authConfig.expectedValue || !safeTokenEquals(token, authConfig.expectedValue)) throw createRuntimeSignalError('runtime fallback signal auth failed', 'UNAUTHORIZED');
37
+ }
38
+ function enforceRuntimeFallbackSignalAuth(c, runtimeSignalConfig) {
39
+ enforceRuntimeFallbackSignalAuthToken(c.req.header(runtimeSignalConfig.auth.headerName), runtimeSignalConfig.auth);
40
+ }
41
+ export { enforceRuntimeFallbackSignalAuth, enforceRuntimeFallbackSignalAuthToken, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig };
@@ -0,0 +1,11 @@
1
+ import "node:module";
2
+ const DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT = '/_modern/contract-gates/runtime-fallback';
3
+ const DEFAULT_RUNTIME_STATUS_ENDPOINT = '/_modern/runtime/status';
4
+ const DEFAULT_RUNTIME_FALLBACK_GATE_NAME = 'runtime-mf-fallback-health';
5
+ const DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS = 300000;
6
+ const DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES = 16384;
7
+ const DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER = 'x-modernjs-runtime-signal-token';
8
+ const DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW = 30;
9
+ const DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS = 60000;
10
+ const DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS = 10000;
11
+ export { DEFAULT_RUNTIME_FALLBACK_AUTH_HEADER, DEFAULT_RUNTIME_FALLBACK_FAILURE_HOLD_MS, DEFAULT_RUNTIME_FALLBACK_GATE_NAME, DEFAULT_RUNTIME_FALLBACK_MAX_BODY_BYTES, DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, DEFAULT_RUNTIME_FALLBACK_TRUST_DEDUPE_WINDOW_MS, DEFAULT_RUNTIME_FALLBACK_TRUST_MAX_SIGNALS_PER_WINDOW, DEFAULT_RUNTIME_FALLBACK_TRUST_WINDOW_MS, DEFAULT_RUNTIME_STATUS_ENDPOINT };
@@ -0,0 +1,27 @@
1
+ import "node:module";
2
+ import { CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION } from "../contract-gate-snapshot-store/index.mjs";
3
+ async function persistRuntimeFallbackContractGate(payload, runtimeSignalConfig) {
4
+ const now = Date.now();
5
+ const gateSnapshotStore = await runtimeSignalConfig.gateSnapshotStore;
6
+ const snapshot = await gateSnapshotStore.readSnapshot() || {};
7
+ const existingGates = snapshot.gates && 'object' == typeof snapshot.gates ? snapshot.gates : {};
8
+ const reason = 'string' == typeof payload.reason ? payload.reason : 'runtime_fallback';
9
+ const phase = 'string' == typeof payload.phase ? payload.phase : 'unknown';
10
+ const appName = 'string' == typeof payload.appName ? payload.appName : 'unknown';
11
+ const entry = 'string' == typeof payload.entry ? payload.entry : void 0;
12
+ snapshot.schemaVersion = 'number' == typeof snapshot.schemaVersion ? snapshot.schemaVersion : CONTRACT_GATE_SNAPSHOT_SCHEMA_VERSION;
13
+ snapshot.updatedAt = now;
14
+ snapshot.gates = {
15
+ ...existingGates,
16
+ [runtimeSignalConfig.gateName]: {
17
+ passed: false,
18
+ reason: `runtime_fallback:${reason} phase=${phase} app=${appName}${entry ? ` entry=${entry}` : ''}`,
19
+ updatedAt: now,
20
+ expiresAt: now + runtimeSignalConfig.failureHoldMs,
21
+ source: 'runtime-mf-fallback-signal',
22
+ metadata: payload
23
+ }
24
+ };
25
+ await gateSnapshotStore.writeSnapshot(snapshot);
26
+ }
27
+ export { persistRuntimeFallbackContractGate };
@@ -0,0 +1,13 @@
1
+ import "node:module";
2
+ import { DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT } from "./constants.mjs";
3
+ function resolveRuntimeFallbackSignalEndpoint(configuredEndpoint) {
4
+ const rawEndpoint = configuredEndpoint?.trim();
5
+ if (!rawEndpoint) return DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
6
+ if (rawEndpoint.startsWith('/')) return rawEndpoint;
7
+ try {
8
+ return new URL(rawEndpoint).pathname || DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT;
9
+ } catch (_error) {
10
+ return `/${rawEndpoint.replace(/^\/+/, '')}`;
11
+ }
12
+ }
13
+ export { resolveRuntimeFallbackSignalEndpoint };
@@ -0,0 +1,7 @@
1
+ import "node:module";
2
+ function createRuntimeSignalError(message, code) {
3
+ const error = new Error(message);
4
+ error.code = code;
5
+ return error;
6
+ }
7
+ export { createRuntimeSignalError };