@bleedingdev/modern-js-bff-effect 3.8.3-ultramodern.2
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.
- package/LICENSE +21 -0
- package/README.md +25 -0
- package/dist/cjs/data-platform/batch/protocol.js +130 -0
- package/dist/cjs/data-platform/batch/queue.js +623 -0
- package/dist/cjs/data-platform/batch/request.js +121 -0
- package/dist/cjs/data-platform/batch/response.js +65 -0
- package/dist/cjs/data-platform/batch/telemetry.js +71 -0
- package/dist/cjs/data-platform/batch/url.js +69 -0
- package/dist/cjs/data-platform/batch-transport.js +59 -0
- package/dist/cjs/data-platform/codec.js +155 -0
- package/dist/cjs/data-platform/index.js +124 -0
- package/dist/cjs/data-platform/invalidation.js +61 -0
- package/dist/cjs/data-platform/trace.js +73 -0
- package/dist/cjs/data-platform/types.js +48 -0
- package/dist/cjs/data-platform/validation.js +178 -0
- package/dist/cjs/effect/context.js +59 -0
- package/dist/cjs/effect/dispatch.js +101 -0
- package/dist/cjs/effect/edge-context.js +61 -0
- package/dist/cjs/effect/edge-dispatcher.js +354 -0
- package/dist/cjs/effect/edge.js +62 -0
- package/dist/cjs/effect/endpoint-contracts.js +121 -0
- package/dist/cjs/effect/entry-shape-registry.js +31 -0
- package/dist/cjs/effect/entry-shape.js +113 -0
- package/dist/cjs/effect/handler/batch-handler.js +270 -0
- package/dist/cjs/effect/handler/batch.js +170 -0
- package/dist/cjs/effect/handler/definition.js +99 -0
- package/dist/cjs/effect/handler/envelope.js +104 -0
- package/dist/cjs/effect/handler/http.js +107 -0
- package/dist/cjs/effect/handler/openapi.js +58 -0
- package/dist/cjs/effect/handler/routing.js +100 -0
- package/dist/cjs/effect/handler/rpc.js +63 -0
- package/dist/cjs/effect/handler/types.js +43 -0
- package/dist/cjs/effect/handler.js +173 -0
- package/dist/cjs/effect/index.js +137 -0
- package/dist/cjs/effect/module.js +118 -0
- package/dist/cjs/effect/operation-context.js +116 -0
- package/dist/cjs/effect/rpcSerialization.js +54 -0
- package/dist/cjs/effect-client/batch.js +73 -0
- package/dist/cjs/effect-client/envelope.js +145 -0
- package/dist/cjs/effect-client/guards.js +44 -0
- package/dist/cjs/effect-client/index.js +208 -0
- package/dist/cjs/effect-client/request-context.js +64 -0
- package/dist/cjs/effect-client/request.js +66 -0
- package/dist/cjs/effect-client/runtime.js +100 -0
- package/dist/cjs/effect-client/types.js +18 -0
- package/dist/cjs/headers.js +46 -0
- package/dist/cjs/index.js +83 -0
- package/dist/esm/data-platform/batch/protocol.mjs +71 -0
- package/dist/esm/data-platform/batch/queue.mjs +582 -0
- package/dist/esm/data-platform/batch/request.mjs +68 -0
- package/dist/esm/data-platform/batch/response.mjs +24 -0
- package/dist/esm/data-platform/batch/telemetry.mjs +27 -0
- package/dist/esm/data-platform/batch/url.mjs +25 -0
- package/dist/esm/data-platform/batch-transport.mjs +12 -0
- package/dist/esm/data-platform/codec.mjs +90 -0
- package/dist/esm/data-platform/index.mjs +7 -0
- package/dist/esm/data-platform/invalidation.mjs +20 -0
- package/dist/esm/data-platform/trace.mjs +29 -0
- package/dist/esm/data-platform/types.mjs +4 -0
- package/dist/esm/data-platform/validation.mjs +128 -0
- package/dist/esm/effect/context.mjs +12 -0
- package/dist/esm/effect/dispatch.mjs +63 -0
- package/dist/esm/effect/edge-context.mjs +14 -0
- package/dist/esm/effect/edge-dispatcher.mjs +115 -0
- package/dist/esm/effect/edge.mjs +1 -0
- package/dist/esm/effect/endpoint-contracts.mjs +68 -0
- package/dist/esm/effect/entry-shape-registry.mjs +17 -0
- package/dist/esm/effect/entry-shape.mjs +51 -0
- package/dist/esm/effect/handler/batch-handler.mjs +232 -0
- package/dist/esm/effect/handler/batch.mjs +105 -0
- package/dist/esm/effect/handler/definition.mjs +58 -0
- package/dist/esm/effect/handler/envelope.mjs +63 -0
- package/dist/esm/effect/handler/http.mjs +69 -0
- package/dist/esm/effect/handler/openapi.mjs +20 -0
- package/dist/esm/effect/handler/routing.mjs +50 -0
- package/dist/esm/effect/handler/rpc.mjs +22 -0
- package/dist/esm/effect/handler/types.mjs +5 -0
- package/dist/esm/effect/handler.mjs +13 -0
- package/dist/esm/effect/index.mjs +7 -0
- package/dist/esm/effect/module.mjs +80 -0
- package/dist/esm/effect/operation-context.mjs +75 -0
- package/dist/esm/effect/rpcSerialization.mjs +16 -0
- package/dist/esm/effect-client/batch.mjs +35 -0
- package/dist/esm/effect-client/envelope.mjs +104 -0
- package/dist/esm/effect-client/guards.mjs +3 -0
- package/dist/esm/effect-client/index.mjs +110 -0
- package/dist/esm/effect-client/request-context.mjs +23 -0
- package/dist/esm/effect-client/request.mjs +28 -0
- package/dist/esm/effect-client/runtime.mjs +62 -0
- package/dist/esm/effect-client/types.mjs +0 -0
- package/dist/esm/headers.mjs +8 -0
- package/dist/esm/index.mjs +4 -0
- package/dist/esm/rslib-runtime.mjs +18 -0
- package/dist/esm-node/data-platform/batch/protocol.mjs +72 -0
- package/dist/esm-node/data-platform/batch/queue.mjs +583 -0
- package/dist/esm-node/data-platform/batch/request.mjs +69 -0
- package/dist/esm-node/data-platform/batch/response.mjs +25 -0
- package/dist/esm-node/data-platform/batch/telemetry.mjs +28 -0
- package/dist/esm-node/data-platform/batch/url.mjs +26 -0
- package/dist/esm-node/data-platform/batch-transport.mjs +13 -0
- package/dist/esm-node/data-platform/codec.mjs +91 -0
- package/dist/esm-node/data-platform/index.mjs +8 -0
- package/dist/esm-node/data-platform/invalidation.mjs +21 -0
- package/dist/esm-node/data-platform/trace.mjs +30 -0
- package/dist/esm-node/data-platform/types.mjs +5 -0
- package/dist/esm-node/data-platform/validation.mjs +129 -0
- package/dist/esm-node/effect/context.mjs +13 -0
- package/dist/esm-node/effect/dispatch.mjs +64 -0
- package/dist/esm-node/effect/edge-context.mjs +15 -0
- package/dist/esm-node/effect/edge-dispatcher.mjs +116 -0
- package/dist/esm-node/effect/edge.mjs +2 -0
- package/dist/esm-node/effect/endpoint-contracts.mjs +69 -0
- package/dist/esm-node/effect/entry-shape-registry.mjs +18 -0
- package/dist/esm-node/effect/entry-shape.mjs +63 -0
- package/dist/esm-node/effect/handler/batch-handler.mjs +233 -0
- package/dist/esm-node/effect/handler/batch.mjs +106 -0
- package/dist/esm-node/effect/handler/definition.mjs +59 -0
- package/dist/esm-node/effect/handler/envelope.mjs +64 -0
- package/dist/esm-node/effect/handler/http.mjs +70 -0
- package/dist/esm-node/effect/handler/openapi.mjs +21 -0
- package/dist/esm-node/effect/handler/routing.mjs +51 -0
- package/dist/esm-node/effect/handler/rpc.mjs +23 -0
- package/dist/esm-node/effect/handler/types.mjs +6 -0
- package/dist/esm-node/effect/handler.mjs +14 -0
- package/dist/esm-node/effect/index.mjs +8 -0
- package/dist/esm-node/effect/module.mjs +81 -0
- package/dist/esm-node/effect/operation-context.mjs +76 -0
- package/dist/esm-node/effect/rpcSerialization.mjs +17 -0
- package/dist/esm-node/effect-client/batch.mjs +36 -0
- package/dist/esm-node/effect-client/envelope.mjs +105 -0
- package/dist/esm-node/effect-client/guards.mjs +4 -0
- package/dist/esm-node/effect-client/index.mjs +111 -0
- package/dist/esm-node/effect-client/request-context.mjs +24 -0
- package/dist/esm-node/effect-client/request.mjs +29 -0
- package/dist/esm-node/effect-client/runtime.mjs +63 -0
- package/dist/esm-node/effect-client/types.mjs +1 -0
- package/dist/esm-node/headers.mjs +9 -0
- package/dist/esm-node/index.mjs +5 -0
- package/dist/esm-node/rslib-runtime.mjs +19 -0
- package/dist/types/data-platform/batch/protocol.d.ts +9 -0
- package/dist/types/data-platform/batch/queue.d.ts +47 -0
- package/dist/types/data-platform/batch/request.d.ts +19 -0
- package/dist/types/data-platform/batch/response.d.ts +3 -0
- package/dist/types/data-platform/batch/telemetry.d.ts +4 -0
- package/dist/types/data-platform/batch/url.d.ts +4 -0
- package/dist/types/data-platform/batch-transport.d.ts +3 -0
- package/dist/types/data-platform/codec.d.ts +17 -0
- package/dist/types/data-platform/index.d.ts +8 -0
- package/dist/types/data-platform/invalidation.d.ts +8 -0
- package/dist/types/data-platform/trace.d.ts +4 -0
- package/dist/types/data-platform/types.d.ts +151 -0
- package/dist/types/data-platform/validation.d.ts +29 -0
- package/dist/types/effect/context.d.ts +5 -0
- package/dist/types/effect/dispatch.d.ts +13 -0
- package/dist/types/effect/edge-context.d.ts +5 -0
- package/dist/types/effect/edge-dispatcher.d.ts +37 -0
- package/dist/types/effect/edge.d.ts +1 -0
- package/dist/types/effect/endpoint-contracts.d.ts +67 -0
- package/dist/types/effect/entry-shape.d.ts +32 -0
- package/dist/types/effect/handler/batch-handler.d.ts +11 -0
- package/dist/types/effect/handler/batch.d.ts +15 -0
- package/dist/types/effect/handler/definition.d.ts +7 -0
- package/dist/types/effect/handler/envelope.d.ts +13 -0
- package/dist/types/effect/handler/http.d.ts +15 -0
- package/dist/types/effect/handler/openapi.d.ts +4 -0
- package/dist/types/effect/handler/routing.d.ts +5 -0
- package/dist/types/effect/handler/rpc.d.ts +7 -0
- package/dist/types/effect/handler/types.d.ts +153 -0
- package/dist/types/effect/handler.d.ts +13 -0
- package/dist/types/effect/index.d.ts +6 -0
- package/dist/types/effect/module.d.ts +36 -0
- package/dist/types/effect/operation-context.d.ts +15 -0
- package/dist/types/effect/rpcSerialization.d.ts +3 -0
- package/dist/types/effect-client/batch.d.ts +2 -0
- package/dist/types/effect-client/envelope.d.ts +15 -0
- package/dist/types/effect-client/guards.d.ts +2 -0
- package/dist/types/effect-client/index.d.ts +58 -0
- package/dist/types/effect-client/request-context.d.ts +3 -0
- package/dist/types/effect-client/request.d.ts +1 -0
- package/dist/types/effect-client/runtime.d.ts +5 -0
- package/dist/types/effect-client/types.d.ts +68 -0
- package/dist/types/headers.d.ts +1 -0
- package/dist/types/index.d.ts +3 -0
- package/package.json +164 -0
- package/src/data-platform/batch/protocol.ts +112 -0
- package/src/data-platform/batch/queue.ts +876 -0
- package/src/data-platform/batch/request.ts +130 -0
- package/src/data-platform/batch/response.ts +74 -0
- package/src/data-platform/batch/telemetry.ts +47 -0
- package/src/data-platform/batch/url.ts +54 -0
- package/src/data-platform/batch-transport.ts +22 -0
- package/src/data-platform/codec.ts +145 -0
- package/src/data-platform/index.ts +63 -0
- package/src/data-platform/invalidation.ts +57 -0
- package/src/data-platform/trace.ts +49 -0
- package/src/data-platform/types.ts +186 -0
- package/src/data-platform/validation.ts +303 -0
- package/src/effect/context.ts +37 -0
- package/src/effect/dispatch.ts +132 -0
- package/src/effect/edge-context.ts +51 -0
- package/src/effect/edge-dispatcher.ts +310 -0
- package/src/effect/edge.ts +1 -0
- package/src/effect/endpoint-contracts.ts +191 -0
- package/src/effect/entry-shape-registry.cjs +16 -0
- package/src/effect/entry-shape-registry.d.cts +6 -0
- package/src/effect/entry-shape.ts +155 -0
- package/src/effect/handler/batch-handler.ts +475 -0
- package/src/effect/handler/batch.ts +182 -0
- package/src/effect/handler/definition.ts +121 -0
- package/src/effect/handler/envelope.ts +133 -0
- package/src/effect/handler/http.ts +133 -0
- package/src/effect/handler/openapi.ts +45 -0
- package/src/effect/handler/routing.ts +91 -0
- package/src/effect/handler/rpc.ts +45 -0
- package/src/effect/handler/types.ts +255 -0
- package/src/effect/handler.ts +33 -0
- package/src/effect/index.ts +22 -0
- package/src/effect/module.ts +186 -0
- package/src/effect/operation-context.ts +144 -0
- package/src/effect/rpcSerialization.ts +20 -0
- package/src/effect-client/batch.ts +50 -0
- package/src/effect-client/envelope.ts +238 -0
- package/src/effect-client/guards.ts +6 -0
- package/src/effect-client/index.ts +325 -0
- package/src/effect-client/request-context.ts +54 -0
- package/src/effect-client/request.ts +51 -0
- package/src/effect-client/runtime.ts +122 -0
- package/src/effect-client/types.ts +84 -0
- package/src/headers.ts +7 -0
- package/src/index.ts +3 -0
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
function createLocalValidatorAwareHandlerFactoryRegistry() {
|
|
2
|
+
const factories = new WeakSet();
|
|
3
|
+
return {
|
|
4
|
+
register (factory) {
|
|
5
|
+
factories.add(factory);
|
|
6
|
+
return factory;
|
|
7
|
+
},
|
|
8
|
+
is (factory) {
|
|
9
|
+
return 'function' == typeof factory && factories.has(factory);
|
|
10
|
+
}
|
|
11
|
+
};
|
|
12
|
+
}
|
|
13
|
+
const validatorAwareHandlerFactoryRegistry = createLocalValidatorAwareHandlerFactoryRegistry();
|
|
14
|
+
function registerValidatorAwareHandlerFactory(factory) {
|
|
15
|
+
return validatorAwareHandlerFactoryRegistry.register(factory);
|
|
16
|
+
}
|
|
17
|
+
function isValidatorAwareHandlerFactory(factory) {
|
|
18
|
+
return validatorAwareHandlerFactoryRegistry.is(factory);
|
|
19
|
+
}
|
|
20
|
+
const strictEffectApproachMessage = '[BFF][Effect] strictEffectApproach is enforced: Effect API entries export defineEffectBff(...) or { api, layer } HttpApi module. Raw handler exports, default request handlers, unbranded custom createHandler factories not valid Effect API entries.';
|
|
21
|
+
function isEffectEntryRecord(value) {
|
|
22
|
+
return 'object' == typeof value && null !== value;
|
|
23
|
+
}
|
|
24
|
+
function classifyEffectBffEntryModule(value, predicates) {
|
|
25
|
+
if (!isEffectEntryRecord(value)) return null;
|
|
26
|
+
const rootModule = value;
|
|
27
|
+
if (predicates.isRequestHandler(rootModule.handler)) return createEntryShapeFacts(rootModule, predicates, '`handler` export');
|
|
28
|
+
const defaultEntry = rootModule.default;
|
|
29
|
+
if (predicates.isRequestHandler(defaultEntry)) return createEntryShapeFacts(rootModule, predicates, 'default request handler');
|
|
30
|
+
const module = isEffectEntryRecord(defaultEntry) ? {
|
|
31
|
+
...rootModule,
|
|
32
|
+
...defaultEntry
|
|
33
|
+
} : rootModule;
|
|
34
|
+
if (predicates.isRequestHandler(module.handler)) return createEntryShapeFacts(module, predicates, '`handler` export');
|
|
35
|
+
return createEntryShapeFacts(module, predicates);
|
|
36
|
+
}
|
|
37
|
+
function createEntryShapeFacts(module, predicates, legacyShape) {
|
|
38
|
+
const createHandler = 'function' == typeof module.createHandler ? module.createHandler : void 0;
|
|
39
|
+
const api = predicates.isHttpApi(module.api) ? module.api : void 0;
|
|
40
|
+
const hasRuntimeLayer = void 0 !== module.layer;
|
|
41
|
+
return {
|
|
42
|
+
module,
|
|
43
|
+
legacyShape,
|
|
44
|
+
createHandler,
|
|
45
|
+
createHandlerValidatorAware: void 0 !== createHandler && predicates.isValidatorAwareHandlerFactory(createHandler),
|
|
46
|
+
api,
|
|
47
|
+
layer: module.layer,
|
|
48
|
+
hasRuntimeLayer
|
|
49
|
+
};
|
|
50
|
+
}
|
|
51
|
+
export { classifyEffectBffEntryModule, isValidatorAwareHandlerFactory, registerValidatorAwareHandlerFactory, strictEffectApproachMessage };
|
|
@@ -0,0 +1,232 @@
|
|
|
1
|
+
import { DEFAULT_DATA_BATCH_HEADER, DEFAULT_DATA_ENVELOPE_HEADER, decodeRequestEnvelopeHeader, isPlainObject, normalizeMethod } from "../../data-platform/index.mjs";
|
|
2
|
+
import { decodeBatchBody, isBatchBody, toBatchResponseItem } from "../../data-platform/batch/protocol.mjs";
|
|
3
|
+
import { BatchItemTimeoutError, createBatchValidationResponse, isBatchRequestPayload, mapWithConcurrency, normalizeBatchAllowedMethods, normalizeBatchPath, promiseWithTimeout, toBatchItemError } from "./batch.mjs";
|
|
4
|
+
import { getMountedPrefixFromContext, removeMountedPrefixFromBatchPath } from "./routing.mjs";
|
|
5
|
+
const HOP_BY_HOP_BATCH_ITEM_HEADERS = new Set([
|
|
6
|
+
'connection',
|
|
7
|
+
'keep-alive',
|
|
8
|
+
'proxy-authenticate',
|
|
9
|
+
'proxy-authorization',
|
|
10
|
+
'proxy-connection',
|
|
11
|
+
'te',
|
|
12
|
+
'trailer',
|
|
13
|
+
'transfer-encoding',
|
|
14
|
+
'upgrade'
|
|
15
|
+
]);
|
|
16
|
+
const OUTER_BOUND_BATCH_ITEM_HEADERS = new Set([
|
|
17
|
+
'authorization',
|
|
18
|
+
'cookie',
|
|
19
|
+
'forwarded',
|
|
20
|
+
'origin',
|
|
21
|
+
'referer',
|
|
22
|
+
'sec-fetch-dest',
|
|
23
|
+
'sec-fetch-mode',
|
|
24
|
+
'sec-fetch-site',
|
|
25
|
+
'sec-fetch-user',
|
|
26
|
+
'x-forwarded-client-cert',
|
|
27
|
+
'x-forwarded-for',
|
|
28
|
+
'x-forwarded-host',
|
|
29
|
+
'x-forwarded-port',
|
|
30
|
+
'x-forwarded-proto',
|
|
31
|
+
'x-real-ip',
|
|
32
|
+
'x-subject-id',
|
|
33
|
+
'x-tenant-id',
|
|
34
|
+
'x-user-id',
|
|
35
|
+
'x-verified-producer'
|
|
36
|
+
]);
|
|
37
|
+
const TRANSPORT_CONTROLLED_BATCH_ITEM_HEADERS = new Set([
|
|
38
|
+
'content-length',
|
|
39
|
+
'host',
|
|
40
|
+
...HOP_BY_HOP_BATCH_ITEM_HEADERS
|
|
41
|
+
]);
|
|
42
|
+
async function readRequestTextWithinLimit(request, maxBytes) {
|
|
43
|
+
const contentLength = request.headers.get('content-length');
|
|
44
|
+
if (null !== contentLength) {
|
|
45
|
+
if (!/^\d+$/.test(contentLength)) return {
|
|
46
|
+
status: 'invalid-content-length'
|
|
47
|
+
};
|
|
48
|
+
if (BigInt(contentLength) > BigInt(maxBytes)) return {
|
|
49
|
+
status: 'too-large'
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
if (null === request.body) return {
|
|
53
|
+
status: 'ok',
|
|
54
|
+
text: ''
|
|
55
|
+
};
|
|
56
|
+
const reader = request.body.getReader();
|
|
57
|
+
const decoder = new TextDecoder();
|
|
58
|
+
const text = [];
|
|
59
|
+
let bytesRead = 0;
|
|
60
|
+
try {
|
|
61
|
+
while(true){
|
|
62
|
+
const chunk = await reader.read();
|
|
63
|
+
if (chunk.done) {
|
|
64
|
+
text.push(decoder.decode());
|
|
65
|
+
return {
|
|
66
|
+
status: 'ok',
|
|
67
|
+
text: text.join('')
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
bytesRead += chunk.value.byteLength;
|
|
71
|
+
if (bytesRead > maxBytes) {
|
|
72
|
+
await reader.cancel('batch-payload-too-large');
|
|
73
|
+
return {
|
|
74
|
+
status: 'too-large'
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
text.push(decoder.decode(chunk.value, {
|
|
78
|
+
stream: true
|
|
79
|
+
}));
|
|
80
|
+
}
|
|
81
|
+
} catch {
|
|
82
|
+
return {
|
|
83
|
+
status: 'read-error'
|
|
84
|
+
};
|
|
85
|
+
} finally{
|
|
86
|
+
reader.releaseLock();
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
function createDataPlatformBatchRequestHandler(options) {
|
|
90
|
+
const dataPlatformBatchOptions = options.dataPlatform?.batch;
|
|
91
|
+
const batchEnabled = dataPlatformBatchOptions?.enabled !== false;
|
|
92
|
+
const batchPath = normalizeBatchPath(dataPlatformBatchOptions?.endpoint);
|
|
93
|
+
const batchMaxSize = Math.max(1, dataPlatformBatchOptions?.maxBatchSize ?? 16);
|
|
94
|
+
const batchMaxBytes = Math.max(1024, dataPlatformBatchOptions?.maxBatchBytes ?? 65536);
|
|
95
|
+
const batchConcurrency = Math.max(1, dataPlatformBatchOptions?.maxConcurrency ?? 4);
|
|
96
|
+
const batchItemTimeoutMs = Math.max(0, dataPlatformBatchOptions?.requestTimeoutMs ?? 10000);
|
|
97
|
+
const batchAllowedMethods = normalizeBatchAllowedMethods(dataPlatformBatchOptions?.allowedMethods);
|
|
98
|
+
const envelopeHeader = options.dataPlatform?.envelopeHeader || DEFAULT_DATA_ENVELOPE_HEADER;
|
|
99
|
+
const normalizedEnvelopeHeader = envelopeHeader.toLowerCase();
|
|
100
|
+
const handle = async (request, context)=>{
|
|
101
|
+
const mountedPrefix = getMountedPrefixFromContext(request, context);
|
|
102
|
+
const method = normalizeMethod(request.method);
|
|
103
|
+
if ('POST' !== method) return createBatchValidationResponse('Batch endpoint only supports POST requests', 405);
|
|
104
|
+
const contentType = request.headers.get('content-type') || '';
|
|
105
|
+
if (!contentType.includes('application/json')) return createBatchValidationResponse('Batch endpoint requires application/json content-type', 415);
|
|
106
|
+
const bodyResult = await readRequestTextWithinLimit(request, batchMaxBytes);
|
|
107
|
+
if ('too-large' === bodyResult.status) return createBatchValidationResponse(`Batch payload exceeds max size (${String(batchMaxBytes)} bytes)`, 413);
|
|
108
|
+
if ('invalid-content-length' === bodyResult.status) return createBatchValidationResponse('Batch payload has invalid content-length');
|
|
109
|
+
if ('read-error' === bodyResult.status) return createBatchValidationResponse('Unable to read batch payload');
|
|
110
|
+
const payloadText = bodyResult.text;
|
|
111
|
+
let payload;
|
|
112
|
+
try {
|
|
113
|
+
payload = JSON.parse(payloadText);
|
|
114
|
+
} catch {
|
|
115
|
+
return createBatchValidationResponse('Invalid batch payload JSON');
|
|
116
|
+
}
|
|
117
|
+
if (!isBatchRequestPayload(payload)) return createBatchValidationResponse('Invalid batch payload shape');
|
|
118
|
+
if (0 === payload.items.length) return createBatchValidationResponse('Batch payload items cannot be empty');
|
|
119
|
+
if (payload.items.length > batchMaxSize) return createBatchValidationResponse(`Batch item count exceeds max size (${String(batchMaxSize)})`, 413);
|
|
120
|
+
const batchRequestOrigin = new URL(request.url).origin;
|
|
121
|
+
const responseItems = await mapWithConcurrency(payload.items, batchConcurrency, async (rawItem, index)=>{
|
|
122
|
+
const fallbackId = `item_${String(index)}`;
|
|
123
|
+
const itemId = isPlainObject(rawItem) && 'string' == typeof rawItem.id ? rawItem.id : fallbackId;
|
|
124
|
+
if (!isPlainObject(rawItem)) return toBatchItemError(itemId, 400, 'Invalid batch item; expected object');
|
|
125
|
+
if ('string' != typeof rawItem.path || 0 === rawItem.path.length) return toBatchItemError(itemId, 400, 'Invalid batch item path');
|
|
126
|
+
if (!rawItem.path.startsWith('/')) return toBatchItemError(itemId, 400, 'Batch item path must start with "/"');
|
|
127
|
+
const normalizedItemPath = removeMountedPrefixFromBatchPath(rawItem.path, mountedPrefix);
|
|
128
|
+
const itemPathname = normalizedItemPath.split('?')[0] || normalizedItemPath;
|
|
129
|
+
if (itemPathname === batchPath || itemPathname.startsWith(`${batchPath}/`)) return toBatchItemError(itemId, 400, 'Batch item path cannot target batch endpoint');
|
|
130
|
+
const itemMethod = normalizeMethod('string' == typeof rawItem.method ? rawItem.method : void 0);
|
|
131
|
+
if (!batchAllowedMethods.has(itemMethod)) return toBatchItemError(itemId, 405, `Batch item method ${itemMethod} is not allowed`);
|
|
132
|
+
if (void 0 !== rawItem.body && !isBatchBody(rawItem.body)) return toBatchItemError(itemId, 400, 'Batch item body must use the base64 body protocol');
|
|
133
|
+
if (('GET' === itemMethod || 'HEAD' === itemMethod) && void 0 !== rawItem.body) return toBatchItemError(itemId, 400, `${itemMethod} batch item cannot include body`);
|
|
134
|
+
const normalizedHeaders = {};
|
|
135
|
+
if (void 0 !== rawItem.headers) {
|
|
136
|
+
if (!isPlainObject(rawItem.headers)) return toBatchItemError(itemId, 400, 'Batch item headers must be an object');
|
|
137
|
+
for (const [key, value] of Object.entries(rawItem.headers)){
|
|
138
|
+
if ('string' != typeof value) return toBatchItemError(itemId, 400, `Invalid header "${key}" for batch item`);
|
|
139
|
+
normalizedHeaders[key.toLowerCase()] = value;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
const connectionScopedHeaders = new Set((normalizedHeaders.connection || '').split(',').map((header)=>header.trim().toLowerCase()).filter(Boolean));
|
|
143
|
+
for (const header of Object.keys(normalizedHeaders))if (TRANSPORT_CONTROLLED_BATCH_ITEM_HEADERS.has(header) || OUTER_BOUND_BATCH_ITEM_HEADERS.has(header) || connectionScopedHeaders.has(header)) delete normalizedHeaders[header];
|
|
144
|
+
if (!normalizedHeaders.traceparent) {
|
|
145
|
+
const encodedEnvelope = normalizedHeaders[normalizedEnvelopeHeader];
|
|
146
|
+
if ('string' == typeof encodedEnvelope) {
|
|
147
|
+
const envelope = decodeRequestEnvelopeHeader(encodedEnvelope);
|
|
148
|
+
if (envelope?.traceparent) normalizedHeaders.traceparent = envelope.traceparent;
|
|
149
|
+
}
|
|
150
|
+
}
|
|
151
|
+
for (const header of OUTER_BOUND_BATCH_ITEM_HEADERS){
|
|
152
|
+
const value = request.headers.get(header);
|
|
153
|
+
if (null !== value) normalizedHeaders[header] = value;
|
|
154
|
+
}
|
|
155
|
+
if (!normalizedHeaders.traceparent) {
|
|
156
|
+
const requestTraceparent = request.headers.get('traceparent');
|
|
157
|
+
if (requestTraceparent) normalizedHeaders.traceparent = requestTraceparent;
|
|
158
|
+
}
|
|
159
|
+
const targetUrl = new URL(normalizedItemPath, request.url);
|
|
160
|
+
if (targetUrl.origin !== batchRequestOrigin) return toBatchItemError(itemId, 400, 'Batch item path must stay on the same origin');
|
|
161
|
+
let requestHeaders;
|
|
162
|
+
try {
|
|
163
|
+
requestHeaders = new Headers(normalizedHeaders);
|
|
164
|
+
} catch {
|
|
165
|
+
return toBatchItemError(itemId, 400, 'Invalid batch item headers');
|
|
166
|
+
}
|
|
167
|
+
const body = 'GET' === itemMethod || 'HEAD' === itemMethod ? void 0 : void 0 === rawItem.body ? void 0 : decodeBatchBody(rawItem.body);
|
|
168
|
+
if (void 0 === body) requestHeaders.delete('content-type');
|
|
169
|
+
const itemAbortController = new AbortController();
|
|
170
|
+
const abortFromBatchRequest = ()=>itemAbortController.abort(request.signal.reason);
|
|
171
|
+
if (request.signal.aborted) abortFromBatchRequest();
|
|
172
|
+
else request.signal.addEventListener('abort', abortFromBatchRequest, {
|
|
173
|
+
once: true
|
|
174
|
+
});
|
|
175
|
+
const itemRequest = new Request(targetUrl.toString(), {
|
|
176
|
+
method: itemMethod,
|
|
177
|
+
headers: requestHeaders,
|
|
178
|
+
body,
|
|
179
|
+
signal: itemAbortController.signal
|
|
180
|
+
});
|
|
181
|
+
try {
|
|
182
|
+
const itemResponse = await promiseWithTimeout(options.handleItem(itemRequest, context), batchItemTimeoutMs, (error)=>itemAbortController.abort(error));
|
|
183
|
+
if (!(itemResponse instanceof Response)) return toBatchItemError(itemId, 500, 'Invalid response returned by batch item handler');
|
|
184
|
+
return toBatchResponseItem(itemId, itemResponse, 'HEAD' === itemMethod);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
if (error instanceof BatchItemTimeoutError) {
|
|
187
|
+
console.error({
|
|
188
|
+
event: 'bff.batch.item.timeout',
|
|
189
|
+
batchId: payload.batchId,
|
|
190
|
+
itemId,
|
|
191
|
+
method: itemMethod,
|
|
192
|
+
path: itemPathname,
|
|
193
|
+
errorName: error.name
|
|
194
|
+
});
|
|
195
|
+
return toBatchItemError(itemId, 504, 'Batch item request timed out');
|
|
196
|
+
}
|
|
197
|
+
if (error instanceof Response) return toBatchResponseItem(itemId, error, 'HEAD' === itemMethod);
|
|
198
|
+
console.error({
|
|
199
|
+
event: 'bff.batch.item.failure',
|
|
200
|
+
batchId: payload.batchId,
|
|
201
|
+
itemId,
|
|
202
|
+
method: itemMethod,
|
|
203
|
+
path: itemPathname,
|
|
204
|
+
errorName: error instanceof Error ? error.name : 'UnknownError'
|
|
205
|
+
});
|
|
206
|
+
return toBatchItemError(itemId, 500, 'Internal Server Error');
|
|
207
|
+
} finally{
|
|
208
|
+
request.signal.removeEventListener('abort', abortFromBatchRequest);
|
|
209
|
+
}
|
|
210
|
+
});
|
|
211
|
+
const responsePayload = {
|
|
212
|
+
protocolVersion: 2,
|
|
213
|
+
batchId: payload.batchId,
|
|
214
|
+
receivedAt: Date.now(),
|
|
215
|
+
items: responseItems
|
|
216
|
+
};
|
|
217
|
+
return new Response(JSON.stringify(responsePayload), {
|
|
218
|
+
status: 200,
|
|
219
|
+
headers: {
|
|
220
|
+
'content-type': 'application/json; charset=utf-8',
|
|
221
|
+
[DEFAULT_DATA_BATCH_HEADER]: '2',
|
|
222
|
+
'x-modernjs-data-batch-id': payload.batchId
|
|
223
|
+
}
|
|
224
|
+
});
|
|
225
|
+
};
|
|
226
|
+
return {
|
|
227
|
+
enabled: batchEnabled,
|
|
228
|
+
path: batchPath,
|
|
229
|
+
handle
|
|
230
|
+
};
|
|
231
|
+
}
|
|
232
|
+
export { createDataPlatformBatchRequestHandler };
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { DEFAULT_DATA_BATCH_ENDPOINT, isPlainObject, normalizeMethod } from "../../data-platform/index.mjs";
|
|
2
|
+
import { encodeBatchText } from "../../data-platform/batch/protocol.mjs";
|
|
3
|
+
function normalizeBatchPath(pathname) {
|
|
4
|
+
if (!pathname || '/' === pathname) return DEFAULT_DATA_BATCH_ENDPOINT;
|
|
5
|
+
if (!pathname.startsWith('/')) return `/${pathname}`;
|
|
6
|
+
return pathname;
|
|
7
|
+
}
|
|
8
|
+
function normalizeBatchAllowedMethods(allowedMethods) {
|
|
9
|
+
const source = Array.isArray(allowedMethods) && allowedMethods.length > 0 ? allowedMethods : [
|
|
10
|
+
'GET'
|
|
11
|
+
];
|
|
12
|
+
return new Set(source.map((method)=>method.toUpperCase()));
|
|
13
|
+
}
|
|
14
|
+
function isBatchRequestPayload(value) {
|
|
15
|
+
return isPlainObject(value) && 2 === value.protocolVersion && 'string' == typeof value.batchId && 'number' == typeof value.sentAt && Array.isArray(value.items);
|
|
16
|
+
}
|
|
17
|
+
function createBatchValidationResponse(message, status = 400) {
|
|
18
|
+
return new Response(JSON.stringify({
|
|
19
|
+
message
|
|
20
|
+
}), {
|
|
21
|
+
status,
|
|
22
|
+
headers: {
|
|
23
|
+
'content-type': 'application/json; charset=utf-8'
|
|
24
|
+
}
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
function cloneWithoutJsonBodyHeaders(request) {
|
|
28
|
+
const headers = new Headers(request.headers);
|
|
29
|
+
headers.delete('content-type');
|
|
30
|
+
headers.delete('content-length');
|
|
31
|
+
return new Request(request.url, {
|
|
32
|
+
method: request.method,
|
|
33
|
+
headers,
|
|
34
|
+
signal: request.signal
|
|
35
|
+
});
|
|
36
|
+
}
|
|
37
|
+
async function prepareJsonRequestBody(request) {
|
|
38
|
+
const method = normalizeMethod(request.method);
|
|
39
|
+
if ('GET' === method || 'HEAD' === method) return request;
|
|
40
|
+
const contentType = (request.headers.get('content-type') || '').toLowerCase();
|
|
41
|
+
if (!contentType.includes('application/json')) return request;
|
|
42
|
+
if (null === request.body) return cloneWithoutJsonBodyHeaders(request);
|
|
43
|
+
try {
|
|
44
|
+
const bodyText = await request.clone().text();
|
|
45
|
+
if ('' === bodyText) return cloneWithoutJsonBodyHeaders(request);
|
|
46
|
+
JSON.parse(bodyText);
|
|
47
|
+
} catch {
|
|
48
|
+
return createBatchValidationResponse('Invalid JSON request body');
|
|
49
|
+
}
|
|
50
|
+
return request;
|
|
51
|
+
}
|
|
52
|
+
function toBatchItemError(id, status, message) {
|
|
53
|
+
return {
|
|
54
|
+
id,
|
|
55
|
+
status,
|
|
56
|
+
headers: [
|
|
57
|
+
[
|
|
58
|
+
'content-type',
|
|
59
|
+
'application/json; charset=utf-8'
|
|
60
|
+
]
|
|
61
|
+
],
|
|
62
|
+
body: encodeBatchText(JSON.stringify({
|
|
63
|
+
message
|
|
64
|
+
}))
|
|
65
|
+
};
|
|
66
|
+
}
|
|
67
|
+
class BatchItemTimeoutError extends Error {
|
|
68
|
+
}
|
|
69
|
+
function promiseWithTimeout(effect, timeoutMs, onTimeout) {
|
|
70
|
+
if (timeoutMs <= 0) return effect;
|
|
71
|
+
return new Promise((resolve, reject)=>{
|
|
72
|
+
const timer = setTimeout(()=>{
|
|
73
|
+
const error = new BatchItemTimeoutError(`Batch item timeout after ${String(timeoutMs)}ms`);
|
|
74
|
+
onTimeout?.(error);
|
|
75
|
+
reject(error);
|
|
76
|
+
}, timeoutMs);
|
|
77
|
+
effect.then((value)=>{
|
|
78
|
+
clearTimeout(timer);
|
|
79
|
+
resolve(value);
|
|
80
|
+
}, (error)=>{
|
|
81
|
+
clearTimeout(timer);
|
|
82
|
+
reject(error);
|
|
83
|
+
});
|
|
84
|
+
});
|
|
85
|
+
}
|
|
86
|
+
async function mapWithConcurrency(items, concurrency, mapper) {
|
|
87
|
+
if (0 === items.length) return [];
|
|
88
|
+
const normalizedConcurrency = Math.max(1, concurrency);
|
|
89
|
+
const output = new Array(items.length);
|
|
90
|
+
let index = 0;
|
|
91
|
+
const workers = Array.from({
|
|
92
|
+
length: Math.min(normalizedConcurrency, items.length)
|
|
93
|
+
}, async ()=>{
|
|
94
|
+
while(true){
|
|
95
|
+
const currentIndex = index;
|
|
96
|
+
index += 1;
|
|
97
|
+
if (currentIndex >= items.length) return;
|
|
98
|
+
output[currentIndex] = await mapper(items[currentIndex], currentIndex);
|
|
99
|
+
}
|
|
100
|
+
});
|
|
101
|
+
await Promise.all(workers);
|
|
102
|
+
return output;
|
|
103
|
+
}
|
|
104
|
+
export { toHeaderRecord } from "../../headers.mjs";
|
|
105
|
+
export { BatchItemTimeoutError, createBatchValidationResponse, isBatchRequestPayload, mapWithConcurrency, normalizeBatchAllowedMethods, normalizeBatchPath, prepareJsonRequestBody, promiseWithTimeout, toBatchItemError };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import { registerValidatorAwareHandlerFactory } from "../entry-shape.mjs";
|
|
2
|
+
import { mergeDataPlatformOptions } from "./envelope.mjs";
|
|
3
|
+
import { createHttpApiHandler } from "./http.mjs";
|
|
4
|
+
import { createRpcApiHandler } from "./rpc.mjs";
|
|
5
|
+
function defineEffectBff(definition) {
|
|
6
|
+
const createHandler = registerValidatorAwareHandlerFactory((options)=>{
|
|
7
|
+
const rpcDefinition = definition.rpc;
|
|
8
|
+
let mergedRpcOptions = rpcDefinition;
|
|
9
|
+
if (rpcDefinition && options?.rpc) mergedRpcOptions = {
|
|
10
|
+
...rpcDefinition,
|
|
11
|
+
...options.rpc
|
|
12
|
+
};
|
|
13
|
+
return createHttpApiHandler({
|
|
14
|
+
api: definition.api,
|
|
15
|
+
layer: definition.layer,
|
|
16
|
+
openapi: options?.openapi,
|
|
17
|
+
rpc: mergedRpcOptions,
|
|
18
|
+
dataPlatform: mergeDataPlatformOptions(definition.dataPlatform, options?.dataPlatform),
|
|
19
|
+
interceptRequest: definition.interceptRequest,
|
|
20
|
+
validateRequest: options?.validateRequest
|
|
21
|
+
});
|
|
22
|
+
});
|
|
23
|
+
const client = createLoaderMaterializedClientPlaceholder();
|
|
24
|
+
return {
|
|
25
|
+
...definition,
|
|
26
|
+
createHandler,
|
|
27
|
+
client
|
|
28
|
+
};
|
|
29
|
+
}
|
|
30
|
+
const LOADER_CLIENT_IGNORED_KEYS = new Set([
|
|
31
|
+
'then',
|
|
32
|
+
'catch',
|
|
33
|
+
'finally',
|
|
34
|
+
'toJSON',
|
|
35
|
+
'$$typeof'
|
|
36
|
+
]);
|
|
37
|
+
function createLoaderMaterializedClientPlaceholder() {
|
|
38
|
+
const explain = (property)=>{
|
|
39
|
+
throw new Error(`[BFF][Effect] client.${String(property)} is not available here: the typed client only exists when the API entry is imported through the "@api/index" transformed path (the BFF loader replaces it with generated client code). On the server, use HttpApiClient or call the Effect layer directly.`);
|
|
40
|
+
};
|
|
41
|
+
return new Proxy(Object.create(null), {
|
|
42
|
+
get (_target, property) {
|
|
43
|
+
if ('symbol' == typeof property || LOADER_CLIENT_IGNORED_KEYS.has(property)) return;
|
|
44
|
+
return explain(property);
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
function defineEffectRpcBff(definition) {
|
|
49
|
+
const createHandler = (options)=>createRpcApiHandler({
|
|
50
|
+
...definition,
|
|
51
|
+
...options
|
|
52
|
+
});
|
|
53
|
+
return {
|
|
54
|
+
...definition,
|
|
55
|
+
createHandler
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
export { defineEffectBff, defineEffectRpcBff };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
import { DEFAULT_DATA_ENVELOPE_HEADER, decodeRequestEnvelopeHeader, validateRequestEnvelope, validateSelectionPlan } from "../../data-platform/index.mjs";
|
|
2
|
+
import { getExpectedEnvelopeOrigin } from "./routing.mjs";
|
|
3
|
+
function createInvalidEnvelopeResponse(message, errors) {
|
|
4
|
+
return new Response(JSON.stringify({
|
|
5
|
+
message,
|
|
6
|
+
...errors && errors.length > 0 ? {
|
|
7
|
+
errors
|
|
8
|
+
} : {}
|
|
9
|
+
}), {
|
|
10
|
+
status: 400,
|
|
11
|
+
headers: {
|
|
12
|
+
'content-type': 'application/json; charset=utf-8'
|
|
13
|
+
}
|
|
14
|
+
});
|
|
15
|
+
}
|
|
16
|
+
function validateDataPlatformRequestEnvelope(request, options) {
|
|
17
|
+
const isEnabled = options?.enabled ?? true;
|
|
18
|
+
if (!isEnabled) return null;
|
|
19
|
+
const envelopeHeader = options?.envelopeHeader || DEFAULT_DATA_ENVELOPE_HEADER;
|
|
20
|
+
const encodedEnvelope = request.headers.get(envelopeHeader);
|
|
21
|
+
if (!encodedEnvelope) {
|
|
22
|
+
if (options?.requireEnvelope) return createInvalidEnvelopeResponse(`Missing required data envelope header: ${envelopeHeader}`);
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
const envelope = decodeRequestEnvelopeHeader(encodedEnvelope);
|
|
26
|
+
if (!envelope) return createInvalidEnvelopeResponse(`Invalid data envelope header format: ${envelopeHeader}`);
|
|
27
|
+
const validation = validateRequestEnvelope(envelope, {
|
|
28
|
+
expectedProtocolVersion: 1,
|
|
29
|
+
expectedNamespace: options?.expectedNamespace,
|
|
30
|
+
expectedOrigin: options?.validateOrigin === false ? void 0 : getExpectedEnvelopeOrigin(request),
|
|
31
|
+
requireTraceContext: options?.requireTraceContext
|
|
32
|
+
});
|
|
33
|
+
if (!validation.ok) return createInvalidEnvelopeResponse('Invalid data envelope', validation.errors);
|
|
34
|
+
if (envelope.selectionPlan) {
|
|
35
|
+
const selectionValidation = validateSelectionPlan(envelope.selectionPlan, {
|
|
36
|
+
maxDepth: options?.selection?.maxDepth,
|
|
37
|
+
maxFields: options?.selection?.maxFields,
|
|
38
|
+
allowedLeafPaths: options?.selection?.allowedLeafPaths
|
|
39
|
+
});
|
|
40
|
+
if (!selectionValidation.ok) return createInvalidEnvelopeResponse('Invalid data envelope selection plan', selectionValidation.errors);
|
|
41
|
+
}
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
function mergeDataPlatformOptions(base, override) {
|
|
45
|
+
if (!base && !override) return;
|
|
46
|
+
const baseSelection = base?.selection;
|
|
47
|
+
const overrideSelection = override?.selection;
|
|
48
|
+
const baseBatch = base?.batch;
|
|
49
|
+
const overrideBatch = override?.batch;
|
|
50
|
+
return {
|
|
51
|
+
...base,
|
|
52
|
+
...override,
|
|
53
|
+
selection: baseSelection || overrideSelection ? {
|
|
54
|
+
...baseSelection,
|
|
55
|
+
...overrideSelection
|
|
56
|
+
} : void 0,
|
|
57
|
+
batch: baseBatch || overrideBatch ? {
|
|
58
|
+
...baseBatch,
|
|
59
|
+
...overrideBatch
|
|
60
|
+
} : void 0
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
export { mergeDataPlatformOptions, validateDataPlatformRequestEnvelope };
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import { HttpRouter, HttpServer } from "effect/unstable/http";
|
|
2
|
+
import { prepareJsonRequestBody } from "./batch.mjs";
|
|
3
|
+
import { createDataPlatformBatchRequestHandler } from "./batch-handler.mjs";
|
|
4
|
+
import { validateDataPlatformRequestEnvelope } from "./envelope.mjs";
|
|
5
|
+
import { createOpenApiLayer } from "./openapi.mjs";
|
|
6
|
+
import { getRequestPathname, isRpcRequest } from "./routing.mjs";
|
|
7
|
+
import { createRpcApiHandler, normalizeRpcPath } from "./rpc.mjs";
|
|
8
|
+
import { toEffectServiceContext } from "./types.mjs";
|
|
9
|
+
import * as __rspack_external_effect_Layer_69c46453 from "effect/Layer";
|
|
10
|
+
function createHttpApiHandler(options) {
|
|
11
|
+
const apiLayer = options.layer.pipe(__rspack_external_effect_Layer_69c46453.provide(HttpServer.layerServices));
|
|
12
|
+
const openApiLayer = createOpenApiLayer(options.api, options.openapi);
|
|
13
|
+
const mergedLayer = openApiLayer ? __rspack_external_effect_Layer_69c46453.mergeAll(apiLayer, openApiLayer) : apiLayer;
|
|
14
|
+
const httpApiHandler = HttpRouter.toWebHandler(mergedLayer);
|
|
15
|
+
const dispatchHttpApiRequest = async (request, context)=>{
|
|
16
|
+
const preparedRequest = await prepareJsonRequestBody(request);
|
|
17
|
+
if (preparedRequest instanceof Response) return preparedRequest;
|
|
18
|
+
const validationError = validateDataPlatformRequestEnvelope(preparedRequest, options.dataPlatform);
|
|
19
|
+
if (validationError) return validationError;
|
|
20
|
+
return httpApiHandler.handler(preparedRequest, toEffectServiceContext(context));
|
|
21
|
+
};
|
|
22
|
+
const withRequestPolicy = async (request, context)=>{
|
|
23
|
+
const policyDenial = options.validateRequest?.(request);
|
|
24
|
+
if (policyDenial) return policyDenial;
|
|
25
|
+
const next = ()=>dispatchHttpApiRequest(request, context);
|
|
26
|
+
return options.interceptRequest ? options.interceptRequest({
|
|
27
|
+
request,
|
|
28
|
+
next
|
|
29
|
+
}) : next();
|
|
30
|
+
};
|
|
31
|
+
const batchHandler = createDataPlatformBatchRequestHandler({
|
|
32
|
+
dataPlatform: options.dataPlatform,
|
|
33
|
+
handleItem: withRequestPolicy
|
|
34
|
+
});
|
|
35
|
+
const handleHttpApiRequest = async (request, context)=>{
|
|
36
|
+
const pathname = getRequestPathname(request);
|
|
37
|
+
if (batchHandler.enabled && pathname === batchHandler.path) return batchHandler.handle(request, context);
|
|
38
|
+
return withRequestPolicy(request, context);
|
|
39
|
+
};
|
|
40
|
+
if (!options.rpc) return {
|
|
41
|
+
handler: handleHttpApiRequest,
|
|
42
|
+
dispose: async ()=>{
|
|
43
|
+
await httpApiHandler.dispose();
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
const rpcPath = normalizeRpcPath(options.rpc.path);
|
|
47
|
+
const rpcHandler = createRpcApiHandler(options.rpc);
|
|
48
|
+
return {
|
|
49
|
+
handler: async (request, context)=>{
|
|
50
|
+
if (isRpcRequest(request, rpcPath)) {
|
|
51
|
+
const policyDenial = options.validateRequest?.(request);
|
|
52
|
+
if (policyDenial) return policyDenial;
|
|
53
|
+
const next = ()=>rpcHandler.handler(request, toEffectServiceContext(context));
|
|
54
|
+
return options.interceptRequest ? options.interceptRequest({
|
|
55
|
+
request,
|
|
56
|
+
next
|
|
57
|
+
}) : next();
|
|
58
|
+
}
|
|
59
|
+
return handleHttpApiRequest(request, context);
|
|
60
|
+
},
|
|
61
|
+
dispose: async ()=>{
|
|
62
|
+
await Promise.all([
|
|
63
|
+
httpApiHandler.dispose(),
|
|
64
|
+
rpcHandler.dispose()
|
|
65
|
+
]);
|
|
66
|
+
}
|
|
67
|
+
};
|
|
68
|
+
}
|
|
69
|
+
export { createHttpApiHandler };
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { HttpRouter, HttpServerResponse } from "effect/unstable/http";
|
|
2
|
+
import { OpenApi } from "effect/unstable/httpapi";
|
|
3
|
+
const DEFAULT_OPENAPI_PATH = '/openapi.json';
|
|
4
|
+
function normalizeOpenApiPath(pathname) {
|
|
5
|
+
if (!pathname.startsWith('/')) return `/${pathname}`;
|
|
6
|
+
return pathname;
|
|
7
|
+
}
|
|
8
|
+
function getOpenApiOptions(openapi) {
|
|
9
|
+
if (false === openapi || void 0 === openapi) return;
|
|
10
|
+
const path = true === openapi ? DEFAULT_OPENAPI_PATH : openapi.path;
|
|
11
|
+
return {
|
|
12
|
+
path: normalizeOpenApiPath(path ?? DEFAULT_OPENAPI_PATH)
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
function createOpenApiLayer(api, openapi) {
|
|
16
|
+
const openApiOptions = getOpenApiOptions(openapi);
|
|
17
|
+
if (!openApiOptions) return null;
|
|
18
|
+
return HttpRouter.add('GET', openApiOptions.path, HttpServerResponse.jsonUnsafe(OpenApi.fromApi(api)));
|
|
19
|
+
}
|
|
20
|
+
export { createOpenApiLayer };
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { isPlainObject } from "../../data-platform/index.mjs";
|
|
2
|
+
function getRequestPathname(request) {
|
|
3
|
+
try {
|
|
4
|
+
return new URL(request.url).pathname;
|
|
5
|
+
} catch {
|
|
6
|
+
return new URL(request.url, 'http://localhost').pathname;
|
|
7
|
+
}
|
|
8
|
+
}
|
|
9
|
+
function normalizeMountPrefix(prefix) {
|
|
10
|
+
if (!prefix || '/' === prefix) return '';
|
|
11
|
+
return prefix.endsWith('/') ? prefix.slice(0, -1) : prefix;
|
|
12
|
+
}
|
|
13
|
+
function getMountedPrefixFromContext(request, context) {
|
|
14
|
+
if (!isPlainObject(context) || 'string' != typeof context.path) return '';
|
|
15
|
+
const contextPath = normalizeMountPrefix(context.path);
|
|
16
|
+
const requestPath = normalizeMountPrefix(getRequestPathname(request));
|
|
17
|
+
if (!contextPath || !requestPath || contextPath === requestPath || !contextPath.endsWith(requestPath)) return '';
|
|
18
|
+
return normalizeMountPrefix(contextPath.slice(0, contextPath.length - requestPath.length));
|
|
19
|
+
}
|
|
20
|
+
function removeMountedPrefixFromBatchPath(pathWithQuery, prefix) {
|
|
21
|
+
const normalizedPrefix = normalizeMountPrefix(prefix);
|
|
22
|
+
if (!normalizedPrefix) return pathWithQuery;
|
|
23
|
+
const [pathname, ...queryParts] = pathWithQuery.split('?');
|
|
24
|
+
if (!pathname) return pathWithQuery;
|
|
25
|
+
let nextPathname = pathname;
|
|
26
|
+
if (pathname === normalizedPrefix) nextPathname = '/';
|
|
27
|
+
else if (pathname.startsWith(`${normalizedPrefix}/`)) {
|
|
28
|
+
const sliced = pathname.slice(normalizedPrefix.length);
|
|
29
|
+
nextPathname = sliced.startsWith('/') ? sliced : `/${sliced}`;
|
|
30
|
+
}
|
|
31
|
+
if (0 === queryParts.length) return nextPathname;
|
|
32
|
+
return `${nextPathname}?${queryParts.join('?')}`;
|
|
33
|
+
}
|
|
34
|
+
function getRequestOrigin(request) {
|
|
35
|
+
try {
|
|
36
|
+
return new URL(request.url).origin;
|
|
37
|
+
} catch {
|
|
38
|
+
return new URL(request.url, 'http://localhost').origin;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
function getExpectedEnvelopeOrigin(request) {
|
|
42
|
+
const origin = request.headers.get('origin');
|
|
43
|
+
if (origin && 'null' !== origin) return origin;
|
|
44
|
+
return getRequestOrigin(request);
|
|
45
|
+
}
|
|
46
|
+
function isRpcRequest(request, rpcPath) {
|
|
47
|
+
const pathname = getRequestPathname(request);
|
|
48
|
+
return pathname === rpcPath || pathname.startsWith(`${rpcPath}/`);
|
|
49
|
+
}
|
|
50
|
+
export { getExpectedEnvelopeOrigin, getMountedPrefixFromContext, getRequestPathname, isRpcRequest, removeMountedPrefixFromBatchPath };
|