@bleedingdev/modern-js-bff-core 3.2.0-ultramodern.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +26 -0
- package/dist/cjs/api.js +88 -0
- package/dist/cjs/client/generateClient.js +136 -0
- package/dist/cjs/client/index.js +58 -0
- package/dist/cjs/client/result.js +56 -0
- package/dist/cjs/compatible.js +18 -0
- package/dist/cjs/contracts/eventContracts.js +68 -0
- package/dist/cjs/errors/http.js +50 -0
- package/dist/cjs/index.js +229 -0
- package/dist/cjs/operators/http.js +220 -0
- package/dist/cjs/router/constants.js +68 -0
- package/dist/cjs/router/index.js +284 -0
- package/dist/cjs/router/types.js +18 -0
- package/dist/cjs/router/utils.js +97 -0
- package/dist/cjs/security/crossProjectPolicy.js +137 -0
- package/dist/cjs/security/operationContracts.js +100 -0
- package/dist/cjs/types.js +88 -0
- package/dist/cjs/utils/alias.js +108 -0
- package/dist/cjs/utils/debug.js +37 -0
- package/dist/cjs/utils/index.js +101 -0
- package/dist/cjs/utils/meta.js +48 -0
- package/dist/cjs/utils/storage.js +64 -0
- package/dist/cjs/utils/validate.js +82 -0
- package/dist/esm/api.mjs +44 -0
- package/dist/esm/client/generateClient.mjs +99 -0
- package/dist/esm/client/index.mjs +1 -0
- package/dist/esm/client/result.mjs +19 -0
- package/dist/esm/compatible.mjs +0 -0
- package/dist/esm/contracts/eventContracts.mjs +28 -0
- package/dist/esm/errors/http.mjs +13 -0
- package/dist/esm/index.mjs +10 -0
- package/dist/esm/operators/http.mjs +135 -0
- package/dist/esm/router/constants.mjs +19 -0
- package/dist/esm/router/index.mjs +192 -0
- package/dist/esm/router/types.mjs +0 -0
- package/dist/esm/router/utils.mjs +41 -0
- package/dist/esm/security/crossProjectPolicy.mjs +94 -0
- package/dist/esm/security/operationContracts.mjs +57 -0
- package/dist/esm/types.mjs +39 -0
- package/dist/esm/utils/alias.mjs +57 -0
- package/dist/esm/utils/debug.mjs +3 -0
- package/dist/esm/utils/index.mjs +5 -0
- package/dist/esm/utils/meta.mjs +5 -0
- package/dist/esm/utils/storage.mjs +30 -0
- package/dist/esm/utils/validate.mjs +32 -0
- package/dist/esm-node/api.mjs +45 -0
- package/dist/esm-node/client/generateClient.mjs +101 -0
- package/dist/esm-node/client/index.mjs +2 -0
- package/dist/esm-node/client/result.mjs +20 -0
- package/dist/esm-node/compatible.mjs +1 -0
- package/dist/esm-node/contracts/eventContracts.mjs +29 -0
- package/dist/esm-node/errors/http.mjs +14 -0
- package/dist/esm-node/index.mjs +11 -0
- package/dist/esm-node/operators/http.mjs +136 -0
- package/dist/esm-node/router/constants.mjs +20 -0
- package/dist/esm-node/router/index.mjs +193 -0
- package/dist/esm-node/router/types.mjs +1 -0
- package/dist/esm-node/router/utils.mjs +42 -0
- package/dist/esm-node/security/crossProjectPolicy.mjs +95 -0
- package/dist/esm-node/security/operationContracts.mjs +58 -0
- package/dist/esm-node/types.mjs +40 -0
- package/dist/esm-node/utils/alias.mjs +58 -0
- package/dist/esm-node/utils/debug.mjs +4 -0
- package/dist/esm-node/utils/index.mjs +6 -0
- package/dist/esm-node/utils/meta.mjs +6 -0
- package/dist/esm-node/utils/storage.mjs +31 -0
- package/dist/esm-node/utils/validate.mjs +33 -0
- package/dist/types/api.d.ts +6 -0
- package/dist/types/client/generateClient.d.ts +21 -0
- package/dist/types/client/index.d.ts +1 -0
- package/dist/types/client/result.d.ts +15 -0
- package/dist/types/compatible.d.ts +9 -0
- package/dist/types/contracts/eventContracts.d.ts +22 -0
- package/dist/types/errors/http.d.ts +8 -0
- package/dist/types/index.d.ts +11 -0
- package/dist/types/operators/http.d.ts +44 -0
- package/dist/types/router/constants.d.ts +6 -0
- package/dist/types/router/index.d.ts +49 -0
- package/dist/types/router/types.d.ts +18 -0
- package/dist/types/router/utils.d.ts +10 -0
- package/dist/types/security/crossProjectPolicy.d.ts +30 -0
- package/dist/types/security/operationContracts.d.ts +28 -0
- package/dist/types/types.d.ts +64 -0
- package/dist/types/utils/alias.d.ts +7 -0
- package/dist/types/utils/debug.d.ts +1 -0
- package/dist/types/utils/index.d.ts +5 -0
- package/dist/types/utils/meta.d.ts +4 -0
- package/dist/types/utils/storage.d.ts +5 -0
- package/dist/types/utils/validate.d.ts +5 -0
- package/package.json +68 -0
- package/rslib.config.mts +4 -0
- package/rstest.config.mts +10 -0
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { fs, logger } from "@modern-js/utils";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import "reflect-metadata";
|
|
5
|
+
import { HttpMethod, OperatorType, TriggerType, httpMethods } from "../types.mjs";
|
|
6
|
+
import { INPUT_PARAMS_DECIDER, debug } from "../utils/index.mjs";
|
|
7
|
+
import { API_FILE_RULES, FRAMEWORK_MODE_LAMBDA_DIR } from "./constants.mjs";
|
|
8
|
+
import { getFiles, getPathFromFilename, requireHandlerModule, sortRoutes } from "./utils.mjs";
|
|
9
|
+
export * from "./constants.mjs";
|
|
10
|
+
export * from "./types.mjs";
|
|
11
|
+
class ApiRouter {
|
|
12
|
+
isExistLambda() {
|
|
13
|
+
return this.existLambdaDir;
|
|
14
|
+
}
|
|
15
|
+
getLambdaDir() {
|
|
16
|
+
return this.lambdaDir;
|
|
17
|
+
}
|
|
18
|
+
isApiFile(filename) {
|
|
19
|
+
if (this.apiFiles.includes(filename)) return true;
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
async getSingleModuleHandlers(filename) {
|
|
23
|
+
const moduleInfo = await this.getModuleInfo(filename);
|
|
24
|
+
if (moduleInfo) return this.getModuleHandlerInfos(moduleInfo);
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
getHandlerInfo(filename, originFuncName, handler) {
|
|
28
|
+
const httpMethod = this.getHttpMethod(originFuncName, handler);
|
|
29
|
+
const routeName = this.getRouteName(filename, handler);
|
|
30
|
+
const action = this.getAction(handler);
|
|
31
|
+
const responseObj = {
|
|
32
|
+
handler,
|
|
33
|
+
name: originFuncName,
|
|
34
|
+
httpMethod,
|
|
35
|
+
routeName,
|
|
36
|
+
filename,
|
|
37
|
+
routePath: this.getRoutePath(this.prefix, routeName)
|
|
38
|
+
};
|
|
39
|
+
if (action) responseObj.action = action;
|
|
40
|
+
if (httpMethod && routeName) return responseObj;
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
getSafeRoutePath(filename, handler) {
|
|
44
|
+
this.loadApiFiles();
|
|
45
|
+
this.validateValidApifile(filename);
|
|
46
|
+
return this.getRouteName(filename, handler);
|
|
47
|
+
}
|
|
48
|
+
getRouteName(filename, handler) {
|
|
49
|
+
if (handler) {
|
|
50
|
+
const trigger = Reflect.getMetadata(OperatorType.Trigger, handler);
|
|
51
|
+
if (trigger && trigger.type === TriggerType.Http) {
|
|
52
|
+
if (!trigger.path) throw new Error(`The http trigger ${trigger.name} needs to specify a path`);
|
|
53
|
+
return trigger.path;
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
let routePath = getPathFromFilename(this.lambdaDir, filename);
|
|
57
|
+
if ('inputParams' === this.httpMethodDecider) if (routePath.endsWith('/')) routePath += `${handler?.name}`;
|
|
58
|
+
else routePath += `/${handler?.name}`;
|
|
59
|
+
return routePath;
|
|
60
|
+
}
|
|
61
|
+
getHttpMethod(originHandlerName, handler) {
|
|
62
|
+
if (handler) {
|
|
63
|
+
const trigger = Reflect.getMetadata(OperatorType.Trigger, handler);
|
|
64
|
+
if (trigger && httpMethods.includes(trigger.method)) return trigger.method;
|
|
65
|
+
}
|
|
66
|
+
if ('functionName' === this.httpMethodDecider) {
|
|
67
|
+
const upperName = originHandlerName.toUpperCase();
|
|
68
|
+
switch(upperName){
|
|
69
|
+
case 'GET':
|
|
70
|
+
return HttpMethod.Get;
|
|
71
|
+
case 'POST':
|
|
72
|
+
return HttpMethod.Post;
|
|
73
|
+
case 'PUT':
|
|
74
|
+
return HttpMethod.Put;
|
|
75
|
+
case 'DELETE':
|
|
76
|
+
case 'DEL':
|
|
77
|
+
return HttpMethod.Delete;
|
|
78
|
+
case 'CONNECT':
|
|
79
|
+
return HttpMethod.Connect;
|
|
80
|
+
case 'TRACE':
|
|
81
|
+
return HttpMethod.Trace;
|
|
82
|
+
case 'PATCH':
|
|
83
|
+
return HttpMethod.Patch;
|
|
84
|
+
case 'OPTIONS':
|
|
85
|
+
return HttpMethod.Options;
|
|
86
|
+
case 'DEFAULT':
|
|
87
|
+
return HttpMethod.Get;
|
|
88
|
+
default:
|
|
89
|
+
if ('test' !== process.env.NODE_ENV) logger.warn(`Only api handlers are allowd to be exported, please remove the function ${originHandlerName} from exports`);
|
|
90
|
+
return null;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
if (!handler) return null;
|
|
94
|
+
if ('function' == typeof handler && handler.length > 0) return HttpMethod.Post;
|
|
95
|
+
return HttpMethod.Get;
|
|
96
|
+
}
|
|
97
|
+
getAction(handler) {
|
|
98
|
+
if (handler) {
|
|
99
|
+
const trigger = Reflect.getMetadata(OperatorType.Trigger, handler);
|
|
100
|
+
if (trigger?.action) return trigger.action;
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
loadApiFiles() {
|
|
104
|
+
if (!this.existLambdaDir) return [];
|
|
105
|
+
const apiFiles = this.apiFiles = getFiles(this.lambdaDir, API_FILE_RULES);
|
|
106
|
+
return apiFiles;
|
|
107
|
+
}
|
|
108
|
+
getApiFiles() {
|
|
109
|
+
if (!this.existLambdaDir) return [];
|
|
110
|
+
if (this.apiFiles.length > 0) return this.apiFiles;
|
|
111
|
+
return this.loadApiFiles();
|
|
112
|
+
}
|
|
113
|
+
async getApiHandlers() {
|
|
114
|
+
const filenames = this.getApiFiles();
|
|
115
|
+
const moduleInfos = await this.getModuleInfos(filenames);
|
|
116
|
+
const apiHandlers = this.getHandlerInfos(moduleInfos);
|
|
117
|
+
debug('apiHandlers', apiHandlers.length, apiHandlers);
|
|
118
|
+
return apiHandlers;
|
|
119
|
+
}
|
|
120
|
+
initPrefix(prefix) {
|
|
121
|
+
if ('/' === prefix) return '';
|
|
122
|
+
return prefix || '/api';
|
|
123
|
+
}
|
|
124
|
+
validateAbsolute(filename, paramsName) {
|
|
125
|
+
if ('string' == typeof filename && !path.isAbsolute(filename)) throw new Error(`The ${paramsName} ${filename} is not a abolute path`);
|
|
126
|
+
}
|
|
127
|
+
async getModuleInfos(filenames) {
|
|
128
|
+
const moduleInfos = await Promise.all(filenames.map((filename)=>this.getModuleInfo(filename)));
|
|
129
|
+
return moduleInfos.filter(Boolean);
|
|
130
|
+
}
|
|
131
|
+
async getModuleInfo(filename) {
|
|
132
|
+
try {
|
|
133
|
+
const module = await requireHandlerModule(filename);
|
|
134
|
+
return {
|
|
135
|
+
filename,
|
|
136
|
+
module
|
|
137
|
+
};
|
|
138
|
+
} catch (err) {
|
|
139
|
+
if ('production' === process.env.NODE_ENV) {
|
|
140
|
+
const error = new Error(`Failed to load BFF module '${filename}': ${err.message}`, {
|
|
141
|
+
cause: err
|
|
142
|
+
});
|
|
143
|
+
throw error;
|
|
144
|
+
}
|
|
145
|
+
console.error(`Failed to load BFF module '${filename}':`, err);
|
|
146
|
+
return null;
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
getHandlerInfos(moduleInfos) {
|
|
150
|
+
let apiHandlers = [];
|
|
151
|
+
moduleInfos.forEach((moduleInfo)=>{
|
|
152
|
+
const handlerInfos = this.getModuleHandlerInfos(moduleInfo);
|
|
153
|
+
if (handlerInfos) apiHandlers = apiHandlers.concat(handlerInfos);
|
|
154
|
+
});
|
|
155
|
+
const sortedHandlers = sortRoutes(apiHandlers);
|
|
156
|
+
return sortedHandlers;
|
|
157
|
+
}
|
|
158
|
+
getModuleHandlerInfos(moduleInfo) {
|
|
159
|
+
const { module, filename } = moduleInfo;
|
|
160
|
+
const { httpMethodDecider } = this;
|
|
161
|
+
return Object.entries(module).filter(([, handler])=>'function' == typeof handler).map(([key])=>{
|
|
162
|
+
const handler = module[key];
|
|
163
|
+
if ('inputParams' === httpMethodDecider) Object.assign(handler, {
|
|
164
|
+
[INPUT_PARAMS_DECIDER]: true
|
|
165
|
+
});
|
|
166
|
+
const handlerInfo = this.getHandlerInfo(filename, key, handler);
|
|
167
|
+
return handlerInfo;
|
|
168
|
+
}).filter((handlerInfo)=>Boolean(handlerInfo));
|
|
169
|
+
}
|
|
170
|
+
validateValidApifile(filename) {
|
|
171
|
+
if (!this.apiFiles.includes(filename)) throw new Error(`The ${filename} is not a valid api file.`);
|
|
172
|
+
}
|
|
173
|
+
getRoutePath(prefix, routeName) {
|
|
174
|
+
const finalRouteName = '/' === routeName ? '' : routeName;
|
|
175
|
+
if ('' === prefix && '' === finalRouteName) return '/';
|
|
176
|
+
return `${prefix}${finalRouteName}`;
|
|
177
|
+
}
|
|
178
|
+
constructor({ appDir, apiDir, lambdaDir, prefix, isBuild, httpMethodDecider = 'functionName' }){
|
|
179
|
+
this.apiFiles = [];
|
|
180
|
+
this.getExactLambdaDir = (apiDir, originLambdaDir)=>originLambdaDir || path.join(apiDir, FRAMEWORK_MODE_LAMBDA_DIR);
|
|
181
|
+
this.validateAbsolute(apiDir, 'apiDir');
|
|
182
|
+
this.validateAbsolute(lambdaDir, 'lambdaDir');
|
|
183
|
+
this.prefix = this.initPrefix(prefix);
|
|
184
|
+
this.appDir = appDir;
|
|
185
|
+
this.apiDir = apiDir;
|
|
186
|
+
this.httpMethodDecider = httpMethodDecider;
|
|
187
|
+
this.isBuild = isBuild;
|
|
188
|
+
this.lambdaDir = this.getExactLambdaDir(this.apiDir, lambdaDir);
|
|
189
|
+
this.existLambdaDir = fs.existsSync(this.lambdaDir);
|
|
190
|
+
debug("apiDir:", this.apiDir, "lambdaDir:", this.lambdaDir);
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
export { ApiRouter };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import "node:module";
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { compatibleRequire, globby } from "@modern-js/utils";
|
|
3
|
+
import path from "path";
|
|
4
|
+
import { INDEX_SUFFIX } from "./constants.mjs";
|
|
5
|
+
const getFiles = (lambdaDir, rules)=>globby.sync(rules, {
|
|
6
|
+
cwd: lambdaDir,
|
|
7
|
+
gitignore: true
|
|
8
|
+
}).map((file)=>path.resolve(lambdaDir, file));
|
|
9
|
+
const getPathFromFilename = (baseDir, filename)=>{
|
|
10
|
+
const relativeName = filename.substring(baseDir.length);
|
|
11
|
+
const relativePath = relativeName.split('.').slice(0, -1).join('.');
|
|
12
|
+
const nameSplit = relativePath.split(path.sep).map((item)=>{
|
|
13
|
+
if (item.length > 2) {
|
|
14
|
+
if (item.startsWith('[') && item.endsWith(']')) return `:${item.substring(1, item.length - 1)}`;
|
|
15
|
+
}
|
|
16
|
+
return item;
|
|
17
|
+
});
|
|
18
|
+
const name = nameSplit.join('/');
|
|
19
|
+
const finalName = name.endsWith(INDEX_SUFFIX) ? name.substring(0, name.length - INDEX_SUFFIX.length) : name;
|
|
20
|
+
return clearRouteName(finalName);
|
|
21
|
+
};
|
|
22
|
+
const clearRouteName = (routeName)=>{
|
|
23
|
+
let finalRouteName = routeName.trim();
|
|
24
|
+
if (!finalRouteName.startsWith('/')) finalRouteName = `/${finalRouteName}`;
|
|
25
|
+
if (finalRouteName.length > 1 && finalRouteName.endsWith('/')) finalRouteName = finalRouteName.substring(0, finalRouteName.length - 1);
|
|
26
|
+
return finalRouteName;
|
|
27
|
+
};
|
|
28
|
+
const isHandler = (input)=>input && 'function' == typeof input;
|
|
29
|
+
const isFunction = (input)=>input && '[object Function]' === ({}).toString.call(input);
|
|
30
|
+
const requireHandlerModule = async (modulePath)=>{
|
|
31
|
+
const module = await compatibleRequire(modulePath, false);
|
|
32
|
+
if (isFunction(module)) return {
|
|
33
|
+
default: module
|
|
34
|
+
};
|
|
35
|
+
return module;
|
|
36
|
+
};
|
|
37
|
+
const routeValue = (routePath)=>{
|
|
38
|
+
if (routePath.includes(':')) return 11;
|
|
39
|
+
return 1;
|
|
40
|
+
};
|
|
41
|
+
const sortRoutes = (apiHandlers)=>apiHandlers.sort((handlerA, handlerB)=>routeValue(handlerA.routeName) - routeValue(handlerB.routeName));
|
|
42
|
+
export { getFiles, getPathFromFilename, isHandler, requireHandlerModule, sortRoutes };
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
const BFF_ENVELOPE_HEADER = 'x-modernjs-bff-envelope';
|
|
3
|
+
const BFF_OPERATION_CONTEXT_HEADER = 'x-operation-id';
|
|
4
|
+
const BFF_OPERATION_CONTEXT_DETAIL_HEADER = 'x-modernjs-bff-operation-context';
|
|
5
|
+
const DEFAULT_DENY_STATUS = 403;
|
|
6
|
+
const normalizeHeaderName = (headerName, fallback)=>(headerName || fallback).trim().toLowerCase();
|
|
7
|
+
const normalizeStatusCode = (statusCode)=>{
|
|
8
|
+
if ('number' == typeof statusCode && Number.isFinite(statusCode) && statusCode >= 400 && statusCode <= 599) return Math.floor(statusCode);
|
|
9
|
+
return DEFAULT_DENY_STATUS;
|
|
10
|
+
};
|
|
11
|
+
const readHeader = (headers, headerName)=>{
|
|
12
|
+
const lowerHeaderName = headerName.toLowerCase();
|
|
13
|
+
for (const [name, value] of Object.entries(headers || {}))if (name.toLowerCase() === lowerHeaderName) {
|
|
14
|
+
if (Array.isArray(value)) return value.length > 0 ? String(value[0]) : void 0;
|
|
15
|
+
if (null == value) return;
|
|
16
|
+
return String(value);
|
|
17
|
+
}
|
|
18
|
+
};
|
|
19
|
+
const extractNamespace = (requestId)=>requestId.split(/[/:.]/)[0]?.trim().toLowerCase();
|
|
20
|
+
const createViolation = (reason, message, status)=>({
|
|
21
|
+
code: 'BFF_CROSS_PROJECT_POLICY_DENIED',
|
|
22
|
+
reason,
|
|
23
|
+
message,
|
|
24
|
+
status
|
|
25
|
+
});
|
|
26
|
+
const evaluateCrossProjectPolicy = (headers, policy)=>{
|
|
27
|
+
if (!policy?.enabled) return null;
|
|
28
|
+
const status = normalizeStatusCode(policy.denyStatus);
|
|
29
|
+
const requireEnvelope = policy.requireEnvelope ?? true;
|
|
30
|
+
const requireOperationContext = policy.requireOperationContext ?? true;
|
|
31
|
+
const requireOperationContextDetails = policy.requireOperationContextDetails ?? true;
|
|
32
|
+
const requireOperationSchemaHash = policy.requireOperationSchemaHash ?? true;
|
|
33
|
+
const requireOperationVersion = policy.requireOperationVersion ?? true;
|
|
34
|
+
const allowUnknownOperations = policy.allowUnknownOperations ?? false;
|
|
35
|
+
const envelopeHeader = normalizeHeaderName(policy.envelopeHeader, BFF_ENVELOPE_HEADER);
|
|
36
|
+
const operationContextHeader = normalizeHeaderName(policy.operationContextHeader, BFF_OPERATION_CONTEXT_HEADER);
|
|
37
|
+
const operationContextDetailHeader = normalizeHeaderName(policy.operationContextDetailHeader, BFF_OPERATION_CONTEXT_DETAIL_HEADER);
|
|
38
|
+
const envelopeRaw = readHeader(headers, envelopeHeader);
|
|
39
|
+
if (!envelopeRaw) {
|
|
40
|
+
if (!requireEnvelope) return null;
|
|
41
|
+
return createViolation('missing_envelope', `Missing cross-project envelope header "${envelopeHeader}"`, status);
|
|
42
|
+
}
|
|
43
|
+
let envelope;
|
|
44
|
+
try {
|
|
45
|
+
const parsed = JSON.parse(envelopeRaw);
|
|
46
|
+
if (!parsed || 'object' != typeof parsed) throw new Error('invalid envelope object');
|
|
47
|
+
envelope = parsed;
|
|
48
|
+
} catch (_error) {
|
|
49
|
+
return createViolation('invalid_envelope', `Invalid cross-project envelope header "${envelopeHeader}"`, status);
|
|
50
|
+
}
|
|
51
|
+
const requestId = String(envelope.requestId || '').trim();
|
|
52
|
+
if (!requestId) return createViolation('missing_request_id', 'Cross-project envelope does not include a valid requestId', status);
|
|
53
|
+
const namespaces = (policy.allowedNamespaces || []).map((item)=>item.trim().toLowerCase()).filter(Boolean);
|
|
54
|
+
if (namespaces.length > 0) {
|
|
55
|
+
const namespace = extractNamespace(requestId);
|
|
56
|
+
if (!namespace || !namespaces.includes(namespace)) return createViolation('namespace_not_allowed', `Producer namespace "${namespace || 'unknown'}" is not allowed`, status);
|
|
57
|
+
}
|
|
58
|
+
if (requireOperationContext) {
|
|
59
|
+
const operationContext = readHeader(headers, operationContextHeader);
|
|
60
|
+
if (!operationContext) return createViolation('missing_operation_context', `Missing operation context header "${operationContextHeader}"`, status);
|
|
61
|
+
if (!operationContext.startsWith(`${requestId}:`)) return createViolation('operation_context_mismatch', `Operation context header "${operationContextHeader}" does not match requestId "${requestId}"`, status);
|
|
62
|
+
const operationContextDetailsRaw = readHeader(headers, operationContextDetailHeader);
|
|
63
|
+
if (!operationContextDetailsRaw) {
|
|
64
|
+
if (requireOperationContextDetails) return createViolation('missing_operation_context_details', `Missing operation context details header "${operationContextDetailHeader}"`, status);
|
|
65
|
+
return null;
|
|
66
|
+
}
|
|
67
|
+
let operationContextDetails;
|
|
68
|
+
try {
|
|
69
|
+
const parsed = JSON.parse(operationContextDetailsRaw);
|
|
70
|
+
if (!parsed || 'object' != typeof parsed || Array.isArray(parsed)) throw new Error('invalid operation context details object');
|
|
71
|
+
operationContextDetails = parsed;
|
|
72
|
+
} catch (_error) {
|
|
73
|
+
return createViolation('invalid_operation_context_details', `Invalid operation context details header "${operationContextDetailHeader}"`, status);
|
|
74
|
+
}
|
|
75
|
+
const detailRequestId = String(operationContextDetails.requestId || '').trim();
|
|
76
|
+
if (detailRequestId && detailRequestId !== requestId) return createViolation('operation_context_details_request_id_mismatch', `Operation context details requestId "${detailRequestId}" does not match envelope requestId "${requestId}"`, status);
|
|
77
|
+
const detailSchemaHash = String(operationContextDetails.schemaHash || '').trim();
|
|
78
|
+
if (requireOperationSchemaHash && !detailSchemaHash) return createViolation('missing_operation_schema_hash', `Operation context details header "${operationContextDetailHeader}" must include schemaHash`, status);
|
|
79
|
+
const detailOperationVersion = operationContextDetails.operationVersion;
|
|
80
|
+
if (requireOperationVersion && 'number' != typeof detailOperationVersion) return createViolation('missing_operation_version', `Operation context details header "${operationContextDetailHeader}" must include operationVersion`, status);
|
|
81
|
+
const expectedContracts = policy.expectedOperationContracts;
|
|
82
|
+
if (expectedContracts && 'object' == typeof expectedContracts && Object.keys(expectedContracts).length > 0) {
|
|
83
|
+
const method = String(operationContextDetails.method || '').toUpperCase();
|
|
84
|
+
const routePath = String(operationContextDetails.routePath || '').trim();
|
|
85
|
+
const operationId = String(operationContextDetails.operationId || '').trim();
|
|
86
|
+
const expectedContract = expectedContracts[`${method}:${routePath}`] || expectedContracts[`operation:${operationId}`];
|
|
87
|
+
if (expectedContract) {
|
|
88
|
+
if (expectedContract.schemaHash && detailSchemaHash && expectedContract.schemaHash !== detailSchemaHash) return createViolation('operation_schema_hash_mismatch', `Operation schema hash mismatch for "${operationId || `${method}:${routePath}`}"`, status);
|
|
89
|
+
if ('number' == typeof expectedContract.operationVersion && 'number' == typeof detailOperationVersion && expectedContract.operationVersion !== detailOperationVersion) return createViolation('operation_version_mismatch', `Operation version mismatch for "${operationId || `${method}:${routePath}`}"`, status);
|
|
90
|
+
} else if (!allowUnknownOperations) return createViolation('unknown_operation_contract', `No expected operation contract found for operation "${operationId || `${method}:${routePath}`}"`, status);
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
return null;
|
|
94
|
+
};
|
|
95
|
+
export { BFF_ENVELOPE_HEADER, BFF_OPERATION_CONTEXT_DETAIL_HEADER, BFF_OPERATION_CONTEXT_HEADER, evaluateCrossProjectPolicy };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { createHash } from "crypto";
|
|
3
|
+
const DEFAULT_OPERATION_VERSION = 1;
|
|
4
|
+
const createOperationEntries = (handlers)=>handlers.map((item)=>({
|
|
5
|
+
name: item.name,
|
|
6
|
+
httpMethod: String(item.httpMethod || '').toUpperCase(),
|
|
7
|
+
routePath: item.routePath
|
|
8
|
+
})).sort((a, b)=>{
|
|
9
|
+
const keyA = `${a.routePath}:${a.httpMethod}:${a.name}`;
|
|
10
|
+
const keyB = `${b.routePath}:${b.httpMethod}:${b.name}`;
|
|
11
|
+
return keyA.localeCompare(keyB);
|
|
12
|
+
});
|
|
13
|
+
const createOperationSchemaHash = (operationEntries, requestId)=>createHash('sha256').update(JSON.stringify({
|
|
14
|
+
operations: operationEntries.map((item)=>({
|
|
15
|
+
name: item.name,
|
|
16
|
+
httpMethod: item.httpMethod,
|
|
17
|
+
routePath: item.routePath
|
|
18
|
+
})),
|
|
19
|
+
requestId
|
|
20
|
+
})).digest('hex');
|
|
21
|
+
const buildOperationContractMap = ({ handlers, requestId })=>{
|
|
22
|
+
const normalizedRequestId = 'string' == typeof requestId && requestId.trim().length > 0 ? requestId.trim() : 'default';
|
|
23
|
+
const byModule = new Map();
|
|
24
|
+
handlers.forEach((item)=>{
|
|
25
|
+
const moduleId = 'string' == typeof item.filename && item.filename.length > 0 ? item.filename : '__anonymous__';
|
|
26
|
+
const group = byModule.get(moduleId) || [];
|
|
27
|
+
group.push({
|
|
28
|
+
name: item.name,
|
|
29
|
+
httpMethod: item.httpMethod.toUpperCase(),
|
|
30
|
+
routePath: item.routePath,
|
|
31
|
+
filename: item.filename
|
|
32
|
+
});
|
|
33
|
+
byModule.set(moduleId, group);
|
|
34
|
+
});
|
|
35
|
+
const contracts = {};
|
|
36
|
+
byModule.forEach((moduleEntries)=>{
|
|
37
|
+
const entries = createOperationEntries(moduleEntries);
|
|
38
|
+
const schemaHash = createOperationSchemaHash(entries, normalizedRequestId);
|
|
39
|
+
const filename = moduleEntries[0]?.filename;
|
|
40
|
+
entries.forEach((entry)=>{
|
|
41
|
+
const operationId = `${normalizedRequestId}:${entry.name}`;
|
|
42
|
+
const contract = {
|
|
43
|
+
requestId: normalizedRequestId,
|
|
44
|
+
operationVersion: DEFAULT_OPERATION_VERSION,
|
|
45
|
+
schemaHash,
|
|
46
|
+
method: entry.httpMethod,
|
|
47
|
+
routePath: entry.routePath,
|
|
48
|
+
operationId,
|
|
49
|
+
handlerName: entry.name,
|
|
50
|
+
filename
|
|
51
|
+
};
|
|
52
|
+
contracts[`${entry.httpMethod}:${entry.routePath}`] = contract;
|
|
53
|
+
contracts[`operation:${operationId}`] = contract;
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
return contracts;
|
|
57
|
+
};
|
|
58
|
+
export { DEFAULT_OPERATION_VERSION, buildOperationContractMap, createOperationEntries, createOperationSchemaHash };
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
var types_OperatorType = /*#__PURE__*/ function(OperatorType) {
|
|
3
|
+
OperatorType[OperatorType["Trigger"] = 0] = "Trigger";
|
|
4
|
+
OperatorType[OperatorType["Middleware"] = 1] = "Middleware";
|
|
5
|
+
return OperatorType;
|
|
6
|
+
}({});
|
|
7
|
+
var types_TriggerType = /*#__PURE__*/ function(TriggerType) {
|
|
8
|
+
TriggerType[TriggerType["Http"] = 0] = "Http";
|
|
9
|
+
return TriggerType;
|
|
10
|
+
}({});
|
|
11
|
+
var types_HttpMetadata = /*#__PURE__*/ function(HttpMetadata) {
|
|
12
|
+
HttpMetadata["Method"] = "METHOD";
|
|
13
|
+
HttpMetadata["Data"] = "DATA";
|
|
14
|
+
HttpMetadata["Query"] = "QUERY";
|
|
15
|
+
HttpMetadata["Params"] = "PARAMS";
|
|
16
|
+
HttpMetadata["Headers"] = "HEADERS";
|
|
17
|
+
HttpMetadata["Response"] = "RESPONSE";
|
|
18
|
+
HttpMetadata["Files"] = "Files";
|
|
19
|
+
return HttpMetadata;
|
|
20
|
+
}({});
|
|
21
|
+
var types_ResponseMetaType = /*#__PURE__*/ function(ResponseMetaType) {
|
|
22
|
+
ResponseMetaType[ResponseMetaType["StatusCode"] = 0] = "StatusCode";
|
|
23
|
+
ResponseMetaType[ResponseMetaType["Redirect"] = 1] = "Redirect";
|
|
24
|
+
ResponseMetaType[ResponseMetaType["Headers"] = 2] = "Headers";
|
|
25
|
+
return ResponseMetaType;
|
|
26
|
+
}({});
|
|
27
|
+
var types_HttpMethod = /*#__PURE__*/ function(HttpMethod) {
|
|
28
|
+
HttpMethod["Get"] = "GET";
|
|
29
|
+
HttpMethod["Post"] = "POST";
|
|
30
|
+
HttpMethod["Put"] = "PUT";
|
|
31
|
+
HttpMethod["Delete"] = "DELETE";
|
|
32
|
+
HttpMethod["Connect"] = "CONNECT";
|
|
33
|
+
HttpMethod["Trace"] = "TRACE";
|
|
34
|
+
HttpMethod["Patch"] = "PATCH";
|
|
35
|
+
HttpMethod["Options"] = "OPTIONS";
|
|
36
|
+
HttpMethod["Head"] = "HEAD";
|
|
37
|
+
return HttpMethod;
|
|
38
|
+
}({});
|
|
39
|
+
const httpMethods = Object.values(types_HttpMethod);
|
|
40
|
+
export { httpMethods, types_HttpMetadata as HttpMetadata, types_HttpMethod as HttpMethod, types_OperatorType as OperatorType, types_ResponseMetaType as ResponseMetaType, types_TriggerType as TriggerType };
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import fs from "fs";
|
|
3
|
+
import module_0 from "module";
|
|
4
|
+
import * as __rspack_external_os from "os";
|
|
5
|
+
import * as __rspack_external_path from "path";
|
|
6
|
+
const getRelativeRuntimePath = (appDirectory, serverRuntimePath)=>{
|
|
7
|
+
let relativeRuntimePath = '';
|
|
8
|
+
relativeRuntimePath = 'win32' === __rspack_external_os.platform() ? `../${__rspack_external_path.relative(appDirectory, serverRuntimePath)}` : __rspack_external_path.join('../', __rspack_external_path.relative(appDirectory, serverRuntimePath));
|
|
9
|
+
if ('development' === process.env.NODE_ENV || 'test' === process.env.NODE_ENV) relativeRuntimePath = `./${__rspack_external_path.relative(appDirectory, serverRuntimePath)}`;
|
|
10
|
+
return relativeRuntimePath;
|
|
11
|
+
};
|
|
12
|
+
const sortByLongestPrefix = (arr)=>arr.concat().sort((a, b)=>b.length - a.length);
|
|
13
|
+
const createMatchPath = (paths)=>{
|
|
14
|
+
const sortedKeys = sortByLongestPrefix(Object.keys(paths));
|
|
15
|
+
const sortedPaths = {};
|
|
16
|
+
sortedKeys.forEach((key)=>{
|
|
17
|
+
sortedPaths[key] = paths[key];
|
|
18
|
+
});
|
|
19
|
+
return (request)=>{
|
|
20
|
+
const found = Object.keys(sortedPaths).find((key)=>request.startsWith(key));
|
|
21
|
+
if (found) {
|
|
22
|
+
let foundPaths = sortedPaths[found];
|
|
23
|
+
if (!Array.isArray(foundPaths)) foundPaths = [
|
|
24
|
+
foundPaths
|
|
25
|
+
];
|
|
26
|
+
foundPaths = foundPaths.filter((foundPath)=>__rspack_external_path.isAbsolute(foundPath));
|
|
27
|
+
for (const p of foundPaths){
|
|
28
|
+
const foundPath = request.replace(found, p);
|
|
29
|
+
if (fs.existsSync(foundPath)) return foundPath;
|
|
30
|
+
}
|
|
31
|
+
return request.replace(found, foundPaths[0]);
|
|
32
|
+
}
|
|
33
|
+
return null;
|
|
34
|
+
};
|
|
35
|
+
};
|
|
36
|
+
const registerPaths = (paths)=>{
|
|
37
|
+
const originalResolveFilename = module_0._resolveFilename;
|
|
38
|
+
const { builtinModules } = module_0;
|
|
39
|
+
const matchPath = createMatchPath(paths);
|
|
40
|
+
module_0._resolveFilename = function(request, _parent) {
|
|
41
|
+
const isCoreModule = builtinModules.includes(request);
|
|
42
|
+
if (!isCoreModule) {
|
|
43
|
+
const matched = matchPath(request);
|
|
44
|
+
if (matched) {
|
|
45
|
+
const modifiedArguments = [
|
|
46
|
+
matched,
|
|
47
|
+
...[].slice.call(arguments, 1)
|
|
48
|
+
];
|
|
49
|
+
return originalResolveFilename.apply(this, modifiedArguments);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
return originalResolveFilename.apply(this, arguments);
|
|
53
|
+
};
|
|
54
|
+
return ()=>{
|
|
55
|
+
module_0._resolveFilename = originalResolveFilename;
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
export { createMatchPath, getRelativeRuntimePath, registerPaths };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
const HANDLER_WITH_META = 'HANDLER_WITH_META';
|
|
3
|
+
const INPUT_PARAMS_DECIDER = 'INPUT_PARAMS_DECIDER';
|
|
4
|
+
const isWithMetaHandler = (handler)=>'function' == typeof handler && handler[HANDLER_WITH_META];
|
|
5
|
+
const isInputParamsDeciderHandler = (handler)=>'function' == typeof handler && handler[INPUT_PARAMS_DECIDER];
|
|
6
|
+
export { HANDLER_WITH_META, INPUT_PARAMS_DECIDER, isInputParamsDeciderHandler, isWithMetaHandler };
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import * as __rspack_external_async_hooks from "async_hooks";
|
|
3
|
+
const createStorage = ()=>{
|
|
4
|
+
let storage;
|
|
5
|
+
if (void 0 !== __rspack_external_async_hooks.AsyncLocalStorage) storage = new __rspack_external_async_hooks.AsyncLocalStorage();
|
|
6
|
+
const run = (context, cb)=>{
|
|
7
|
+
if (!storage) throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
|
|
8
|
+
`);
|
|
9
|
+
return new Promise((resolve, reject)=>{
|
|
10
|
+
storage.run(context, ()=>{
|
|
11
|
+
try {
|
|
12
|
+
return resolve(cb());
|
|
13
|
+
} catch (error) {
|
|
14
|
+
return reject(error);
|
|
15
|
+
}
|
|
16
|
+
});
|
|
17
|
+
});
|
|
18
|
+
};
|
|
19
|
+
const useContext = ()=>{
|
|
20
|
+
if (!storage) throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
|
|
21
|
+
`);
|
|
22
|
+
const context = storage.getStore();
|
|
23
|
+
if (!context) throw new Error("Can't call useContext out of scope, it should be placed in the bff function");
|
|
24
|
+
return context;
|
|
25
|
+
};
|
|
26
|
+
return {
|
|
27
|
+
run,
|
|
28
|
+
useContext
|
|
29
|
+
};
|
|
30
|
+
};
|
|
31
|
+
export { createStorage };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import util from "util";
|
|
3
|
+
const getTypeErrorMessage = (actual)=>{
|
|
4
|
+
let msg = '';
|
|
5
|
+
if (null == actual) msg += `. Received ${actual}`;
|
|
6
|
+
else if ('function' == typeof actual && actual.name) msg += `. Received function ${actual.name}`;
|
|
7
|
+
else if ('object' == typeof actual) if (actual.constructor?.name) msg += `. Received an instance of ${actual.constructor.name}`;
|
|
8
|
+
else {
|
|
9
|
+
const inspected = util.inspect(actual, {
|
|
10
|
+
depth: -1
|
|
11
|
+
});
|
|
12
|
+
msg += `. Received ${inspected}`;
|
|
13
|
+
}
|
|
14
|
+
else {
|
|
15
|
+
let inspected = util.inspect(actual, {
|
|
16
|
+
colors: false
|
|
17
|
+
});
|
|
18
|
+
if (inspected.length > 25) inspected = `${inspected.slice(0, 25)}...`;
|
|
19
|
+
msg += `. Received type ${typeof actual} (${inspected})`;
|
|
20
|
+
}
|
|
21
|
+
return msg;
|
|
22
|
+
};
|
|
23
|
+
class ERR_INVALID_ARG_TYPE extends Error {
|
|
24
|
+
constructor(funcName, expectedType, actual){
|
|
25
|
+
const message = `[ERR_INVALID_ARG_TYPE]: The '${funcName}' argument must be of type ${expectedType}${getTypeErrorMessage(actual)}`;
|
|
26
|
+
super(message);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
const validateFunction = (maybeFunc, name)=>{
|
|
30
|
+
if ('function' != typeof maybeFunc) throw new ERR_INVALID_ARG_TYPE(name, 'function', maybeFunc);
|
|
31
|
+
return true;
|
|
32
|
+
};
|
|
33
|
+
export { ERR_INVALID_ARG_TYPE, getTypeErrorMessage, validateFunction };
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
import 'reflect-metadata';
|
|
2
|
+
import type { ApiRunner, ArrayToObject, ExtractInputType, ExtractOuputType, MaybeAsync, Operator } from './types';
|
|
3
|
+
export declare function Api<Operators extends Operator<any, any>[], Res extends MaybeAsync<any>>(...args: [
|
|
4
|
+
...operators: Operators,
|
|
5
|
+
handler: (arg: ArrayToObject<ExtractOuputType<Operators>>) => Res
|
|
6
|
+
]): ApiRunner<ExtractInputType<Operators> extends void[] ? void : ArrayToObject<ExtractInputType<Operators>>, Res>;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import type { HttpMethodDecider } from '@modern-js/types';
|
|
2
|
+
import { type Result } from './result';
|
|
3
|
+
export type GenClientResult = Result<string>;
|
|
4
|
+
export type GenClientOptions = {
|
|
5
|
+
resourcePath: string;
|
|
6
|
+
source: string;
|
|
7
|
+
appDir: string;
|
|
8
|
+
apiDir: string;
|
|
9
|
+
lambdaDir: string;
|
|
10
|
+
prefix: string;
|
|
11
|
+
port: number;
|
|
12
|
+
requestCreator?: string;
|
|
13
|
+
fetcher?: string;
|
|
14
|
+
target?: string;
|
|
15
|
+
requireResolve?: typeof require.resolve;
|
|
16
|
+
httpMethodDecider?: HttpMethodDecider;
|
|
17
|
+
domain?: string;
|
|
18
|
+
requestId?: string;
|
|
19
|
+
};
|
|
20
|
+
export declare const INNER_CLIENT_REQUEST_CREATOR = "@modern-js/plugin-bff/client";
|
|
21
|
+
export declare const generateClient: ({ appDir, resourcePath, apiDir, lambdaDir, prefix, port, target, requestCreator, fetcher, requireResolve, httpMethodDecider, domain, requestId, }: GenClientOptions) => Promise<GenClientResult>;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export * from './generateClient';
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
export type Err<T = unknown> = {
|
|
2
|
+
kind: 'Err';
|
|
3
|
+
value: T;
|
|
4
|
+
isErr: true;
|
|
5
|
+
isOk: false;
|
|
6
|
+
};
|
|
7
|
+
export type Ok<T = unknown> = {
|
|
8
|
+
kind: 'Ok';
|
|
9
|
+
value: T;
|
|
10
|
+
isErr: false;
|
|
11
|
+
isOk: true;
|
|
12
|
+
};
|
|
13
|
+
export type Result<T = unknown, E = string> = Err<E> | Ok<T>;
|
|
14
|
+
export declare const Err: <E = string>(value: E) => Err<E>;
|
|
15
|
+
export declare const Ok: <T, E = string>(value: T) => Result<T, E>;
|