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