@bleedingdev/modern-js-create-request 3.2.0-ultramodern.0

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.
@@ -0,0 +1,15 @@
1
+ const handleRes = async (res)=>{
2
+ const contentType = res.headers.get('content-type');
3
+ if (!res.ok) {
4
+ const data = await res.json();
5
+ res.data = data;
6
+ throw res;
7
+ }
8
+ if (contentType?.includes('application/json') || contentType?.includes('text/json')) return res.json();
9
+ if (contentType?.includes('text/html') || contentType?.includes('text/plain')) return res.text();
10
+ if ((contentType?.includes('application/x-www-form-urlencoded') || contentType?.includes('multipart/form-data')) && res instanceof Response) return res.formData();
11
+ if (contentType?.includes('application/octet-stream')) return res.arrayBuffer();
12
+ if (contentType?.includes('image/png')) return res;
13
+ return res.text();
14
+ };
15
+ export { handleRes };
@@ -0,0 +1,405 @@
1
+ import { storage } from "@modern-js/runtime-utils/node";
2
+ import { compile } from "path-to-regexp";
3
+ import { stringify } from "qs";
4
+ import { handleRes } from "./handleRes.mjs";
5
+ import { executeWithResilience } from "./transport.mjs";
6
+ import { BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS, BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER } from "./types.mjs";
7
+ import { getUploadPayload } from "./utiles.mjs";
8
+ export * from "./requestContext.mjs";
9
+ export * from "./types.mjs";
10
+ const realRequest = new Map();
11
+ const realAllowedHeaders = new Map();
12
+ const realResolveHeaders = new Map();
13
+ const realRequireEnvelope = new Map();
14
+ const realAllowCrossOriginEnvelope = new Map();
15
+ const realTransportResilience = new Map();
16
+ const realIdentityBinding = new Map();
17
+ const realOperationContract = new Map();
18
+ const domainMap = new Map();
19
+ const isEmptyDomain = (domain)=>'string' != typeof domain || '' === domain.trim();
20
+ const TRACEPARENT_HEADER = 'traceparent';
21
+ const OPERATION_CONTEXT_DETAIL_HEADER = BFF_OPERATION_CONTEXT_DETAIL_HEADER;
22
+ const TRACEPARENT_REGEX = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/i;
23
+ const isStrictDefaultRequestIdEnabled = ()=>'true' === process.env.MODERN_BFF_STRICT_DEFAULT_REQUEST_ID;
24
+ const isSecuredRequestId = (requestId)=>'default' !== requestId || isStrictDefaultRequestIdEnabled();
25
+ const firstHeaderValue = (value)=>Array.isArray(value) ? value[0] : value;
26
+ const findHeaderKey = (headers, header)=>{
27
+ const normalized = header.toLowerCase();
28
+ return Object.keys(headers).find((key)=>key.toLowerCase() === normalized);
29
+ };
30
+ const readHeader = (headers, header)=>{
31
+ const key = findHeaderKey(headers, header);
32
+ return 'string' == typeof key ? headers[key] : void 0;
33
+ };
34
+ const writeHeader = (headers, header, value)=>{
35
+ if (void 0 === value) return;
36
+ const key = findHeaderKey(headers, header);
37
+ if ('string' == typeof key && key !== header) delete headers[key];
38
+ headers[header] = value;
39
+ };
40
+ const deleteHeader = (headers, header)=>{
41
+ const key = findHeaderKey(headers, header);
42
+ if ('string' == typeof key) delete headers[key];
43
+ };
44
+ const toOrigin = (value)=>{
45
+ if (!value) return;
46
+ try {
47
+ return new URL(value).origin;
48
+ } catch (error) {
49
+ return;
50
+ }
51
+ };
52
+ const parseTraceparent = (value)=>{
53
+ const traceparent = firstHeaderValue(value);
54
+ if ('string' != typeof traceparent) return;
55
+ const match = traceparent.trim().match(TRACEPARENT_REGEX);
56
+ if (!match) return;
57
+ const [, traceId, spanId] = match;
58
+ if (!traceId || !spanId) return;
59
+ return {
60
+ traceId: traceId.toLowerCase(),
61
+ spanId: spanId.toLowerCase()
62
+ };
63
+ };
64
+ const resolveSourceOrigin = (headers)=>{
65
+ const origin = toOrigin(firstHeaderValue(headers.origin));
66
+ if (origin) return origin;
67
+ const referer = toOrigin(firstHeaderValue(headers.referer));
68
+ if (referer) return referer;
69
+ const host = firstHeaderValue(headers.host);
70
+ if (!host) return;
71
+ const proto = firstHeaderValue(headers['x-forwarded-proto']) || 'http';
72
+ return `${proto}://${host}`;
73
+ };
74
+ const extractPathParamNames = (path)=>Array.from(path.matchAll(/:([A-Za-z0-9_]+)/g)).map(([, key])=>key);
75
+ const originFetch = (...params)=>{
76
+ const [, init] = params;
77
+ if (init?.method?.toLowerCase() === 'get') init.body = void 0;
78
+ return fetch(...params).then(handleRes);
79
+ };
80
+ const buildOperationContext = ({ requestId, method, path, operationContext, traceparent })=>{
81
+ const routePath = operationContext?.routePath || path;
82
+ const operationMethod = (operationContext?.method || method || 'GET').toUpperCase();
83
+ const rawOperationId = operationContext?.operationId || `${operationMethod}:${routePath}`;
84
+ const operationId = rawOperationId.startsWith(`${requestId}:`) ? rawOperationId : `${requestId}:${rawOperationId}`;
85
+ const traceparentValue = operationContext?.traceparent || ('string' == typeof firstHeaderValue(traceparent) ? String(firstHeaderValue(traceparent)) : void 0);
86
+ const parsedTraceContext = operationContext?.traceId && operationContext?.spanId ? {
87
+ traceId: operationContext.traceId,
88
+ spanId: operationContext.spanId
89
+ } : parseTraceparent(traceparentValue);
90
+ return {
91
+ requestId,
92
+ operationId,
93
+ routePath,
94
+ method: operationMethod,
95
+ ...operationContext?.schemaHash ? {
96
+ schemaHash: operationContext.schemaHash
97
+ } : {},
98
+ ...'number' == typeof operationContext?.operationVersion ? {
99
+ operationVersion: operationContext.operationVersion
100
+ } : {},
101
+ ...traceparentValue ? {
102
+ traceparent: traceparentValue
103
+ } : {},
104
+ ...parsedTraceContext ? {
105
+ traceId: parsedTraceContext.traceId,
106
+ spanId: parsedTraceContext.spanId
107
+ } : {}
108
+ };
109
+ };
110
+ class ProducerClientNotInitializedError extends Error {
111
+ constructor(requestId){
112
+ 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';
113
+ this.name = 'ProducerClientNotInitializedError';
114
+ }
115
+ }
116
+ class ProducerDomainNotConfiguredError extends Error {
117
+ constructor(requestId){
118
+ super(`Producer client "${requestId}" must provide setDomain() during configure().`), this.code = 'BFF_PRODUCER_DOMAIN_NOT_CONFIGURED';
119
+ this.name = 'ProducerDomainNotConfiguredError';
120
+ }
121
+ }
122
+ class CrossOriginEnvelopePolicyError extends Error {
123
+ constructor(requestId, sourceOrigin, targetOrigin){
124
+ 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';
125
+ this.name = 'CrossOriginEnvelopePolicyError';
126
+ }
127
+ }
128
+ class IdentityBindingViolationError extends Error {
129
+ constructor(violation){
130
+ super(`Identity header "${violation.header}" for producer "${violation.requestId}" was rejected by server-derived identity binding.`), this.code = 'BFF_IDENTITY_BINDING_VIOLATION';
131
+ this.name = 'IdentityBindingViolationError';
132
+ this.violation = violation;
133
+ }
134
+ }
135
+ class OperationContractViolationError extends Error {
136
+ constructor(violation){
137
+ super(`Operation contract violation "${violation.reason}" for producer "${violation.requestId}" operation "${violation.operationId}".`), this.code = 'BFF_OPERATION_CONTRACT_VIOLATION';
138
+ this.name = 'OperationContractViolationError';
139
+ this.violation = violation;
140
+ }
141
+ }
142
+ const validateOperationContract = (requestId, contextPayload)=>{
143
+ const operationContract = realOperationContract.get(requestId);
144
+ const operationContractEnabled = operationContract?.enabled ?? isSecuredRequestId(requestId);
145
+ if (!operationContractEnabled) return;
146
+ const strict = operationContract?.strict ?? true;
147
+ const requireSchemaHash = operationContract?.requireSchemaHash ?? true;
148
+ const requireOperationVersion = operationContract?.requireOperationVersion ?? true;
149
+ const maybeReportViolation = (reason)=>{
150
+ const violation = {
151
+ requestId,
152
+ target: 'server',
153
+ operationId: contextPayload.operationId,
154
+ routePath: contextPayload.routePath,
155
+ method: contextPayload.method,
156
+ schemaHash: 'string' == typeof contextPayload.schemaHash ? contextPayload.schemaHash : void 0,
157
+ operationVersion: 'number' == typeof contextPayload.operationVersion ? contextPayload.operationVersion : void 0,
158
+ reason
159
+ };
160
+ operationContract?.onViolation?.(violation);
161
+ if (strict) throw new OperationContractViolationError(violation);
162
+ };
163
+ if (requireSchemaHash && 'string' != typeof contextPayload.schemaHash) maybeReportViolation('missing_schema_hash');
164
+ if (requireOperationVersion && 'number' != typeof contextPayload.operationVersion) maybeReportViolation('missing_operation_version');
165
+ };
166
+ const getConfiguredRequest = (requestId, fallback)=>{
167
+ const configuredRequest = realRequest.get(requestId);
168
+ if (configuredRequest) return configuredRequest;
169
+ if ('default' !== requestId) throw new ProducerClientNotInitializedError(requestId);
170
+ return fallback;
171
+ };
172
+ const configure = (options)=>{
173
+ const { request, interceptor, allowedHeaders, resolveHeaders, transport, requireEnvelope, allowCrossOriginEnvelope, identityBinding, operationContract, setDomain, requestId = 'default' } = options;
174
+ const hasExistingDomain = domainMap.has(requestId);
175
+ if ('default' !== requestId && !setDomain && !hasExistingDomain) throw new ProducerDomainNotConfiguredError(requestId);
176
+ let configuredRequest = request || originFetch;
177
+ if (interceptor && !request) configuredRequest = interceptor(fetch);
178
+ if (Array.isArray(allowedHeaders)) realAllowedHeaders.set(requestId, allowedHeaders);
179
+ if ('function' == typeof resolveHeaders) realResolveHeaders.set(requestId, resolveHeaders);
180
+ if (transport && 'object' == typeof transport) realTransportResilience.set(requestId, transport);
181
+ if (identityBinding && 'object' == typeof identityBinding) realIdentityBinding.set(requestId, identityBinding);
182
+ if (operationContract && 'object' == typeof operationContract) realOperationContract.set(requestId, operationContract);
183
+ if ('boolean' == typeof requireEnvelope) realRequireEnvelope.set(requestId, requireEnvelope);
184
+ if ('boolean' == typeof allowCrossOriginEnvelope || 'function' == typeof allowCrossOriginEnvelope) realAllowCrossOriginEnvelope.set(requestId, allowCrossOriginEnvelope);
185
+ if (setDomain) {
186
+ const resolvedDomain = setDomain({
187
+ target: 'server',
188
+ requestId
189
+ });
190
+ if ('default' !== requestId && isEmptyDomain(resolvedDomain)) throw new ProducerDomainNotConfiguredError(requestId);
191
+ if ('string' == typeof resolvedDomain) domainMap.set(requestId, resolvedDomain);
192
+ }
193
+ realRequest.set(requestId, configuredRequest);
194
+ };
195
+ const normalizeRequestOptions = (...args)=>{
196
+ if ('object' == typeof args[0] && null !== args[0]) return args[0];
197
+ const [path, method, port, httpMethodDecider, fetch1, requestId, operationContext] = args;
198
+ return {
199
+ path,
200
+ method,
201
+ port,
202
+ httpMethodDecider,
203
+ fetch: fetch1,
204
+ requestId,
205
+ operationContext
206
+ };
207
+ };
208
+ const createRequest = (...args)=>{
209
+ const { path, method, port, httpMethodDecider = 'functionName', fetch: fetch1 = originFetch, requestId = 'default', operationContext } = normalizeRequestOptions(...args);
210
+ const getFinalPath = compile(path, {
211
+ encode: encodeURIComponent
212
+ });
213
+ const keyNames = extractPathParamNames(path);
214
+ const sender = (...args)=>{
215
+ const fetcher = getConfiguredRequest(requestId, fetch1);
216
+ let webRequestHeaders = {};
217
+ try {
218
+ webRequestHeaders = storage.useContext().headers || {};
219
+ } catch (error) {
220
+ webRequestHeaders = {};
221
+ }
222
+ let body;
223
+ let headers;
224
+ let url;
225
+ if ('inputParams' === httpMethodDecider) {
226
+ const configDomain = domainMap.get(requestId);
227
+ if ('default' !== requestId && isEmptyDomain(configDomain)) throw new ProducerDomainNotConfiguredError(requestId);
228
+ url = `${configDomain || `http://127.0.0.1:${port}`}${path}`;
229
+ body = args;
230
+ headers = {
231
+ 'Content-Type': 'application/json'
232
+ };
233
+ } else {
234
+ const payload = 'object' == typeof args[args.length - 1] ? args[args.length - 1] : {};
235
+ payload.params = payload.params || {};
236
+ const requestParams = args[0];
237
+ if ('object' == typeof requestParams && requestParams.params) {
238
+ const { params } = requestParams;
239
+ keyNames.forEach((keyName)=>{
240
+ payload.params[keyName] = params[keyName];
241
+ });
242
+ } else keyNames.forEach((keyName, index)=>{
243
+ payload.params[keyName] = args[index];
244
+ });
245
+ const plainPath = getFinalPath(payload.params);
246
+ const finalPath = payload.query ? `${plainPath}?${stringify(payload.query)}` : plainPath;
247
+ headers = payload.headers ? {
248
+ ...payload.headers
249
+ } : {};
250
+ const identityBinding = realIdentityBinding.get(requestId);
251
+ const identityBindingEnabled = identityBinding?.enabled ?? isSecuredRequestId(requestId);
252
+ const identityBindingStrict = identityBinding?.strict ?? isSecuredRequestId(requestId);
253
+ const protectedIdentityHeaders = (identityBinding?.protectedHeaders || BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS).map((header)=>header.toLowerCase());
254
+ const targetAllowedHeaders = realAllowedHeaders.get(requestId) || [];
255
+ const forwardedHeaders = {};
256
+ for (const key of targetAllowedHeaders)if (void 0 !== webRequestHeaders[key]) forwardedHeaders[key] = webRequestHeaders[key];
257
+ if (identityBindingEnabled) {
258
+ const derivedIdentityHeaders = {};
259
+ for (const header of protectedIdentityHeaders){
260
+ const incomingHeaderValue = readHeader(webRequestHeaders, header);
261
+ if (void 0 !== incomingHeaderValue) writeHeader(derivedIdentityHeaders, header, incomingHeaderValue);
262
+ }
263
+ const customDerivedHeaders = identityBinding?.deriveHeaders?.({
264
+ requestId,
265
+ target: 'server',
266
+ incomingHeaders: {
267
+ ...webRequestHeaders
268
+ },
269
+ protectedHeaders: [
270
+ ...protectedIdentityHeaders
271
+ ]
272
+ });
273
+ if (customDerivedHeaders && 'object' == typeof customDerivedHeaders) for (const header of protectedIdentityHeaders){
274
+ const customValue = readHeader(customDerivedHeaders, header);
275
+ if (void 0 !== customValue) writeHeader(derivedIdentityHeaders, header, customValue);
276
+ }
277
+ for (const header of protectedIdentityHeaders){
278
+ const attemptedValue = readHeader(headers, header);
279
+ if (void 0 === attemptedValue) continue;
280
+ const violation = {
281
+ requestId,
282
+ target: 'server',
283
+ header,
284
+ attemptedValue,
285
+ derivedValue: readHeader(derivedIdentityHeaders, header),
286
+ reason: identityBindingStrict ? 'client_override_rejected' : 'client_override_blocked'
287
+ };
288
+ identityBinding?.onViolation?.(violation);
289
+ if (identityBindingStrict) throw new IdentityBindingViolationError(violation);
290
+ deleteHeader(headers, header);
291
+ }
292
+ Object.keys(derivedIdentityHeaders).forEach((header)=>{
293
+ writeHeader(forwardedHeaders, header, derivedIdentityHeaders[header]);
294
+ });
295
+ }
296
+ const resolveHeaders = realResolveHeaders.get(requestId);
297
+ if (resolveHeaders) {
298
+ const resolvedHeaders = resolveHeaders({
299
+ requestId,
300
+ allowedHeaders: targetAllowedHeaders,
301
+ incomingHeaders: {
302
+ ...forwardedHeaders
303
+ }
304
+ });
305
+ if (resolvedHeaders && 'object' == typeof resolvedHeaders) {
306
+ for (const key of targetAllowedHeaders)if (void 0 !== resolvedHeaders[key]) forwardedHeaders[key] = resolvedHeaders[key];
307
+ }
308
+ }
309
+ headers = {
310
+ ...headers,
311
+ ...forwardedHeaders
312
+ };
313
+ if (payload.data) {
314
+ headers['Content-Type'] = 'application/json';
315
+ body = 'object' == typeof payload.data ? JSON.stringify(payload.data) : payload.body;
316
+ } else if (payload.body) {
317
+ headers['Content-Type'] = 'text/plain';
318
+ body = payload.body;
319
+ } else if (payload.formData) body = payload.formData;
320
+ else if (payload.formUrlencoded) {
321
+ headers['Content-Type'] = 'application/x-www-form-urlencoded';
322
+ body = 'object' == typeof payload.formUrlencoded ? stringify(payload.formUrlencoded) : payload.formUrlencoded;
323
+ }
324
+ const configDomain = domainMap.get(requestId);
325
+ if ('default' !== requestId && isEmptyDomain(configDomain)) throw new ProducerDomainNotConfiguredError(requestId);
326
+ url = `${configDomain || `http://127.0.0.1:${port}`}${finalPath}`;
327
+ }
328
+ if (void 0 === readHeader(headers, TRACEPARENT_HEADER)) {
329
+ const incomingTraceparent = firstHeaderValue(readHeader(webRequestHeaders, TRACEPARENT_HEADER));
330
+ if ('string' == typeof incomingTraceparent) writeHeader(headers, TRACEPARENT_HEADER, incomingTraceparent);
331
+ }
332
+ if (void 0 === readHeader(headers, TRACEPARENT_HEADER) && operationContext?.traceparent) writeHeader(headers, TRACEPARENT_HEADER, operationContext.traceparent);
333
+ const shouldRequireEnvelope = realRequireEnvelope.get(requestId) ?? isSecuredRequestId(requestId);
334
+ if (shouldRequireEnvelope) {
335
+ const sourceOrigin = resolveSourceOrigin(webRequestHeaders);
336
+ const targetOrigin = toOrigin(url);
337
+ const traceContext = parseTraceparent(readHeader(headers, TRACEPARENT_HEADER));
338
+ const isCrossOrigin = Boolean(sourceOrigin) && Boolean(targetOrigin) && sourceOrigin !== targetOrigin;
339
+ if (isCrossOrigin) {
340
+ const policy = realAllowCrossOriginEnvelope.get(requestId);
341
+ const isAllowed = 'function' == typeof policy ? policy({
342
+ requestId,
343
+ sourceOrigin,
344
+ targetOrigin,
345
+ target: 'server'
346
+ }) : true === policy;
347
+ if (!isAllowed) throw new CrossOriginEnvelopePolicyError(requestId, sourceOrigin, targetOrigin);
348
+ }
349
+ headers[BFF_ENVELOPE_HEADER] = JSON.stringify({
350
+ requestId,
351
+ target: 'server',
352
+ timestamp: Date.now(),
353
+ sourceOrigin,
354
+ targetOrigin,
355
+ ...traceContext ? {
356
+ traceId: traceContext.traceId,
357
+ spanId: traceContext.spanId
358
+ } : {}
359
+ });
360
+ }
361
+ if (isSecuredRequestId(requestId)) {
362
+ const contextPayload = buildOperationContext({
363
+ requestId,
364
+ method,
365
+ path,
366
+ operationContext,
367
+ traceparent: readHeader(headers, TRACEPARENT_HEADER)
368
+ });
369
+ validateOperationContract(requestId, contextPayload);
370
+ if (void 0 === readHeader(headers, BFF_OPERATION_CONTEXT_HEADER)) writeHeader(headers, BFF_OPERATION_CONTEXT_HEADER, contextPayload.operationId);
371
+ writeHeader(headers, OPERATION_CONTEXT_DETAIL_HEADER, JSON.stringify(contextPayload));
372
+ }
373
+ if ('get' === method.toLowerCase()) body = void 0;
374
+ headers.accept = "application/json,*/*;q=0.8";
375
+ return executeWithResilience({
376
+ requestId,
377
+ target: 'server',
378
+ method,
379
+ url,
380
+ init: {
381
+ method,
382
+ body,
383
+ headers
384
+ },
385
+ fetcher,
386
+ transport: realTransportResilience.get(requestId)
387
+ });
388
+ };
389
+ return sender;
390
+ };
391
+ const createUploader = ({ path, requestId = 'default' })=>{
392
+ const sender = (...args)=>{
393
+ const fetcher = getConfiguredRequest(requestId, originFetch);
394
+ const { body, headers } = getUploadPayload(args);
395
+ const configDomain = domainMap.get(requestId);
396
+ const finalURL = `${configDomain || ''}${path}`;
397
+ return fetcher(finalURL, {
398
+ method: 'POST',
399
+ body,
400
+ headers
401
+ });
402
+ };
403
+ return sender;
404
+ };
405
+ export { CrossOriginEnvelopePolicyError, IdentityBindingViolationError, OperationContractViolationError, ProducerClientNotInitializedError, ProducerDomainNotConfiguredError, configure, createRequest, createUploader };
@@ -0,0 +1 @@
1
+ export { parse, stringify } from "qs";
@@ -0,0 +1,51 @@
1
+ const BFF_LOCALE_HEADER = 'accept-language';
2
+ const BFF_TRACEPARENT_HEADER = 'traceparent';
3
+ const TRACEPARENT_REGEX = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/i;
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 parseTraceparent(traceparent) {
14
+ if (!traceparent) return;
15
+ const match = traceparent.trim().match(TRACEPARENT_REGEX);
16
+ if (!match) return;
17
+ const [, traceId, spanId] = match;
18
+ if (!traceId || !spanId) return;
19
+ return {
20
+ traceId: traceId.toLowerCase(),
21
+ spanId: spanId.toLowerCase()
22
+ };
23
+ }
24
+ function createRequestContextSnapshot(input = {}) {
25
+ const locale = readString(input.locale) || readString(readHeader(input.headers, BFF_LOCALE_HEADER));
26
+ const traceparent = readString(input.traceparent) || readString(input.operationContext?.traceparent) || readString(readHeader(input.headers, BFF_TRACEPARENT_HEADER));
27
+ const parsedTraceparent = input.operationContext?.traceId && input.operationContext?.spanId ? {
28
+ traceId: input.operationContext.traceId,
29
+ spanId: input.operationContext.spanId
30
+ } : parseTraceparent(traceparent);
31
+ const headers = {};
32
+ if (locale) headers[BFF_LOCALE_HEADER] = locale;
33
+ if (traceparent) headers[BFF_TRACEPARENT_HEADER] = traceparent;
34
+ return {
35
+ headers,
36
+ ...locale ? {
37
+ locale
38
+ } : {},
39
+ ...traceparent ? {
40
+ traceparent
41
+ } : {},
42
+ ...parsedTraceparent ? {
43
+ traceId: parsedTraceparent.traceId,
44
+ spanId: parsedTraceparent.spanId
45
+ } : {}
46
+ };
47
+ }
48
+ function createRequestContextHeaders(input = {}) {
49
+ return createRequestContextSnapshot(input).headers;
50
+ }
51
+ export { BFF_LOCALE_HEADER, BFF_TRACEPARENT_HEADER, createRequestContextHeaders, createRequestContextSnapshot };
@@ -0,0 +1,179 @@
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 createTimeoutError = (timeoutMs)=>{
14
+ const error = new Error(`Request timed out after ${timeoutMs}ms`);
15
+ error.name = 'TimeoutError';
16
+ return error;
17
+ };
18
+ const wait = (ms)=>new Promise((resolve)=>{
19
+ const timer = setTimeout(()=>resolve(), ms);
20
+ if ('function' == typeof timer.unref) timer.unref();
21
+ });
22
+ const toStatusCode = (error)=>{
23
+ if (!error || 'object' != typeof error) return;
24
+ const status = error.status;
25
+ if ('number' == typeof status) return status;
26
+ const responseStatus = error.response?.status;
27
+ if ('number' == typeof responseStatus) return responseStatus;
28
+ };
29
+ const isRetryableNetworkError = (error)=>{
30
+ if (!error || 'object' != typeof error) return false;
31
+ const name = error.name;
32
+ if ('AbortError' === name || 'FetchError' === name || 'TimeoutError' === name || 'TypeError' === name) return true;
33
+ const code = error.code;
34
+ return 'ECONNRESET' === code || 'ETIMEDOUT' === code || 'ECONNREFUSED' === code || 'EPIPE' === code;
35
+ };
36
+ const normalizePositiveNumber = (value, fallback)=>'number' == typeof value && Number.isFinite(value) && value > 0 ? value : fallback;
37
+ const normalizeNonNegativeInt = (value, fallback)=>'number' == typeof value && Number.isFinite(value) && value >= 0 ? Math.floor(value) : fallback;
38
+ const normalizeJitterRatio = (value)=>{
39
+ if ('number' != typeof value || !Number.isFinite(value)) return DEFAULT_JITTER_RATIO;
40
+ return Math.max(0, Math.min(1, value));
41
+ };
42
+ const shouldRetryWithDefaults = (statusCode, error, retryableStatusCodes)=>{
43
+ if ('number' == typeof statusCode) return retryableStatusCodes.includes(statusCode);
44
+ return isRetryableNetworkError(error);
45
+ };
46
+ const shouldRetry = (retryOptions, context, retryableStatusCodes)=>{
47
+ if ('function' == typeof retryOptions?.shouldRetry) try {
48
+ return retryOptions.shouldRetry(context);
49
+ } catch (error) {
50
+ return false;
51
+ }
52
+ return shouldRetryWithDefaults(context.statusCode, context.error, retryableStatusCodes);
53
+ };
54
+ const getBackoffMs = (retryOptions, attempt)=>{
55
+ const baseDelayMs = normalizePositiveNumber(retryOptions?.baseDelayMs, DEFAULT_BASE_DELAY_MS);
56
+ const maxDelayMs = normalizePositiveNumber(retryOptions?.maxDelayMs, DEFAULT_MAX_DELAY_MS);
57
+ const jitterRatio = normalizeJitterRatio(retryOptions?.jitterRatio);
58
+ const exponentialDelay = Math.min(maxDelayMs, baseDelayMs * 2 ** Math.max(0, attempt - 1));
59
+ const jitterFactor = 0 === jitterRatio ? 1 : 1 + (2 * Math.random() - 1) * jitterRatio;
60
+ return Math.max(0, Math.floor(exponentialDelay * jitterFactor));
61
+ };
62
+ const emitDegradedEvent = (transport, event)=>{
63
+ if ('function' != typeof transport?.onDegraded) return;
64
+ try {
65
+ transport.onDegraded(event);
66
+ } catch (error) {}
67
+ };
68
+ const withTimeout = async (promise, timeoutMs, signalBuilder)=>{
69
+ if (!timeoutMs || timeoutMs <= 0) {
70
+ const result = await promise;
71
+ return {
72
+ result
73
+ };
74
+ }
75
+ const controller = signalBuilder?.();
76
+ let timeoutTriggered = false;
77
+ let rejectTimeout;
78
+ const timeoutPromise = new Promise((_, reject)=>{
79
+ rejectTimeout = reject;
80
+ });
81
+ const timer = setTimeout(()=>{
82
+ timeoutTriggered = true;
83
+ if (controller) controller.abort();
84
+ rejectTimeout?.(createTimeoutError(timeoutMs));
85
+ }, timeoutMs);
86
+ if ('function' == typeof timer.unref) timer.unref();
87
+ try {
88
+ const result = await Promise.race([
89
+ promise,
90
+ timeoutPromise
91
+ ]);
92
+ return {
93
+ result,
94
+ timeoutTriggered
95
+ };
96
+ } catch (error) {
97
+ if (timeoutTriggered && error?.name === 'AbortError') throw createTimeoutError(timeoutMs);
98
+ throw error;
99
+ } finally{
100
+ clearTimeout(timer);
101
+ }
102
+ };
103
+ const executeWithResilience = async ({ requestId, target, method, url, init, fetcher, transport })=>{
104
+ const retries = normalizeNonNegativeInt(transport?.retry?.retries, 0);
105
+ const timeoutMs = 'number' == typeof transport?.timeoutMs && transport.timeoutMs > 0 ? transport.timeoutMs : void 0;
106
+ const maxAttempts = retries + 1;
107
+ const retryableStatusCodes = transport?.retry?.retryableStatusCodes && transport.retry.retryableStatusCodes.length > 0 ? transport.retry.retryableStatusCodes : DEFAULT_RETRYABLE_STATUS_CODES;
108
+ let attempt = 0;
109
+ while(attempt < maxAttempts){
110
+ attempt += 1;
111
+ const canUseAbortController = "u" > typeof AbortController;
112
+ let controller;
113
+ if (timeoutMs && canUseAbortController) controller = new AbortController();
114
+ const nextInit = controller && !init.signal ? {
115
+ ...init,
116
+ signal: controller.signal
117
+ } : init;
118
+ try {
119
+ const { result } = await withTimeout(fetcher(url, nextInit), timeoutMs, ()=>controller);
120
+ return result;
121
+ } catch (error) {
122
+ const statusCode = toStatusCode(error);
123
+ const decisionContext = {
124
+ requestId,
125
+ target,
126
+ method,
127
+ url,
128
+ attempt,
129
+ maxAttempts,
130
+ error,
131
+ statusCode
132
+ };
133
+ if (error?.name === 'TimeoutError') emitDegradedEvent(transport, {
134
+ requestId,
135
+ target,
136
+ method,
137
+ url,
138
+ reason: 'timeout',
139
+ attempt,
140
+ maxAttempts,
141
+ timeoutMs,
142
+ statusCode,
143
+ error
144
+ });
145
+ const canRetry = attempt < maxAttempts && shouldRetry(transport?.retry, decisionContext, retryableStatusCodes);
146
+ if (!canRetry) {
147
+ if (retries > 0 || error?.name === 'TimeoutError') emitDegradedEvent(transport, {
148
+ requestId,
149
+ target,
150
+ method,
151
+ url,
152
+ reason: 'retry_exhausted',
153
+ attempt,
154
+ maxAttempts,
155
+ timeoutMs,
156
+ statusCode,
157
+ error
158
+ });
159
+ throw error;
160
+ }
161
+ const backoffMs = getBackoffMs(transport?.retry, attempt);
162
+ emitDegradedEvent(transport, {
163
+ requestId,
164
+ target,
165
+ method,
166
+ url,
167
+ reason: 'retry',
168
+ attempt,
169
+ maxAttempts,
170
+ timeoutMs,
171
+ backoffMs,
172
+ statusCode,
173
+ error
174
+ });
175
+ if (backoffMs > 0) await wait(backoffMs);
176
+ }
177
+ }
178
+ };
179
+ 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 };