@bleedingdev/modern-js-create-request 3.9.0-ultramodern.2 → 3.9.0-ultramodern.20

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.
@@ -1,174 +0,0 @@
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 ? true === 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, parseTraceparentValue, readHeader, resolveConfiguredRequest, toOrigin, validateOperationContract, writeHeader };
@@ -1,74 +0,0 @@
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_LOCALE_HEADER, BFF_TRACEPARENT_HEADER, createRequestContextHeaders, createRequestContextSnapshot };
@@ -1,18 +0,0 @@
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 };
@@ -1,196 +0,0 @@
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 };
@@ -1,175 +0,0 @@
1
- import "node:module";
2
- import { parseTraceparent } from "./traceparent.mjs";
3
- const TRACEPARENT_HEADER = 'traceparent';
4
- const readProcessEnv = (key)=>{
5
- if ("u" < typeof process || void 0 === process.env || 'string' != typeof process.env[key]) return;
6
- return process.env[key];
7
- };
8
- const isStrictDefaultRequestIdEnabled = ()=>'true' === readProcessEnv('MODERN_BFF_STRICT_DEFAULT_REQUEST_ID');
9
- const isSecuredRequestId = (requestId)=>'default' !== requestId || isStrictDefaultRequestIdEnabled();
10
- const isEmptyDomain = (domain)=>'string' != typeof domain || '' === domain.trim();
11
- const firstHeaderValue = (value)=>Array.isArray(value) ? value[0] : value;
12
- const findHeaderKey = (headers, header)=>{
13
- const normalized = header.toLowerCase();
14
- return Object.keys(headers).find((key)=>key.toLowerCase() === normalized);
15
- };
16
- const readHeader = (headers, header)=>{
17
- const key = findHeaderKey(headers, header);
18
- return 'string' == typeof key ? headers[key] : void 0;
19
- };
20
- const writeHeader = (headers, header, value)=>{
21
- if (void 0 === value) return;
22
- const key = findHeaderKey(headers, header);
23
- if ('string' == typeof key && key !== header) delete headers[key];
24
- headers[header] = value;
25
- };
26
- const deleteHeader = (headers, header)=>{
27
- const key = findHeaderKey(headers, header);
28
- if ('string' == typeof key) delete headers[key];
29
- };
30
- const toOrigin = (value)=>{
31
- if (!value) return;
32
- try {
33
- return new URL(value).origin;
34
- } catch (error) {
35
- return;
36
- }
37
- };
38
- const parseTraceparentValue = (value)=>parseTraceparent(firstHeaderValue(value));
39
- const extractPathParamNames = (path)=>Array.from(path.matchAll(/:([A-Za-z0-9_]+)/g)).flatMap(([, key])=>key ? [
40
- key
41
- ] : []);
42
- const buildOperationContext = ({ requestId, method, path, operationContext, traceparent })=>{
43
- const routePath = operationContext?.routePath || path;
44
- const operationMethod = (operationContext?.method || method || 'GET').toUpperCase();
45
- const rawOperationId = operationContext?.operationId || `${operationMethod}:${routePath}`;
46
- const operationId = rawOperationId.startsWith(`${requestId}:`) ? rawOperationId : `${requestId}:${rawOperationId}`;
47
- const traceparentValue = operationContext?.traceparent || ('string' == typeof firstHeaderValue(traceparent) ? String(firstHeaderValue(traceparent)) : void 0);
48
- const parsedTraceContext = operationContext?.traceId && operationContext?.spanId ? {
49
- traceId: operationContext.traceId,
50
- spanId: operationContext.spanId
51
- } : parseTraceparentValue(traceparentValue);
52
- return {
53
- requestId,
54
- operationId,
55
- routePath,
56
- method: operationMethod,
57
- ...operationContext?.schemaHash ? {
58
- schemaHash: operationContext.schemaHash
59
- } : {},
60
- ...'number' == typeof operationContext?.operationVersion ? {
61
- operationVersion: operationContext.operationVersion
62
- } : {},
63
- ...traceparentValue ? {
64
- traceparent: traceparentValue
65
- } : {},
66
- ...parsedTraceContext ? {
67
- traceId: parsedTraceContext.traceId,
68
- spanId: parsedTraceContext.spanId
69
- } : {}
70
- };
71
- };
72
- class ProducerClientNotInitializedError extends Error {
73
- constructor(requestId){
74
- 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';
75
- this.name = 'ProducerClientNotInitializedError';
76
- }
77
- }
78
- class ProducerDomainNotConfiguredError extends Error {
79
- constructor(requestId){
80
- super(`Producer client "${requestId}" must provide setDomain() during configure().`), this.code = 'BFF_PRODUCER_DOMAIN_NOT_CONFIGURED';
81
- this.name = 'ProducerDomainNotConfiguredError';
82
- }
83
- }
84
- class CrossOriginEnvelopePolicyError extends Error {
85
- constructor(requestId, sourceOrigin, targetOrigin){
86
- 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';
87
- this.name = 'CrossOriginEnvelopePolicyError';
88
- }
89
- }
90
- class IdentityBindingViolationError extends Error {
91
- constructor(violation){
92
- super(`Identity header "${violation.header}" for producer "${violation.requestId}" was rejected by server-derived identity binding.`), this.code = 'BFF_IDENTITY_BINDING_VIOLATION';
93
- this.name = 'IdentityBindingViolationError';
94
- this.violation = violation;
95
- }
96
- }
97
- class OperationContractViolationError extends Error {
98
- constructor(violation){
99
- super(`Operation contract violation "${violation.reason}" for producer "${violation.requestId}" operation "${violation.operationId}".`), this.code = 'BFF_OPERATION_CONTRACT_VIOLATION';
100
- this.name = 'OperationContractViolationError';
101
- this.violation = violation;
102
- }
103
- }
104
- const validateOperationContract = ({ requestId, target, contextPayload, operationContract })=>{
105
- const operationContractEnabled = operationContract?.enabled ?? isSecuredRequestId(requestId);
106
- if (!operationContractEnabled) return;
107
- const strict = operationContract?.strict ?? true;
108
- const requireSchemaHash = operationContract?.requireSchemaHash ?? true;
109
- const requireOperationVersion = operationContract?.requireOperationVersion ?? true;
110
- const maybeReportViolation = (reason)=>{
111
- const violation = {
112
- requestId,
113
- target,
114
- operationId: contextPayload.operationId,
115
- routePath: contextPayload.routePath,
116
- method: contextPayload.method,
117
- schemaHash: 'string' == typeof contextPayload.schemaHash ? contextPayload.schemaHash : void 0,
118
- operationVersion: 'number' == typeof contextPayload.operationVersion ? contextPayload.operationVersion : void 0,
119
- reason
120
- };
121
- operationContract?.onViolation?.(violation);
122
- if (strict) throw new OperationContractViolationError(violation);
123
- };
124
- if (requireSchemaHash && 'string' != typeof contextPayload.schemaHash) maybeReportViolation('missing_schema_hash');
125
- if (requireOperationVersion && 'number' != typeof contextPayload.operationVersion) maybeReportViolation('missing_operation_version');
126
- };
127
- const resolveConfiguredRequest = (configuredRequests, requestId, fallback)=>{
128
- const configuredRequest = configuredRequests.get(requestId);
129
- if (configuredRequest) return configuredRequest;
130
- if ('default' !== requestId) throw new ProducerClientNotInitializedError(requestId);
131
- return fallback;
132
- };
133
- const buildEnvelopeHeaderValue = ({ requestId, target, sourceOrigin, targetOrigin, traceContext, allowCrossOriginEnvelope })=>{
134
- const isCrossOrigin = Boolean(sourceOrigin) && Boolean(targetOrigin) && sourceOrigin !== targetOrigin;
135
- if (isCrossOrigin) {
136
- const isAllowed = 'function' == typeof allowCrossOriginEnvelope ? true === allowCrossOriginEnvelope({
137
- requestId,
138
- sourceOrigin,
139
- targetOrigin,
140
- target
141
- }) : true === allowCrossOriginEnvelope;
142
- if (!isAllowed) throw new CrossOriginEnvelopePolicyError(requestId, sourceOrigin, targetOrigin);
143
- }
144
- return JSON.stringify({
145
- requestId,
146
- target,
147
- timestamp: Date.now(),
148
- sourceOrigin,
149
- targetOrigin,
150
- ...traceContext ? {
151
- traceId: traceContext.traceId,
152
- spanId: traceContext.spanId
153
- } : {}
154
- });
155
- };
156
- const attachOperationContextHeaders = ({ headers, requestId, target, method, path, operationContext, operationContract, operationContextHeader, operationContextDetailHeader })=>{
157
- if (void 0 === readHeader(headers, TRACEPARENT_HEADER) && operationContext?.traceparent) writeHeader(headers, TRACEPARENT_HEADER, operationContext.traceparent);
158
- const contextPayload = buildOperationContext({
159
- requestId,
160
- method,
161
- path,
162
- operationContext,
163
- traceparent: readHeader(headers, TRACEPARENT_HEADER)
164
- });
165
- validateOperationContract({
166
- requestId,
167
- target,
168
- contextPayload,
169
- operationContract
170
- });
171
- if (void 0 === readHeader(headers, operationContextHeader)) writeHeader(headers, operationContextHeader, contextPayload.operationId);
172
- writeHeader(headers, operationContextDetailHeader, JSON.stringify(contextPayload));
173
- return contextPayload;
174
- };
175
- export { CrossOriginEnvelopePolicyError, IdentityBindingViolationError, OperationContractViolationError, ProducerClientNotInitializedError, ProducerDomainNotConfiguredError, TRACEPARENT_HEADER, attachOperationContextHeaders, buildEnvelopeHeaderValue, buildOperationContext, deleteHeader, extractPathParamNames, findHeaderKey, firstHeaderValue, isEmptyDomain, isSecuredRequestId, parseTraceparentValue, readHeader, resolveConfiguredRequest, toOrigin, validateOperationContract, writeHeader };