@bleedingdev/modern-js-runtime-extensions 3.9.0-ultramodern.1 → 3.9.0-ultramodern.11
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/buildIdentity.js +73 -0
- 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/localisedLoaderIdentity.js +51 -0
- package/dist/cjs/prefetchPolicy.js +52 -0
- package/dist/cjs/reactContext.js +45 -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 +105 -0
- package/dist/cjs/routerState.js +204 -0
- package/dist/cjs/routerStatePlugin.js +86 -0
- package/dist/cjs/routerStateTypes.js +18 -0
- package/dist/cjs/rsc-disabled/rscDisabledClientBrowserRuntime.js +69 -0
- package/dist/cjs/rsc-disabled/rscDisabledClientEdgeRuntime.js +61 -0
- package/dist/cjs/rsc-disabled/rscDisabledClientNodeRuntime.js +65 -0
- package/dist/cjs/rsc-disabled/rscDisabledRuntimeError.js +42 -0
- package/dist/cjs/rsc-disabled/rscDisabledServerEdgeRuntime.js +93 -0
- package/dist/cjs/rsc-disabled/rscDisabledServerNodeRuntime.js +101 -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/buildIdentity.mjs +35 -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/localisedLoaderIdentity.mjs +13 -0
- package/dist/esm/prefetchPolicy.mjs +11 -0
- package/dist/esm/reactContext.mjs +7 -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 +58 -0
- package/dist/esm/routerState.mjs +139 -0
- package/dist/esm/routerStatePlugin.mjs +48 -0
- package/dist/esm/routerStateTypes.mjs +0 -0
- package/dist/esm/rsc-disabled/rscDisabledClientBrowserRuntime.mjs +10 -0
- package/dist/esm/rsc-disabled/rscDisabledClientEdgeRuntime.mjs +8 -0
- package/dist/esm/rsc-disabled/rscDisabledClientNodeRuntime.mjs +9 -0
- package/dist/esm/rsc-disabled/rscDisabledRuntimeError.mjs +4 -0
- package/dist/esm/rsc-disabled/rscDisabledServerEdgeRuntime.mjs +16 -0
- package/dist/esm/rsc-disabled/rscDisabledServerNodeRuntime.mjs +18 -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/buildIdentity.mjs +36 -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/localisedLoaderIdentity.mjs +14 -0
- package/dist/esm-node/prefetchPolicy.mjs +12 -0
- package/dist/esm-node/reactContext.mjs +8 -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 +59 -0
- package/dist/esm-node/routerState.mjs +140 -0
- package/dist/esm-node/routerStatePlugin.mjs +49 -0
- package/dist/esm-node/routerStateTypes.mjs +1 -0
- package/dist/esm-node/rsc-disabled/rscDisabledClientBrowserRuntime.mjs +11 -0
- package/dist/esm-node/rsc-disabled/rscDisabledClientEdgeRuntime.mjs +9 -0
- package/dist/esm-node/rsc-disabled/rscDisabledClientNodeRuntime.mjs +10 -0
- package/dist/esm-node/rsc-disabled/rscDisabledRuntimeError.mjs +5 -0
- package/dist/esm-node/rsc-disabled/rscDisabledServerEdgeRuntime.mjs +17 -0
- package/dist/esm-node/rsc-disabled/rscDisabledServerNodeRuntime.mjs +19 -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/buildIdentity.d.ts +37 -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/localisedLoaderIdentity.d.ts +10 -0
- package/dist/types/prefetchPolicy.d.ts +4 -0
- package/dist/types/reactContext.d.ts +6 -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 +55 -0
- package/dist/types/routerState.d.ts +18 -0
- package/dist/types/routerStatePlugin.d.ts +19 -0
- package/dist/types/routerStateTypes.d.ts +40 -0
- package/dist/types/rsc-disabled/rscDisabledClientBrowserRuntime.d.ts +9 -0
- package/dist/types/rsc-disabled/rscDisabledClientEdgeRuntime.d.ts +7 -0
- package/dist/types/rsc-disabled/rscDisabledClientNodeRuntime.d.ts +8 -0
- package/dist/types/rsc-disabled/rscDisabledRuntimeError.d.ts +1 -0
- package/dist/types/rsc-disabled/rscDisabledServerEdgeRuntime.d.ts +15 -0
- package/dist/types/rsc-disabled/rscDisabledServerNodeRuntime.d.ts +17 -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 +239 -14
- package/rslib.config.mts +17 -2
- package/rstest.config.mts +33 -2
- package/src/buildIdentity.ts +61 -0
- 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/localisedLoaderIdentity.ts +30 -0
- package/src/prefetchPolicy.ts +33 -0
- package/src/reactContext.ts +16 -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 +160 -0
- package/src/routerState.ts +290 -0
- package/src/routerStatePlugin.ts +86 -0
- package/src/routerStateTypes.ts +46 -0
- package/src/rsc-disabled/rscDisabledClientBrowserRuntime.ts +10 -0
- package/src/rsc-disabled/rscDisabledClientEdgeRuntime.ts +8 -0
- package/src/rsc-disabled/rscDisabledClientNodeRuntime.ts +9 -0
- package/src/rsc-disabled/rscDisabledRuntimeError.ts +3 -0
- package/src/rsc-disabled/rscDisabledServerEdgeRuntime.ts +16 -0
- package/src/rsc-disabled/rscDisabledServerNodeRuntime.ts +18 -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 +51 -0
- package/tests/contextExtensions.test.ts +27 -0
- package/tests/headRuntime.test.tsx +229 -0
- package/tests/rendererHead.test.ts +1 -113
- package/tests/request-policy/browser-policy.test.ts +108 -0
- package/tests/request-policy/client-isolation.test.ts +109 -0
- package/tests/request-policy/node-policy.test.ts +447 -0
- package/tests/request-policy/policyCore.test.ts +129 -0
- package/tests/request-policy/requestContext.test.ts +66 -0
- package/tests/request-policy/requestFactory.outbound-contract.test.ts +290 -0
- package/tests/request-policy/traceparent.test.ts +52 -0
- package/tests/request-policy/transport-retry.test.ts +367 -0
- package/tests/routeHydration.test.ts +180 -0
- package/tests/routerPrefetchPolicy.test.ts +102 -0
- package/tests/routerProvider.test.ts +29 -0
- package/tests/routerState.test.ts +78 -0
- package/tests/routerStatePlugin.test.ts +63 -0
- package/tests/runtimeContextProjection.test.ts +83 -0
- package/tests/safeFailure.test.ts +10 -28
- package/tests/shellStream.test.ts +37 -0
- package/tests/workspaceEvents.test.ts +221 -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,171 @@
|
|
|
1
|
+
import { parseTraceparent } from "./traceparent.mjs";
|
|
2
|
+
const TRACEPARENT_HEADER = 'traceparent';
|
|
3
|
+
const readProcessEnv = (key)=>{
|
|
4
|
+
if ("u" < typeof process || void 0 === process.env || 'string' != typeof process.env[key]) return;
|
|
5
|
+
return process.env[key];
|
|
6
|
+
};
|
|
7
|
+
const isStrictDefaultRequestIdEnabled = ()=>'true' === readProcessEnv('MODERN_BFF_STRICT_DEFAULT_REQUEST_ID');
|
|
8
|
+
const isSecuredRequestId = (requestId)=>'default' !== requestId || isStrictDefaultRequestIdEnabled();
|
|
9
|
+
const isEmptyDomain = (domain)=>'string' != typeof domain || '' === domain.trim();
|
|
10
|
+
const firstHeaderValue = (value)=>Array.isArray(value) ? value[0] : value;
|
|
11
|
+
const findHeaderKey = (headers, header)=>{
|
|
12
|
+
const normalized = header.toLowerCase();
|
|
13
|
+
return Object.keys(headers).find((key)=>key.toLowerCase() === normalized);
|
|
14
|
+
};
|
|
15
|
+
const readHeader = (headers, header)=>{
|
|
16
|
+
const key = findHeaderKey(headers, header);
|
|
17
|
+
return 'string' == typeof key ? headers[key] : void 0;
|
|
18
|
+
};
|
|
19
|
+
const writeHeader = (headers, header, value)=>{
|
|
20
|
+
if (void 0 === value) return;
|
|
21
|
+
const key = findHeaderKey(headers, header);
|
|
22
|
+
if ('string' == typeof key && key !== header) delete headers[key];
|
|
23
|
+
headers[header] = value;
|
|
24
|
+
};
|
|
25
|
+
const deleteHeader = (headers, header)=>{
|
|
26
|
+
const key = findHeaderKey(headers, header);
|
|
27
|
+
if ('string' == typeof key) delete headers[key];
|
|
28
|
+
};
|
|
29
|
+
const toOrigin = (value)=>{
|
|
30
|
+
if (!value) return;
|
|
31
|
+
try {
|
|
32
|
+
return new URL(value).origin;
|
|
33
|
+
} catch (error) {
|
|
34
|
+
return;
|
|
35
|
+
}
|
|
36
|
+
};
|
|
37
|
+
const parseTraceparentValue = (value)=>parseTraceparent(firstHeaderValue(value));
|
|
38
|
+
const buildOperationContext = ({ requestId, method, path, operationContext, traceparent })=>{
|
|
39
|
+
const routePath = operationContext?.routePath || path;
|
|
40
|
+
const operationMethod = (operationContext?.method || method || 'GET').toUpperCase();
|
|
41
|
+
const rawOperationId = operationContext?.operationId || `${operationMethod}:${routePath}`;
|
|
42
|
+
const operationId = rawOperationId.startsWith(`${requestId}:`) ? rawOperationId : `${requestId}:${rawOperationId}`;
|
|
43
|
+
const traceparentValue = operationContext?.traceparent || ('string' == typeof firstHeaderValue(traceparent) ? String(firstHeaderValue(traceparent)) : void 0);
|
|
44
|
+
const parsedTraceContext = operationContext?.traceId && operationContext?.spanId ? {
|
|
45
|
+
traceId: operationContext.traceId,
|
|
46
|
+
spanId: operationContext.spanId
|
|
47
|
+
} : parseTraceparentValue(traceparentValue);
|
|
48
|
+
return {
|
|
49
|
+
requestId,
|
|
50
|
+
operationId,
|
|
51
|
+
routePath,
|
|
52
|
+
method: operationMethod,
|
|
53
|
+
...operationContext?.schemaHash ? {
|
|
54
|
+
schemaHash: operationContext.schemaHash
|
|
55
|
+
} : {},
|
|
56
|
+
...'number' == typeof operationContext?.operationVersion ? {
|
|
57
|
+
operationVersion: operationContext.operationVersion
|
|
58
|
+
} : {},
|
|
59
|
+
...traceparentValue ? {
|
|
60
|
+
traceparent: traceparentValue
|
|
61
|
+
} : {},
|
|
62
|
+
...parsedTraceContext ? {
|
|
63
|
+
traceId: parsedTraceContext.traceId,
|
|
64
|
+
spanId: parsedTraceContext.spanId
|
|
65
|
+
} : {}
|
|
66
|
+
};
|
|
67
|
+
};
|
|
68
|
+
class ProducerClientNotInitializedError extends Error {
|
|
69
|
+
constructor(requestId){
|
|
70
|
+
super(`Producer client "${requestId}" is not initialized. Call initProducerClient() (or configure()) before using generated APIs for this requestId.`), this.code = 'BFF_PRODUCER_CLIENT_NOT_INITIALIZED';
|
|
71
|
+
this.name = 'ProducerClientNotInitializedError';
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
class ProducerDomainNotConfiguredError extends Error {
|
|
75
|
+
constructor(requestId){
|
|
76
|
+
super(`Producer client "${requestId}" must provide setDomain() during configure().`), this.code = 'BFF_PRODUCER_DOMAIN_NOT_CONFIGURED';
|
|
77
|
+
this.name = 'ProducerDomainNotConfiguredError';
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
class CrossOriginEnvelopePolicyError extends Error {
|
|
81
|
+
constructor(requestId, sourceOrigin, targetOrigin){
|
|
82
|
+
super(`Cross-origin envelope is not allowed for producer "${requestId}" (${sourceOrigin || 'unknown-origin'} -> ${targetOrigin || 'unknown-origin'}). Configure allowCrossOriginEnvelope to explicitly allow this flow.`), this.code = 'BFF_CROSS_ORIGIN_ENVELOPE_NOT_ALLOWED';
|
|
83
|
+
this.name = 'CrossOriginEnvelopePolicyError';
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
class IdentityBindingViolationError extends Error {
|
|
87
|
+
constructor(violation){
|
|
88
|
+
super(`Identity header "${violation.header}" for producer "${violation.requestId}" was rejected by server-derived identity binding.`), this.code = 'BFF_IDENTITY_BINDING_VIOLATION';
|
|
89
|
+
this.name = 'IdentityBindingViolationError';
|
|
90
|
+
this.violation = violation;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
class OperationContractViolationError extends Error {
|
|
94
|
+
constructor(violation){
|
|
95
|
+
super(`Operation contract violation "${violation.reason}" for producer "${violation.requestId}" operation "${violation.operationId}".`), this.code = 'BFF_OPERATION_CONTRACT_VIOLATION';
|
|
96
|
+
this.name = 'OperationContractViolationError';
|
|
97
|
+
this.violation = violation;
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const validateOperationContract = ({ requestId, target, contextPayload, operationContract })=>{
|
|
101
|
+
const operationContractEnabled = operationContract?.enabled ?? isSecuredRequestId(requestId);
|
|
102
|
+
if (!operationContractEnabled) return;
|
|
103
|
+
const strict = operationContract?.strict ?? true;
|
|
104
|
+
const requireSchemaHash = operationContract?.requireSchemaHash ?? true;
|
|
105
|
+
const requireOperationVersion = operationContract?.requireOperationVersion ?? true;
|
|
106
|
+
const maybeReportViolation = (reason)=>{
|
|
107
|
+
const violation = {
|
|
108
|
+
requestId,
|
|
109
|
+
target,
|
|
110
|
+
operationId: contextPayload.operationId,
|
|
111
|
+
routePath: contextPayload.routePath,
|
|
112
|
+
method: contextPayload.method,
|
|
113
|
+
schemaHash: 'string' == typeof contextPayload.schemaHash ? contextPayload.schemaHash : void 0,
|
|
114
|
+
operationVersion: 'number' == typeof contextPayload.operationVersion ? contextPayload.operationVersion : void 0,
|
|
115
|
+
reason
|
|
116
|
+
};
|
|
117
|
+
operationContract?.onViolation?.(violation);
|
|
118
|
+
if (strict) throw new OperationContractViolationError(violation);
|
|
119
|
+
};
|
|
120
|
+
if (requireSchemaHash && 'string' != typeof contextPayload.schemaHash) maybeReportViolation('missing_schema_hash');
|
|
121
|
+
if (requireOperationVersion && 'number' != typeof contextPayload.operationVersion) maybeReportViolation('missing_operation_version');
|
|
122
|
+
};
|
|
123
|
+
const resolveConfiguredRequest = (configuredRequests, requestId, fallback)=>{
|
|
124
|
+
const configuredRequest = configuredRequests.get(requestId);
|
|
125
|
+
if (configuredRequest) return configuredRequest;
|
|
126
|
+
if ('default' !== requestId) throw new ProducerClientNotInitializedError(requestId);
|
|
127
|
+
return fallback;
|
|
128
|
+
};
|
|
129
|
+
const buildEnvelopeHeaderValue = ({ requestId, target, sourceOrigin, targetOrigin, traceContext, allowCrossOriginEnvelope })=>{
|
|
130
|
+
const isCrossOrigin = Boolean(sourceOrigin) && Boolean(targetOrigin) && sourceOrigin !== targetOrigin;
|
|
131
|
+
if (isCrossOrigin) {
|
|
132
|
+
const isAllowed = 'function' == typeof allowCrossOriginEnvelope ? true === allowCrossOriginEnvelope({
|
|
133
|
+
requestId,
|
|
134
|
+
sourceOrigin,
|
|
135
|
+
targetOrigin,
|
|
136
|
+
target
|
|
137
|
+
}) : true === allowCrossOriginEnvelope;
|
|
138
|
+
if (!isAllowed) throw new CrossOriginEnvelopePolicyError(requestId, sourceOrigin, targetOrigin);
|
|
139
|
+
}
|
|
140
|
+
return JSON.stringify({
|
|
141
|
+
requestId,
|
|
142
|
+
target,
|
|
143
|
+
timestamp: Date.now(),
|
|
144
|
+
sourceOrigin,
|
|
145
|
+
targetOrigin,
|
|
146
|
+
...traceContext ? {
|
|
147
|
+
traceId: traceContext.traceId,
|
|
148
|
+
spanId: traceContext.spanId
|
|
149
|
+
} : {}
|
|
150
|
+
});
|
|
151
|
+
};
|
|
152
|
+
const attachOperationContextHeaders = ({ headers, requestId, target, method, path, operationContext, operationContract, operationContextHeader, operationContextDetailHeader })=>{
|
|
153
|
+
if (void 0 === readHeader(headers, TRACEPARENT_HEADER) && operationContext?.traceparent) writeHeader(headers, TRACEPARENT_HEADER, operationContext.traceparent);
|
|
154
|
+
const contextPayload = buildOperationContext({
|
|
155
|
+
requestId,
|
|
156
|
+
method,
|
|
157
|
+
path,
|
|
158
|
+
operationContext,
|
|
159
|
+
traceparent: readHeader(headers, TRACEPARENT_HEADER)
|
|
160
|
+
});
|
|
161
|
+
validateOperationContract({
|
|
162
|
+
requestId,
|
|
163
|
+
target,
|
|
164
|
+
contextPayload,
|
|
165
|
+
operationContract
|
|
166
|
+
});
|
|
167
|
+
if (void 0 === readHeader(headers, operationContextHeader)) writeHeader(headers, operationContextHeader, contextPayload.operationId);
|
|
168
|
+
writeHeader(headers, operationContextDetailHeader, JSON.stringify(contextPayload));
|
|
169
|
+
return contextPayload;
|
|
170
|
+
};
|
|
171
|
+
export { CrossOriginEnvelopePolicyError, IdentityBindingViolationError, OperationContractViolationError, ProducerClientNotInitializedError, ProducerDomainNotConfiguredError, TRACEPARENT_HEADER, attachOperationContextHeaders, buildEnvelopeHeaderValue, buildOperationContext, deleteHeader, findHeaderKey, firstHeaderValue, isEmptyDomain, isSecuredRequestId, parseTraceparentValue, readHeader, resolveConfiguredRequest, toOrigin, validateOperationContract, writeHeader };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import { parseTraceparent } from "./traceparent.mjs";
|
|
2
|
+
const BFF_LOCALE_HEADER = 'accept-language';
|
|
3
|
+
const BFF_TRACEPARENT_HEADER = 'traceparent';
|
|
4
|
+
const readHeader = (headers, header)=>{
|
|
5
|
+
if (!headers) return;
|
|
6
|
+
const normalized = header.toLowerCase();
|
|
7
|
+
const key = Object.keys(headers).find((current)=>current.toLowerCase() === normalized);
|
|
8
|
+
if (!key) return;
|
|
9
|
+
const value = headers[key];
|
|
10
|
+
return Array.isArray(value) ? value[0] : value;
|
|
11
|
+
};
|
|
12
|
+
const readString = (value)=>'string' == typeof value && value.length > 0 ? value : void 0;
|
|
13
|
+
function createOperationContextSnapshot(operationContext, safeContext) {
|
|
14
|
+
if (!operationContext) return;
|
|
15
|
+
const snapshot = {
|
|
16
|
+
...operationContext,
|
|
17
|
+
...safeContext.locale || operationContext?.locale ? {
|
|
18
|
+
locale: safeContext.locale || operationContext?.locale
|
|
19
|
+
} : {},
|
|
20
|
+
...safeContext.traceparent || operationContext?.traceparent ? {
|
|
21
|
+
traceparent: safeContext.traceparent || operationContext?.traceparent
|
|
22
|
+
} : {},
|
|
23
|
+
...safeContext.traceId || operationContext?.traceId ? {
|
|
24
|
+
traceId: safeContext.traceId || operationContext?.traceId
|
|
25
|
+
} : {},
|
|
26
|
+
...safeContext.spanId || operationContext?.spanId ? {
|
|
27
|
+
spanId: safeContext.spanId || operationContext?.spanId
|
|
28
|
+
} : {}
|
|
29
|
+
};
|
|
30
|
+
return Object.keys(snapshot).some((key)=>void 0 !== snapshot[key]) ? snapshot : void 0;
|
|
31
|
+
}
|
|
32
|
+
function createRequestContextSnapshot(input = {}) {
|
|
33
|
+
const locale = readString(input.locale) || readString(readHeader(input.headers, BFF_LOCALE_HEADER));
|
|
34
|
+
const traceparent = readString(input.traceparent) || readString(input.operationContext?.traceparent) || readString(readHeader(input.headers, BFF_TRACEPARENT_HEADER));
|
|
35
|
+
const parsedTraceparent = input.operationContext?.traceId && input.operationContext?.spanId ? {
|
|
36
|
+
traceId: input.operationContext.traceId,
|
|
37
|
+
spanId: input.operationContext.spanId
|
|
38
|
+
} : parseTraceparent(traceparent);
|
|
39
|
+
const headers = {};
|
|
40
|
+
if (locale) headers[BFF_LOCALE_HEADER] = locale;
|
|
41
|
+
if (traceparent) headers[BFF_TRACEPARENT_HEADER] = traceparent;
|
|
42
|
+
const operationContext = createOperationContextSnapshot(input.operationContext, {
|
|
43
|
+
...locale ? {
|
|
44
|
+
locale
|
|
45
|
+
} : {},
|
|
46
|
+
...traceparent ? {
|
|
47
|
+
traceparent
|
|
48
|
+
} : {},
|
|
49
|
+
...parsedTraceparent ? {
|
|
50
|
+
traceId: parsedTraceparent.traceId,
|
|
51
|
+
spanId: parsedTraceparent.spanId
|
|
52
|
+
} : {}
|
|
53
|
+
});
|
|
54
|
+
return {
|
|
55
|
+
headers,
|
|
56
|
+
...locale ? {
|
|
57
|
+
locale
|
|
58
|
+
} : {},
|
|
59
|
+
...traceparent ? {
|
|
60
|
+
traceparent
|
|
61
|
+
} : {},
|
|
62
|
+
...parsedTraceparent ? {
|
|
63
|
+
traceId: parsedTraceparent.traceId,
|
|
64
|
+
spanId: parsedTraceparent.spanId
|
|
65
|
+
} : {},
|
|
66
|
+
...operationContext ? {
|
|
67
|
+
operationContext
|
|
68
|
+
} : {}
|
|
69
|
+
};
|
|
70
|
+
}
|
|
71
|
+
function createRequestContextHeaders(input = {}) {
|
|
72
|
+
return createRequestContextSnapshot(input).headers;
|
|
73
|
+
}
|
|
74
|
+
export { BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS, BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER } from "./types.mjs";
|
|
75
|
+
export { BFF_LOCALE_HEADER, BFF_TRACEPARENT_HEADER, createRequestContextHeaders, createRequestContextSnapshot, parseTraceparent };
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
const TRACEPARENT_REGEX = /^00-([0-9a-f]{32})-([0-9a-f]{16})-([0-9a-f]{2})$/i;
|
|
2
|
+
const isAllZeroHex = (value)=>/^0+$/.test(value);
|
|
3
|
+
function parseTraceparent(traceparent) {
|
|
4
|
+
if (!traceparent) return;
|
|
5
|
+
const match = traceparent.trim().match(TRACEPARENT_REGEX);
|
|
6
|
+
if (!match) return;
|
|
7
|
+
const [, rawTraceId, rawSpanId, rawFlags] = match;
|
|
8
|
+
if (!rawTraceId || !rawSpanId || !rawFlags) return;
|
|
9
|
+
const traceId = rawTraceId.toLowerCase();
|
|
10
|
+
const spanId = rawSpanId.toLowerCase();
|
|
11
|
+
if (isAllZeroHex(traceId) || isAllZeroHex(spanId)) return;
|
|
12
|
+
return {
|
|
13
|
+
traceId,
|
|
14
|
+
spanId,
|
|
15
|
+
sampled: (0x1 & Number.parseInt(rawFlags, 16)) === 1
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
export { parseTraceparent };
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
const DEFAULT_RETRYABLE_STATUS_CODES = [
|
|
2
|
+
408,
|
|
3
|
+
425,
|
|
4
|
+
429,
|
|
5
|
+
500,
|
|
6
|
+
502,
|
|
7
|
+
503,
|
|
8
|
+
504
|
|
9
|
+
];
|
|
10
|
+
const DEFAULT_BASE_DELAY_MS = 100;
|
|
11
|
+
const DEFAULT_MAX_DELAY_MS = 1000;
|
|
12
|
+
const DEFAULT_JITTER_RATIO = 0.1;
|
|
13
|
+
const DEFAULT_RETRYABLE_METHODS = new Set([
|
|
14
|
+
'DELETE',
|
|
15
|
+
'GET',
|
|
16
|
+
'HEAD',
|
|
17
|
+
'OPTIONS',
|
|
18
|
+
'PUT',
|
|
19
|
+
'TRACE'
|
|
20
|
+
]);
|
|
21
|
+
const createTimeoutError = (timeoutMs)=>{
|
|
22
|
+
const error = new Error(`Request timed out after ${timeoutMs}ms`);
|
|
23
|
+
error.name = 'TimeoutError';
|
|
24
|
+
return error;
|
|
25
|
+
};
|
|
26
|
+
const unrefTimer = (timer)=>{
|
|
27
|
+
if ('object' == typeof timer && null !== timer && 'unref' in timer && 'function' == typeof timer.unref) timer.unref();
|
|
28
|
+
};
|
|
29
|
+
const wait = (ms)=>new Promise((resolve)=>{
|
|
30
|
+
const timer = setTimeout(()=>resolve(), ms);
|
|
31
|
+
unrefTimer(timer);
|
|
32
|
+
});
|
|
33
|
+
const toStatusCode = (error)=>{
|
|
34
|
+
if (!error || 'object' != typeof error) return;
|
|
35
|
+
const status = error.status;
|
|
36
|
+
if ('number' == typeof status) return status;
|
|
37
|
+
const responseStatus = error.response?.status;
|
|
38
|
+
if ('number' == typeof responseStatus) return responseStatus;
|
|
39
|
+
};
|
|
40
|
+
const isRetryableNetworkError = (error)=>{
|
|
41
|
+
if (!error || 'object' != typeof error) return false;
|
|
42
|
+
const name = error.name;
|
|
43
|
+
if ('FetchError' === name || 'TimeoutError' === name || 'TypeError' === name) return true;
|
|
44
|
+
const code = error.code;
|
|
45
|
+
return 'ECONNRESET' === code || 'ETIMEDOUT' === code || 'ECONNREFUSED' === code || 'EPIPE' === code;
|
|
46
|
+
};
|
|
47
|
+
const normalizePositiveNumber = (value, fallback)=>'number' == typeof value && Number.isFinite(value) && value > 0 ? value : fallback;
|
|
48
|
+
const normalizeNonNegativeInt = (value, fallback)=>'number' == typeof value && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
|
|
49
|
+
const normalizeJitterRatio = (value)=>{
|
|
50
|
+
if ('number' != typeof value || !Number.isFinite(value)) return DEFAULT_JITTER_RATIO;
|
|
51
|
+
return Math.max(0, Math.min(1, value));
|
|
52
|
+
};
|
|
53
|
+
const shouldRetryWithDefaults = (method, statusCode, error, retryableStatusCodes)=>{
|
|
54
|
+
if (!DEFAULT_RETRYABLE_METHODS.has(method.toUpperCase())) return false;
|
|
55
|
+
if ('number' == typeof statusCode) return retryableStatusCodes.includes(statusCode);
|
|
56
|
+
return isRetryableNetworkError(error);
|
|
57
|
+
};
|
|
58
|
+
const shouldRetry = (retryOptions, context, retryableStatusCodes)=>{
|
|
59
|
+
if ('function' == typeof retryOptions?.shouldRetry) try {
|
|
60
|
+
return retryOptions.shouldRetry(context);
|
|
61
|
+
} catch (error) {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
return shouldRetryWithDefaults(context.method, context.statusCode, context.error, retryableStatusCodes);
|
|
65
|
+
};
|
|
66
|
+
const getBackoffMs = (retryOptions, attempt)=>{
|
|
67
|
+
const baseDelayMs = normalizePositiveNumber(retryOptions?.baseDelayMs, DEFAULT_BASE_DELAY_MS);
|
|
68
|
+
const maxDelayMs = normalizePositiveNumber(retryOptions?.maxDelayMs, DEFAULT_MAX_DELAY_MS);
|
|
69
|
+
const jitterRatio = normalizeJitterRatio(retryOptions?.jitterRatio);
|
|
70
|
+
const exponentialDelay = Math.min(maxDelayMs, baseDelayMs * 2 ** Math.max(0, attempt - 1));
|
|
71
|
+
const jitterFactor = 0 === jitterRatio ? 1 : 1 + (2 * Math.random() - 1) * jitterRatio;
|
|
72
|
+
return Math.max(0, Math.floor(exponentialDelay * jitterFactor));
|
|
73
|
+
};
|
|
74
|
+
const emitDegradedEvent = (transport, event)=>{
|
|
75
|
+
if ('function' != typeof transport?.onDegraded) return;
|
|
76
|
+
try {
|
|
77
|
+
transport.onDegraded(event);
|
|
78
|
+
} catch (error) {}
|
|
79
|
+
};
|
|
80
|
+
const withTimeout = async (promise, timeoutMs, signalBuilder)=>{
|
|
81
|
+
if (!timeoutMs || timeoutMs <= 0) {
|
|
82
|
+
const result = await promise;
|
|
83
|
+
return {
|
|
84
|
+
result
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
const controller = signalBuilder?.();
|
|
88
|
+
let timeoutTriggered = false;
|
|
89
|
+
let rejectTimeout;
|
|
90
|
+
const timeoutPromise = new Promise((_, reject)=>{
|
|
91
|
+
rejectTimeout = reject;
|
|
92
|
+
});
|
|
93
|
+
const timer = setTimeout(()=>{
|
|
94
|
+
timeoutTriggered = true;
|
|
95
|
+
if (controller) controller.abort();
|
|
96
|
+
rejectTimeout?.(createTimeoutError(timeoutMs));
|
|
97
|
+
}, timeoutMs);
|
|
98
|
+
unrefTimer(timer);
|
|
99
|
+
try {
|
|
100
|
+
const result = await Promise.race([
|
|
101
|
+
promise,
|
|
102
|
+
timeoutPromise
|
|
103
|
+
]);
|
|
104
|
+
return {
|
|
105
|
+
result,
|
|
106
|
+
timeoutTriggered
|
|
107
|
+
};
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (timeoutTriggered && error?.name === 'AbortError') throw createTimeoutError(timeoutMs);
|
|
110
|
+
throw error;
|
|
111
|
+
} finally{
|
|
112
|
+
clearTimeout(timer);
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
const executeWithResilience = async ({ requestId, target, method, url, init, fetcher, transport })=>{
|
|
116
|
+
const retries = normalizeNonNegativeInt(transport?.retry?.retries, 0);
|
|
117
|
+
const timeoutMs = 'number' == typeof transport?.timeoutMs && transport.timeoutMs > 0 ? transport.timeoutMs : void 0;
|
|
118
|
+
const maxAttempts = retries + 1;
|
|
119
|
+
const retryableStatusCodes = transport?.retry?.retryableStatusCodes && transport.retry.retryableStatusCodes.length > 0 ? transport.retry.retryableStatusCodes : DEFAULT_RETRYABLE_STATUS_CODES;
|
|
120
|
+
let attempt = 0;
|
|
121
|
+
while(attempt < maxAttempts){
|
|
122
|
+
attempt += 1;
|
|
123
|
+
const canUseAbortController = "u" > typeof AbortController;
|
|
124
|
+
let controller;
|
|
125
|
+
if (timeoutMs && canUseAbortController) controller = new AbortController();
|
|
126
|
+
const callerSignal = init.signal;
|
|
127
|
+
const requestSignal = controller ? callerSignal && !callerSignal.aborted ? AbortSignal.any([
|
|
128
|
+
callerSignal,
|
|
129
|
+
controller.signal
|
|
130
|
+
]) : callerSignal || controller.signal : callerSignal;
|
|
131
|
+
const nextInit = requestSignal ? {
|
|
132
|
+
...init,
|
|
133
|
+
signal: requestSignal
|
|
134
|
+
} : init;
|
|
135
|
+
try {
|
|
136
|
+
const { result } = await withTimeout(fetcher(url, nextInit), timeoutMs, ()=>controller);
|
|
137
|
+
return result;
|
|
138
|
+
} catch (error) {
|
|
139
|
+
const statusCode = toStatusCode(error);
|
|
140
|
+
const decisionContext = {
|
|
141
|
+
requestId,
|
|
142
|
+
target,
|
|
143
|
+
method,
|
|
144
|
+
url,
|
|
145
|
+
attempt,
|
|
146
|
+
maxAttempts,
|
|
147
|
+
error,
|
|
148
|
+
statusCode
|
|
149
|
+
};
|
|
150
|
+
if (error?.name === 'TimeoutError') emitDegradedEvent(transport, {
|
|
151
|
+
requestId,
|
|
152
|
+
target,
|
|
153
|
+
method,
|
|
154
|
+
url,
|
|
155
|
+
reason: 'timeout',
|
|
156
|
+
attempt,
|
|
157
|
+
maxAttempts,
|
|
158
|
+
timeoutMs,
|
|
159
|
+
statusCode,
|
|
160
|
+
error
|
|
161
|
+
});
|
|
162
|
+
const canRetry = attempt < maxAttempts && shouldRetry(transport?.retry, decisionContext, retryableStatusCodes);
|
|
163
|
+
if (!canRetry) {
|
|
164
|
+
if (retries > 0 || error?.name === 'TimeoutError') emitDegradedEvent(transport, {
|
|
165
|
+
requestId,
|
|
166
|
+
target,
|
|
167
|
+
method,
|
|
168
|
+
url,
|
|
169
|
+
reason: 'retry_exhausted',
|
|
170
|
+
attempt,
|
|
171
|
+
maxAttempts,
|
|
172
|
+
timeoutMs,
|
|
173
|
+
statusCode,
|
|
174
|
+
error
|
|
175
|
+
});
|
|
176
|
+
throw error;
|
|
177
|
+
}
|
|
178
|
+
const backoffMs = getBackoffMs(transport?.retry, attempt);
|
|
179
|
+
emitDegradedEvent(transport, {
|
|
180
|
+
requestId,
|
|
181
|
+
target,
|
|
182
|
+
method,
|
|
183
|
+
url,
|
|
184
|
+
reason: 'retry',
|
|
185
|
+
attempt,
|
|
186
|
+
maxAttempts,
|
|
187
|
+
timeoutMs,
|
|
188
|
+
backoffMs,
|
|
189
|
+
statusCode,
|
|
190
|
+
error
|
|
191
|
+
});
|
|
192
|
+
if (backoffMs > 0) await wait(backoffMs);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
export { executeWithResilience };
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
const BFF_ENVELOPE_HEADER = 'x-modernjs-bff-envelope';
|
|
2
|
+
const BFF_OPERATION_CONTEXT_HEADER = 'x-operation-id';
|
|
3
|
+
const BFF_OPERATION_CONTEXT_DETAIL_HEADER = 'x-modernjs-bff-operation-context';
|
|
4
|
+
const BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS = [
|
|
5
|
+
'x-tenant-id',
|
|
6
|
+
'x-subject-id',
|
|
7
|
+
'x-user-id',
|
|
8
|
+
BFF_OPERATION_CONTEXT_HEADER
|
|
9
|
+
];
|
|
10
|
+
export { BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS, BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER };
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { escapeHtmlAttribute } from "./html.mjs";
|
|
2
|
+
function getScriptTags(template) {
|
|
3
|
+
const scriptRegExp = /<script\b[^>]*\bsrc=(["'])(.*?)\1[^>]*><\/script>/g;
|
|
4
|
+
return Array.from(template.matchAll(scriptRegExp)).map((match)=>({
|
|
5
|
+
index: match.index ?? 0,
|
|
6
|
+
tag: match[0],
|
|
7
|
+
src: match[2]
|
|
8
|
+
}));
|
|
9
|
+
}
|
|
10
|
+
function getAssetBasename(src) {
|
|
11
|
+
const withoutQuery = src.split(/[?#]/)[0];
|
|
12
|
+
return withoutQuery.split('/').pop() || withoutQuery;
|
|
13
|
+
}
|
|
14
|
+
function isEntryScript(src, entryName, asyncEntry) {
|
|
15
|
+
const basename = getAssetBasename(src);
|
|
16
|
+
const prefix = asyncEntry ? `async-${entryName}` : entryName;
|
|
17
|
+
return basename === `${prefix}.js` || basename.startsWith(`${prefix}.`) || basename.startsWith(`${prefix}-`);
|
|
18
|
+
}
|
|
19
|
+
const dedupeByUrl = (chunks)=>{
|
|
20
|
+
const seen = new Set();
|
|
21
|
+
return chunks.filter((chunk)=>{
|
|
22
|
+
if (void 0 === chunk.url || '' === chunk.url || seen.has(chunk.url)) return false;
|
|
23
|
+
seen.add(chunk.url);
|
|
24
|
+
return true;
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
const isAsyncEntryScriptChunk = (chunk, entryName)=>{
|
|
28
|
+
if (void 0 === chunk.url || !chunk.url.endsWith('.js')) return false;
|
|
29
|
+
const asyncEntryName = `async-${entryName}`;
|
|
30
|
+
const filename = chunk.filename ?? chunk.url;
|
|
31
|
+
const basename = filename.split('/').pop() ?? filename;
|
|
32
|
+
return basename === `${asyncEntryName}.js` || basename.startsWith(`${asyncEntryName}.`) || basename.startsWith(`${asyncEntryName}-`);
|
|
33
|
+
};
|
|
34
|
+
function getMatchedRouteChunks(routeManifest, matchedRouteIds, routeAssetToChunk) {
|
|
35
|
+
const routeAssets = routeManifest?.routeAssets;
|
|
36
|
+
if (void 0 === routeAssets) return [];
|
|
37
|
+
return matchedRouteIds.flatMap((routeId)=>routeAssets[routeId]?.assets ?? []).map(routeAssetToChunk);
|
|
38
|
+
}
|
|
39
|
+
const orderHydrationScriptChunks = ({ asyncEntryChunks, collectedChunks, matchedRouteChunks, entryName })=>{
|
|
40
|
+
const asyncEntryScriptChunks = [];
|
|
41
|
+
const asyncEntryDependencyChunks = [];
|
|
42
|
+
for (const chunk of asyncEntryChunks)if (isAsyncEntryScriptChunk(chunk, entryName)) asyncEntryScriptChunks.push(chunk);
|
|
43
|
+
else asyncEntryDependencyChunks.push(chunk);
|
|
44
|
+
return dedupeByUrl([
|
|
45
|
+
...asyncEntryDependencyChunks,
|
|
46
|
+
...collectedChunks,
|
|
47
|
+
...matchedRouteChunks,
|
|
48
|
+
...asyncEntryScriptChunks
|
|
49
|
+
]);
|
|
50
|
+
};
|
|
51
|
+
function injectBeforeHydrationEntryScript(template, scripts, entryName = 'index') {
|
|
52
|
+
if ('' === scripts) return template;
|
|
53
|
+
const scriptTags = getScriptTags(template);
|
|
54
|
+
const target = scriptTags.find((match)=>isEntryScript(match.src, entryName, false)) ?? scriptTags.find((match)=>isEntryScript(match.src, entryName, true));
|
|
55
|
+
if (void 0 === target) return template;
|
|
56
|
+
return `${template.slice(0, target.index)}${scripts}${template.slice(target.index)}`;
|
|
57
|
+
}
|
|
58
|
+
function replaceChunkJsPlaceholder(template, scripts, entryName, placeholder) {
|
|
59
|
+
if (!template.includes(placeholder)) return template;
|
|
60
|
+
if ('' === scripts) return template.replace(placeholder, ()=>'');
|
|
61
|
+
const withoutPlaceholder = template.replace(placeholder, ()=>'');
|
|
62
|
+
const withEarlyScripts = injectBeforeHydrationEntryScript(withoutPlaceholder, scripts, entryName);
|
|
63
|
+
if (withEarlyScripts !== withoutPlaceholder) return withEarlyScripts;
|
|
64
|
+
return template.replace(placeholder, ()=>scripts);
|
|
65
|
+
}
|
|
66
|
+
function createRouteHydrationScriptTags(routeManifest, matchedRouteIds, entryName, options = {}) {
|
|
67
|
+
const { nonce, template } = options;
|
|
68
|
+
const routeAssets = routeManifest?.routeAssets;
|
|
69
|
+
if (void 0 === routeAssets) return '';
|
|
70
|
+
const existingScriptSrcs = void 0 === template ? new Set() : new Set(getScriptTags(template).map(({ src })=>src));
|
|
71
|
+
const jsAssets = Array.from(new Set([
|
|
72
|
+
...getMatchedRouteChunks(routeManifest, matchedRouteIds, (asset)=>asset),
|
|
73
|
+
...routeAssets[`async-${entryName}`]?.assets ?? []
|
|
74
|
+
].filter((asset)=>asset.endsWith('.js'))));
|
|
75
|
+
return jsAssets.filter((asset)=>!existingScriptSrcs.has(asset)).map((asset)=>`<script src="${escapeHtmlAttribute(asset)}"${nonce ? ` nonce="${escapeHtmlAttribute(nonce)}"` : ''}></script>`).join(' ');
|
|
76
|
+
}
|
|
77
|
+
export { createRouteHydrationScriptTags, getMatchedRouteChunks, injectBeforeHydrationEntryScript, orderHydrationScriptChunks, replaceChunkJsPlaceholder };
|
|
@@ -0,0 +1,115 @@
|
|
|
1
|
+
import { getNavigationWarmupCacheKey } from "./navigationWarmup.mjs";
|
|
2
|
+
import { normalizePreloadBehavior } from "./prefetchPolicy.mjs";
|
|
3
|
+
const INTENT_DELAY = 100;
|
|
4
|
+
const VIEWPORT_ROOT_MARGIN = '200px';
|
|
5
|
+
const MAX_CONCURRENT_WARMUPS = 4;
|
|
6
|
+
const WARMUP_TTL = 30000;
|
|
7
|
+
function createRouterPrefetchPolicy() {
|
|
8
|
+
const cache = new Map();
|
|
9
|
+
const queue = [];
|
|
10
|
+
let activeWarmups = 0;
|
|
11
|
+
const canWarmup = ()=>{
|
|
12
|
+
const navigator = globalThis.navigator;
|
|
13
|
+
const connection = navigator?.connection || navigator?.mozConnection || navigator?.webkitConnection;
|
|
14
|
+
return !connection?.saveData && connection?.effectiveType !== 'slow-2g' && connection?.effectiveType !== '2g';
|
|
15
|
+
};
|
|
16
|
+
const runNext = ()=>{
|
|
17
|
+
while(activeWarmups < MAX_CONCURRENT_WARMUPS && queue.length > 0){
|
|
18
|
+
const task = queue.shift();
|
|
19
|
+
if (task.cancelled) continue;
|
|
20
|
+
activeWarmups += 1;
|
|
21
|
+
task.run().catch(()=>{
|
|
22
|
+
cache.delete(task.key);
|
|
23
|
+
}).finally(()=>{
|
|
24
|
+
activeWarmups -= 1;
|
|
25
|
+
runNext();
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
};
|
|
29
|
+
return {
|
|
30
|
+
canWarmup,
|
|
31
|
+
allowData (route) {
|
|
32
|
+
return route?.handle?.navigationWarmup?.data !== false;
|
|
33
|
+
},
|
|
34
|
+
observe ({ element, prefetch: inputPrefetch, preload: inputPreload, notify }) {
|
|
35
|
+
const prefetch = inputPrefetch ?? 'render';
|
|
36
|
+
const preload = normalizePreloadBehavior(inputPreload, prefetch);
|
|
37
|
+
let state = {
|
|
38
|
+
code: 'render' === prefetch || 'render' === preload,
|
|
39
|
+
data: 'render' === prefetch
|
|
40
|
+
};
|
|
41
|
+
let timer;
|
|
42
|
+
let observer;
|
|
43
|
+
const update = (next)=>{
|
|
44
|
+
state = next;
|
|
45
|
+
notify(state);
|
|
46
|
+
};
|
|
47
|
+
const cancelTimer = ()=>{
|
|
48
|
+
if (void 0 !== timer) {
|
|
49
|
+
clearTimeout(timer);
|
|
50
|
+
timer = void 0;
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
notify(state);
|
|
54
|
+
if (element && ('viewport' === prefetch || 'viewport' === preload) && "u" > typeof IntersectionObserver) {
|
|
55
|
+
observer = new IntersectionObserver((entries)=>{
|
|
56
|
+
if (!entries.some((entry)=>entry.isIntersecting)) return;
|
|
57
|
+
update({
|
|
58
|
+
code: true,
|
|
59
|
+
data: state.data || 'viewport' === prefetch
|
|
60
|
+
});
|
|
61
|
+
observer?.disconnect();
|
|
62
|
+
}, {
|
|
63
|
+
rootMargin: VIEWPORT_ROOT_MARGIN
|
|
64
|
+
});
|
|
65
|
+
observer.observe(element);
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
onIntent () {
|
|
69
|
+
if ('intent' !== prefetch && 'intent' !== preload) return;
|
|
70
|
+
if (void 0 !== timer) return;
|
|
71
|
+
timer = setTimeout(()=>{
|
|
72
|
+
timer = void 0;
|
|
73
|
+
update({
|
|
74
|
+
code: true,
|
|
75
|
+
data: state.data || 'intent' === prefetch
|
|
76
|
+
});
|
|
77
|
+
}, INTENT_DELAY);
|
|
78
|
+
},
|
|
79
|
+
onCancel () {
|
|
80
|
+
if ('intent' === prefetch || 'intent' === preload) {
|
|
81
|
+
cancelTimer();
|
|
82
|
+
update({
|
|
83
|
+
code: false,
|
|
84
|
+
data: false
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
dispose () {
|
|
89
|
+
cancelTimer();
|
|
90
|
+
observer?.disconnect();
|
|
91
|
+
}
|
|
92
|
+
};
|
|
93
|
+
},
|
|
94
|
+
schedule ({ runtimeContext, chunkLoader, publicPath, key: operationKey, run }) {
|
|
95
|
+
if (!canWarmup()) return ()=>{};
|
|
96
|
+
const now = performance.now();
|
|
97
|
+
for (const [key, timestamp] of cache)if (now - timestamp > WARMUP_TTL) cache.delete(key);
|
|
98
|
+
const key = getNavigationWarmupCacheKey(runtimeContext, chunkLoader, publicPath, operationKey);
|
|
99
|
+
if (cache.has(key)) return ()=>{};
|
|
100
|
+
cache.set(key, now);
|
|
101
|
+
const task = {
|
|
102
|
+
key,
|
|
103
|
+
run,
|
|
104
|
+
cancelled: false
|
|
105
|
+
};
|
|
106
|
+
queue.push(task);
|
|
107
|
+
runNext();
|
|
108
|
+
return ()=>{
|
|
109
|
+
task.cancelled = true;
|
|
110
|
+
if (queue.includes(task)) cache.delete(key);
|
|
111
|
+
};
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
export { createRouterPrefetchPolicy };
|