@bleedingdev/modern-js-create-request 3.2.0-ultramodern.98 → 3.4.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,174 @@
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 extractPathParamNames = (path)=>Array.from(path.matchAll(/:([A-Za-z0-9_]+)/g)).flatMap(([, key])=>key ? [
39
+ key
40
+ ] : []);
41
+ const buildOperationContext = ({ requestId, method, path, operationContext, traceparent })=>{
42
+ const routePath = operationContext?.routePath || path;
43
+ const operationMethod = (operationContext?.method || method || 'GET').toUpperCase();
44
+ const rawOperationId = operationContext?.operationId || `${operationMethod}:${routePath}`;
45
+ const operationId = rawOperationId.startsWith(`${requestId}:`) ? rawOperationId : `${requestId}:${rawOperationId}`;
46
+ const traceparentValue = operationContext?.traceparent || ('string' == typeof firstHeaderValue(traceparent) ? String(firstHeaderValue(traceparent)) : void 0);
47
+ const parsedTraceContext = operationContext?.traceId && operationContext?.spanId ? {
48
+ traceId: operationContext.traceId,
49
+ spanId: operationContext.spanId
50
+ } : parseTraceparentValue(traceparentValue);
51
+ return {
52
+ requestId,
53
+ operationId,
54
+ routePath,
55
+ method: operationMethod,
56
+ ...operationContext?.schemaHash ? {
57
+ schemaHash: operationContext.schemaHash
58
+ } : {},
59
+ ...'number' == typeof operationContext?.operationVersion ? {
60
+ operationVersion: operationContext.operationVersion
61
+ } : {},
62
+ ...traceparentValue ? {
63
+ traceparent: traceparentValue
64
+ } : {},
65
+ ...parsedTraceContext ? {
66
+ traceId: parsedTraceContext.traceId,
67
+ spanId: parsedTraceContext.spanId
68
+ } : {}
69
+ };
70
+ };
71
+ class ProducerClientNotInitializedError extends Error {
72
+ constructor(requestId){
73
+ 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';
74
+ this.name = 'ProducerClientNotInitializedError';
75
+ }
76
+ }
77
+ class ProducerDomainNotConfiguredError extends Error {
78
+ constructor(requestId){
79
+ super(`Producer client "${requestId}" must provide setDomain() during configure().`), this.code = 'BFF_PRODUCER_DOMAIN_NOT_CONFIGURED';
80
+ this.name = 'ProducerDomainNotConfiguredError';
81
+ }
82
+ }
83
+ class CrossOriginEnvelopePolicyError extends Error {
84
+ constructor(requestId, sourceOrigin, targetOrigin){
85
+ 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';
86
+ this.name = 'CrossOriginEnvelopePolicyError';
87
+ }
88
+ }
89
+ class IdentityBindingViolationError extends Error {
90
+ constructor(violation){
91
+ super(`Identity header "${violation.header}" for producer "${violation.requestId}" was rejected by server-derived identity binding.`), this.code = 'BFF_IDENTITY_BINDING_VIOLATION';
92
+ this.name = 'IdentityBindingViolationError';
93
+ this.violation = violation;
94
+ }
95
+ }
96
+ class OperationContractViolationError extends Error {
97
+ constructor(violation){
98
+ super(`Operation contract violation "${violation.reason}" for producer "${violation.requestId}" operation "${violation.operationId}".`), this.code = 'BFF_OPERATION_CONTRACT_VIOLATION';
99
+ this.name = 'OperationContractViolationError';
100
+ this.violation = violation;
101
+ }
102
+ }
103
+ const validateOperationContract = ({ requestId, target, contextPayload, operationContract })=>{
104
+ const operationContractEnabled = operationContract?.enabled ?? isSecuredRequestId(requestId);
105
+ if (!operationContractEnabled) return;
106
+ const strict = operationContract?.strict ?? true;
107
+ const requireSchemaHash = operationContract?.requireSchemaHash ?? true;
108
+ const requireOperationVersion = operationContract?.requireOperationVersion ?? true;
109
+ const maybeReportViolation = (reason)=>{
110
+ const violation = {
111
+ requestId,
112
+ target,
113
+ operationId: contextPayload.operationId,
114
+ routePath: contextPayload.routePath,
115
+ method: contextPayload.method,
116
+ schemaHash: 'string' == typeof contextPayload.schemaHash ? contextPayload.schemaHash : void 0,
117
+ operationVersion: 'number' == typeof contextPayload.operationVersion ? contextPayload.operationVersion : void 0,
118
+ reason
119
+ };
120
+ operationContract?.onViolation?.(violation);
121
+ if (strict) throw new OperationContractViolationError(violation);
122
+ };
123
+ if (requireSchemaHash && 'string' != typeof contextPayload.schemaHash) maybeReportViolation('missing_schema_hash');
124
+ if (requireOperationVersion && 'number' != typeof contextPayload.operationVersion) maybeReportViolation('missing_operation_version');
125
+ };
126
+ const resolveConfiguredRequest = (configuredRequests, requestId, fallback)=>{
127
+ const configuredRequest = configuredRequests.get(requestId);
128
+ if (configuredRequest) return configuredRequest;
129
+ if ('default' !== requestId) throw new ProducerClientNotInitializedError(requestId);
130
+ return fallback;
131
+ };
132
+ const buildEnvelopeHeaderValue = ({ requestId, target, sourceOrigin, targetOrigin, traceContext, allowCrossOriginEnvelope })=>{
133
+ const isCrossOrigin = Boolean(sourceOrigin) && Boolean(targetOrigin) && sourceOrigin !== targetOrigin;
134
+ if (isCrossOrigin) {
135
+ const isAllowed = 'function' == typeof allowCrossOriginEnvelope ? allowCrossOriginEnvelope({
136
+ requestId,
137
+ sourceOrigin,
138
+ targetOrigin,
139
+ target
140
+ }) : true === allowCrossOriginEnvelope;
141
+ if (!isAllowed) throw new CrossOriginEnvelopePolicyError(requestId, sourceOrigin, targetOrigin);
142
+ }
143
+ return JSON.stringify({
144
+ requestId,
145
+ target,
146
+ timestamp: Date.now(),
147
+ sourceOrigin,
148
+ targetOrigin,
149
+ ...traceContext ? {
150
+ traceId: traceContext.traceId,
151
+ spanId: traceContext.spanId
152
+ } : {}
153
+ });
154
+ };
155
+ const attachOperationContextHeaders = ({ headers, requestId, target, method, path, operationContext, operationContract, operationContextHeader, operationContextDetailHeader })=>{
156
+ if (void 0 === readHeader(headers, TRACEPARENT_HEADER) && operationContext?.traceparent) writeHeader(headers, TRACEPARENT_HEADER, operationContext.traceparent);
157
+ const contextPayload = buildOperationContext({
158
+ requestId,
159
+ method,
160
+ path,
161
+ operationContext,
162
+ traceparent: readHeader(headers, TRACEPARENT_HEADER)
163
+ });
164
+ validateOperationContract({
165
+ requestId,
166
+ target,
167
+ contextPayload,
168
+ operationContract
169
+ });
170
+ if (void 0 === readHeader(headers, operationContextHeader)) writeHeader(headers, operationContextHeader, contextPayload.operationId);
171
+ writeHeader(headers, operationContextDetailHeader, JSON.stringify(contextPayload));
172
+ return contextPayload;
173
+ };
174
+ export { CrossOriginEnvelopePolicyError, IdentityBindingViolationError, OperationContractViolationError, ProducerClientNotInitializedError, ProducerDomainNotConfiguredError, TRACEPARENT_HEADER, attachOperationContextHeaders, buildEnvelopeHeaderValue, buildOperationContext, deleteHeader, extractPathParamNames, findHeaderKey, firstHeaderValue, isEmptyDomain, isSecuredRequestId, isStrictDefaultRequestIdEnabled, parseTraceparentValue, readHeader, resolveConfiguredRequest, toOrigin, validateOperationContract, writeHeader };
@@ -1,6 +1,6 @@
1
+ import { parseTraceparent } from "./traceparent.mjs";
1
2
  const BFF_LOCALE_HEADER = 'accept-language';
2
3
  const BFF_TRACEPARENT_HEADER = 'traceparent';
3
- const TRACEPARENT_REGEX = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/i;
4
4
  const readHeader = (headers, header)=>{
5
5
  if (!headers) return;
6
6
  const normalized = header.toLowerCase();
@@ -10,17 +10,6 @@ const readHeader = (headers, header)=>{
10
10
  return Array.isArray(value) ? value[0] : value;
11
11
  };
12
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
13
  function createOperationContextSnapshot(operationContext, safeContext) {
25
14
  if (!operationContext) return;
26
15
  const snapshot = {
@@ -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 };
@@ -2,10 +2,12 @@ import "node:module";
2
2
  import { compile } from "path-to-regexp";
3
3
  import { stringify } from "qs";
4
4
  import { handleRes } from "./handleRes.mjs";
5
+ import { CrossOriginEnvelopePolicyError, IdentityBindingViolationError, OperationContractViolationError, ProducerClientNotInitializedError, ProducerDomainNotConfiguredError, TRACEPARENT_HEADER, attachOperationContextHeaders, buildEnvelopeHeaderValue, deleteHeader, extractPathParamNames, isEmptyDomain, isSecuredRequestId, parseTraceparentValue, readHeader, resolveConfiguredRequest, toOrigin, writeHeader } from "./policyCore.mjs";
5
6
  import { executeWithResilience } from "./transport.mjs";
6
7
  import { BFF_DEFAULT_PROTECTED_IDENTITY_HEADERS, BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER } from "./types.mjs";
7
8
  import { getUploadPayload } from "./utiles.mjs";
8
9
  export * from "./requestContext.mjs";
10
+ export * from "./traceparent.mjs";
9
11
  export * from "./types.mjs";
10
12
  const realRequest = new Map();
11
13
  const realAllowedHeaders = new Map();
@@ -15,154 +17,38 @@ const realTransportResilience = new Map();
15
17
  const realIdentityBinding = new Map();
16
18
  const realOperationContract = new Map();
17
19
  const domainMap = new Map();
18
- const isEmptyDomain = (domain)=>'string' != typeof domain || '' === domain.trim();
19
- const TRACEPARENT_HEADER = 'traceparent';
20
20
  const OPERATION_CONTEXT_DETAIL_HEADER = BFF_OPERATION_CONTEXT_DETAIL_HEADER;
21
- const TRACEPARENT_REGEX = /^00-([0-9a-f]{32})-([0-9a-f]{16})-[0-9a-f]{2}$/i;
22
- const readProcessEnv = (key)=>{
23
- if ("u" < typeof process || void 0 === process.env || 'string' != typeof process.env[key]) return;
24
- return process.env[key];
25
- };
26
- const isStrictDefaultRequestIdEnabled = ()=>'true' === readProcessEnv('MODERN_BFF_STRICT_DEFAULT_REQUEST_ID');
27
- const isSecuredRequestId = (requestId)=>'default' !== requestId || isStrictDefaultRequestIdEnabled();
28
- const firstHeaderValue = (value)=>Array.isArray(value) ? value[0] : value;
29
- const findHeaderKey = (headers, header)=>{
30
- const normalized = header.toLowerCase();
31
- return Object.keys(headers).find((key)=>key.toLowerCase() === normalized);
32
- };
33
- const readHeader = (headers, header)=>{
34
- const key = findHeaderKey(headers, header);
35
- return 'string' == typeof key ? headers[key] : void 0;
36
- };
37
- const writeHeader = (headers, header, value)=>{
38
- if (void 0 === value) return;
39
- const key = findHeaderKey(headers, header);
40
- if ('string' == typeof key && key !== header) delete headers[key];
41
- headers[header] = value;
42
- };
43
- const deleteHeader = (headers, header)=>{
44
- const key = findHeaderKey(headers, header);
45
- if ('string' == typeof key) delete headers[key];
46
- };
47
- const toOrigin = (value)=>{
48
- if (!value) return;
49
- try {
50
- return new URL(value).origin;
51
- } catch (error) {
52
- return;
53
- }
54
- };
55
- const parseTraceparent = (value)=>{
56
- const traceparent = firstHeaderValue(value);
57
- if ('string' != typeof traceparent) return;
58
- const match = traceparent.trim().match(TRACEPARENT_REGEX);
59
- if (!match) return;
60
- const [, traceId, spanId] = match;
61
- if (!traceId || !spanId) return;
62
- return {
63
- traceId: traceId.toLowerCase(),
64
- spanId: spanId.toLowerCase()
65
- };
66
- };
67
- const extractPathParamNames = (path)=>Array.from(path.matchAll(/:([A-Za-z0-9_]+)/g)).flatMap(([, key])=>key ? [
68
- key
69
- ] : []);
21
+ const resolveBrowserOrigin = ()=>"u" > typeof window ? window.location.origin : void 0;
70
22
  const originFetch = (...params)=>{
71
23
  const [url, init] = params;
72
24
  if (init?.method?.toLowerCase() === 'get') init.body = void 0;
73
25
  return fetch(url, init).then(handleRes);
74
26
  };
75
- const buildOperationContext = ({ requestId, method, path, operationContext, traceparent })=>{
76
- const routePath = operationContext?.routePath || path;
77
- const operationMethod = (operationContext?.method || method || 'GET').toUpperCase();
78
- const rawOperationId = operationContext?.operationId || `${operationMethod}:${routePath}`;
79
- const operationId = rawOperationId.startsWith(`${requestId}:`) ? rawOperationId : `${requestId}:${rawOperationId}`;
80
- const traceparentValue = operationContext?.traceparent || ('string' == typeof firstHeaderValue(traceparent) ? String(firstHeaderValue(traceparent)) : void 0);
81
- const parsedTraceContext = operationContext?.traceId && operationContext?.spanId ? {
82
- traceId: operationContext.traceId,
83
- spanId: operationContext.spanId
84
- } : parseTraceparent(traceparentValue);
85
- return {
27
+ const attachEnvelopeHeaderIfRequired = (headers, requestId, finalURL)=>{
28
+ const shouldRequireEnvelope = realRequireEnvelope.get(requestId) ?? isSecuredRequestId(requestId);
29
+ if (!shouldRequireEnvelope) return;
30
+ headers[BFF_ENVELOPE_HEADER] = buildEnvelopeHeaderValue({
86
31
  requestId,
87
- operationId,
88
- routePath,
89
- method: operationMethod,
90
- ...operationContext?.schemaHash ? {
91
- schemaHash: operationContext.schemaHash
92
- } : {},
93
- ...'number' == typeof operationContext?.operationVersion ? {
94
- operationVersion: operationContext.operationVersion
95
- } : {},
96
- ...traceparentValue ? {
97
- traceparent: traceparentValue
98
- } : {},
99
- ...parsedTraceContext ? {
100
- traceId: parsedTraceContext.traceId,
101
- spanId: parsedTraceContext.spanId
102
- } : {}
103
- };
104
- };
105
- class ProducerClientNotInitializedError extends Error {
106
- constructor(requestId){
107
- 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';
108
- this.name = 'ProducerClientNotInitializedError';
109
- }
110
- }
111
- class ProducerDomainNotConfiguredError extends Error {
112
- constructor(requestId){
113
- super(`Producer client "${requestId}" must provide setDomain() during configure().`), this.code = 'BFF_PRODUCER_DOMAIN_NOT_CONFIGURED';
114
- this.name = 'ProducerDomainNotConfiguredError';
115
- }
116
- }
117
- class CrossOriginEnvelopePolicyError extends Error {
118
- constructor(requestId, sourceOrigin, targetOrigin){
119
- 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';
120
- this.name = 'CrossOriginEnvelopePolicyError';
121
- }
122
- }
123
- class IdentityBindingViolationError extends Error {
124
- constructor(violation){
125
- super(`Identity header "${violation.header}" for producer "${violation.requestId}" was rejected by server-derived identity binding.`), this.code = 'BFF_IDENTITY_BINDING_VIOLATION';
126
- this.name = 'IdentityBindingViolationError';
127
- this.violation = violation;
128
- }
129
- }
130
- class OperationContractViolationError extends Error {
131
- constructor(violation){
132
- super(`Operation contract violation "${violation.reason}" for producer "${violation.requestId}" operation "${violation.operationId}".`), this.code = 'BFF_OPERATION_CONTRACT_VIOLATION';
133
- this.name = 'OperationContractViolationError';
134
- this.violation = violation;
135
- }
136
- }
137
- const validateOperationContract = (requestId, contextPayload)=>{
138
- const operationContract = realOperationContract.get(requestId);
139
- const operationContractEnabled = operationContract?.enabled ?? isSecuredRequestId(requestId);
140
- if (!operationContractEnabled) return;
141
- const strict = operationContract?.strict ?? true;
142
- const requireSchemaHash = operationContract?.requireSchemaHash ?? true;
143
- const requireOperationVersion = operationContract?.requireOperationVersion ?? true;
144
- const maybeReportViolation = (reason)=>{
145
- const violation = {
146
- requestId,
147
- target: 'browser',
148
- operationId: contextPayload.operationId,
149
- routePath: contextPayload.routePath,
150
- method: contextPayload.method,
151
- schemaHash: 'string' == typeof contextPayload.schemaHash ? contextPayload.schemaHash : void 0,
152
- operationVersion: 'number' == typeof contextPayload.operationVersion ? contextPayload.operationVersion : void 0,
153
- reason
154
- };
155
- operationContract?.onViolation?.(violation);
156
- if (strict) throw new OperationContractViolationError(violation);
157
- };
158
- if (requireSchemaHash && 'string' != typeof contextPayload.schemaHash) maybeReportViolation('missing_schema_hash');
159
- if (requireOperationVersion && 'number' != typeof contextPayload.operationVersion) maybeReportViolation('missing_operation_version');
32
+ target: 'browser',
33
+ sourceOrigin: resolveBrowserOrigin(),
34
+ targetOrigin: toOrigin(finalURL),
35
+ traceContext: parseTraceparentValue(readHeader(headers, TRACEPARENT_HEADER)),
36
+ allowCrossOriginEnvelope: realAllowCrossOriginEnvelope.get(requestId)
37
+ });
160
38
  };
161
- const getConfiguredRequest = (requestId, fallback)=>{
162
- const configuredRequest = realRequest.get(requestId);
163
- if (configuredRequest) return configuredRequest;
164
- if ('default' !== requestId) throw new ProducerClientNotInitializedError(requestId);
165
- return fallback;
39
+ const attachSecuredOperationHeaders = (headers, requestId, method, path, operationContext)=>{
40
+ if (!isSecuredRequestId(requestId)) return;
41
+ attachOperationContextHeaders({
42
+ headers,
43
+ requestId,
44
+ target: 'browser',
45
+ method,
46
+ path,
47
+ operationContext,
48
+ operationContract: realOperationContract.get(requestId),
49
+ operationContextHeader: BFF_OPERATION_CONTEXT_HEADER,
50
+ operationContextDetailHeader: OPERATION_CONTEXT_DETAIL_HEADER
51
+ });
166
52
  };
167
53
  const configure = (options)=>{
168
54
  const { request, interceptor, allowedHeaders, transport, requireEnvelope, allowCrossOriginEnvelope, identityBinding, operationContract, setDomain, requestId = 'default' } = options;
@@ -206,7 +92,7 @@ const createRequest = (...args)=>{
206
92
  });
207
93
  const keyNames = extractPathParamNames(path);
208
94
  const sender = async (...args)=>{
209
- const fetcher = getConfiguredRequest(requestId, fetch1);
95
+ const fetcher = resolveConfiguredRequest(realRequest, requestId, fetch1);
210
96
  let body;
211
97
  let finalURL;
212
98
  let headers;
@@ -289,47 +175,8 @@ const createRequest = (...args)=>{
289
175
  const configDomain = domainMap.get(requestId);
290
176
  if ('default' !== requestId && isEmptyDomain(configDomain)) throw new ProducerDomainNotConfiguredError(requestId);
291
177
  finalURL = `${configDomain || ''}${finalURL}`;
292
- const shouldRequireEnvelope = realRequireEnvelope.get(requestId) ?? isSecuredRequestId(requestId);
293
- if (shouldRequireEnvelope) {
294
- const sourceOrigin = "u" > typeof window ? window.location.origin : void 0;
295
- const targetOrigin = toOrigin(finalURL);
296
- const traceContext = parseTraceparent(readHeader(headers, TRACEPARENT_HEADER));
297
- const isCrossOrigin = Boolean(sourceOrigin) && Boolean(targetOrigin) && sourceOrigin !== targetOrigin;
298
- if (isCrossOrigin) {
299
- const policy = realAllowCrossOriginEnvelope.get(requestId);
300
- const isAllowed = 'function' == typeof policy ? policy({
301
- requestId,
302
- sourceOrigin,
303
- targetOrigin,
304
- target: 'browser'
305
- }) : true === policy;
306
- if (!isAllowed) throw new CrossOriginEnvelopePolicyError(requestId, sourceOrigin, targetOrigin);
307
- }
308
- headers[BFF_ENVELOPE_HEADER] = JSON.stringify({
309
- requestId,
310
- target: 'browser',
311
- timestamp: Date.now(),
312
- sourceOrigin,
313
- targetOrigin,
314
- ...traceContext ? {
315
- traceId: traceContext.traceId,
316
- spanId: traceContext.spanId
317
- } : {}
318
- });
319
- }
320
- if (isSecuredRequestId(requestId)) {
321
- if (void 0 === readHeader(headers, TRACEPARENT_HEADER) && operationContext?.traceparent) writeHeader(headers, TRACEPARENT_HEADER, operationContext.traceparent);
322
- const contextPayload = buildOperationContext({
323
- requestId,
324
- method,
325
- path,
326
- operationContext,
327
- traceparent: readHeader(headers, TRACEPARENT_HEADER)
328
- });
329
- validateOperationContract(requestId, contextPayload);
330
- if (void 0 === readHeader(headers, BFF_OPERATION_CONTEXT_HEADER)) writeHeader(headers, BFF_OPERATION_CONTEXT_HEADER, contextPayload.operationId);
331
- writeHeader(headers, OPERATION_CONTEXT_DETAIL_HEADER, JSON.stringify(contextPayload));
332
- }
178
+ attachEnvelopeHeaderIfRequired(headers, requestId, finalURL);
179
+ attachSecuredOperationHeaders(headers, requestId, method, path, operationContext);
333
180
  return executeWithResilience({
334
181
  requestId,
335
182
  target: 'browser',
@@ -346,16 +193,21 @@ const createRequest = (...args)=>{
346
193
  };
347
194
  return sender;
348
195
  };
349
- const createUploader = ({ path, domain, requestId = 'default' })=>{
196
+ const createUploader = ({ path, domain, requestId = 'default', operationContext })=>{
350
197
  const getFinalPath = compile(path, {
351
198
  encode: encodeURIComponent
352
199
  });
353
200
  const sender = (...args)=>{
354
- const fetcher = getConfiguredRequest(requestId, originFetch);
355
- const { body, headers, params } = getUploadPayload(args);
201
+ const fetcher = resolveConfiguredRequest(realRequest, requestId, originFetch);
202
+ const { body, headers: uploadHeaders, params } = getUploadPayload(args);
203
+ const headers = {
204
+ ...uploadHeaders
205
+ };
356
206
  const finalPath = getFinalPath(params);
357
207
  const configDomain = domainMap.get(requestId);
358
208
  const finalURL = `${configDomain || domain || ''}${finalPath}`;
209
+ attachEnvelopeHeaderIfRequired(headers, requestId, finalURL);
210
+ attachSecuredOperationHeaders(headers, requestId, 'POST', path, operationContext);
359
211
  return fetcher(finalURL, {
360
212
  method: 'POST',
361
213
  body,