@bleedingdev/modern-js-federation-runtime 0.0.0 → 3.9.0-ultramodern.5

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 (33) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cjs/module-federation/consume-surface.js +199 -0
  3. package/dist/cjs/module-federation/distributed-ssr.js +135 -0
  4. package/dist/cjs/module-federation/index.js +316 -0
  5. package/dist/cjs/module-federation/last-known-good.js +157 -0
  6. package/dist/cjs/module-federation/manifest-recovery-runtime-plugin.js +130 -0
  7. package/dist/cjs/module-federation/surface-resolution-types.js +61 -0
  8. package/dist/esm/module-federation/consume-surface.mjs +158 -0
  9. package/dist/esm/module-federation/distributed-ssr.mjs +82 -0
  10. package/dist/esm/module-federation/index.mjs +115 -0
  11. package/dist/esm/module-federation/last-known-good.mjs +113 -0
  12. package/dist/esm/module-federation/manifest-recovery-runtime-plugin.mjs +90 -0
  13. package/dist/esm/module-federation/surface-resolution-types.mjs +8 -0
  14. package/dist/esm-node/module-federation/consume-surface.mjs +159 -0
  15. package/dist/esm-node/module-federation/distributed-ssr.mjs +83 -0
  16. package/dist/esm-node/module-federation/index.mjs +116 -0
  17. package/dist/esm-node/module-federation/last-known-good.mjs +114 -0
  18. package/dist/esm-node/module-federation/manifest-recovery-runtime-plugin.mjs +91 -0
  19. package/dist/esm-node/module-federation/surface-resolution-types.mjs +9 -0
  20. package/dist/types/module-federation/consume-surface.d.ts +104 -0
  21. package/dist/types/module-federation/distributed-ssr.d.ts +61 -0
  22. package/dist/types/module-federation/index.d.ts +71 -0
  23. package/dist/types/module-federation/last-known-good.d.ts +52 -0
  24. package/dist/types/module-federation/manifest-recovery-runtime-plugin.d.ts +25 -0
  25. package/dist/types/module-federation/surface-resolution-types.d.ts +23 -0
  26. package/package.json +86 -4
  27. package/src/module-federation/consume-surface.ts +369 -0
  28. package/src/module-federation/distributed-ssr.tsx +240 -0
  29. package/src/module-federation/index.ts +274 -0
  30. package/src/module-federation/last-known-good.ts +292 -0
  31. package/src/module-federation/manifest-recovery-runtime-plugin.ts +215 -0
  32. package/src/module-federation/surface-resolution-types.ts +60 -0
  33. package/README.md +0 -3
@@ -0,0 +1,115 @@
1
+ export * from "./consume-surface.mjs";
2
+ export * from "./distributed-ssr.mjs";
3
+ export * from "./last-known-good.mjs";
4
+ export * from "./manifest-recovery-runtime-plugin.mjs";
5
+ export * from "./surface-resolution-types.mjs";
6
+ const MODULE_FEDERATION_FALLBACK_SIGNAL_EVENT = 'modernjs:mf-runtime-fallback';
7
+ const MODULE_FEDERATION_RECOVERY_SIGNAL_EVENT = 'modernjs:mf-runtime-recovery';
8
+ const DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT = '/_modern/contract-gates/runtime-fallback';
9
+ const DEFAULT_RUNTIME_FALLBACK_SIGNAL_AUTH_HEADER = 'x-modernjs-runtime-signal-token';
10
+ class ModuleFederationRemoteLoadTimeoutError extends Error {
11
+ constructor(remote, timeoutMs){
12
+ super(`Loading remote "${remote}" timed out after ${timeoutMs}ms`);
13
+ this.name = 'ModuleFederationRemoteLoadTimeoutError';
14
+ }
15
+ }
16
+ class ModuleFederationRemoteLoadError extends Error {
17
+ constructor(remote, attempts, causeError){
18
+ super(`Unable to load remote "${remote}" after ${attempts} attempt${attempts > 1 ? 's' : ''}: ${causeError.message}`);
19
+ this.name = 'ModuleFederationRemoteLoadError';
20
+ this.remote = remote;
21
+ this.attempts = attempts;
22
+ this.causeError = causeError;
23
+ }
24
+ }
25
+ class ModuleFederationRemoteComponentContractError extends Error {
26
+ constructor(remote, exportName){
27
+ super(`Remote "${remote}" export "${exportName}" is not a valid React component`);
28
+ this.name = 'ModuleFederationRemoteComponentContractError';
29
+ }
30
+ }
31
+ function toError(error) {
32
+ if (error instanceof Error) return error;
33
+ return new Error('string' == typeof error ? error : 'Unknown remote load error');
34
+ }
35
+ function classifyModuleFederationFallback(error) {
36
+ const normalizedError = toError(error);
37
+ if (normalizedError instanceof ModuleFederationRemoteLoadError) return classifyModuleFederationFallback(normalizedError.causeError);
38
+ if (normalizedError instanceof ModuleFederationRemoteLoadTimeoutError) return 'timeout';
39
+ if (normalizedError instanceof ModuleFederationRemoteComponentContractError) return 'contract';
40
+ const message = normalizedError.message;
41
+ if (/version|requiredVersion|singleton|share scope|shared module/i.test(message)) return 'version-skew';
42
+ if (/network|fetch|script|timeout|chunk|loading/i.test(message)) return 'network';
43
+ return 'remote-unavailable';
44
+ }
45
+ function createModuleFederationFallbackTelemetry(input) {
46
+ const error = void 0 !== input.error ? toError(input.error) : void 0;
47
+ const status = input.status ?? 'degraded';
48
+ const eventName = input.eventName ?? ('recovered' === status ? MODULE_FEDERATION_RECOVERY_SIGNAL_EVENT : MODULE_FEDERATION_FALLBACK_SIGNAL_EVENT);
49
+ const metadata = {
50
+ ...input.metadata ?? {},
51
+ classification: input.classification,
52
+ remote: input.remote,
53
+ status
54
+ };
55
+ if (void 0 !== input.exportName) metadata.exportName = input.exportName;
56
+ if (void 0 !== input.runtimeDigest) metadata.runtimeDigest = input.runtimeDigest;
57
+ if (void 0 !== error) {
58
+ metadata.errorName = error.name;
59
+ metadata.errorMessage = error.message;
60
+ }
61
+ const payload = {
62
+ appName: input.appName,
63
+ eventName,
64
+ metadata,
65
+ phase: input.phase,
66
+ reason: input.classification,
67
+ schemaVersion: 1
68
+ };
69
+ if (void 0 !== input.entry) payload.entry = input.entry;
70
+ if (void 0 !== input.runtimeDigest) payload.runtimeDigest = input.runtimeDigest;
71
+ return payload;
72
+ }
73
+ function toModuleFederationFallbackAttributes(payload) {
74
+ return {
75
+ 'data-mf-fallback-app': payload.appName,
76
+ 'data-mf-fallback-classification': payload.reason,
77
+ 'data-mf-fallback-phase': payload.phase,
78
+ 'data-mf-fallback-remote': String(payload.metadata.remote),
79
+ 'data-mf-fallback-status': String(payload.metadata.status),
80
+ 'data-mf-telemetry-event': payload.eventName
81
+ };
82
+ }
83
+ async function emitModuleFederationFallbackTelemetry(input, options = {}) {
84
+ const payload = createModuleFederationFallbackTelemetry(input);
85
+ if ("u" > typeof window && 'function' == typeof window.dispatchEvent && "u" > typeof CustomEvent) window.dispatchEvent(new CustomEvent(payload.eventName, {
86
+ detail: payload
87
+ }));
88
+ const shouldPost = true === options.postSignal || Boolean(options.endpoint);
89
+ if (!shouldPost) return {
90
+ dispatched: true,
91
+ posted: false
92
+ };
93
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
94
+ if ('function' != typeof fetchImpl) return {
95
+ dispatched: true,
96
+ posted: false
97
+ };
98
+ const headers = new Headers({
99
+ 'content-type': 'application/json'
100
+ });
101
+ if (void 0 !== options.authToken && options.authToken.length > 0) headers.set(options.authHeaderName ?? DEFAULT_RUNTIME_FALLBACK_SIGNAL_AUTH_HEADER, options.authToken);
102
+ const response = await fetchImpl(options.endpoint ?? DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, {
103
+ body: JSON.stringify(payload),
104
+ headers,
105
+ method: 'POST',
106
+ keepalive: true
107
+ });
108
+ return {
109
+ dispatched: true,
110
+ posted: true,
111
+ postStatus: response.status
112
+ };
113
+ }
114
+ export { DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY, useDistributedSsrFragmentProps } from "./distributed-ssr.mjs";
115
+ export { DEFAULT_RUNTIME_FALLBACK_SIGNAL_AUTH_HEADER, DEFAULT_RUNTIME_FALLBACK_SIGNAL_ENDPOINT, MODULE_FEDERATION_FALLBACK_SIGNAL_EVENT, MODULE_FEDERATION_RECOVERY_SIGNAL_EVENT, ModuleFederationRemoteComponentContractError, ModuleFederationRemoteLoadError, ModuleFederationRemoteLoadTimeoutError, classifyModuleFederationFallback, createModuleFederationFallbackTelemetry, emitModuleFederationFallbackTelemetry, toModuleFederationFallbackAttributes };
@@ -0,0 +1,113 @@
1
+ import { selectResolvedSurface } from "@modern-js/surface-resolution";
2
+ import { createDiscoveryError, deliveryUnitResolutionKey } from "./surface-resolution-types.mjs";
3
+ const LAST_KNOWN_GOOD_PROVIDER_NAME = 'last-known-good';
4
+ function createInMemoryLkgStorage() {
5
+ const map = new Map();
6
+ return {
7
+ read (key) {
8
+ return map.get(key);
9
+ },
10
+ write (key, record) {
11
+ map.set(key, record);
12
+ }
13
+ };
14
+ }
15
+ function markDegraded(resolved, reason) {
16
+ return {
17
+ ...resolved,
18
+ compatibility: {
19
+ ...resolved.compatibility,
20
+ status: 'degraded',
21
+ reason
22
+ }
23
+ };
24
+ }
25
+ function staleRecordResult(ref, env, ageMs, maxStaleMs) {
26
+ return {
27
+ ok: false,
28
+ error: createDiscoveryError('stale-record', ref, `Last-known-good record for surface is stale: age ${ageMs}ms exceeds maxStaleMs ${maxStaleMs}ms`, {
29
+ env,
30
+ ageMs,
31
+ maxStaleMs
32
+ })
33
+ };
34
+ }
35
+ function resolutionAnswersRef(resolved, ref) {
36
+ const selected = selectResolvedSurface(resolved, ref);
37
+ return selected.ok && selected.surface.servedMajor === ref.major;
38
+ }
39
+ function createLastKnownGoodProvider(options) {
40
+ const storage = options.storage ?? createInMemoryLkgStorage();
41
+ const now = options.now ?? (()=>Math.floor(performance.timeOrigin + performance.now()));
42
+ const maxStaleMs = options.freshness?.maxStaleMs;
43
+ let nextResolutionGeneration = 0;
44
+ const latestCacheableGenerationByKey = new Map();
45
+ const writeTailByKey = new Map();
46
+ async function cacheCompatibleResolution(key, generation, record) {
47
+ latestCacheableGenerationByKey.set(key, Math.max(latestCacheableGenerationByKey.get(key) ?? 0, generation));
48
+ const previous = writeTailByKey.get(key) ?? Promise.resolve();
49
+ const write = previous.catch(()=>void 0).then(async ()=>{
50
+ if (latestCacheableGenerationByKey.get(key) !== generation) return;
51
+ await storage.write(key, record);
52
+ });
53
+ writeTailByKey.set(key, write);
54
+ try {
55
+ await write;
56
+ } finally{
57
+ if (writeTailByKey.get(key) === write) writeTailByKey.delete(key);
58
+ }
59
+ }
60
+ async function serveFromCache(ref, env, fallback) {
61
+ const key = deliveryUnitResolutionKey(ref.unitId, env);
62
+ const cached = await storage.read(key);
63
+ if (!cached) return fallback();
64
+ if (cached.major !== ref.major) return fallback();
65
+ if (!resolutionAnswersRef(cached.resolved, ref)) return fallback();
66
+ if ('compatible' !== cached.resolved.compatibility.status) return fallback();
67
+ const ageMs = now() - cached.storedAt;
68
+ if (void 0 !== maxStaleMs && ageMs > maxStaleMs) return staleRecordResult(ref, env, ageMs, maxStaleMs);
69
+ return {
70
+ ok: true,
71
+ unit: markDegraded(cached.resolved, `served last-known-good record (age ${ageMs}ms) after provider failure`)
72
+ };
73
+ }
74
+ return {
75
+ name: LAST_KNOWN_GOOD_PROVIDER_NAME,
76
+ async resolve (ref, env) {
77
+ const key = deliveryUnitResolutionKey(ref.unitId, env);
78
+ const generation = ++nextResolutionGeneration;
79
+ let resolution;
80
+ try {
81
+ resolution = await options.provider.resolve(ref, env);
82
+ } catch (error) {
83
+ return serveFromCache(ref, env, ()=>({
84
+ ok: false,
85
+ error: createDiscoveryError('provider-unavailable', ref, error instanceof Error ? error.message : 'provider threw a non-error value', {
86
+ env,
87
+ provider: options.provider.name
88
+ })
89
+ }));
90
+ }
91
+ if (!resolution.ok) {
92
+ const failure = resolution;
93
+ return serveFromCache(ref, env, ()=>failure);
94
+ }
95
+ if (!resolutionAnswersRef(resolution.unit, ref)) return serveFromCache(ref, env, ()=>({
96
+ ok: false,
97
+ error: createDiscoveryError('identity-mismatch', ref, `Provider ${options.provider.name} returned a delivery unit that does not answer the requested surface.`, {
98
+ env,
99
+ provider: options.provider.name,
100
+ recordUnitId: resolution.unit.unitId,
101
+ availableSurfaces: resolution.unit.surfaces.map((surface)=>surface.surfaceId)
102
+ })
103
+ }));
104
+ if ('compatible' === resolution.unit.compatibility.status) await cacheCompatibleResolution(key, generation, {
105
+ resolved: resolution.unit,
106
+ storedAt: now(),
107
+ major: ref.major
108
+ });
109
+ return resolution;
110
+ }
111
+ };
112
+ }
113
+ export { LAST_KNOWN_GOOD_PROVIDER_NAME, createInMemoryLkgStorage, createLastKnownGoodProvider };
@@ -0,0 +1,90 @@
1
+ const DEFAULT_ATTEMPTS = 3;
2
+ const DEFAULT_RETRY_DELAY_MS = 100;
3
+ const DEFAULT_TIMEOUT_MS = 1000;
4
+ const MAX_ATTEMPTS = 5;
5
+ const MAX_RETRY_DELAY_MS = 1000;
6
+ const MAX_TIMEOUT_MS = 5000;
7
+ const RETRYABLE_HTTP_STATUSES = new Set([
8
+ 408,
9
+ 425,
10
+ 429,
11
+ 500,
12
+ 502,
13
+ 503,
14
+ 504
15
+ ]);
16
+ const NON_RETRYABLE_ERROR_PATTERNS = [
17
+ /RUNTIME-013/i,
18
+ /invalid manifest/i,
19
+ /manifest (?:schema|contract|version|identity)/i,
20
+ /(?:incompatible|mismatch).*(?:manifest|remote)/i
21
+ ];
22
+ const clampInteger = (value, fallback, minimum, maximum)=>{
23
+ if (void 0 === value || !Number.isFinite(value)) return fallback;
24
+ return Math.min(maximum, Math.max(minimum, Math.floor(value)));
25
+ };
26
+ const getErrorMessage = (error)=>{
27
+ if (error instanceof Error) return error.message;
28
+ return 'string' == typeof error ? error : '';
29
+ };
30
+ const getErrorStatus = (error)=>{
31
+ if ('object' == typeof error && null !== error && 'status' in error && 'number' == typeof error.status) return error.status;
32
+ };
33
+ const isRetryableError = (error)=>{
34
+ if (error instanceof SyntaxError) return false;
35
+ const message = getErrorMessage(error);
36
+ if (NON_RETRYABLE_ERROR_PATTERNS.some((pattern)=>pattern.test(message))) return false;
37
+ const status = getErrorStatus(error);
38
+ if (void 0 !== status) return RETRYABLE_HTTP_STATUSES.has(status);
39
+ if (error instanceof Error && [
40
+ 'AbortError',
41
+ 'TimeoutError'
42
+ ].includes(error.name)) return true;
43
+ return error instanceof TypeError || /(?:fetch failed|network|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN)/i.test(message);
44
+ };
45
+ const isHttpManifestUrl = (id)=>{
46
+ if (void 0 === id || 0 === id.length) return false;
47
+ try {
48
+ const url = new URL(id);
49
+ return ('http:' === url.protocol || 'https:' === url.protocol) && url.pathname.endsWith('.json');
50
+ } catch {
51
+ return false;
52
+ }
53
+ };
54
+ const defaultWait = (milliseconds)=>new Promise((resolve)=>{
55
+ setTimeout(resolve, milliseconds);
56
+ });
57
+ const fetchWithTimeout = (fetchImpl, url, timeoutMs)=>fetchImpl(url, {
58
+ signal: AbortSignal.timeout(timeoutMs)
59
+ });
60
+ const createModuleFederationManifestRecoveryPlugin = (options = {})=>{
61
+ const attempts = clampInteger(options.attempts, DEFAULT_ATTEMPTS, 1, MAX_ATTEMPTS);
62
+ const retryDelayMs = clampInteger(options.retryDelayMs, DEFAULT_RETRY_DELAY_MS, 0, MAX_RETRY_DELAY_MS);
63
+ const timeoutMs = clampInteger(options.timeoutMs, DEFAULT_TIMEOUT_MS, 1, MAX_TIMEOUT_MS);
64
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
65
+ const waitImpl = options.waitImpl ?? defaultWait;
66
+ const recoverManifest = (url, attempt)=>{
67
+ const fetchManifest = ()=>Promise.resolve().then(()=>fetchWithTimeout(fetchImpl, url, timeoutMs)).then((response)=>{
68
+ if (!response.ok) {
69
+ if (!RETRYABLE_HTTP_STATUSES.has(response.status) || attempt === attempts - 1) return;
70
+ return recoverManifest(url, attempt + 1);
71
+ }
72
+ return Promise.resolve().then(()=>response.json()).then((manifest)=>manifest, ()=>void 0);
73
+ }, (error)=>{
74
+ if (!isRetryableError(error) || attempt === attempts - 1) return;
75
+ return recoverManifest(url, attempt + 1);
76
+ });
77
+ if (attempt > 0 && retryDelayMs > 0) return waitImpl(retryDelayMs).then(fetchManifest);
78
+ return fetchManifest();
79
+ };
80
+ return {
81
+ name: 'modern-js-manifest-recovery-plugin',
82
+ errorLoadRemote (args) {
83
+ if ('afterResolve' !== args.lifecycle || !isHttpManifestUrl(args.id) || !isRetryableError(args.error) || 'function' != typeof fetchImpl) return Promise.resolve(void 0);
84
+ return recoverManifest(args.id, 0);
85
+ }
86
+ };
87
+ };
88
+ const manifest_recovery_runtime_plugin = createModuleFederationManifestRecoveryPlugin;
89
+ export default manifest_recovery_runtime_plugin;
90
+ export { createModuleFederationManifestRecoveryPlugin };
@@ -0,0 +1,8 @@
1
+ import { createDiscoveryError, formatSurfaceRef, parseSurfaceRef, validateSurfaceRef } from "@modern-js/surface-resolution";
2
+ function surfaceResolutionKey(ref, env) {
3
+ return `${env}::${formatSurfaceRef(ref)}`;
4
+ }
5
+ function deliveryUnitResolutionKey(unitId, env) {
6
+ return `${env}::${unitId}`;
7
+ }
8
+ export { createDiscoveryError, deliveryUnitResolutionKey, formatSurfaceRef, parseSurfaceRef, surfaceResolutionKey, validateSurfaceRef };
@@ -0,0 +1,159 @@
1
+ import "node:module";
2
+ import { classifyModuleFederationFallback, createModuleFederationFallbackTelemetry, emitModuleFederationFallbackTelemetry } from "./index.mjs";
3
+ import { createDiscoveryError, formatSurfaceRef, parseSurfaceRef, validateSurfaceRef } from "./surface-resolution-types.mjs";
4
+ function classifyDiscoveryError(code) {
5
+ switch(code){
6
+ case 'major-not-published':
7
+ case 'stale-record':
8
+ return 'version-skew';
9
+ case 'identity-mismatch':
10
+ return 'contract';
11
+ case 'unknown-unit':
12
+ case 'unknown-surface':
13
+ case 'provider-unavailable':
14
+ return 'remote-unavailable';
15
+ default:
16
+ return 'remote-unavailable';
17
+ }
18
+ }
19
+ function toRemoteString(ref) {
20
+ return void 0 === validateSurfaceRef(ref) ? formatSurfaceRef(ref) : `${ref.unitId}#${ref.surfaceId}`;
21
+ }
22
+ async function reportFailure(options, ref, base) {
23
+ const remote = toRemoteString(ref);
24
+ const telemetry = createModuleFederationFallbackTelemetry({
25
+ appName: options.appName,
26
+ classification: base.classification,
27
+ error: base.error ?? base.discoveryError,
28
+ metadata: {
29
+ env: options.env,
30
+ surfaceRef: remote,
31
+ ...base.discoveryError ? {
32
+ discoveryErrorCode: base.discoveryError.code
33
+ } : {},
34
+ ...base.resolved ? {
35
+ buildMarker: base.resolved.buildMarker
36
+ } : {}
37
+ },
38
+ phase: base.phase,
39
+ remote,
40
+ status: 'degraded'
41
+ });
42
+ try {
43
+ await emitModuleFederationFallbackTelemetry({
44
+ appName: options.appName,
45
+ classification: base.classification,
46
+ error: base.error ?? base.discoveryError,
47
+ metadata: telemetry.metadata,
48
+ phase: base.phase,
49
+ remote,
50
+ status: 'degraded'
51
+ }, options.telemetry ?? {});
52
+ } catch {}
53
+ const failure = {
54
+ ref,
55
+ env: options.env,
56
+ phase: base.phase,
57
+ classification: base.classification,
58
+ telemetry
59
+ };
60
+ if (base.discoveryError) failure.discoveryError = base.discoveryError;
61
+ if (void 0 !== base.error) failure.error = base.error;
62
+ if (base.resolved) failure.resolved = base.resolved;
63
+ const critical = (options.classification ?? 'critical') === 'critical';
64
+ const reason = base.discoveryError ?? (void 0 !== base.error ? base.error : createDiscoveryError('identity-mismatch', remote, `resolved record for "${remote}" is incompatible`, {
65
+ env: options.env
66
+ }));
67
+ let degradedValue;
68
+ try {
69
+ degradedValue = await options.degraded(failure);
70
+ } catch (handlerError) {
71
+ try {
72
+ await emitModuleFederationFallbackTelemetry({
73
+ appName: options.appName,
74
+ classification: base.classification,
75
+ error: handlerError,
76
+ metadata: {
77
+ ...telemetry.metadata,
78
+ degradedHandlerFailed: true
79
+ },
80
+ phase: base.phase,
81
+ remote,
82
+ status: 'failed'
83
+ }, options.telemetry ?? {});
84
+ } catch {}
85
+ if (critical) throw reason;
86
+ return;
87
+ }
88
+ if (critical) throw reason;
89
+ return degradedValue;
90
+ }
91
+ async function consumeSurface(options) {
92
+ let ref;
93
+ if ('string' == typeof options.ref) {
94
+ const parsed = parseSurfaceRef(options.ref);
95
+ if (!parsed.ok) {
96
+ const hashIndex = options.ref.indexOf('#');
97
+ const echoed = -1 === hashIndex ? {
98
+ unitId: options.ref,
99
+ surfaceId: ''
100
+ } : {
101
+ unitId: options.ref.slice(0, hashIndex),
102
+ surfaceId: options.ref.slice(hashIndex + 1)
103
+ };
104
+ return reportFailure(options, echoed, {
105
+ phase: 'discovery',
106
+ classification: 'remote-unavailable',
107
+ discoveryError: createDiscoveryError('unknown-surface', options.ref, `SurfaceRef "${options.ref}" is not a valid canonical reference (${parsed.error.code}).`, {
108
+ parseError: parsed.error,
109
+ env: options.env
110
+ })
111
+ });
112
+ }
113
+ ref = parsed.ref;
114
+ } else ref = options.ref;
115
+ let resolution;
116
+ try {
117
+ resolution = await options.provider.resolve(ref, options.env);
118
+ } catch (error) {
119
+ return reportFailure(options, ref, {
120
+ phase: 'discovery',
121
+ classification: classifyModuleFederationFallback(error),
122
+ error
123
+ });
124
+ }
125
+ if (!resolution.ok) return reportFailure(options, ref, {
126
+ phase: 'discovery',
127
+ classification: classifyDiscoveryError(resolution.error.code),
128
+ discoveryError: resolution.error
129
+ });
130
+ const resolved = resolution.unit;
131
+ if ('incompatible' === resolved.compatibility.status) return reportFailure(options, ref, {
132
+ phase: 'discovery',
133
+ classification: 'contract',
134
+ resolved
135
+ });
136
+ try {
137
+ return await options.load({
138
+ resolved,
139
+ ref,
140
+ env: options.env
141
+ });
142
+ } catch (error) {
143
+ return reportFailure(options, ref, {
144
+ phase: 'load',
145
+ classification: classifyModuleFederationFallback(error),
146
+ error,
147
+ resolved
148
+ });
149
+ }
150
+ }
151
+ function createSurfaceConsumer(base) {
152
+ return function(options) {
153
+ return consumeSurface({
154
+ ...base,
155
+ ...options
156
+ });
157
+ };
158
+ }
159
+ export { consumeSurface, createSurfaceConsumer };
@@ -0,0 +1,83 @@
1
+ import "node:module";
2
+ import { jsx } from "react/jsx-runtime";
3
+ import { useRuntimeContext } from "@modern-js/runtime";
4
+ const DISTRIBUTED_SSR_FRAGMENTS_LOCALS_KEY = '__modernDistributedSsrFragments';
5
+ const DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY = '__modernDistributedSsrFragmentRequest';
6
+ function distributedSsrFragmentKey(remote, expose) {
7
+ return `${remote}::${expose}`;
8
+ }
9
+ function getDistributedSsrFragmentContext(response) {
10
+ const locals = response?.locals;
11
+ if ('object' != typeof locals || null === locals) return;
12
+ const context = DISTRIBUTED_SSR_FRAGMENTS_LOCALS_KEY in locals ? locals[DISTRIBUTED_SSR_FRAGMENTS_LOCALS_KEY] : void 0;
13
+ if ('object' != typeof context || null === context) return;
14
+ return context;
15
+ }
16
+ function useDistributedSsrFragmentProps({ boundaryId, expose }) {
17
+ const runtimeContext = useRuntimeContext();
18
+ const locals = runtimeContext.requestContext?.response?.locals;
19
+ const request = 'object' == typeof locals && null !== locals && DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY in locals ? locals[DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY] : void 0;
20
+ if ('object' != typeof request || null === request || !('boundaryId' in request) || request.boundaryId !== boundaryId || !('expose' in request) || request.expose !== expose) throw new Error(`Distributed SSR fragment request contract mismatch for ${boundaryId} ${expose}.`);
21
+ const props = 'props' in request ? request.props : void 0;
22
+ if ('object' != typeof props || null === props || Array.isArray(props)) throw new Error(`Distributed SSR fragment request props must be an object for ${boundaryId} ${expose}.`);
23
+ return props;
24
+ }
25
+ function isThenable(value) {
26
+ return void 0 !== value && 'then' in value && 'function' == typeof value.then;
27
+ }
28
+ function DistributedSsrBoundary({ children, expose, fallback, fragmentProps, remote }) {
29
+ const runtimeContext = useRuntimeContext();
30
+ const key = distributedSsrFragmentKey(remote, expose);
31
+ const attributes = {
32
+ 'data-modern-distributed-ssr-boundary': key
33
+ };
34
+ if (runtimeContext.isBrowser) return /*#__PURE__*/ jsx("div", {
35
+ ...attributes,
36
+ children: children
37
+ });
38
+ const fragmentContext = getDistributedSsrFragmentContext(runtimeContext.requestContext?.response);
39
+ if (void 0 === fragmentContext) return /*#__PURE__*/ jsx("div", {
40
+ ...attributes,
41
+ children: children
42
+ });
43
+ const resolverFragmentProps = void 0 === fragmentProps ? {} : Object.fromEntries(Object.entries(fragmentProps));
44
+ const fragmentOrPromise = fragmentContext.resolve?.(remote, expose, resolverFragmentProps) ?? fragmentContext.fragments?.[key];
45
+ if (isThenable(fragmentOrPromise)) throw fragmentOrPromise;
46
+ const fragment = fragmentOrPromise;
47
+ if (fragment?.status === 'ready') return /*#__PURE__*/ jsx("div", {
48
+ ...attributes,
49
+ "data-modern-distributed-ssr-build": fragment.buildMarker,
50
+ "data-modern-distributed-ssr-digest": fragment.digest,
51
+ "data-modern-distributed-ssr-status": "ready",
52
+ dangerouslySetInnerHTML: {
53
+ __html: fragment.html
54
+ }
55
+ });
56
+ return /*#__PURE__*/ jsx("div", {
57
+ ...attributes,
58
+ "data-modern-distributed-ssr-reason": fragment?.reason ?? 'missing',
59
+ "data-modern-distributed-ssr-status": "degraded",
60
+ children: fallback
61
+ });
62
+ }
63
+ function createDistributedSsrComponent({ createComponent, expose, fallback, remote }) {
64
+ let RemoteComponent;
65
+ function DeferredRemoteComponent(props) {
66
+ RemoteComponent ??= createComponent();
67
+ return /*#__PURE__*/ jsx(RemoteComponent, {
68
+ ...props
69
+ });
70
+ }
71
+ return function(props) {
72
+ return /*#__PURE__*/ jsx(DistributedSsrBoundary, {
73
+ expose: expose,
74
+ fallback: fallback,
75
+ fragmentProps: props,
76
+ remote: remote,
77
+ children: /*#__PURE__*/ jsx(DeferredRemoteComponent, {
78
+ ...props
79
+ })
80
+ });
81
+ };
82
+ }
83
+ export { DISTRIBUTED_SSR_FRAGMENTS_LOCALS_KEY, DISTRIBUTED_SSR_FRAGMENT_REQUEST_LOCALS_KEY, DistributedSsrBoundary, createDistributedSsrComponent, distributedSsrFragmentKey, useDistributedSsrFragmentProps };