@bleedingdev/modern-js-server-runtime-extensions 3.8.3-ultramodern.1 → 3.8.3-ultramodern.3

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 (82) hide show
  1. package/dist/cjs/backend-federation-security/index.js +415 -0
  2. package/dist/cjs/backend-federation-security/node.js +74 -0
  3. package/dist/cjs/contract-gate-snapshot-store/http-store.js +1 -1
  4. package/dist/cjs/contract-gate-snapshot-store/resolve.js +4 -4
  5. package/dist/cjs/{contractGateAutopilot.js → contractGateSnapshotObserver.js} +14 -17
  6. package/dist/cjs/index.js +45 -13
  7. package/dist/cjs/runtime-fallback-signal/resolver.js +3 -3
  8. package/dist/cjs/runtimeLifecycle.js +129 -0
  9. package/dist/cjs/telemetry/{canaryEvaluation.js → healthEvaluation.js} +11 -13
  10. package/dist/cjs/telemetry/{canary.js → healthMonitor.js} +27 -44
  11. package/dist/cjs/telemetry/{canarySetup.js → healthSetup.js} +35 -39
  12. package/dist/cjs/telemetry/lifecycle.js +14 -14
  13. package/dist/cjs/telemetry/plugin.js +9 -9
  14. package/dist/cjs/telemetry/runtimeEndpoints.js +3 -3
  15. package/dist/cjs/telemetryCore.js +4 -4
  16. package/dist/esm/backend-federation-security/index.mjs +361 -0
  17. package/dist/esm/backend-federation-security/node.mjs +30 -0
  18. package/dist/esm/contract-gate-snapshot-store/http-store.mjs +1 -1
  19. package/dist/esm/contract-gate-snapshot-store/resolve.mjs +4 -4
  20. package/dist/esm/{contractGateAutopilot.mjs → contractGateSnapshotObserver.mjs} +12 -15
  21. package/dist/esm/index.mjs +4 -2
  22. package/dist/esm/runtime-fallback-signal/resolver.mjs +3 -3
  23. package/dist/esm/runtimeLifecycle.mjs +82 -0
  24. package/dist/esm/telemetry/{canaryEvaluation.mjs → healthEvaluation.mjs} +9 -11
  25. package/dist/esm/telemetry/{canary.mjs → healthMonitor.mjs} +25 -42
  26. package/dist/esm/telemetry/healthSetup.mjs +65 -0
  27. package/dist/esm/telemetry/lifecycle.mjs +14 -14
  28. package/dist/esm/telemetry/plugin.mjs +8 -8
  29. package/dist/esm/telemetry/runtimeEndpoints.mjs +3 -3
  30. package/dist/esm/telemetryCore.mjs +1 -1
  31. package/dist/esm-node/backend-federation-security/index.mjs +362 -0
  32. package/dist/esm-node/backend-federation-security/node.mjs +31 -0
  33. package/dist/esm-node/contract-gate-snapshot-store/http-store.mjs +1 -1
  34. package/dist/esm-node/contract-gate-snapshot-store/resolve.mjs +4 -4
  35. package/dist/esm-node/{contractGateAutopilot.mjs → contractGateSnapshotObserver.mjs} +12 -15
  36. package/dist/esm-node/index.mjs +4 -2
  37. package/dist/esm-node/runtime-fallback-signal/resolver.mjs +3 -3
  38. package/dist/esm-node/runtimeLifecycle.mjs +83 -0
  39. package/dist/esm-node/telemetry/{canaryEvaluation.mjs → healthEvaluation.mjs} +9 -11
  40. package/dist/esm-node/telemetry/{canary.mjs → healthMonitor.mjs} +25 -42
  41. package/dist/esm-node/telemetry/healthSetup.mjs +66 -0
  42. package/dist/esm-node/telemetry/lifecycle.mjs +14 -14
  43. package/dist/esm-node/telemetry/plugin.mjs +8 -8
  44. package/dist/esm-node/telemetry/runtimeEndpoints.mjs +3 -3
  45. package/dist/esm-node/telemetryCore.mjs +1 -1
  46. package/dist/types/backend-federation-security/index.d.ts +68 -0
  47. package/dist/types/backend-federation-security/node.d.ts +3 -0
  48. package/dist/types/{contractGateAutopilot.d.ts → contractGateSnapshotObserver.d.ts} +7 -6
  49. package/dist/types/index.d.ts +4 -2
  50. package/dist/types/runtime-fallback-signal/resolver.d.ts +2 -2
  51. package/dist/types/runtimeLifecycle.d.ts +10 -0
  52. package/dist/types/telemetry/healthEvaluation.d.ts +20 -0
  53. package/dist/types/telemetry/{canary.d.ts → healthMonitor.d.ts} +31 -28
  54. package/dist/types/telemetry/{canarySetup.d.ts → healthSetup.d.ts} +6 -6
  55. package/dist/types/telemetry/lifecycle.d.ts +4 -4
  56. package/dist/types/telemetry/plugin.d.ts +1 -1
  57. package/dist/types/telemetry/runtimeEndpoints.d.ts +3 -3
  58. package/dist/types/telemetryCore.d.ts +1 -1
  59. package/package.json +46 -8
  60. package/src/backend-federation-security/index.ts +831 -0
  61. package/src/backend-federation-security/node.ts +51 -0
  62. package/src/contract-gate-snapshot-store/http-store.ts +1 -1
  63. package/src/contract-gate-snapshot-store/resolve.ts +4 -4
  64. package/src/{contractGateAutopilot.ts → contractGateSnapshotObserver.ts} +18 -25
  65. package/src/index.ts +42 -6
  66. package/src/runtime-fallback-signal/resolver.ts +5 -5
  67. package/src/runtimeLifecycle.ts +125 -0
  68. package/src/telemetry/{canaryEvaluation.ts → healthEvaluation.ts} +14 -17
  69. package/src/telemetry/{canary.ts → healthMonitor.ts} +72 -84
  70. package/src/telemetry/{canarySetup.ts → healthSetup.ts} +50 -53
  71. package/src/telemetry/lifecycle.ts +20 -20
  72. package/src/telemetry/plugin.ts +16 -16
  73. package/src/telemetry/runtimeEndpoints.ts +6 -6
  74. package/src/telemetryCore.ts +11 -11
  75. package/tests/backendFederationSecurity.test.ts +416 -0
  76. package/tests/{contractGateAutopilot.test.ts → contractGateSnapshotObserver.test.ts} +59 -62
  77. package/tests/runtimeLifecycle.test.ts +107 -0
  78. package/tests/telemetryHealthMonitor.test.ts +187 -0
  79. package/dist/esm/telemetry/canarySetup.mjs +0 -69
  80. package/dist/esm-node/telemetry/canarySetup.mjs +0 -70
  81. package/dist/types/telemetry/canaryEvaluation.d.ts +0 -20
  82. package/tests/telemetryCanaryOrchestrator.test.ts +0 -365
@@ -0,0 +1,362 @@
1
+ import "node:module";
2
+ const DEFAULT_MAX_ENTRY_BYTES = 16777216;
3
+ const DEFAULT_MAX_RESOURCE_BYTES = 1048576;
4
+ const DEFAULT_ENTRY_TIMEOUT_MS = 10000;
5
+ class BackendFederationRemoteEntryError extends Error {
6
+ constructor(code, message, options = {}){
7
+ super(message, void 0 === options.cause ? void 0 : options);
8
+ this.name = 'BackendFederationRemoteEntryError';
9
+ this.code = code;
10
+ this.details = options.details;
11
+ }
12
+ }
13
+ const isRecord = (value)=>'object' == typeof value && null !== value;
14
+ const recordField = (value, key)=>{
15
+ if (!isRecord(value)) return;
16
+ const field = value[key];
17
+ return isRecord(field) ? field : void 0;
18
+ };
19
+ const stringField = (value)=>'string' == typeof value && value.length > 0 ? value : void 0;
20
+ function resolveBackendFederationRemoteEntryVerification(manifest) {
21
+ if (!isRecord(manifest)) return;
22
+ const entry = recordField(manifest, 'entry');
23
+ const sha256 = entry?.sha256;
24
+ const byteLength = entry?.byteLength;
25
+ if (void 0 === sha256 && void 0 === byteLength) return;
26
+ const backendFederation = recordField(manifest, 'backendFederation');
27
+ const boundary = recordField(backendFederation, 'versionBoundary');
28
+ const boundaryDeliveryUnit = recordField(boundary, 'deliveryUnit');
29
+ const deliveryUnit = recordField(backendFederation, 'deliveryUnit');
30
+ const remoteName = stringField(backendFederation?.name) ?? stringField(manifest.name) ?? stringField(manifest.id);
31
+ const entryUrl = stringField(entry?.url);
32
+ const containerEntry = stringField(backendFederation?.containerEntry);
33
+ if ('string' != typeof sha256 || 'number' != typeof byteLength || void 0 === remoteName || void 0 === entryUrl) throw new BackendFederationRemoteEntryError('invalid_verification', '[Module Federation] Backend manifest entry verification requires remote name, entry.url, sha256, and byteLength.');
34
+ if (void 0 !== containerEntry && canonicalEntryUrl(containerEntry).href !== canonicalEntryUrl(entryUrl).href) throw new BackendFederationRemoteEntryError('identity_mismatch', '[Module Federation] Backend manifest containerEntry must match entry.url before remote execution.', {
35
+ details: {
36
+ containerEntry: redactBackendFederationUrl(containerEntry),
37
+ entryUrl: redactBackendFederationUrl(entryUrl)
38
+ }
39
+ });
40
+ const buildMarker = stringField(boundaryDeliveryUnit?.buildMarker) ?? stringField(deliveryUnit?.buildMarker);
41
+ const unitId = stringField(boundaryDeliveryUnit?.unitId) ?? stringField(deliveryUnit?.unitId);
42
+ return {
43
+ byteLength,
44
+ entryUrl,
45
+ remoteName,
46
+ sha256,
47
+ ...buildMarker ? {
48
+ buildMarker
49
+ } : {},
50
+ ...unitId ? {
51
+ unitId
52
+ } : {}
53
+ };
54
+ }
55
+ const canonicalEntryUrl = (value)=>{
56
+ let url;
57
+ try {
58
+ url = new URL(value);
59
+ } catch (cause) {
60
+ throw new BackendFederationRemoteEntryError('invalid_verification', '[Module Federation] Invalid backend federation URL.', {
61
+ cause
62
+ });
63
+ }
64
+ if (url.username || url.password) throw new BackendFederationRemoteEntryError('invalid_verification', '[Module Federation] Backend remote entry URLs must not contain credentials.');
65
+ url.hash = '';
66
+ return url;
67
+ };
68
+ function redactBackendFederationUrl(value) {
69
+ try {
70
+ const url = new URL(value);
71
+ url.username = '';
72
+ url.password = '';
73
+ url.search = '';
74
+ url.hash = '';
75
+ return url.href;
76
+ } catch {
77
+ return '[local or invalid reference]';
78
+ }
79
+ }
80
+ const isLoopback = (hostname)=>'localhost' === hostname || '127.0.0.1' === hostname || '[::1]' === hostname;
81
+ const assertAllowedEntryUrl = (url, allowInsecureHttp)=>{
82
+ if ('https:' === url.protocol) return;
83
+ if ('http:' === url.protocol && (allowInsecureHttp || isLoopback(url.hostname))) return;
84
+ throw new BackendFederationRemoteEntryError('unsupported_entry', `[Module Federation] Backend federation resource ${redactBackendFederationUrl(url.href)} must use HTTPS (loopback HTTP is allowed for local development).`);
85
+ };
86
+ const assertVerification = (remote, verification, expected, allowInsecureHttp)=>{
87
+ if (void 0 !== remote.type && 'commonjs-module' !== remote.type) throw new BackendFederationRemoteEntryError('unsupported_entry', `[Module Federation] Verified backend remote ${remote.name} must be a self-contained CommonJS container.`);
88
+ if (!/^[a-f0-9]{64}$/u.test(verification.sha256)) throw new BackendFederationRemoteEntryError('invalid_verification', '[Module Federation] Backend remote entry SHA-256 must be 64 lowercase hexadecimal characters.');
89
+ if (!Number.isSafeInteger(verification.byteLength) || verification.byteLength < 0) throw new BackendFederationRemoteEntryError('invalid_verification', '[Module Federation] Backend remote entry byteLength must be a non-negative safe integer.');
90
+ const requestedUrl = canonicalEntryUrl(remote.entry);
91
+ const verifiedUrl = canonicalEntryUrl(verification.entryUrl);
92
+ assertAllowedEntryUrl(requestedUrl, allowInsecureHttp);
93
+ if (remote.name !== verification.remoteName || requestedUrl.href !== verifiedUrl.href) throw new BackendFederationRemoteEntryError('identity_mismatch', '[Module Federation] Backend remote name or entry URL does not match its verified identity.', {
94
+ details: {
95
+ requestedEntry: redactBackendFederationUrl(requestedUrl.href),
96
+ requestedName: remote.name,
97
+ verifiedEntry: redactBackendFederationUrl(verifiedUrl.href),
98
+ verifiedName: verification.remoteName
99
+ }
100
+ });
101
+ for (const key of [
102
+ 'buildMarker',
103
+ 'byteLength',
104
+ 'entryUrl',
105
+ 'remoteName',
106
+ 'sha256',
107
+ 'unitId'
108
+ ]){
109
+ const expectedValue = expected[key];
110
+ if (void 0 !== expectedValue && expectedValue !== verification[key]) throw new BackendFederationRemoteEntryError('identity_mismatch', `[Module Federation] Backend remote entry ${key} does not match the trusted expectation.`, {
111
+ details: {
112
+ expected: 'entryUrl' === key && 'string' == typeof expectedValue ? redactBackendFederationUrl(expectedValue) : expectedValue,
113
+ field: key,
114
+ received: 'entryUrl' === key ? redactBackendFederationUrl(verification.entryUrl) : verification[key]
115
+ }
116
+ });
117
+ }
118
+ return requestedUrl;
119
+ };
120
+ const resolveTrustedVerification = (verification, expected)=>{
121
+ if (verification) return verification;
122
+ if ('number' == typeof expected.byteLength && 'string' == typeof expected.entryUrl && 'string' == typeof expected.remoteName && 'string' == typeof expected.sha256) return expected;
123
+ throw new BackendFederationRemoteEntryError('invalid_verification', '[Module Federation] Verified backend network loading requires trusted entryUrl, remoteName, sha256, and byteLength values.');
124
+ };
125
+ const readWithAbort = (promise, signal)=>new Promise((resolve, reject)=>{
126
+ if (signal.aborted) return void reject(signal.reason);
127
+ const onAbort = ()=>reject(signal.reason);
128
+ signal.addEventListener('abort', onAbort, {
129
+ once: true
130
+ });
131
+ promise.then(resolve, reject).finally(()=>{
132
+ signal.removeEventListener('abort', onAbort);
133
+ });
134
+ });
135
+ const parseContentLength = (value)=>{
136
+ if (null === value || !/^\d+$/u.test(value)) return;
137
+ const parsed = Number(value);
138
+ return Number.isSafeInteger(parsed) ? parsed : void 0;
139
+ };
140
+ const sha256Hex = async (bytes, signal)=>{
141
+ const subtle = globalThis.crypto?.subtle;
142
+ if (void 0 === subtle) throw new BackendFederationRemoteEntryError('unsupported_entry', '[Module Federation] Verified backend remote loading requires Web Crypto SHA-256 support.');
143
+ const digest = new Uint8Array(await readWithAbort(subtle.digest('SHA-256', bytes), signal));
144
+ return Array.from(digest, (byte)=>byte.toString(16).padStart(2, '0')).join('');
145
+ };
146
+ async function loadBoundedBackendFederationResource(resourceUrl, options = {}) {
147
+ const requestedUrl = canonicalEntryUrl(resourceUrl);
148
+ assertAllowedEntryUrl(requestedUrl, true === options.allowInsecureHttp);
149
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_RESOURCE_BYTES;
150
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new BackendFederationRemoteEntryError('invalid_verification', '[Module Federation] Backend federation resource maxBytes must be a positive safe integer.');
151
+ const timeoutMs = options.timeoutMs ?? DEFAULT_ENTRY_TIMEOUT_MS;
152
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0) throw new BackendFederationRemoteEntryError('invalid_verification', '[Module Federation] Backend federation resource timeoutMs must be a non-negative safe integer.');
153
+ const controller = new AbortController();
154
+ let timedOut = false;
155
+ let callerAborted = false;
156
+ const onCallerAbort = ()=>{
157
+ callerAborted = true;
158
+ controller.abort(options.signal?.reason);
159
+ };
160
+ if (options.signal?.aborted) onCallerAbort();
161
+ else options.signal?.addEventListener('abort', onCallerAbort, {
162
+ once: true
163
+ });
164
+ const timeout = timeoutMs > 0 ? setTimeout(()=>{
165
+ timedOut = true;
166
+ controller.abort(new Error(`Backend federation ${options.kind ?? 'manifest'} timed out after ${timeoutMs}ms`));
167
+ }, timeoutMs) : void 0;
168
+ const fetchResource = options.fetch ?? globalThis.fetch;
169
+ let reader;
170
+ const resourceKind = options.kind ?? 'manifest';
171
+ const cancellationError = (cause)=>new BackendFederationRemoteEntryError(timedOut ? 'timeout' : 'aborted', timedOut ? `[Module Federation] Backend federation ${resourceKind} timed out after ${timeoutMs}ms.` : `[Module Federation] Backend federation ${resourceKind} loading was aborted.`, {
172
+ cause
173
+ });
174
+ try {
175
+ if (controller.signal.aborted) throw cancellationError(controller.signal.reason);
176
+ if ('function' != typeof fetchResource) throw new BackendFederationRemoteEntryError('fetch_failed', `[Module Federation] Backend federation ${resourceKind} loading requires fetch.`);
177
+ let response;
178
+ try {
179
+ response = await readWithAbort(fetchResource(requestedUrl.href, {
180
+ cache: 'no-store',
181
+ redirect: 'error',
182
+ signal: controller.signal
183
+ }), controller.signal);
184
+ } catch (cause) {
185
+ if (controller.signal.aborted) throw cancellationError(cause);
186
+ throw new BackendFederationRemoteEntryError('fetch_failed', `[Module Federation] Failed to fetch backend federation ${resourceKind}.`, {
187
+ cause
188
+ });
189
+ }
190
+ if (!response.ok) throw new BackendFederationRemoteEntryError('fetch_failed', `[Module Federation] Backend federation ${resourceKind} returned HTTP ${response.status}.`);
191
+ if (response.url) {
192
+ const responseUrl = canonicalEntryUrl(response.url);
193
+ if (responseUrl.href !== requestedUrl.href) throw new BackendFederationRemoteEntryError('redirect_mismatch', `[Module Federation] Backend federation ${resourceKind} redirected outside its trusted URL.`, {
194
+ details: {
195
+ expected: redactBackendFederationUrl(requestedUrl.href),
196
+ received: redactBackendFederationUrl(responseUrl.href)
197
+ }
198
+ });
199
+ }
200
+ const contentLength = parseContentLength(response.headers?.get('content-length') ?? null);
201
+ if (void 0 !== contentLength && contentLength > maxBytes) {
202
+ controller.abort();
203
+ await response.body?.cancel().catch(()=>void 0);
204
+ throw new BackendFederationRemoteEntryError('entry_too_large', `[Module Federation] Backend federation ${resourceKind} declares ${contentLength} bytes, exceeding its ${maxBytes}-byte policy limit.`);
205
+ }
206
+ const chunks = [];
207
+ let byteLength = 0;
208
+ if (response.body) {
209
+ reader = response.body.getReader();
210
+ while(true){
211
+ const result = await readWithAbort(reader.read(), controller.signal);
212
+ if (result.done) break;
213
+ byteLength += result.value.byteLength;
214
+ if (byteLength > maxBytes) throw new BackendFederationRemoteEntryError('entry_too_large', `[Module Federation] Backend federation ${resourceKind} exceeded its ${maxBytes}-byte limit while streaming.`);
215
+ chunks.push(result.value);
216
+ }
217
+ } else if (response.text) {
218
+ const bytes = new TextEncoder().encode(await readWithAbort(response.text(), controller.signal));
219
+ if (bytes.byteLength > maxBytes) throw new BackendFederationRemoteEntryError('entry_too_large', `[Module Federation] Backend federation ${resourceKind} exceeded its ${maxBytes}-byte limit.`);
220
+ chunks.push(bytes);
221
+ byteLength = bytes.byteLength;
222
+ }
223
+ const bytes = new Uint8Array(byteLength);
224
+ let offset = 0;
225
+ for (const chunk of chunks){
226
+ bytes.set(chunk, offset);
227
+ offset += chunk.byteLength;
228
+ }
229
+ if (controller.signal.aborted) throw cancellationError(controller.signal.reason);
230
+ return bytes;
231
+ } catch (cause) {
232
+ if (!controller.signal.aborted) controller.abort(cause);
233
+ await reader?.cancel(cause).catch(()=>void 0);
234
+ if (cause instanceof BackendFederationRemoteEntryError) throw cause;
235
+ if (timedOut || callerAborted) throw cancellationError(cause);
236
+ throw new BackendFederationRemoteEntryError('fetch_failed', `[Module Federation] Backend federation ${resourceKind} loading failed.`, {
237
+ cause
238
+ });
239
+ } finally{
240
+ if (timeout) clearTimeout(timeout);
241
+ options.signal?.removeEventListener('abort', onCallerAbort);
242
+ }
243
+ }
244
+ const evaluateBackendFederationCommonJsEntry = (remote, bytes, evaluator)=>{
245
+ let source;
246
+ try {
247
+ source = new TextDecoder('utf-8', {
248
+ fatal: true
249
+ }).decode(bytes);
250
+ } catch (cause) {
251
+ throw new BackendFederationRemoteEntryError('integrity_mismatch', `[Module Federation] Backend remote ${remote.name} is not valid UTF-8 JavaScript.`, {
252
+ cause
253
+ });
254
+ }
255
+ if (void 0 === evaluator) throw new BackendFederationRemoteEntryError('unsupported_entry', `[Module Federation] Backend remote ${remote.name} requires an explicit runtime evaluator. Node callers should use the Node security subpath; edge callers should use a service binding or native module provider.`);
256
+ const evaluated = evaluator(source, {
257
+ remote
258
+ });
259
+ const defaultExport = 'object' == typeof evaluated && null !== evaluated && 'default' in evaluated ? evaluated.default : void 0;
260
+ const entry = defaultExport ?? evaluated;
261
+ if ('object' != typeof entry || null === entry || 'function' != typeof entry.get) throw new BackendFederationRemoteEntryError('fetch_failed', `[Module Federation] Backend remote ${remote.name} did not evaluate to a container entry.`);
262
+ return entry;
263
+ };
264
+ async function loadVerifiedBackendFederationEntry(options) {
265
+ const verification = resolveTrustedVerification(options.verification, options.expected ?? {});
266
+ const requestedUrl = assertVerification(options.remote, verification, options.expected ?? {}, true === options.allowInsecureHttp);
267
+ const maxBytes = options.maxBytes ?? DEFAULT_MAX_ENTRY_BYTES;
268
+ if (!Number.isSafeInteger(maxBytes) || maxBytes <= 0) throw new BackendFederationRemoteEntryError('invalid_verification', '[Module Federation] Backend remote entry maxBytes must be a positive safe integer.');
269
+ if (verification.byteLength > maxBytes) throw new BackendFederationRemoteEntryError('entry_too_large', `[Module Federation] Backend remote entry exceeds the ${maxBytes}-byte policy limit.`);
270
+ const timeoutMs = options.timeoutMs ?? DEFAULT_ENTRY_TIMEOUT_MS;
271
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs < 0) throw new BackendFederationRemoteEntryError('invalid_verification', '[Module Federation] Backend remote entry timeoutMs must be a non-negative safe integer.');
272
+ const controller = new AbortController();
273
+ let timedOut = false;
274
+ let callerAborted = false;
275
+ const onCallerAbort = ()=>{
276
+ callerAborted = true;
277
+ controller.abort(options.signal?.reason);
278
+ };
279
+ if (options.signal?.aborted) onCallerAbort();
280
+ else options.signal?.addEventListener('abort', onCallerAbort, {
281
+ once: true
282
+ });
283
+ const timeout = timeoutMs > 0 ? setTimeout(()=>{
284
+ timedOut = true;
285
+ controller.abort(new Error(`Backend remote entry timed out after ${timeoutMs}ms`));
286
+ }, timeoutMs) : void 0;
287
+ const fetchEntry = options.fetch ?? globalThis.fetch;
288
+ let reader;
289
+ const cancellationError = (cause)=>new BackendFederationRemoteEntryError(timedOut ? 'timeout' : 'aborted', timedOut ? `[Module Federation] Backend remote ${options.remote.name} timed out after ${timeoutMs}ms.` : `[Module Federation] Backend remote ${options.remote.name} loading was aborted.`, {
290
+ cause
291
+ });
292
+ try {
293
+ if (controller.signal.aborted) throw cancellationError(controller.signal.reason);
294
+ if ('function' != typeof fetchEntry) throw new BackendFederationRemoteEntryError('fetch_failed', '[Module Federation] Backend remote entry loading requires fetch.');
295
+ let response;
296
+ try {
297
+ response = await readWithAbort(fetchEntry(requestedUrl.href, {
298
+ cache: 'no-store',
299
+ redirect: 'error',
300
+ signal: controller.signal
301
+ }), controller.signal);
302
+ } catch (cause) {
303
+ if (controller.signal.aborted) throw cancellationError(cause);
304
+ throw new BackendFederationRemoteEntryError('fetch_failed', `[Module Federation] Failed to fetch backend remote ${options.remote.name}.`, {
305
+ cause
306
+ });
307
+ }
308
+ if (!response.ok) throw new BackendFederationRemoteEntryError('fetch_failed', `[Module Federation] Backend remote ${options.remote.name} returned HTTP ${response.status}.`);
309
+ if (response.url) {
310
+ const responseUrl = canonicalEntryUrl(response.url);
311
+ if (responseUrl.href !== requestedUrl.href) throw new BackendFederationRemoteEntryError('redirect_mismatch', `[Module Federation] Backend remote ${options.remote.name} redirected outside its verified entry URL.`, {
312
+ details: {
313
+ expected: redactBackendFederationUrl(requestedUrl.href),
314
+ received: redactBackendFederationUrl(responseUrl.href)
315
+ }
316
+ });
317
+ }
318
+ const contentLength = parseContentLength(response.headers?.get('content-length') ?? null);
319
+ const byteLimit = Math.min(maxBytes, verification.byteLength);
320
+ if (void 0 !== contentLength && contentLength > maxBytes) {
321
+ controller.abort();
322
+ await response.body?.cancel().catch(()=>void 0);
323
+ throw new BackendFederationRemoteEntryError('entry_too_large', `[Module Federation] Backend remote ${options.remote.name} declares ${contentLength} bytes, exceeding its ${maxBytes}-byte policy limit.`);
324
+ }
325
+ reader = response.body?.getReader();
326
+ const bytes = new Uint8Array(verification.byteLength);
327
+ let byteLength = 0;
328
+ if (reader) while(true){
329
+ const result = await readWithAbort(reader.read(), controller.signal);
330
+ if (result.done) break;
331
+ const nextByteLength = byteLength + result.value.byteLength;
332
+ if (nextByteLength > byteLimit) throw new BackendFederationRemoteEntryError('entry_too_large', `[Module Federation] Backend remote ${options.remote.name} exceeded its ${byteLimit}-byte limit while streaming.`);
333
+ bytes.set(result.value, byteLength);
334
+ byteLength = nextByteLength;
335
+ }
336
+ if (byteLength !== verification.byteLength) throw new BackendFederationRemoteEntryError('byte_length_mismatch', `[Module Federation] Backend remote ${options.remote.name} byte length mismatch.`, {
337
+ details: {
338
+ expected: verification.byteLength,
339
+ received: byteLength
340
+ }
341
+ });
342
+ const actualDigest = await sha256Hex(bytes, controller.signal);
343
+ if (controller.signal.aborted) throw cancellationError(controller.signal.reason);
344
+ if (actualDigest !== verification.sha256) throw new BackendFederationRemoteEntryError('integrity_mismatch', `[Module Federation] Backend remote ${options.remote.name} SHA-256 mismatch.`, {
345
+ details: {
346
+ expected: verification.sha256,
347
+ received: actualDigest
348
+ }
349
+ });
350
+ return evaluateBackendFederationCommonJsEntry(options.remote, bytes, options.evaluateCommonJs);
351
+ } catch (cause) {
352
+ if (!controller.signal.aborted) controller.abort(cause);
353
+ await reader?.cancel(cause).catch(()=>void 0);
354
+ if (cause instanceof BackendFederationRemoteEntryError && !('aborted' === cause.code && timedOut)) throw cause;
355
+ if (controller.signal.aborted && (timedOut || callerAborted)) throw cancellationError(cause);
356
+ throw cause;
357
+ } finally{
358
+ if (timeout) clearTimeout(timeout);
359
+ options.signal?.removeEventListener('abort', onCallerAbort);
360
+ }
361
+ }
362
+ export { BackendFederationRemoteEntryError, evaluateBackendFederationCommonJsEntry, loadBoundedBackendFederationResource, loadVerifiedBackendFederationEntry, redactBackendFederationUrl, resolveBackendFederationRemoteEntryVerification };
@@ -0,0 +1,31 @@
1
+ import "node:module";
2
+ import { createHash } from "node:crypto";
3
+ import { builtinModules, createRequire } from "node:module";
4
+ import { BackendFederationRemoteEntryError } from "./index.mjs";
5
+ const nodeRequire = createRequire(import.meta.url);
6
+ const nodeBuiltins = new Set([
7
+ ...builtinModules,
8
+ ...builtinModules.map((name)=>`node:${name}`)
9
+ ]);
10
+ const toBytes = (value)=>'string' == typeof value ? new TextEncoder().encode(value) : value;
11
+ function createBackendFederationEntryIntegrity(value) {
12
+ const bytes = toBytes(value);
13
+ return {
14
+ byteLength: bytes.byteLength,
15
+ sha256: createHash('sha256').update(bytes).digest('hex')
16
+ };
17
+ }
18
+ const evaluateNodeBackendFederationCommonJs = (source, { remote })=>{
19
+ const module = {
20
+ exports: {}
21
+ };
22
+ const exports = module.exports;
23
+ const requireBuiltin = (specifier)=>{
24
+ if (!nodeBuiltins.has(specifier)) throw new BackendFederationRemoteEntryError('unsupported_entry', `[Module Federation] Backend remote ${remote.name} attempted to require non-builtin module ${specifier}. Bundle package dependencies into the remote entry.`);
25
+ return nodeRequire(specifier);
26
+ };
27
+ const evaluate = new Function('module', 'exports', 'globalThis', 'require', source);
28
+ evaluate(module, exports, globalThis, requireBuiltin);
29
+ return module.exports;
30
+ };
31
+ export { createBackendFederationEntryIntegrity, evaluateNodeBackendFederationCommonJs };
@@ -11,7 +11,7 @@ const BUILTIN_HTTP_STATE_STORE_MODULES = new Set([
11
11
  ]);
12
12
  const normalizeHttpStoreOptions = (options)=>{
13
13
  const endpoint = 'string' == typeof options?.endpoint ? options.endpoint.trim() : '';
14
- if (!endpoint) throw new Error('[telemetry.canary.autopilot] HTTP stateStore requires options.endpoint');
14
+ if (!endpoint) throw new Error('[telemetry.health.snapshot] HTTP stateStore requires options.endpoint');
15
15
  const readMethod = 'string' == typeof options?.readMethod && options.readMethod.trim() ? options.readMethod.trim().toUpperCase() : 'GET';
16
16
  const writeMethod = 'string' == typeof options?.writeMethod && options.writeMethod.trim() ? options.writeMethod.trim().toUpperCase() : 'PUT';
17
17
  const timeoutMsRaw = Number(options?.timeoutMs);
@@ -46,7 +46,7 @@ const resolveContractGateSnapshotStore = async (input)=>{
46
46
  stateStore
47
47
  });
48
48
  if (builtinStore) {
49
- logger?.info?.(`[telemetry.canary.autopilot] using built-in contract gate snapshot store "${builtinStore.name}"`);
49
+ logger?.info?.(`[telemetry.health.snapshot] using built-in contract gate snapshot store "${builtinStore.name}"`);
50
50
  return builtinStore;
51
51
  }
52
52
  const modulePath = resolveStoreModulePath(appDirectory, stateStore.module);
@@ -54,10 +54,10 @@ const resolveContractGateSnapshotStore = async (input)=>{
54
54
  try {
55
55
  mod = await import(toStoreModuleImportSpecifier(modulePath));
56
56
  } catch (error) {
57
- throw new Error(`[telemetry.canary.autopilot] Failed to load stateStore.module "${stateStore.module}" (${modulePath}): ${error instanceof Error ? error.message : String(error)}`);
57
+ throw new Error(`[telemetry.health.snapshot] Failed to load stateStore.module "${stateStore.module}" (${modulePath}): ${error instanceof Error ? error.message : String(error)}`);
58
58
  }
59
59
  const factory = pickStoreFactory(mod);
60
- if (!factory) throw new Error(`[telemetry.canary.autopilot] stateStore.module "${stateStore.module}" does not export createContractGateSnapshotStore()`);
60
+ if (!factory) throw new Error(`[telemetry.health.snapshot] stateStore.module "${stateStore.module}" does not export createContractGateSnapshotStore()`);
61
61
  const store = await factory({
62
62
  appDirectory,
63
63
  gateSnapshotPath,
@@ -65,7 +65,7 @@ const resolveContractGateSnapshotStore = async (input)=>{
65
65
  logger
66
66
  });
67
67
  ensureStoreShape(store, modulePath);
68
- logger?.info?.(`[telemetry.canary.autopilot] using contract gate snapshot store "${store.name || modulePath}"`);
68
+ logger?.info?.(`[telemetry.health.snapshot] using contract gate snapshot store "${store.name || modulePath}"`);
69
69
  return store;
70
70
  };
71
71
  export { isRecord, normalizeSnapshot, resolveContractGateSnapshotStore };
@@ -3,7 +3,7 @@ import { getSnapshotGateNames, normalizeSnapshot } from "./contract-gate-snapsho
3
3
  import { createFileContractGateSnapshotStore } from "./contract-gate-snapshot-store/file-store.mjs";
4
4
  const DEFAULT_POLL_INTERVAL_MS = 15000;
5
5
  const DEFAULT_GATE_STALE_AFTER_MS = 600000;
6
- class ContractGateAutopilot {
6
+ class ContractGateSnapshotObserver {
7
7
  async start() {
8
8
  await this.syncOnce();
9
9
  if (this.poller) return;
@@ -21,8 +21,7 @@ class ContractGateAutopilot {
21
21
  async syncOnce() {
22
22
  const syncGeneration = ++this.syncGeneration;
23
23
  const snapshot = await this.loadSnapshot();
24
- if (syncGeneration !== this.syncGeneration) return 0;
25
- if (!snapshot) return 0;
24
+ if (syncGeneration !== this.syncGeneration || !snapshot) return 0;
26
25
  const snapshotGateNames = getSnapshotGateNames(snapshot);
27
26
  const gates = normalizeSnapshot(snapshot, {
28
27
  now: Date.now(),
@@ -30,13 +29,13 @@ class ContractGateAutopilot {
30
29
  });
31
30
  let updatedCount = snapshotGateNames ? this.clearOmittedGates(snapshotGateNames) : 0;
32
31
  for (const gate of gates){
33
- this.orchestrator.addRequiredContractGate(gate.name);
32
+ this.monitor.addRequiredContractGate(gate.name);
34
33
  const fingerprint = `${gate.passed ? '1' : '0'}:${gate.reason || ''}`;
35
34
  if (this.appliedGateFingerprints.get(gate.name) !== fingerprint) {
36
- this.orchestrator.setContractGate(gate.name, gate.passed, gate.reason);
35
+ this.monitor.setContractGate(gate.name, gate.passed, gate.reason);
37
36
  this.appliedGateFingerprints.set(gate.name, fingerprint);
38
37
  updatedCount += 1;
39
- this.logger?.info?.(`[telemetry.canary.autopilot] gate=${gate.name} passed=${String(gate.passed)} reason=${gate.reason || 'none'}`);
38
+ this.logger?.info?.(`[telemetry.health.snapshot] gate=${gate.name} passed=${String(gate.passed)} reason=${gate.reason || 'none'}`);
40
39
  }
41
40
  }
42
41
  return updatedCount;
@@ -44,29 +43,27 @@ class ContractGateAutopilot {
44
43
  clearOmittedGates(snapshotGateNames) {
45
44
  let updatedCount = 0;
46
45
  for (const gateName of Array.from(this.appliedGateFingerprints.keys()))if (!snapshotGateNames.has(gateName)) {
47
- this.orchestrator.setContractGate(gateName, true);
46
+ this.monitor.setContractGate(gateName, true);
48
47
  this.appliedGateFingerprints.delete(gateName);
49
48
  updatedCount += 1;
50
- this.logger?.info?.(`[telemetry.canary.autopilot] gate=${gateName} passed=true reason=omitted`);
49
+ this.logger?.info?.(`[telemetry.health.snapshot] gate=${gateName} passed=true reason=omitted`);
51
50
  }
52
51
  return updatedCount;
53
52
  }
54
53
  async loadSnapshot() {
55
54
  try {
56
- const snapshot = await this.gateSnapshotStore.readSnapshot();
57
- if (!snapshot) return;
58
- return snapshot;
55
+ return await this.gateSnapshotStore.readSnapshot() || void 0;
59
56
  } catch (error) {
60
57
  const source = this.gateSnapshotPath || this.gateSnapshotStore.name || 'stateStore';
61
- this.logger?.warn?.(`[telemetry.canary.autopilot] failed to load gate snapshot ${source}: ${error instanceof Error ? error.message : String(error)}`);
58
+ this.logger?.warn?.(`[telemetry.health.snapshot] failed to load gate snapshot ${source}: ${error instanceof Error ? error.message : String(error)}`);
62
59
  return;
63
60
  }
64
61
  }
65
62
  constructor(options){
66
63
  this.syncGeneration = 0;
67
64
  this.appliedGateFingerprints = new Map();
68
- this.orchestrator = options.orchestrator;
69
- if (!options.gateSnapshotStore && !options.gateSnapshotPath) throw new Error('ContractGateAutopilot requires gateSnapshotPath or gateSnapshotStore');
65
+ this.monitor = options.monitor;
66
+ if (!options.gateSnapshotStore && !options.gateSnapshotPath) throw new Error('ContractGateSnapshotObserver requires gateSnapshotPath or gateSnapshotStore');
70
67
  this.gateSnapshotPath = options.gateSnapshotPath;
71
68
  this.gateSnapshotStore = options.gateSnapshotStore || createFileContractGateSnapshotStore(options.gateSnapshotPath);
72
69
  this.pollIntervalMs = Math.max(250, options.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);
@@ -74,4 +71,4 @@ class ContractGateAutopilot {
74
71
  this.logger = options.logger;
75
72
  }
76
73
  }
77
- export { ContractGateAutopilot };
74
+ export { ContractGateSnapshotObserver };
@@ -1,6 +1,8 @@
1
1
  import "node:module";
2
- export { ContractGateAutopilot } from "./contractGateAutopilot.mjs";
2
+ export { BackendFederationRemoteEntryError, evaluateBackendFederationCommonJsEntry, loadBoundedBackendFederationResource, loadVerifiedBackendFederationEntry, redactBackendFederationUrl, resolveBackendFederationRemoteEntryVerification } from "./backend-federation-security/index.mjs";
3
+ export { ContractGateSnapshotObserver } from "./contractGateSnapshotObserver.mjs";
3
4
  export { DEFAULT_ENVIRONMENT_NAME, parseServerRuntimeExtensionsEnv } from "./env.mjs";
4
5
  export { getRequestPathname, injectMfAssetCacheHeadersPlugin, isMfManifestAsset, isMfRemoteEntryAsset, resolveMfAssetCacheHeaders } from "./mfCache.mjs";
5
6
  export { collectDirectRemoteModuleFederationCss, collectDirectRemoteModuleFederationCssWithMeta, collectModuleFederationManifestCss, createModuleFederationCssCollector, injectModuleFederationCssPlugin } from "./module-federation-css/index.mjs";
6
- 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";
7
+ export { createDisposableServerRuntimeHandle, disposeServerRuntime, initializeDisposableServerRuntime, registerServerRuntimeDisposer } from "./runtimeLifecycle.mjs";
8
+ export { DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, DEFAULT_RUNTIME_STATUS_ENDPOINT, TelemetryHealthMonitor, TelemetryRegistry, TelemetryStartupHealthError, createOtlpTelemetryExporter, createRuntimeFallbackSignalRuntimeState, createRuntimeSignalError, createTelemetryAwareMetrics, createVictoriaMetricsTelemetryExporter, enforceRuntimeFallbackSignalAuthToken, enforceRuntimeFallbackSignalTrustPolicy, getRuntimeSignalErrorStatusCode, hasEnabledTelemetryExporters, injectTelemetryPlugin, normalizeRequiredRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackSignalAuthConfig, normalizeRuntimeFallbackTrustPolicy, parseRuntimeFallbackSignalPayloadFromRawBody, resolveRuntimeFallbackSignalEndpoint, resolveTelemetrySloOptions } from "./telemetry.mjs";
@@ -12,7 +12,7 @@ function normalizeRuntimeFallbackSignalAuthConfig(configured) {
12
12
  const expectedFromConfig = 'string' == typeof configured?.expectedValue && configured.expectedValue.trim().length > 0 ? configured.expectedValue.trim() : void 0;
13
13
  const expectedValue = expectedFromConfig || expectedFromEnv;
14
14
  const enabled = configured?.enabled === true;
15
- if (enabled && !expectedValue) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] auth.enabled true but no expected token configured');
15
+ if (enabled && !expectedValue) throw new Error('[telemetry.health.runtimeFallbackSignal] auth.enabled true but no expected token configured');
16
16
  return {
17
17
  enabled,
18
18
  headerName,
@@ -20,9 +20,9 @@ function normalizeRuntimeFallbackSignalAuthConfig(configured) {
20
20
  };
21
21
  }
22
22
  function normalizeRequiredRuntimeFallbackSignalAuthConfig(configured) {
23
- if (configured?.enabled === false) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] auth.enabled cannot be false when runtimeFallbackSignal.enabled is true');
23
+ if (configured?.enabled === false) throw new Error('[telemetry.health.runtimeFallbackSignal] auth.enabled cannot be false when runtimeFallbackSignal.enabled is true');
24
24
  const authConfig = normalizeRuntimeFallbackSignalAuthConfig(configured);
25
- if (!authConfig.expectedValue) throw new Error('[telemetry.canary.autopilot.runtimeFallbackSignal] auth.expectedValue or auth.expectedValueEnv is required when runtimeFallbackSignal.enabled is true');
25
+ if (!authConfig.expectedValue) throw new Error('[telemetry.health.runtimeFallbackSignal] auth.expectedValue or auth.expectedValueEnv is required when runtimeFallbackSignal.enabled is true');
26
26
  return {
27
27
  ...authConfig,
28
28
  enabled: true
@@ -0,0 +1,83 @@
1
+ import "node:module";
2
+ const runtimeLifecycleStates = new WeakMap();
3
+ const getRuntimeLifecycleState = (owner)=>{
4
+ let state = runtimeLifecycleStates.get(owner);
5
+ if (!state) {
6
+ state = {
7
+ disposers: new Set(),
8
+ retired: false
9
+ };
10
+ runtimeLifecycleStates.set(owner, state);
11
+ }
12
+ return state;
13
+ };
14
+ const registerServerRuntimeDisposer = (owner, disposer)=>{
15
+ const state = getRuntimeLifecycleState(owner);
16
+ if (state.retired) throw new Error('Cannot register a disposer on a retired server runtime.');
17
+ state.disposers.add(disposer);
18
+ return ()=>{
19
+ state.disposers.delete(disposer);
20
+ };
21
+ };
22
+ const disposeServerRuntime = (owner)=>{
23
+ const state = getRuntimeLifecycleState(owner);
24
+ if (state.disposePromise) return state.disposePromise;
25
+ state.retired = true;
26
+ state.disposePromise = Promise.resolve().then(async ()=>{
27
+ const disposers = [
28
+ ...state.disposers
29
+ ].reverse();
30
+ state.disposers.clear();
31
+ const errors = [];
32
+ for (const disposer of disposers)try {
33
+ await disposer();
34
+ } catch (error) {
35
+ errors.push(error);
36
+ }
37
+ if (errors.length > 0) throw new AggregateError(errors, 'Failed to dispose server runtime.');
38
+ });
39
+ return state.disposePromise;
40
+ };
41
+ const createDisposableServerRuntimeHandle = (owner, handle)=>{
42
+ let activeRequests = 0;
43
+ let retired = false;
44
+ let resolveDrained;
45
+ let drained;
46
+ let disposePromise;
47
+ const disposableHandle = async (request, ...args)=>{
48
+ if (retired) throw new Error('Cannot dispatch through a retired server runtime.');
49
+ activeRequests += 1;
50
+ try {
51
+ return await handle(request, ...args);
52
+ } finally{
53
+ activeRequests -= 1;
54
+ if (0 === activeRequests) resolveDrained?.();
55
+ }
56
+ };
57
+ disposableHandle.dispose = ()=>{
58
+ disposePromise ??= (async ()=>{
59
+ retired = true;
60
+ if (activeRequests > 0) {
61
+ drained ??= new Promise((resolve)=>{
62
+ resolveDrained = resolve;
63
+ });
64
+ await drained;
65
+ }
66
+ await disposeServerRuntime(owner);
67
+ })();
68
+ return disposePromise;
69
+ };
70
+ return disposableHandle;
71
+ };
72
+ const initializeDisposableServerRuntime = async (owner, handle, initialize)=>{
73
+ try {
74
+ await initialize();
75
+ } catch (error) {
76
+ try {
77
+ await disposeServerRuntime(owner);
78
+ } catch {}
79
+ throw error;
80
+ }
81
+ return createDisposableServerRuntimeHandle(owner, handle);
82
+ };
83
+ export { createDisposableServerRuntimeHandle, disposeServerRuntime, initializeDisposableServerRuntime, registerServerRuntimeDisposer };