@bleedingdev/modern-js-plugin-bff 3.2.0-ultramodern.12 → 3.2.0-ultramodern.121

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.
Files changed (80) hide show
  1. package/dist/cjs/cli.js +9 -5
  2. package/dist/cjs/constants.js +13 -9
  3. package/dist/cjs/index.js +9 -5
  4. package/dist/cjs/loader.js +32 -5
  5. package/dist/cjs/runtime/create-request/index.js +9 -5
  6. package/dist/cjs/runtime/data-platform/index.js +50 -26
  7. package/dist/cjs/runtime/effect/adapter.js +99 -93
  8. package/dist/cjs/runtime/effect/context.js +19 -7
  9. package/dist/cjs/runtime/effect/edge.js +169 -0
  10. package/dist/cjs/runtime/effect/endpoint-contracts.js +130 -0
  11. package/dist/cjs/runtime/effect/handler.js +642 -0
  12. package/dist/cjs/runtime/effect/index.js +30 -547
  13. package/dist/cjs/runtime/effect/module.js +151 -0
  14. package/dist/cjs/runtime/effect/operation-context.js +103 -0
  15. package/dist/cjs/runtime/effect-client/index.js +22 -6
  16. package/dist/cjs/runtime/effect-client/runtime.js +266 -0
  17. package/dist/cjs/runtime/hono/adapter.js +30 -14
  18. package/dist/cjs/runtime/hono/index.js +9 -5
  19. package/dist/cjs/runtime/hono/operators.js +9 -5
  20. package/dist/cjs/runtime/safe-failure.js +83 -0
  21. package/dist/cjs/server.js +9 -5
  22. package/dist/cjs/utils/clientGenerator.js +13 -9
  23. package/dist/cjs/utils/createHonoRoutes.js +9 -5
  24. package/dist/cjs/utils/crossProjectApiPlugin.js +9 -5
  25. package/dist/cjs/utils/crossProjectServerPolicy.js +104 -0
  26. package/dist/cjs/utils/effectClientGenerator.js +116 -488
  27. package/dist/cjs/utils/pluginGenerator.js +9 -5
  28. package/dist/cjs/utils/runtimeGenerator.js +9 -5
  29. package/dist/esm/loader.mjs +23 -0
  30. package/dist/esm/runtime/data-platform/index.mjs +33 -22
  31. package/dist/esm/runtime/effect/adapter.mjs +91 -89
  32. package/dist/esm/runtime/effect/context.mjs +3 -1
  33. package/dist/esm/runtime/effect/edge.mjs +83 -0
  34. package/dist/esm/runtime/effect/endpoint-contracts.mjs +68 -0
  35. package/dist/esm/runtime/effect/handler.mjs +470 -0
  36. package/dist/esm/runtime/effect/index.mjs +3 -437
  37. package/dist/esm/runtime/effect/module.mjs +113 -0
  38. package/dist/esm/runtime/effect/operation-context.mjs +65 -0
  39. package/dist/esm/runtime/effect-client/index.mjs +14 -2
  40. package/dist/esm/runtime/effect-client/runtime.mjs +228 -0
  41. package/dist/esm/runtime/hono/adapter.mjs +21 -9
  42. package/dist/esm/runtime/safe-failure.mjs +45 -0
  43. package/dist/esm/utils/clientGenerator.mjs +5 -5
  44. package/dist/esm/utils/crossProjectServerPolicy.mjs +50 -0
  45. package/dist/esm/utils/effectClientGenerator.mjs +105 -484
  46. package/dist/esm-node/loader.mjs +23 -0
  47. package/dist/esm-node/runtime/data-platform/index.mjs +33 -22
  48. package/dist/esm-node/runtime/effect/adapter.mjs +91 -89
  49. package/dist/esm-node/runtime/effect/context.mjs +3 -1
  50. package/dist/esm-node/runtime/effect/edge.mjs +84 -0
  51. package/dist/esm-node/runtime/effect/endpoint-contracts.mjs +69 -0
  52. package/dist/esm-node/runtime/effect/handler.mjs +471 -0
  53. package/dist/esm-node/runtime/effect/index.mjs +3 -437
  54. package/dist/esm-node/runtime/effect/module.mjs +114 -0
  55. package/dist/esm-node/runtime/effect/operation-context.mjs +66 -0
  56. package/dist/esm-node/runtime/effect-client/index.mjs +14 -2
  57. package/dist/esm-node/runtime/effect-client/runtime.mjs +229 -0
  58. package/dist/esm-node/runtime/hono/adapter.mjs +21 -9
  59. package/dist/esm-node/runtime/safe-failure.mjs +46 -0
  60. package/dist/esm-node/utils/clientGenerator.mjs +5 -5
  61. package/dist/esm-node/utils/crossProjectServerPolicy.mjs +52 -0
  62. package/dist/esm-node/utils/effectClientGenerator.mjs +105 -484
  63. package/dist/types/runtime/create-request/index.d.ts +1 -0
  64. package/dist/types/runtime/data-platform/index.d.ts +4 -0
  65. package/dist/types/runtime/effect/adapter.d.ts +25 -0
  66. package/dist/types/runtime/effect/context.d.ts +3 -6
  67. package/dist/types/runtime/effect/edge.d.ts +25 -0
  68. package/dist/types/runtime/effect/endpoint-contracts.d.ts +62 -0
  69. package/dist/types/runtime/effect/handler.d.ts +203 -0
  70. package/dist/types/runtime/effect/index.d.ts +2 -170
  71. package/dist/types/runtime/effect/module.d.ts +48 -0
  72. package/dist/types/runtime/effect/operation-context.d.ts +10 -0
  73. package/dist/types/runtime/effect-client/index.d.ts +6 -1
  74. package/dist/types/runtime/effect-client/runtime.d.ts +71 -0
  75. package/dist/types/runtime/hono/adapter.d.ts +3 -0
  76. package/dist/types/runtime/safe-failure.d.ts +1 -0
  77. package/dist/types/utils/createHonoRoutes.d.ts +3 -3
  78. package/dist/types/utils/crossProjectServerPolicy.d.ts +35 -0
  79. package/dist/types/utils/effectClientGenerator.d.ts +16 -2
  80. package/package.json +41 -20
@@ -0,0 +1,471 @@
1
+ import "node:module";
2
+ import * as __rspack_external_effect_Layer_16f7a8fc from "effect/Layer";
3
+ import { HttpRouter, HttpServer, HttpServerResponse, HttpTraceContext } from "effect/unstable/http";
4
+ import { HttpApiBuilder, OpenApi } from "effect/unstable/httpapi";
5
+ import { RpcSerialization, RpcServer } from "effect/unstable/rpc";
6
+ import { DEFAULT_DATA_BATCH_ENDPOINT, DEFAULT_DATA_BATCH_HEADER, DEFAULT_DATA_ENVELOPE_HEADER, decodeRequestEnvelopeHeader, validateRequestEnvelope, validateSelectionPlan } from "../data-platform/index.mjs";
7
+ import * as __rspack_external_effect_Config_29be8a92 from "effect/Config";
8
+ import * as __rspack_external_effect_Effect_194ac36c from "effect/Effect";
9
+ import * as __rspack_external_effect_Option_4d691636 from "effect/Option";
10
+ import * as __rspack_external_effect_Schema_f8472650 from "effect/Schema";
11
+ export * from "effect/unstable/http";
12
+ export * from "effect/unstable/httpapi";
13
+ export * from "effect/unstable/rpc";
14
+ import * as __rspack_external_effect_Context_f1289ca3 from "effect/Context";
15
+ const emptyEffectServiceContext = __rspack_external_effect_Context_f1289ca3.empty();
16
+ const EFFECT_VALIDATOR_AWARE_FACTORY = Symbol.for('modernjs.effect.validatorAware');
17
+ function isValidatorAwareHandlerFactory(factory) {
18
+ return 'function' == typeof factory && true === factory[EFFECT_VALIDATOR_AWARE_FACTORY];
19
+ }
20
+ function normalizeOpenApiPath(pathname) {
21
+ if (!pathname.startsWith('/')) return `/${pathname}`;
22
+ return pathname;
23
+ }
24
+ function getOpenApiOptions(openapi) {
25
+ if (!openapi || 'object' != typeof openapi) return;
26
+ if (!openapi.path) return;
27
+ return {
28
+ path: normalizeOpenApiPath(openapi.path)
29
+ };
30
+ }
31
+ function normalizeRpcPath(pathname) {
32
+ if (!pathname || '/' === pathname) return '/rpc';
33
+ if (!pathname.startsWith('/')) return `/${pathname}`;
34
+ return pathname;
35
+ }
36
+ function normalizeBatchPath(pathname) {
37
+ if (!pathname || '/' === pathname) return DEFAULT_DATA_BATCH_ENDPOINT;
38
+ if (!pathname.startsWith('/')) return `/${pathname}`;
39
+ return pathname;
40
+ }
41
+ function isPlainObject(value) {
42
+ return 'object' == typeof value && null !== value && !Array.isArray(value);
43
+ }
44
+ function toTextLength(value) {
45
+ if ("u" > typeof TextEncoder) return new TextEncoder().encode(value).length;
46
+ if ("u" > typeof Buffer) return Buffer.byteLength(value);
47
+ return value.length;
48
+ }
49
+ function toHeaderRecord(headers) {
50
+ const record = {};
51
+ headers.forEach((value, key)=>{
52
+ record[key] = value;
53
+ });
54
+ return record;
55
+ }
56
+ function normalizeItemMethod(method) {
57
+ return (method || 'GET').toUpperCase();
58
+ }
59
+ function normalizeBatchAllowedMethods(allowedMethods) {
60
+ const source = Array.isArray(allowedMethods) && allowedMethods.length > 0 ? allowedMethods : [
61
+ 'GET'
62
+ ];
63
+ return new Set(source.map((method)=>method.toUpperCase()));
64
+ }
65
+ function isBatchRequestPayload(value) {
66
+ return isPlainObject(value) && 1 === value.protocolVersion && 'string' == typeof value.batchId && 'number' == typeof value.sentAt && Array.isArray(value.items);
67
+ }
68
+ function createBatchValidationResponse(message, status = 400) {
69
+ return new Response(JSON.stringify({
70
+ message
71
+ }), {
72
+ status,
73
+ headers: {
74
+ 'content-type': 'application/json; charset=utf-8'
75
+ }
76
+ });
77
+ }
78
+ function toBatchItemError(id, status, message) {
79
+ return {
80
+ id,
81
+ status,
82
+ headers: {
83
+ 'content-type': 'application/json; charset=utf-8'
84
+ },
85
+ body: JSON.stringify({
86
+ message
87
+ })
88
+ };
89
+ }
90
+ function promiseWithTimeout(effect, timeoutMs) {
91
+ if (timeoutMs <= 0) return effect;
92
+ return new Promise((resolve, reject)=>{
93
+ const timer = setTimeout(()=>{
94
+ reject(new Error(`Batch item timeout after ${String(timeoutMs)}ms`));
95
+ }, timeoutMs);
96
+ effect.then((value)=>{
97
+ clearTimeout(timer);
98
+ resolve(value);
99
+ }, (error)=>{
100
+ clearTimeout(timer);
101
+ reject(error);
102
+ });
103
+ });
104
+ }
105
+ async function mapWithConcurrency(items, concurrency, mapper) {
106
+ if (0 === items.length) return [];
107
+ const normalizedConcurrency = Math.max(1, concurrency);
108
+ const output = new Array(items.length);
109
+ let index = 0;
110
+ const workers = Array.from({
111
+ length: Math.min(normalizedConcurrency, items.length)
112
+ }, async ()=>{
113
+ while(true){
114
+ const currentIndex = index;
115
+ index += 1;
116
+ if (currentIndex >= items.length) return;
117
+ output[currentIndex] = await mapper(items[currentIndex], currentIndex);
118
+ }
119
+ });
120
+ await Promise.all(workers);
121
+ return output;
122
+ }
123
+ function getRequestPathname(request) {
124
+ try {
125
+ return new URL(request.url).pathname;
126
+ } catch {
127
+ return new URL(request.url, 'http://localhost').pathname;
128
+ }
129
+ }
130
+ function normalizeMountPrefix(prefix) {
131
+ if (!prefix || '/' === prefix) return '';
132
+ return prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
133
+ }
134
+ function getMountedPrefixFromContext(request, context) {
135
+ if (!isPlainObject(context) || 'string' != typeof context.path) return '';
136
+ const contextPath = normalizeMountPrefix(context.path);
137
+ const requestPath = normalizeMountPrefix(getRequestPathname(request));
138
+ if (!contextPath || !requestPath || contextPath === requestPath || !contextPath.endsWith(requestPath)) return '';
139
+ return normalizeMountPrefix(contextPath.slice(0, contextPath.length - requestPath.length));
140
+ }
141
+ function removeMountedPrefixFromBatchPath(pathWithQuery, prefix) {
142
+ const normalizedPrefix = normalizeMountPrefix(prefix);
143
+ if (!normalizedPrefix) return pathWithQuery;
144
+ const [pathname, ...queryParts] = pathWithQuery.split('?');
145
+ if (!pathname) return pathWithQuery;
146
+ let nextPathname = pathname;
147
+ if (pathname === normalizedPrefix) nextPathname = '/';
148
+ else if (pathname.startsWith(`${normalizedPrefix}/`)) {
149
+ const sliced = pathname.slice(normalizedPrefix.length);
150
+ nextPathname = sliced.startsWith('/') ? sliced : `/${sliced}`;
151
+ }
152
+ if (0 === queryParts.length) return nextPathname;
153
+ return `${nextPathname}?${queryParts.join('?')}`;
154
+ }
155
+ function getRequestOrigin(request) {
156
+ try {
157
+ return new URL(request.url).origin;
158
+ } catch {
159
+ return new URL(request.url, 'http://localhost').origin;
160
+ }
161
+ }
162
+ function getExpectedEnvelopeOrigin(request) {
163
+ const origin = request.headers.get('origin');
164
+ if (origin && 'null' !== origin) return origin;
165
+ return getRequestOrigin(request);
166
+ }
167
+ function isRpcRequest(request, rpcPath) {
168
+ const pathname = getRequestPathname(request);
169
+ return pathname === rpcPath || pathname.startsWith(`${rpcPath}/`);
170
+ }
171
+ function getRpcSerializationLayer(serialization) {
172
+ switch(serialization){
173
+ case 'ndjson':
174
+ return RpcSerialization.layerNdjson;
175
+ case 'jsonRpc':
176
+ return RpcSerialization.layerJsonRpc();
177
+ case 'ndJsonRpc':
178
+ return RpcSerialization.layerNdJsonRpc();
179
+ case 'msgPack':
180
+ return RpcSerialization.layerMsgPack;
181
+ default:
182
+ return RpcSerialization.layerJsonRpc();
183
+ }
184
+ }
185
+ function createRpcApiHandler(options) {
186
+ const rpcPath = normalizeRpcPath(options.path);
187
+ const rpcLayer = __rspack_external_effect_Layer_16f7a8fc.provide(RpcServer.layerHttp({
188
+ group: options.group,
189
+ path: rpcPath,
190
+ protocol: 'http',
191
+ disableTracing: options.disableTracing,
192
+ spanPrefix: options.spanPrefix,
193
+ spanAttributes: options.spanAttributes
194
+ }), __rspack_external_effect_Layer_16f7a8fc.mergeAll(options.layer, getRpcSerializationLayer(options.serialization)));
195
+ return HttpRouter.toWebHandler(rpcLayer);
196
+ }
197
+ function createOpenApiLayer(api, openapi) {
198
+ const openApiOptions = getOpenApiOptions(openapi);
199
+ if (!openApiOptions) return null;
200
+ return HttpRouter.add('GET', openApiOptions.path, HttpServerResponse.jsonUnsafe(OpenApi.fromApi(api)));
201
+ }
202
+ function createInvalidEnvelopeResponse(message, errors) {
203
+ return new Response(JSON.stringify({
204
+ message,
205
+ ...errors && errors.length > 0 ? {
206
+ errors
207
+ } : {}
208
+ }), {
209
+ status: 400,
210
+ headers: {
211
+ 'content-type': 'application/json; charset=utf-8'
212
+ }
213
+ });
214
+ }
215
+ function validateDataPlatformRequestEnvelope(request, options) {
216
+ const isEnabled = options?.enabled ?? true;
217
+ if (!isEnabled) return null;
218
+ const envelopeHeader = options?.envelopeHeader || DEFAULT_DATA_ENVELOPE_HEADER;
219
+ const encodedEnvelope = request.headers.get(envelopeHeader);
220
+ if (!encodedEnvelope) {
221
+ if (options?.requireEnvelope) return createInvalidEnvelopeResponse(`Missing required data envelope header: ${envelopeHeader}`);
222
+ return null;
223
+ }
224
+ const envelope = decodeRequestEnvelopeHeader(encodedEnvelope);
225
+ if (!envelope) return createInvalidEnvelopeResponse(`Invalid data envelope header format: ${envelopeHeader}`);
226
+ const validation = validateRequestEnvelope(envelope, {
227
+ expectedProtocolVersion: 1,
228
+ expectedNamespace: options?.expectedNamespace,
229
+ expectedOrigin: options?.validateOrigin === false ? void 0 : getExpectedEnvelopeOrigin(request),
230
+ requireTraceContext: options?.requireTraceContext
231
+ });
232
+ if (!validation.ok) return createInvalidEnvelopeResponse('Invalid data envelope', validation.errors);
233
+ if (envelope.selectionPlan) {
234
+ const selectionValidation = validateSelectionPlan(envelope.selectionPlan, {
235
+ maxDepth: options?.selection?.maxDepth,
236
+ maxFields: options?.selection?.maxFields,
237
+ allowedLeafPaths: options?.selection?.allowedLeafPaths
238
+ });
239
+ if (!selectionValidation.ok) return createInvalidEnvelopeResponse('Invalid data envelope selection plan', selectionValidation.errors);
240
+ }
241
+ return null;
242
+ }
243
+ function mergeDataPlatformOptions(base, override) {
244
+ if (!base && !override) return;
245
+ const baseSelection = base?.selection;
246
+ const overrideSelection = override?.selection;
247
+ const baseBatch = base?.batch;
248
+ const overrideBatch = override?.batch;
249
+ return {
250
+ ...base,
251
+ ...override,
252
+ selection: baseSelection || overrideSelection ? {
253
+ ...baseSelection,
254
+ ...overrideSelection
255
+ } : void 0,
256
+ batch: baseBatch || overrideBatch ? {
257
+ ...baseBatch,
258
+ ...overrideBatch
259
+ } : void 0
260
+ };
261
+ }
262
+ function defineEffectBff(definition) {
263
+ const createHandler = (options)=>{
264
+ const rpcDefinition = definition.rpc;
265
+ let mergedRpcOptions = rpcDefinition;
266
+ if (rpcDefinition && options?.rpc) mergedRpcOptions = {
267
+ ...rpcDefinition,
268
+ ...options.rpc
269
+ };
270
+ return createHttpApiHandler({
271
+ api: definition.api,
272
+ layer: definition.layer,
273
+ openapi: options?.openapi,
274
+ rpc: mergedRpcOptions,
275
+ dataPlatform: mergeDataPlatformOptions(definition.dataPlatform, options?.dataPlatform),
276
+ validateRequest: options?.validateRequest
277
+ });
278
+ };
279
+ Object.defineProperty(createHandler, EFFECT_VALIDATOR_AWARE_FACTORY, {
280
+ value: true
281
+ });
282
+ const client = createLoaderMaterializedClientPlaceholder();
283
+ return {
284
+ ...definition,
285
+ createHandler,
286
+ client
287
+ };
288
+ }
289
+ const LOADER_CLIENT_IGNORED_KEYS = new Set([
290
+ 'then',
291
+ 'catch',
292
+ 'finally',
293
+ 'toJSON',
294
+ '$$typeof'
295
+ ]);
296
+ function createLoaderMaterializedClientPlaceholder() {
297
+ const explain = (property)=>{
298
+ throw new Error(`[BFF][Effect] effectBff.client.${String(property)} is not available here: the typed client only exists when this module is imported through the "@api/effect/*" transformed path (the BFF loader replaces it with generated client code). On the server, use HttpApiClient or call the Effect layer directly.`);
299
+ };
300
+ return new Proxy(Object.create(null), {
301
+ get (_target, property) {
302
+ if ('symbol' == typeof property || LOADER_CLIENT_IGNORED_KEYS.has(property)) return;
303
+ return explain(property);
304
+ }
305
+ });
306
+ }
307
+ function defineEffectRpcBff(definition) {
308
+ const createHandler = (options)=>createRpcApiHandler({
309
+ ...definition,
310
+ ...options
311
+ });
312
+ return {
313
+ ...definition,
314
+ createHandler
315
+ };
316
+ }
317
+ function createHttpApiHandler(options) {
318
+ const apiLayer = options.layer.pipe(__rspack_external_effect_Layer_16f7a8fc.provide(HttpServer.layerServices));
319
+ const openApiLayer = createOpenApiLayer(options.api, options.openapi);
320
+ const mergedLayer = openApiLayer ? __rspack_external_effect_Layer_16f7a8fc.mergeAll(apiLayer, openApiLayer) : apiLayer;
321
+ const httpApiHandler = HttpRouter.toWebHandler(mergedLayer);
322
+ const dataPlatformBatchOptions = options.dataPlatform?.batch;
323
+ const batchEnabled = dataPlatformBatchOptions?.enabled !== false;
324
+ const batchPath = normalizeBatchPath(dataPlatformBatchOptions?.endpoint);
325
+ const batchMaxSize = Math.max(1, dataPlatformBatchOptions?.maxBatchSize ?? 16);
326
+ const batchMaxBytes = Math.max(1024, dataPlatformBatchOptions?.maxBatchBytes ?? 65536);
327
+ const batchConcurrency = Math.max(1, dataPlatformBatchOptions?.maxConcurrency ?? 4);
328
+ const batchItemTimeoutMs = Math.max(0, dataPlatformBatchOptions?.requestTimeoutMs ?? 10000);
329
+ const batchAllowedMethods = normalizeBatchAllowedMethods(dataPlatformBatchOptions?.allowedMethods);
330
+ const envelopeHeader = options.dataPlatform?.envelopeHeader || DEFAULT_DATA_ENVELOPE_HEADER;
331
+ const normalizedEnvelopeHeader = envelopeHeader.toLowerCase();
332
+ const withDataPlatformValidation = async (request, context)=>{
333
+ const policyDenial = options.validateRequest?.(request);
334
+ if (policyDenial) return policyDenial;
335
+ const validationError = validateDataPlatformRequestEnvelope(request, options.dataPlatform);
336
+ if (validationError) return validationError;
337
+ return httpApiHandler.handler(request, context ?? emptyEffectServiceContext);
338
+ };
339
+ const handleBatchRequest = async (request, context)=>{
340
+ const mountedPrefix = getMountedPrefixFromContext(request, context);
341
+ const method = normalizeItemMethod(request.method);
342
+ if ('POST' !== method) return createBatchValidationResponse('Batch endpoint only supports POST requests', 405);
343
+ const contentType = request.headers.get('content-type') || '';
344
+ if (!contentType.includes('application/json')) return createBatchValidationResponse('Batch endpoint requires application/json content-type', 415);
345
+ const payloadText = await request.text();
346
+ if (toTextLength(payloadText) > batchMaxBytes) return createBatchValidationResponse(`Batch payload exceeds max size (${String(batchMaxBytes)} bytes)`, 413);
347
+ let payload;
348
+ try {
349
+ payload = JSON.parse(payloadText);
350
+ } catch {
351
+ return createBatchValidationResponse('Invalid batch payload JSON');
352
+ }
353
+ if (!isBatchRequestPayload(payload)) return createBatchValidationResponse('Invalid batch payload shape');
354
+ if (0 === payload.items.length) return createBatchValidationResponse('Batch payload items cannot be empty');
355
+ if (payload.items.length > batchMaxSize) return createBatchValidationResponse(`Batch item count exceeds max size (${String(batchMaxSize)})`, 413);
356
+ const responseItems = await mapWithConcurrency(payload.items, batchConcurrency, async (rawItem, index)=>{
357
+ const fallbackId = `item_${String(index)}`;
358
+ const itemId = isPlainObject(rawItem) && 'string' == typeof rawItem.id ? rawItem.id : fallbackId;
359
+ if (!isPlainObject(rawItem)) return toBatchItemError(itemId, 400, 'Invalid batch item; expected object');
360
+ if ('string' != typeof rawItem.path || 0 === rawItem.path.length) return toBatchItemError(itemId, 400, 'Invalid batch item path');
361
+ if (!rawItem.path.startsWith('/')) return toBatchItemError(itemId, 400, 'Batch item path must start with "/"');
362
+ const normalizedItemPath = removeMountedPrefixFromBatchPath(rawItem.path, mountedPrefix);
363
+ const itemPathname = normalizedItemPath.split('?')[0] || normalizedItemPath;
364
+ if (itemPathname === batchPath || itemPathname.startsWith(`${batchPath}/`)) return toBatchItemError(itemId, 400, 'Batch item path cannot target batch endpoint');
365
+ const itemMethod = normalizeItemMethod('string' == typeof rawItem.method ? rawItem.method : void 0);
366
+ if (!batchAllowedMethods.has(itemMethod)) return toBatchItemError(itemId, 405, `Batch item method ${itemMethod} is not allowed`);
367
+ if (void 0 !== rawItem.body && null !== rawItem.body && 'string' != typeof rawItem.body) return toBatchItemError(itemId, 400, 'Batch item body must be a string when provided');
368
+ if (('GET' === itemMethod || 'HEAD' === itemMethod) && 'string' == typeof rawItem.body) return toBatchItemError(itemId, 400, `${itemMethod} batch item cannot include body`);
369
+ const normalizedHeaders = {};
370
+ if (void 0 !== rawItem.headers) {
371
+ if (!isPlainObject(rawItem.headers)) return toBatchItemError(itemId, 400, 'Batch item headers must be an object');
372
+ for (const [key, value] of Object.entries(rawItem.headers)){
373
+ if ('string' != typeof value) return toBatchItemError(itemId, 400, `Invalid header "${key}" for batch item`);
374
+ normalizedHeaders[key.toLowerCase()] = value;
375
+ }
376
+ }
377
+ if (!normalizedHeaders.traceparent) {
378
+ const encodedEnvelope = normalizedHeaders[normalizedEnvelopeHeader];
379
+ if ('string' == typeof encodedEnvelope) {
380
+ const envelope = decodeRequestEnvelopeHeader(encodedEnvelope);
381
+ if (envelope?.traceparent) normalizedHeaders.traceparent = envelope.traceparent;
382
+ }
383
+ }
384
+ if (!normalizedHeaders.traceparent) {
385
+ const requestTraceparent = request.headers.get('traceparent');
386
+ if (requestTraceparent) normalizedHeaders.traceparent = requestTraceparent;
387
+ }
388
+ const targetUrl = new URL(normalizedItemPath, request.url);
389
+ const requestHeaders = new Headers(normalizedHeaders);
390
+ const body = 'GET' === itemMethod || 'HEAD' === itemMethod ? void 0 : rawItem.body;
391
+ if (void 0 === body) requestHeaders.delete('content-type');
392
+ const itemRequest = new Request(targetUrl.toString(), {
393
+ method: itemMethod,
394
+ headers: requestHeaders,
395
+ body
396
+ });
397
+ try {
398
+ const itemResponse = await promiseWithTimeout(withDataPlatformValidation(itemRequest, context), batchItemTimeoutMs);
399
+ if (!(itemResponse instanceof Response)) return toBatchItemError(itemId, 500, 'Invalid response returned by batch item handler');
400
+ const bodyText = await itemResponse.text();
401
+ const responseItem = {
402
+ id: itemId,
403
+ status: itemResponse.status,
404
+ headers: toHeaderRecord(itemResponse.headers),
405
+ ...bodyText ? {
406
+ body: bodyText
407
+ } : {}
408
+ };
409
+ return responseItem;
410
+ } catch (error) {
411
+ if (error instanceof Response) {
412
+ const bodyText = await error.text();
413
+ return {
414
+ id: itemId,
415
+ status: error.status,
416
+ headers: toHeaderRecord(error.headers),
417
+ ...bodyText ? {
418
+ body: bodyText
419
+ } : {}
420
+ };
421
+ }
422
+ const message = error instanceof Error ? error.message : String(error);
423
+ return toBatchItemError(itemId, 500, message);
424
+ }
425
+ });
426
+ const responsePayload = {
427
+ protocolVersion: 1,
428
+ batchId: payload.batchId,
429
+ receivedAt: Date.now(),
430
+ items: responseItems
431
+ };
432
+ return new Response(JSON.stringify(responsePayload), {
433
+ status: 200,
434
+ headers: {
435
+ 'content-type': 'application/json; charset=utf-8',
436
+ [DEFAULT_DATA_BATCH_HEADER]: '1',
437
+ 'x-modernjs-data-batch-id': payload.batchId
438
+ }
439
+ });
440
+ };
441
+ const handleHttpApiRequest = async (request, context)=>{
442
+ const pathname = getRequestPathname(request);
443
+ if (batchEnabled && pathname === batchPath) return handleBatchRequest(request, context);
444
+ return withDataPlatformValidation(request, context);
445
+ };
446
+ if (!options.rpc) return {
447
+ handler: handleHttpApiRequest,
448
+ dispose: async ()=>{
449
+ await httpApiHandler.dispose();
450
+ }
451
+ };
452
+ const rpcPath = normalizeRpcPath(options.rpc.path);
453
+ const rpcHandler = createRpcApiHandler(options.rpc);
454
+ return {
455
+ handler: async (request, context)=>{
456
+ if (isRpcRequest(request, rpcPath)) {
457
+ const policyDenial = options.validateRequest?.(request);
458
+ if (policyDenial) return policyDenial;
459
+ return rpcHandler.handler(request, context ?? emptyEffectServiceContext);
460
+ }
461
+ return handleHttpApiRequest(request);
462
+ },
463
+ dispose: async ()=>{
464
+ await Promise.all([
465
+ httpApiHandler.dispose(),
466
+ rpcHandler.dispose()
467
+ ]);
468
+ }
469
+ };
470
+ }
471
+ export { EFFECT_VALIDATOR_AWARE_FACTORY, HttpApiBuilder, HttpTraceContext, __rspack_external_effect_Config_29be8a92 as Config, __rspack_external_effect_Effect_194ac36c as Effect, __rspack_external_effect_Layer_16f7a8fc as Layer, __rspack_external_effect_Option_4d691636 as Option, __rspack_external_effect_Schema_f8472650 as Schema, createHttpApiHandler, defineEffectBff, defineEffectRpcBff, isValidatorAwareHandlerFactory };