@bleedingdev/modern-js-runtime-extensions 3.9.0-ultramodern.4 → 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.
- package/dist/cjs/contextExtensions.js +74 -0
- package/dist/cjs/headRuntime.js +91 -0
- package/dist/cjs/helmetContext.js +54 -0
- package/dist/cjs/index.js +18 -4
- package/dist/cjs/prefetchPolicy.js +52 -0
- package/dist/cjs/request-policy/browser.js +139 -0
- package/dist/cjs/request-policy/client.js +234 -0
- package/dist/cjs/request-policy/node.js +149 -0
- package/dist/cjs/request-policy/policyCore.js +266 -0
- package/dist/cjs/request-policy/requestContext.js +137 -0
- package/dist/cjs/request-policy/traceparent.js +56 -0
- package/dist/cjs/request-policy/transport.js +234 -0
- package/dist/cjs/request-policy/types.js +57 -0
- package/dist/cjs/routeHydration.js +127 -0
- package/dist/cjs/routerPrefetchPolicy.js +153 -0
- package/dist/cjs/routerProvider.js +170 -0
- package/dist/cjs/routerState.js +167 -0
- package/dist/cjs/routerStatePlugin.js +86 -0
- package/dist/cjs/routerStateTypes.js +18 -0
- package/dist/cjs/runtimeContextProjection.js +112 -0
- package/dist/cjs/server-config/bffRuntime.js +18 -0
- package/dist/cjs/server-config/index.js +18 -0
- package/dist/cjs/server-config/serverTelemetry.js +18 -0
- package/dist/cjs/shellStream.js +34 -2
- package/dist/cjs/workspaceEvents.js +159 -0
- package/dist/esm/contextExtensions.mjs +33 -0
- package/dist/esm/headRuntime.mjs +43 -0
- package/dist/esm/helmetContext.mjs +13 -0
- package/dist/esm/index.mjs +2 -0
- package/dist/esm/prefetchPolicy.mjs +11 -0
- package/dist/esm/request-policy/browser.mjs +11 -0
- package/dist/esm/request-policy/client.mjs +195 -0
- package/dist/esm/request-policy/policyCore.mjs +171 -0
- package/dist/esm/request-policy/requestContext.mjs +75 -0
- package/dist/esm/request-policy/traceparent.mjs +18 -0
- package/dist/esm/request-policy/transport.mjs +196 -0
- package/dist/esm/request-policy/types.mjs +10 -0
- package/dist/esm/routeHydration.mjs +77 -0
- package/dist/esm/routerPrefetchPolicy.mjs +115 -0
- package/dist/esm/routerProvider.mjs +117 -0
- package/dist/esm/routerState.mjs +105 -0
- package/dist/esm/routerStatePlugin.mjs +48 -0
- package/dist/esm/routerStateTypes.mjs +0 -0
- package/dist/esm/runtimeContextProjection.mjs +74 -0
- package/dist/esm/server-config/bffRuntime.mjs +0 -0
- package/dist/esm/server-config/index.mjs +0 -0
- package/dist/esm/server-config/serverTelemetry.mjs +0 -0
- package/dist/esm/shellStream.mjs +34 -2
- package/dist/esm/workspaceEvents.mjs +66 -0
- package/dist/esm-node/contextExtensions.mjs +34 -0
- package/dist/esm-node/headRuntime.mjs +44 -0
- package/dist/esm-node/helmetContext.mjs +14 -0
- package/dist/esm-node/index.mjs +2 -0
- package/dist/esm-node/prefetchPolicy.mjs +12 -0
- package/dist/esm-node/request-policy/browser.mjs +12 -0
- package/dist/esm-node/request-policy/client.mjs +196 -0
- package/dist/esm-node/request-policy/node.mjs +22 -0
- package/dist/esm-node/request-policy/policyCore.mjs +172 -0
- package/dist/esm-node/request-policy/requestContext.mjs +76 -0
- package/dist/esm-node/request-policy/traceparent.mjs +19 -0
- package/dist/esm-node/request-policy/transport.mjs +197 -0
- package/dist/esm-node/request-policy/types.mjs +11 -0
- package/dist/esm-node/routeHydration.mjs +78 -0
- package/dist/esm-node/routerPrefetchPolicy.mjs +116 -0
- package/dist/esm-node/routerProvider.mjs +118 -0
- package/dist/esm-node/routerState.mjs +106 -0
- package/dist/esm-node/routerStatePlugin.mjs +49 -0
- package/dist/esm-node/routerStateTypes.mjs +1 -0
- package/dist/esm-node/runtimeContextProjection.mjs +75 -0
- package/dist/esm-node/server-config/bffRuntime.mjs +1 -0
- package/dist/esm-node/server-config/index.mjs +1 -0
- package/dist/esm-node/server-config/serverTelemetry.mjs +1 -0
- package/dist/esm-node/shellStream.mjs +34 -2
- package/dist/esm-node/workspaceEvents.mjs +67 -0
- package/dist/types/contextExtensions.d.ts +34 -0
- package/dist/types/headRuntime.d.ts +12 -0
- package/dist/types/helmetContext.d.ts +10 -0
- package/dist/types/index.d.ts +2 -0
- package/dist/types/prefetchPolicy.d.ts +4 -0
- package/dist/types/request-policy/browser.d.ts +10 -0
- package/dist/types/request-policy/client.d.ts +14 -0
- package/dist/types/request-policy/node.d.ts +10 -0
- package/dist/types/request-policy/policyCore.d.ts +107 -0
- package/dist/types/request-policy/requestContext.d.ts +22 -0
- package/dist/types/request-policy/traceparent.d.ts +10 -0
- package/dist/types/request-policy/transport.d.ts +12 -0
- package/dist/types/request-policy/types.d.ts +144 -0
- package/dist/types/routeHydration.d.ts +24 -0
- package/dist/types/routerPrefetchPolicy.d.ts +28 -0
- package/dist/types/routerProvider.d.ts +77 -0
- package/dist/types/routerState.d.ts +12 -0
- package/dist/types/routerStatePlugin.d.ts +19 -0
- package/dist/types/routerStateTypes.d.ts +40 -0
- package/dist/types/runtimeContextProjection.d.ts +30 -0
- package/dist/types/server-config/bffRuntime.d.ts +122 -0
- package/dist/types/server-config/index.d.ts +2 -0
- package/dist/types/server-config/serverTelemetry.d.ts +322 -0
- package/dist/types/workspaceEvents.d.ts +62 -0
- package/package.json +198 -13
- package/rslib.config.mts +17 -2
- package/rstest.config.mts +33 -2
- package/src/contextExtensions.ts +81 -0
- package/src/headRuntime.tsx +77 -0
- package/src/helmetContext.ts +31 -0
- package/src/index.ts +2 -0
- package/src/prefetchPolicy.ts +33 -0
- package/src/request-policy/browser.ts +22 -0
- package/src/request-policy/client.ts +404 -0
- package/src/request-policy/node.ts +41 -0
- package/src/request-policy/policyCore.ts +424 -0
- package/src/request-policy/requestContext.ts +149 -0
- package/src/request-policy/traceparent.ts +43 -0
- package/src/request-policy/transport.ts +349 -0
- package/src/request-policy/types.ts +229 -0
- package/src/routeHydration.ts +208 -0
- package/src/routerPrefetchPolicy.ts +195 -0
- package/src/routerProvider.ts +340 -0
- package/src/routerState.ts +208 -0
- package/src/routerStatePlugin.ts +86 -0
- package/src/routerStateTypes.ts +46 -0
- package/src/runtimeContextProjection.ts +105 -0
- package/src/server-config/bffRuntime.ts +136 -0
- package/src/server-config/index.ts +2 -0
- package/src/server-config/serverTelemetry.ts +337 -0
- package/src/shellStream.ts +55 -25
- package/src/workspaceEvents.ts +324 -0
- package/tests/buildIdentity.test.ts +2 -4
- package/tests/contextExtensions.test.ts +71 -0
- package/tests/headRuntime.test.tsx +369 -0
- package/tests/nativeSafeFailureCompatibility.test.ts +117 -0
- package/tests/prefetchPolicy.test.ts +51 -0
- package/tests/rendererHead.test.ts +1 -72
- package/tests/request-policy/browser-policy.test.ts +608 -0
- package/tests/request-policy/client-isolation.test.ts +149 -0
- package/tests/request-policy/identityBinding.test.ts +75 -0
- package/tests/request-policy/node-policy.test.ts +741 -0
- package/tests/request-policy/policyCore.test.ts +250 -0
- package/tests/request-policy/requestContext.test.ts +80 -0
- package/tests/request-policy/requestFactory.outbound-contract.test.ts +691 -0
- package/tests/request-policy/traceparent.test.ts +55 -0
- package/tests/request-policy/transport-retry.test.ts +370 -0
- package/tests/routeHydration.test.ts +180 -0
- package/tests/routerPrefetchPolicy.test.ts +102 -0
- package/tests/routerProvider.test.ts +38 -0
- package/tests/routerState.test.ts +157 -0
- package/tests/routerStatePlugin.test.ts +108 -0
- package/tests/runtimeContextProjection.test.ts +135 -0
- package/tests/shellStream.test.ts +37 -0
- package/tests/workspaceEvents.test.ts +391 -0
- package/dist/cjs/rscHtmlStream.js +0 -128
- package/dist/esm/rscHtmlStream.mjs +0 -86
- package/dist/esm-node/rscHtmlStream.mjs +0 -87
- package/dist/types/rscHtmlStream.d.ts +0 -4
- package/src/rscHtmlStream.ts +0 -142
- package/tests/rscHtmlStream.test.ts +0 -153
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
const DEFAULT_RETRYABLE_STATUS_CODES = [
|
|
3
|
+
408,
|
|
4
|
+
425,
|
|
5
|
+
429,
|
|
6
|
+
500,
|
|
7
|
+
502,
|
|
8
|
+
503,
|
|
9
|
+
504
|
|
10
|
+
];
|
|
11
|
+
const DEFAULT_BASE_DELAY_MS = 100;
|
|
12
|
+
const DEFAULT_MAX_DELAY_MS = 1000;
|
|
13
|
+
const DEFAULT_JITTER_RATIO = 0.1;
|
|
14
|
+
const DEFAULT_RETRYABLE_METHODS = new Set([
|
|
15
|
+
'DELETE',
|
|
16
|
+
'GET',
|
|
17
|
+
'HEAD',
|
|
18
|
+
'OPTIONS',
|
|
19
|
+
'PUT',
|
|
20
|
+
'TRACE'
|
|
21
|
+
]);
|
|
22
|
+
const createTimeoutError = (timeoutMs)=>{
|
|
23
|
+
const error = new Error(`Request timed out after ${timeoutMs}ms`);
|
|
24
|
+
error.name = 'TimeoutError';
|
|
25
|
+
return error;
|
|
26
|
+
};
|
|
27
|
+
const unrefTimer = (timer)=>{
|
|
28
|
+
if ('object' == typeof timer && null !== timer && 'unref' in timer && 'function' == typeof timer.unref) timer.unref();
|
|
29
|
+
};
|
|
30
|
+
const wait = (ms)=>new Promise((resolve)=>{
|
|
31
|
+
const timer = setTimeout(()=>resolve(), ms);
|
|
32
|
+
unrefTimer(timer);
|
|
33
|
+
});
|
|
34
|
+
const toStatusCode = (error)=>{
|
|
35
|
+
if (!error || 'object' != typeof error) return;
|
|
36
|
+
const status = error.status;
|
|
37
|
+
if ('number' == typeof status) return status;
|
|
38
|
+
const responseStatus = error.response?.status;
|
|
39
|
+
if ('number' == typeof responseStatus) return responseStatus;
|
|
40
|
+
};
|
|
41
|
+
const isRetryableNetworkError = (error)=>{
|
|
42
|
+
if (!error || 'object' != typeof error) return false;
|
|
43
|
+
const name = error.name;
|
|
44
|
+
if ('FetchError' === name || 'TimeoutError' === name || 'TypeError' === name) return true;
|
|
45
|
+
const code = error.code;
|
|
46
|
+
return 'ECONNRESET' === code || 'ETIMEDOUT' === code || 'ECONNREFUSED' === code || 'EPIPE' === code;
|
|
47
|
+
};
|
|
48
|
+
const normalizePositiveNumber = (value, fallback)=>'number' == typeof value && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
49
|
+
const normalizeNonNegativeInt = (value, fallback)=>'number' == typeof value && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
|
|
50
|
+
const normalizeJitterRatio = (value)=>{
|
|
51
|
+
if ('number' != typeof value || !Number.isFinite(value)) return DEFAULT_JITTER_RATIO;
|
|
52
|
+
return Math.max(0, Math.min(1, value));
|
|
53
|
+
};
|
|
54
|
+
const shouldRetryWithDefaults = (method, statusCode, error, retryableStatusCodes)=>{
|
|
55
|
+
if (!DEFAULT_RETRYABLE_METHODS.has(method.toUpperCase())) return false;
|
|
56
|
+
if ('number' == typeof statusCode) return retryableStatusCodes.includes(statusCode);
|
|
57
|
+
return isRetryableNetworkError(error);
|
|
58
|
+
};
|
|
59
|
+
const shouldRetry = (retryOptions, context, retryableStatusCodes)=>{
|
|
60
|
+
if ('function' == typeof retryOptions?.shouldRetry) try {
|
|
61
|
+
return retryOptions.shouldRetry(context);
|
|
62
|
+
} catch (error) {
|
|
63
|
+
return false;
|
|
64
|
+
}
|
|
65
|
+
return shouldRetryWithDefaults(context.method, context.statusCode, context.error, retryableStatusCodes);
|
|
66
|
+
};
|
|
67
|
+
const getBackoffMs = (retryOptions, attempt)=>{
|
|
68
|
+
const baseDelayMs = normalizePositiveNumber(retryOptions?.baseDelayMs, DEFAULT_BASE_DELAY_MS);
|
|
69
|
+
const maxDelayMs = normalizePositiveNumber(retryOptions?.maxDelayMs, DEFAULT_MAX_DELAY_MS);
|
|
70
|
+
const jitterRatio = normalizeJitterRatio(retryOptions?.jitterRatio);
|
|
71
|
+
const exponentialDelay = Math.min(maxDelayMs, baseDelayMs * 2 ** Math.max(0, attempt - 1));
|
|
72
|
+
const jitterFactor = 0 === jitterRatio ? 1 : 1 + (2 * Math.random() - 1) * jitterRatio;
|
|
73
|
+
return Math.max(0, Math.floor(exponentialDelay * jitterFactor));
|
|
74
|
+
};
|
|
75
|
+
const emitDegradedEvent = (transport, event)=>{
|
|
76
|
+
if ('function' != typeof transport?.onDegraded) return;
|
|
77
|
+
try {
|
|
78
|
+
transport.onDegraded(event);
|
|
79
|
+
} catch (error) {}
|
|
80
|
+
};
|
|
81
|
+
const withTimeout = async (promise, timeoutMs, signalBuilder)=>{
|
|
82
|
+
if (!timeoutMs || timeoutMs <= 0) {
|
|
83
|
+
const result = await promise;
|
|
84
|
+
return {
|
|
85
|
+
result
|
|
86
|
+
};
|
|
87
|
+
}
|
|
88
|
+
const controller = signalBuilder?.();
|
|
89
|
+
let timeoutTriggered = false;
|
|
90
|
+
let rejectTimeout;
|
|
91
|
+
const timeoutPromise = new Promise((_, reject)=>{
|
|
92
|
+
rejectTimeout = reject;
|
|
93
|
+
});
|
|
94
|
+
const timer = setTimeout(()=>{
|
|
95
|
+
timeoutTriggered = true;
|
|
96
|
+
if (controller) controller.abort();
|
|
97
|
+
rejectTimeout?.(createTimeoutError(timeoutMs));
|
|
98
|
+
}, timeoutMs);
|
|
99
|
+
unrefTimer(timer);
|
|
100
|
+
try {
|
|
101
|
+
const result = await Promise.race([
|
|
102
|
+
promise,
|
|
103
|
+
timeoutPromise
|
|
104
|
+
]);
|
|
105
|
+
return {
|
|
106
|
+
result,
|
|
107
|
+
timeoutTriggered
|
|
108
|
+
};
|
|
109
|
+
} catch (error) {
|
|
110
|
+
if (timeoutTriggered && error?.name === 'AbortError') throw createTimeoutError(timeoutMs);
|
|
111
|
+
throw error;
|
|
112
|
+
} finally{
|
|
113
|
+
clearTimeout(timer);
|
|
114
|
+
}
|
|
115
|
+
};
|
|
116
|
+
const executeWithResilience = async ({ requestId, target, method, url, init, fetcher, transport })=>{
|
|
117
|
+
const retries = normalizeNonNegativeInt(transport?.retry?.retries, 0);
|
|
118
|
+
const timeoutMs = 'number' == typeof transport?.timeoutMs && transport.timeoutMs > 0 ? transport.timeoutMs : void 0;
|
|
119
|
+
const maxAttempts = retries + 1;
|
|
120
|
+
const retryableStatusCodes = transport?.retry?.retryableStatusCodes && transport.retry.retryableStatusCodes.length > 0 ? transport.retry.retryableStatusCodes : DEFAULT_RETRYABLE_STATUS_CODES;
|
|
121
|
+
let attempt = 0;
|
|
122
|
+
while(attempt < maxAttempts){
|
|
123
|
+
attempt += 1;
|
|
124
|
+
const canUseAbortController = "u" > typeof AbortController;
|
|
125
|
+
let controller;
|
|
126
|
+
if (timeoutMs && canUseAbortController) controller = new AbortController();
|
|
127
|
+
const callerSignal = init.signal;
|
|
128
|
+
const requestSignal = controller ? callerSignal && !callerSignal.aborted ? AbortSignal.any([
|
|
129
|
+
callerSignal,
|
|
130
|
+
controller.signal
|
|
131
|
+
]) : callerSignal || controller.signal : callerSignal;
|
|
132
|
+
const nextInit = requestSignal ? {
|
|
133
|
+
...init,
|
|
134
|
+
signal: requestSignal
|
|
135
|
+
} : init;
|
|
136
|
+
try {
|
|
137
|
+
const { result } = await withTimeout(fetcher(url, nextInit), timeoutMs, ()=>controller);
|
|
138
|
+
return result;
|
|
139
|
+
} catch (error) {
|
|
140
|
+
const statusCode = toStatusCode(error);
|
|
141
|
+
const decisionContext = {
|
|
142
|
+
requestId,
|
|
143
|
+
target,
|
|
144
|
+
method,
|
|
145
|
+
url,
|
|
146
|
+
attempt,
|
|
147
|
+
maxAttempts,
|
|
148
|
+
error,
|
|
149
|
+
statusCode
|
|
150
|
+
};
|
|
151
|
+
if (error?.name === 'TimeoutError') emitDegradedEvent(transport, {
|
|
152
|
+
requestId,
|
|
153
|
+
target,
|
|
154
|
+
method,
|
|
155
|
+
url,
|
|
156
|
+
reason: 'timeout',
|
|
157
|
+
attempt,
|
|
158
|
+
maxAttempts,
|
|
159
|
+
timeoutMs,
|
|
160
|
+
statusCode,
|
|
161
|
+
error
|
|
162
|
+
});
|
|
163
|
+
const canRetry = attempt < maxAttempts && shouldRetry(transport?.retry, decisionContext, retryableStatusCodes);
|
|
164
|
+
if (!canRetry) {
|
|
165
|
+
if (retries > 0 || error?.name === 'TimeoutError') emitDegradedEvent(transport, {
|
|
166
|
+
requestId,
|
|
167
|
+
target,
|
|
168
|
+
method,
|
|
169
|
+
url,
|
|
170
|
+
reason: 'retry_exhausted',
|
|
171
|
+
attempt,
|
|
172
|
+
maxAttempts,
|
|
173
|
+
timeoutMs,
|
|
174
|
+
statusCode,
|
|
175
|
+
error
|
|
176
|
+
});
|
|
177
|
+
throw error;
|
|
178
|
+
}
|
|
179
|
+
const backoffMs = getBackoffMs(transport?.retry, attempt);
|
|
180
|
+
emitDegradedEvent(transport, {
|
|
181
|
+
requestId,
|
|
182
|
+
target,
|
|
183
|
+
method,
|
|
184
|
+
url,
|
|
185
|
+
reason: 'retry',
|
|
186
|
+
attempt,
|
|
187
|
+
maxAttempts,
|
|
188
|
+
timeoutMs,
|
|
189
|
+
backoffMs,
|
|
190
|
+
statusCode,
|
|
191
|
+
error
|
|
192
|
+
});
|
|
193
|
+
if (backoffMs > 0) await wait(backoffMs);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
export { executeWithResilience };
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
const BFF_ENVELOPE_HEADER = 'x-modernjs-bff-envelope';
|
|
3
|
+
const BFF_OPERATION_CONTEXT_HEADER = 'x-operation-id';
|
|
4
|
+
const BFF_OPERATION_CONTEXT_DETAIL_HEADER = 'x-modernjs-bff-operation-context';
|
|
5
|
+
const BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS = [
|
|
6
|
+
'x-tenant-id',
|
|
7
|
+
'x-subject-id',
|
|
8
|
+
'x-user-id',
|
|
9
|
+
BFF_OPERATION_CONTEXT_HEADER
|
|
10
|
+
];
|
|
11
|
+
export { BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS, BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER };
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { escapeHtmlAttribute } from "./html.mjs";
|
|
3
|
+
function getScriptTags(template) {
|
|
4
|
+
const scriptRegExp = /<script\b[^>]*\bsrc=(["'])(.*?)\1[^>]*><\/script>/g;
|
|
5
|
+
return Array.from(template.matchAll(scriptRegExp)).map((match)=>({
|
|
6
|
+
index: match.index ?? 0,
|
|
7
|
+
tag: match[0],
|
|
8
|
+
src: match[2]
|
|
9
|
+
}));
|
|
10
|
+
}
|
|
11
|
+
function getAssetBasename(src) {
|
|
12
|
+
const withoutQuery = src.split(/[?#]/)[0];
|
|
13
|
+
return withoutQuery.split('/').pop() || withoutQuery;
|
|
14
|
+
}
|
|
15
|
+
function isEntryScript(src, entryName, asyncEntry) {
|
|
16
|
+
const basename = getAssetBasename(src);
|
|
17
|
+
const prefix = asyncEntry ? `async-${entryName}` : entryName;
|
|
18
|
+
return basename === `${prefix}.js` || basename.startsWith(`${prefix}.`) || basename.startsWith(`${prefix}-`);
|
|
19
|
+
}
|
|
20
|
+
const dedupeByUrl = (chunks)=>{
|
|
21
|
+
const seen = new Set();
|
|
22
|
+
return chunks.filter((chunk)=>{
|
|
23
|
+
if (void 0 === chunk.url || '' === chunk.url || seen.has(chunk.url)) return false;
|
|
24
|
+
seen.add(chunk.url);
|
|
25
|
+
return true;
|
|
26
|
+
});
|
|
27
|
+
};
|
|
28
|
+
const isAsyncEntryScriptChunk = (chunk, entryName)=>{
|
|
29
|
+
if (void 0 === chunk.url || !chunk.url.endsWith('.js')) return false;
|
|
30
|
+
const asyncEntryName = `async-${entryName}`;
|
|
31
|
+
const filename = chunk.filename ?? chunk.url;
|
|
32
|
+
const basename = filename.split('/').pop() ?? filename;
|
|
33
|
+
return basename === `${asyncEntryName}.js` || basename.startsWith(`${asyncEntryName}.`) || basename.startsWith(`${asyncEntryName}-`);
|
|
34
|
+
};
|
|
35
|
+
function getMatchedRouteChunks(routeManifest, matchedRouteIds, routeAssetToChunk) {
|
|
36
|
+
const routeAssets = routeManifest?.routeAssets;
|
|
37
|
+
if (void 0 === routeAssets) return [];
|
|
38
|
+
return matchedRouteIds.flatMap((routeId)=>routeAssets[routeId]?.assets ?? []).map(routeAssetToChunk);
|
|
39
|
+
}
|
|
40
|
+
const orderHydrationScriptChunks = ({ asyncEntryChunks, collectedChunks, matchedRouteChunks, entryName })=>{
|
|
41
|
+
const asyncEntryScriptChunks = [];
|
|
42
|
+
const asyncEntryDependencyChunks = [];
|
|
43
|
+
for (const chunk of asyncEntryChunks)if (isAsyncEntryScriptChunk(chunk, entryName)) asyncEntryScriptChunks.push(chunk);
|
|
44
|
+
else asyncEntryDependencyChunks.push(chunk);
|
|
45
|
+
return dedupeByUrl([
|
|
46
|
+
...asyncEntryDependencyChunks,
|
|
47
|
+
...collectedChunks,
|
|
48
|
+
...matchedRouteChunks,
|
|
49
|
+
...asyncEntryScriptChunks
|
|
50
|
+
]);
|
|
51
|
+
};
|
|
52
|
+
function injectBeforeHydrationEntryScript(template, scripts, entryName = 'index') {
|
|
53
|
+
if ('' === scripts) return template;
|
|
54
|
+
const scriptTags = getScriptTags(template);
|
|
55
|
+
const target = scriptTags.find((match)=>isEntryScript(match.src, entryName, false)) ?? scriptTags.find((match)=>isEntryScript(match.src, entryName, true));
|
|
56
|
+
if (void 0 === target) return template;
|
|
57
|
+
return `${template.slice(0, target.index)}${scripts}${template.slice(target.index)}`;
|
|
58
|
+
}
|
|
59
|
+
function replaceChunkJsPlaceholder(template, scripts, entryName, placeholder) {
|
|
60
|
+
if (!template.includes(placeholder)) return template;
|
|
61
|
+
if ('' === scripts) return template.replace(placeholder, ()=>'');
|
|
62
|
+
const withoutPlaceholder = template.replace(placeholder, ()=>'');
|
|
63
|
+
const withEarlyScripts = injectBeforeHydrationEntryScript(withoutPlaceholder, scripts, entryName);
|
|
64
|
+
if (withEarlyScripts !== withoutPlaceholder) return withEarlyScripts;
|
|
65
|
+
return template.replace(placeholder, ()=>scripts);
|
|
66
|
+
}
|
|
67
|
+
function createRouteHydrationScriptTags(routeManifest, matchedRouteIds, entryName, options = {}) {
|
|
68
|
+
const { nonce, template } = options;
|
|
69
|
+
const routeAssets = routeManifest?.routeAssets;
|
|
70
|
+
if (void 0 === routeAssets) return '';
|
|
71
|
+
const existingScriptSrcs = void 0 === template ? new Set() : new Set(getScriptTags(template).map(({ src })=>src));
|
|
72
|
+
const jsAssets = Array.from(new Set([
|
|
73
|
+
...getMatchedRouteChunks(routeManifest, matchedRouteIds, (asset)=>asset),
|
|
74
|
+
...routeAssets[`async-${entryName}`]?.assets ?? []
|
|
75
|
+
].filter((asset)=>asset.endsWith('.js'))));
|
|
76
|
+
return jsAssets.filter((asset)=>!existingScriptSrcs.has(asset)).map((asset)=>`<script src="${escapeHtmlAttribute(asset)}"${nonce ? ` nonce="${escapeHtmlAttribute(nonce)}"` : ''}></script>`).join(' ');
|
|
77
|
+
}
|
|
78
|
+
export { createRouteHydrationScriptTags, getMatchedRouteChunks, injectBeforeHydrationEntryScript, orderHydrationScriptChunks, replaceChunkJsPlaceholder };
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { getNavigationWarmupCacheKey } from "./navigationWarmup.mjs";
|
|
3
|
+
import { normalizePreloadBehavior } from "./prefetchPolicy.mjs";
|
|
4
|
+
const INTENT_DELAY = 100;
|
|
5
|
+
const VIEWPORT_ROOT_MARGIN = '200px';
|
|
6
|
+
const MAX_CONCURRENT_WARMUPS = 4;
|
|
7
|
+
const WARMUP_TTL = 30000;
|
|
8
|
+
function createRouterPrefetchPolicy() {
|
|
9
|
+
const cache = new Map();
|
|
10
|
+
const queue = [];
|
|
11
|
+
let activeWarmups = 0;
|
|
12
|
+
const canWarmup = ()=>{
|
|
13
|
+
const navigator = globalThis.navigator;
|
|
14
|
+
const connection = navigator?.connection || navigator?.mozConnection || navigator?.webkitConnection;
|
|
15
|
+
return !connection?.saveData && connection?.effectiveType !== 'slow-2g' && connection?.effectiveType !== '2g';
|
|
16
|
+
};
|
|
17
|
+
const runNext = ()=>{
|
|
18
|
+
while(activeWarmups < MAX_CONCURRENT_WARMUPS && queue.length > 0){
|
|
19
|
+
const task = queue.shift();
|
|
20
|
+
if (task.cancelled) continue;
|
|
21
|
+
activeWarmups += 1;
|
|
22
|
+
task.run().catch(()=>{
|
|
23
|
+
cache.delete(task.key);
|
|
24
|
+
}).finally(()=>{
|
|
25
|
+
activeWarmups -= 1;
|
|
26
|
+
runNext();
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
canWarmup,
|
|
32
|
+
allowData (route) {
|
|
33
|
+
return route?.handle?.navigationWarmup?.data !== false;
|
|
34
|
+
},
|
|
35
|
+
observe ({ element, prefetch: inputPrefetch, preload: inputPreload, notify }) {
|
|
36
|
+
const prefetch = inputPrefetch ?? 'render';
|
|
37
|
+
const preload = normalizePreloadBehavior(inputPreload, prefetch);
|
|
38
|
+
let state = {
|
|
39
|
+
code: 'render' === prefetch || 'render' === preload,
|
|
40
|
+
data: 'render' === prefetch
|
|
41
|
+
};
|
|
42
|
+
let timer;
|
|
43
|
+
let observer;
|
|
44
|
+
const update = (next)=>{
|
|
45
|
+
state = next;
|
|
46
|
+
notify(state);
|
|
47
|
+
};
|
|
48
|
+
const cancelTimer = ()=>{
|
|
49
|
+
if (void 0 !== timer) {
|
|
50
|
+
clearTimeout(timer);
|
|
51
|
+
timer = void 0;
|
|
52
|
+
}
|
|
53
|
+
};
|
|
54
|
+
notify(state);
|
|
55
|
+
if (element && ('viewport' === prefetch || 'viewport' === preload) && "u" > typeof IntersectionObserver) {
|
|
56
|
+
observer = new IntersectionObserver((entries)=>{
|
|
57
|
+
if (!entries.some((entry)=>entry.isIntersecting)) return;
|
|
58
|
+
update({
|
|
59
|
+
code: true,
|
|
60
|
+
data: state.data || 'viewport' === prefetch
|
|
61
|
+
});
|
|
62
|
+
observer?.disconnect();
|
|
63
|
+
}, {
|
|
64
|
+
rootMargin: VIEWPORT_ROOT_MARGIN
|
|
65
|
+
});
|
|
66
|
+
observer.observe(element);
|
|
67
|
+
}
|
|
68
|
+
return {
|
|
69
|
+
onIntent () {
|
|
70
|
+
if ('intent' !== prefetch && 'intent' !== preload) return;
|
|
71
|
+
if (void 0 !== timer) return;
|
|
72
|
+
timer = setTimeout(()=>{
|
|
73
|
+
timer = void 0;
|
|
74
|
+
update({
|
|
75
|
+
code: true,
|
|
76
|
+
data: state.data || 'intent' === prefetch
|
|
77
|
+
});
|
|
78
|
+
}, INTENT_DELAY);
|
|
79
|
+
},
|
|
80
|
+
onCancel () {
|
|
81
|
+
if ('intent' === prefetch || 'intent' === preload) {
|
|
82
|
+
cancelTimer();
|
|
83
|
+
update({
|
|
84
|
+
code: false,
|
|
85
|
+
data: false
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
dispose () {
|
|
90
|
+
cancelTimer();
|
|
91
|
+
observer?.disconnect();
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
},
|
|
95
|
+
schedule ({ runtimeContext, chunkLoader, publicPath, key: operationKey, run }) {
|
|
96
|
+
if (!canWarmup()) return ()=>{};
|
|
97
|
+
const now = performance.now();
|
|
98
|
+
for (const [key, timestamp] of cache)if (now - timestamp > WARMUP_TTL) cache.delete(key);
|
|
99
|
+
const key = getNavigationWarmupCacheKey(runtimeContext, chunkLoader, publicPath, operationKey);
|
|
100
|
+
if (cache.has(key)) return ()=>{};
|
|
101
|
+
cache.set(key, now);
|
|
102
|
+
const task = {
|
|
103
|
+
key,
|
|
104
|
+
run,
|
|
105
|
+
cancelled: false
|
|
106
|
+
};
|
|
107
|
+
queue.push(task);
|
|
108
|
+
runNext();
|
|
109
|
+
return ()=>{
|
|
110
|
+
task.cancelled = true;
|
|
111
|
+
if (queue.includes(task)) cache.delete(key);
|
|
112
|
+
};
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
export { createRouterPrefetchPolicy };
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { merge } from "@modern-js/runtime-utils/merge";
|
|
3
|
+
function reportUnsupportedProviderRegistryHooks(providerPlugin, routerProviderRegistryHooks) {
|
|
4
|
+
const unsupportedHookNames = Object.keys(providerPlugin.registryHooks ?? {}).filter((hookName)=>!(hookName in routerProviderRegistryHooks));
|
|
5
|
+
if (unsupportedHookNames.length > 0) console.warn(`[@modern-js/runtime] The router provider "${providerPlugin.name}" declares registry hooks outside the router hook contract: ${unsupportedHookNames.join(', ')}. These hooks are not registered when the provider is resolved through \`runtime.router.framework\` — declare them on a separate runtime plugin instead.`);
|
|
6
|
+
return unsupportedHookNames;
|
|
7
|
+
}
|
|
8
|
+
function createRouterProviderRealm(registrations) {
|
|
9
|
+
const providers = new Map();
|
|
10
|
+
let defaultProvider;
|
|
11
|
+
for (const registration of registrations){
|
|
12
|
+
if (0 === registration.name.length) throw new Error('[@modern-js/runtime] A router provider realm cannot contain an unnamed provider.');
|
|
13
|
+
if (providers.has(registration.name)) throw new Error(`[@modern-js/runtime] Router provider "${registration.name}" is declared more than once in the same runtime realm.`);
|
|
14
|
+
if (true === registration.isDefault && void 0 !== defaultProvider && defaultProvider !== registration.name) throw new Error(`[@modern-js/runtime] Router provider realm declares both "${defaultProvider}" and "${registration.name}" as defaults.`);
|
|
15
|
+
providers.set(registration.name, registration.factory);
|
|
16
|
+
if (true === registration.isDefault) defaultProvider = registration.name;
|
|
17
|
+
}
|
|
18
|
+
const providerNames = Object.freeze([
|
|
19
|
+
...providers.keys()
|
|
20
|
+
]);
|
|
21
|
+
return Object.freeze({
|
|
22
|
+
...void 0 !== defaultProvider ? {
|
|
23
|
+
defaultProvider
|
|
24
|
+
} : {},
|
|
25
|
+
get: (name)=>providers.get(name),
|
|
26
|
+
names: ()=>providerNames
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
const REGISTRY_SLOT = Symbol.for('@modern-js/runtime:router-providers:v3');
|
|
30
|
+
const LEGACY_V2_REGISTRY_SLOT = Symbol.for('@modern-js/runtime:router-providers:v2');
|
|
31
|
+
function getRegistry() {
|
|
32
|
+
const host = globalThis;
|
|
33
|
+
host[REGISTRY_SLOT] ??= {
|
|
34
|
+
providers: new Map(),
|
|
35
|
+
duplicateProviders: new Set(),
|
|
36
|
+
warnedDuplicates: new Set()
|
|
37
|
+
};
|
|
38
|
+
host[REGISTRY_SLOT].duplicateProviders ??= new Set();
|
|
39
|
+
host[REGISTRY_SLOT].warnedDuplicates ??= new Set();
|
|
40
|
+
return host[REGISTRY_SLOT];
|
|
41
|
+
}
|
|
42
|
+
function getLegacyV2Registry() {
|
|
43
|
+
const host = globalThis;
|
|
44
|
+
return host[LEGACY_V2_REGISTRY_SLOT];
|
|
45
|
+
}
|
|
46
|
+
function registerRouterProvider(name, factory, options = {}) {
|
|
47
|
+
const registry = getRegistry();
|
|
48
|
+
const existing = registry.providers.get(name);
|
|
49
|
+
if (void 0 !== existing) {
|
|
50
|
+
if (existing !== factory) registry.duplicateProviders.add(name);
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
if (true === options.isDefault) registry.defaultProvider = name;
|
|
54
|
+
registry.providers.set(name, factory);
|
|
55
|
+
}
|
|
56
|
+
function resolveRouterProvider(framework, options = {}) {
|
|
57
|
+
if (void 0 !== options.realm) {
|
|
58
|
+
const name = framework || options.realm.defaultProvider;
|
|
59
|
+
const realmProviderNames = options.realm.names();
|
|
60
|
+
if (void 0 === name) throw new Error(`[@modern-js/runtime] The app-owned router provider realm does not declare a default provider. Available realm providers: ${realmProviderNames.join(', ') || '(none)'}.`);
|
|
61
|
+
const factory = options.realm.get(name);
|
|
62
|
+
if (void 0 === factory) throw new Error(`[@modern-js/runtime] Router provider "${name}" is not registered in the app-owned router provider realm. Available realm providers: ${realmProviderNames.join(', ') || '(none)'}. Compatibility registry fallback is disabled for app-owned realms.`);
|
|
63
|
+
return factory;
|
|
64
|
+
}
|
|
65
|
+
const registry = getRegistry();
|
|
66
|
+
const legacyV2Registry = getLegacyV2Registry();
|
|
67
|
+
const name = framework || options.localDefault?.name || registry.defaultProvider || legacyV2Registry?.defaultProvider;
|
|
68
|
+
if (void 0 === name) throw new Error('[@modern-js/runtime] No default router provider is registered. This is a bug in the runtime setup.');
|
|
69
|
+
if (void 0 !== options.localDefault && name === options.localDefault.name) return options.localDefault.factory;
|
|
70
|
+
const factory = registry.providers.get(name);
|
|
71
|
+
if (void 0 !== factory) {
|
|
72
|
+
if (registry.duplicateProviders.has(name) && !registry.warnedDuplicates.has(name)) {
|
|
73
|
+
registry.warnedDuplicates.add(name);
|
|
74
|
+
console.warn(`[@modern-js/runtime] The router provider "${name}" was registered more than once with different module instances, and a router wrapper without an app-owned provider realm is resolving the mixed-version compatibility fallback. The fallback is keeping the first registration. Modern router wrappers isolate app-owned realms automatically. For an older wrapper, share the provider runtime between Module Federation host and remotes or upgrade every app to a realm-aware runtime.`);
|
|
75
|
+
}
|
|
76
|
+
return factory;
|
|
77
|
+
}
|
|
78
|
+
const legacyV2Factory = legacyV2Registry?.providers.get(name);
|
|
79
|
+
if (void 0 !== legacyV2Factory) return legacyV2Factory;
|
|
80
|
+
if ('tanstack' === name) throw new Error("[@modern-js/runtime] `runtime.router.framework` is set to \"tanstack\", but no TanStack router provider is registered. Install @modern-js/plugin-tanstack, add `tanstackRouterPlugin()` to the `plugins` array in modern.config.ts, and make sure '@modern-js/plugin-tanstack/runtime' is imported (e.g. in modern.runtime.ts).");
|
|
81
|
+
throw new Error(`[@modern-js/runtime] Unknown router framework "${name}". Registered providers: ${[
|
|
82
|
+
...new Set([
|
|
83
|
+
...registry.providers.keys(),
|
|
84
|
+
...legacyV2Registry?.providers.keys() ?? []
|
|
85
|
+
])
|
|
86
|
+
].join(', ') || '(none)'}. Install and register the plugin that provides this router framework.`);
|
|
87
|
+
}
|
|
88
|
+
function unsafe_resetRouterProvidersForTesting() {
|
|
89
|
+
const host = globalThis;
|
|
90
|
+
delete host[REGISTRY_SLOT];
|
|
91
|
+
delete host[LEGACY_V2_REGISTRY_SLOT];
|
|
92
|
+
}
|
|
93
|
+
function createRouterPlugin({ defaultProvider, registryHooks, localProviders = [] }) {
|
|
94
|
+
registerRouterProvider(defaultProvider.name, defaultProvider.factory, {
|
|
95
|
+
isDefault: true
|
|
96
|
+
});
|
|
97
|
+
const realm = createRouterProviderRealm([
|
|
98
|
+
{
|
|
99
|
+
...defaultProvider,
|
|
100
|
+
isDefault: true
|
|
101
|
+
},
|
|
102
|
+
...localProviders
|
|
103
|
+
]);
|
|
104
|
+
return (userConfig = {})=>({
|
|
105
|
+
name: '@modern-js/plugin-router',
|
|
106
|
+
registryHooks,
|
|
107
|
+
setup (api) {
|
|
108
|
+
const mergedConfig = merge(api.getRuntimeConfig().router || {}, userConfig);
|
|
109
|
+
const factory = resolveRouterProvider(mergedConfig.framework, {
|
|
110
|
+
realm
|
|
111
|
+
});
|
|
112
|
+
const provider = factory(userConfig);
|
|
113
|
+
reportUnsupportedProviderRegistryHooks(provider, registryHooks);
|
|
114
|
+
provider.setup?.(api);
|
|
115
|
+
}
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
export { createRouterPlugin, createRouterProviderRealm, registerRouterProvider, reportUnsupportedProviderRegistryHooks, resolveRouterProvider, unsafe_resetRouterProvidersForTesting };
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { createRuntimeContextExtension } from "./contextExtensions.mjs";
|
|
3
|
+
const routerRuntimeStateExtension = createRuntimeContextExtension('@modern-js/runtime:router-runtime-state');
|
|
4
|
+
const routerServerSnapshotExtension = createRuntimeContextExtension('@modern-js/runtime:router-server-snapshot');
|
|
5
|
+
function getRouterRuntimeState(runtimeContext) {
|
|
6
|
+
return routerRuntimeStateExtension.get(runtimeContext);
|
|
7
|
+
}
|
|
8
|
+
function getRouterServerSnapshot(runtimeContext) {
|
|
9
|
+
return routerServerSnapshotExtension.get(runtimeContext);
|
|
10
|
+
}
|
|
11
|
+
function toHydrationScripts(state) {
|
|
12
|
+
if (state.hydrationScripts?.length) return state.hydrationScripts;
|
|
13
|
+
return state.hydrationScript ? [
|
|
14
|
+
state.hydrationScript
|
|
15
|
+
] : void 0;
|
|
16
|
+
}
|
|
17
|
+
function getMatchedRouteIdsFromMatches(matches) {
|
|
18
|
+
const routeIds = matches?.map((match)=>match.assetRouteId ?? match.routeId).filter((routeId)=>'string' == typeof routeId);
|
|
19
|
+
return routeIds?.length ? routeIds : void 0;
|
|
20
|
+
}
|
|
21
|
+
function createRouterServerSnapshot(state) {
|
|
22
|
+
const hydrationScripts = toHydrationScripts(state);
|
|
23
|
+
const matchedRouteIds = state.matchedRouteIds ?? getMatchedRouteIdsFromMatches(state.matches);
|
|
24
|
+
return {
|
|
25
|
+
...state,
|
|
26
|
+
...hydrationScripts?.length ? {
|
|
27
|
+
hydrationScript: state.hydrationScript ?? hydrationScripts[0],
|
|
28
|
+
hydrationScripts
|
|
29
|
+
} : {},
|
|
30
|
+
...matchedRouteIds ? {
|
|
31
|
+
matchedRouteIds
|
|
32
|
+
} : {}
|
|
33
|
+
};
|
|
34
|
+
}
|
|
35
|
+
function createRouterRuntimeState(state) {
|
|
36
|
+
const hasSnapshotState = Boolean(state.serverSnapshot) || Boolean(state.hydrationScript) || Boolean(state.hydrationScripts?.length) || Boolean(state.matchedRouteIds?.length) || Boolean(state.matches?.length);
|
|
37
|
+
const serverSnapshot = state.serverSnapshot ? createRouterServerSnapshot({
|
|
38
|
+
...state.serverSnapshot,
|
|
39
|
+
framework: state.serverSnapshot.framework ?? state.framework,
|
|
40
|
+
basename: state.serverSnapshot.basename ?? state.basename,
|
|
41
|
+
hydrationScript: state.serverSnapshot.hydrationScript ?? state.hydrationScript,
|
|
42
|
+
hydrationScripts: state.serverSnapshot.hydrationScripts ?? state.hydrationScripts,
|
|
43
|
+
matchedRouteIds: state.serverSnapshot.matchedRouteIds ?? state.matchedRouteIds,
|
|
44
|
+
matches: state.serverSnapshot.matches ?? state.matches
|
|
45
|
+
}) : hasSnapshotState ? createRouterServerSnapshot({
|
|
46
|
+
framework: state.framework,
|
|
47
|
+
basename: state.basename,
|
|
48
|
+
hydrationScript: state.hydrationScript,
|
|
49
|
+
hydrationScripts: state.hydrationScripts,
|
|
50
|
+
matchedRouteIds: state.matchedRouteIds,
|
|
51
|
+
matches: state.matches
|
|
52
|
+
}) : void 0;
|
|
53
|
+
const hydrationScripts = toHydrationScripts({
|
|
54
|
+
hydrationScript: state.hydrationScript ?? serverSnapshot?.hydrationScript,
|
|
55
|
+
hydrationScripts: state.hydrationScripts ?? serverSnapshot?.hydrationScripts
|
|
56
|
+
});
|
|
57
|
+
const matchedRouteIds = state.matchedRouteIds ?? serverSnapshot?.matchedRouteIds ?? getMatchedRouteIdsFromMatches(state.matches);
|
|
58
|
+
return {
|
|
59
|
+
...state,
|
|
60
|
+
...hydrationScripts?.length ? {
|
|
61
|
+
hydrationScript: state.hydrationScript ?? hydrationScripts[0],
|
|
62
|
+
hydrationScripts
|
|
63
|
+
} : {},
|
|
64
|
+
...matchedRouteIds ? {
|
|
65
|
+
matchedRouteIds
|
|
66
|
+
} : {},
|
|
67
|
+
...serverSnapshot ? {
|
|
68
|
+
serverSnapshot
|
|
69
|
+
} : {}
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
function applyRouterRuntimeState(runtimeContext, state) {
|
|
73
|
+
const normalized = createRouterRuntimeState(state);
|
|
74
|
+
routerRuntimeStateExtension.set(runtimeContext, normalized);
|
|
75
|
+
if (normalized.serverSnapshot) routerServerSnapshotExtension.set(runtimeContext, normalized.serverSnapshot);
|
|
76
|
+
return runtimeContext;
|
|
77
|
+
}
|
|
78
|
+
function applyRouterServerPrepareResult(runtimeContext, result) {
|
|
79
|
+
const state = createRouterRuntimeState({
|
|
80
|
+
...result.state,
|
|
81
|
+
cleanup: result.cleanup ?? result.state.cleanup,
|
|
82
|
+
serverSnapshot: result.snapshot ?? result.state.serverSnapshot
|
|
83
|
+
});
|
|
84
|
+
applyRouterRuntimeState(runtimeContext, state);
|
|
85
|
+
return runtimeContext;
|
|
86
|
+
}
|
|
87
|
+
function getRouterHydrationScripts(runtimeContext) {
|
|
88
|
+
const serverSnapshot = getRouterServerSnapshot(runtimeContext);
|
|
89
|
+
const runtimeState = getRouterRuntimeState(runtimeContext);
|
|
90
|
+
return serverSnapshot?.hydrationScripts ?? toHydrationScripts({
|
|
91
|
+
hydrationScript: serverSnapshot?.hydrationScript
|
|
92
|
+
}) ?? runtimeState?.hydrationScripts ?? toHydrationScripts({
|
|
93
|
+
hydrationScript: runtimeState?.hydrationScript
|
|
94
|
+
}) ?? [];
|
|
95
|
+
}
|
|
96
|
+
function getRouterMatchedRouteIds(runtimeContext) {
|
|
97
|
+
const serverSnapshot = getRouterServerSnapshot(runtimeContext);
|
|
98
|
+
const runtimeState = getRouterRuntimeState(runtimeContext);
|
|
99
|
+
return serverSnapshot?.matchedRouteIds ?? getMatchedRouteIdsFromMatches(serverSnapshot?.matches) ?? runtimeState?.matchedRouteIds ?? getMatchedRouteIdsFromMatches(runtimeState?.matches);
|
|
100
|
+
}
|
|
101
|
+
async function cleanupRouterRuntimeState(runtimeContext) {
|
|
102
|
+
try {
|
|
103
|
+
await getRouterRuntimeState(runtimeContext)?.cleanup?.();
|
|
104
|
+
} catch {}
|
|
105
|
+
}
|
|
106
|
+
export { applyRouterRuntimeState, applyRouterServerPrepareResult, cleanupRouterRuntimeState, createRouterRuntimeState, createRouterServerSnapshot, getRouterHydrationScripts, getRouterMatchedRouteIds, getRouterRuntimeState, getRouterServerSnapshot };
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { createRouterPrefetchPolicy } from "./routerPrefetchPolicy.mjs";
|
|
3
|
+
import { applyRouterRuntimeState, createRouterServerSnapshot } from "./routerState.mjs";
|
|
4
|
+
function createRouterStatePlugin({ registryHooks }) {
|
|
5
|
+
return {
|
|
6
|
+
name: '@modern-js/router-runtime-policy',
|
|
7
|
+
registryHooks,
|
|
8
|
+
setup (api) {
|
|
9
|
+
api.onBeforeRender((context)=>{
|
|
10
|
+
const runtimeContext = context;
|
|
11
|
+
runtimeContext.linkPrefetchPolicy ??= createRouterPrefetchPolicy();
|
|
12
|
+
});
|
|
13
|
+
api.onAfterCreateRouter((event)=>{
|
|
14
|
+
if ('react-router' !== event.framework) return;
|
|
15
|
+
if ('ssr-prepare' === event.phase) {
|
|
16
|
+
const { routerContext } = event.runtimeContext;
|
|
17
|
+
if (!routerContext) return;
|
|
18
|
+
const serverSnapshot = createRouterServerSnapshot({
|
|
19
|
+
framework: event.framework,
|
|
20
|
+
basename: event.basename,
|
|
21
|
+
statusCode: routerContext.statusCode,
|
|
22
|
+
errors: routerContext.errors ?? void 0,
|
|
23
|
+
routerData: {
|
|
24
|
+
loaderData: routerContext.loaderData,
|
|
25
|
+
errors: routerContext.errors ?? void 0
|
|
26
|
+
},
|
|
27
|
+
matches: routerContext.matches.flatMap((match)=>'string' == typeof match.route.id ? [
|
|
28
|
+
{
|
|
29
|
+
routeId: match.route.id
|
|
30
|
+
}
|
|
31
|
+
] : [])
|
|
32
|
+
});
|
|
33
|
+
applyRouterRuntimeState(event.runtimeContext, {
|
|
34
|
+
framework: event.framework,
|
|
35
|
+
basename: event.basename,
|
|
36
|
+
instance: event.router,
|
|
37
|
+
matchedRouteIds: serverSnapshot.matchedRouteIds,
|
|
38
|
+
serverSnapshot
|
|
39
|
+
});
|
|
40
|
+
} else if ('client-create' === event.phase) applyRouterRuntimeState(event.runtimeContext, {
|
|
41
|
+
framework: event.framework,
|
|
42
|
+
basename: event.basename,
|
|
43
|
+
instance: event.router
|
|
44
|
+
});
|
|
45
|
+
});
|
|
46
|
+
}
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
export { createRouterStatePlugin };
|