@modern-js/bff-core 1.21.7-beta.0 → 1.22.1

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.
@@ -14,23 +14,30 @@ export const getPathFromFilename = (baseDir, filename) => {
14
14
  return `:${item.substring(1, item.length - 1)}`;
15
15
  }
16
16
  }
17
+
17
18
  return item;
18
19
  });
19
20
  const name = nameSplit.join('/');
20
21
  const finalName = name.endsWith(INDEX_SUFFIX) ? name.substring(0, name.length - INDEX_SUFFIX.length) : name;
21
22
  return clearRouteName(finalName);
22
23
  };
24
+
23
25
  const clearRouteName = routeName => {
24
26
  let finalRouteName = routeName.trim();
27
+
25
28
  if (!finalRouteName.startsWith('/')) {
26
29
  finalRouteName = `/${finalRouteName}`;
27
30
  }
31
+
28
32
  if (finalRouteName.length > 1 && finalRouteName.endsWith('/')) {
29
33
  finalRouteName = finalRouteName.substring(0, finalRouteName.length - 1);
30
34
  }
35
+
31
36
  return finalRouteName;
32
37
  };
38
+
33
39
  export const isHandler = input => input && typeof input === 'function';
40
+
34
41
  const enableRegister = requireFn => {
35
42
  // esbuild-register 做 unRegister 时,不会删除 register 添加的 require.extensions,导致第二次调用时 require.extensions['.ts'] 是 nodejs 默认 loader
36
43
  // 所以这里根据第一次调用时,require.extensions 有没有,来判断是否需要使用 esbuild-register
@@ -42,41 +49,51 @@ const enableRegister = requireFn => {
42
49
  existTsLoader = Boolean(require.extensions['.ts']);
43
50
  firstCall = false;
44
51
  }
52
+
45
53
  if (!existTsLoader) {
46
54
  const {
47
55
  register
48
56
  } = require('esbuild-register/dist/node');
57
+
49
58
  const {
50
59
  unregister
51
60
  } = register({
52
- extensions: ['.ts', '.js']
61
+ extensions: ['.ts']
53
62
  });
54
63
  const requiredModule = requireFn(modulePath);
55
64
  unregister();
56
65
  return requiredModule;
57
66
  }
67
+
58
68
  const requiredModule = requireFn(modulePath);
59
69
  return requiredModule;
60
70
  };
61
71
  };
72
+
62
73
  const isFunction = input => input && {}.toString.call(input) === '[object Function]';
74
+
63
75
  export const requireHandlerModule = enableRegister(modulePath => {
64
76
  // 测试环境不走缓存,因为缓存的 h andler 文件,会被 mockAPI 函数进行 mock,升级 jest28,setupFilesAfterEnv 能做异步操作的话,可解此问题
65
77
  const originRequire = process.env.NODE_ENV === 'test' ? jest.requireActual : require;
66
78
  const module = originRequire(modulePath);
79
+
67
80
  if (isFunction(module)) {
68
81
  return {
69
82
  default: module
70
83
  };
71
84
  }
85
+
72
86
  return module;
73
87
  });
88
+
74
89
  const routeValue = routePath => {
75
90
  if (routePath.includes(':')) {
76
91
  return 11;
77
92
  }
93
+
78
94
  return 1;
79
95
  };
96
+
80
97
  export const sortRoutes = apiHandlers => {
81
98
  return apiHandlers.sort((handlerA, handlerB) => {
82
99
  return routeValue(handlerA.routeName) - routeValue(handlerB.routeName);
@@ -1,13 +1,18 @@
1
1
  export let OperatorType;
2
+
2
3
  (function (OperatorType) {
3
4
  OperatorType[OperatorType["Trigger"] = 0] = "Trigger";
4
5
  OperatorType[OperatorType["Middleware"] = 1] = "Middleware";
5
6
  })(OperatorType || (OperatorType = {}));
7
+
6
8
  export let TriggerType;
9
+
7
10
  (function (TriggerType) {
8
11
  TriggerType[TriggerType["Http"] = 0] = "Http";
9
12
  })(TriggerType || (TriggerType = {}));
13
+
10
14
  export let HttpMetadata;
15
+
11
16
  (function (HttpMetadata) {
12
17
  HttpMetadata["Method"] = "METHOD";
13
18
  HttpMetadata["Data"] = "DATA";
@@ -16,13 +21,17 @@ export let HttpMetadata;
16
21
  HttpMetadata["Headers"] = "HEADERS";
17
22
  HttpMetadata["Response"] = "RESPONSE";
18
23
  })(HttpMetadata || (HttpMetadata = {}));
24
+
19
25
  export let ResponseMetaType;
26
+
20
27
  (function (ResponseMetaType) {
21
28
  ResponseMetaType[ResponseMetaType["StatusCode"] = 0] = "StatusCode";
22
29
  ResponseMetaType[ResponseMetaType["Redirect"] = 1] = "Redirect";
23
30
  ResponseMetaType[ResponseMetaType["Headers"] = 2] = "Headers";
24
31
  })(ResponseMetaType || (ResponseMetaType = {}));
32
+
25
33
  export let HttpMethod;
34
+
26
35
  (function (HttpMethod) {
27
36
  HttpMethod["Get"] = "GET";
28
37
  HttpMethod["Post"] = "POST";
@@ -34,4 +43,5 @@ export let HttpMethod;
34
43
  HttpMethod["Option"] = "OPTION";
35
44
  HttpMethod["Head"] = "HEAD";
36
45
  })(HttpMethod || (HttpMethod = {}));
46
+
37
47
  export const httpMethods = Object.values(HttpMethod);
@@ -4,6 +4,7 @@ import fs from 'fs';
4
4
  import Module from 'module';
5
5
  export const getRelativeRuntimePath = (appDirectory, serverRuntimePath) => {
6
6
  let relativeRuntimePath = '';
7
+
7
8
  if (os.platform() === 'win32') {
8
9
  // isRelative function in babel-plugin-resolver plugin can't handle windows relative path correctly, see babel-plugin-resolver's utils.
9
10
  relativeRuntimePath = `../${path.relative(appDirectory, serverRuntimePath)}`;
@@ -11,14 +12,18 @@ export const getRelativeRuntimePath = (appDirectory, serverRuntimePath) => {
11
12
  // Look up one level, because the artifacts after build have dist directories
12
13
  relativeRuntimePath = path.join('../', path.relative(appDirectory, serverRuntimePath));
13
14
  }
15
+
14
16
  if (process.env.NODE_ENV === 'development' || process.env.NODE_ENV === 'test') {
15
17
  relativeRuntimePath = `./${path.relative(appDirectory, serverRuntimePath)}`;
16
18
  }
19
+
17
20
  return relativeRuntimePath;
18
21
  };
22
+
19
23
  const sortByLongestPrefix = arr => {
20
24
  return arr.concat().sort((a, b) => b.length - a.length);
21
25
  };
26
+
22
27
  export const createMatchPath = paths => {
23
28
  const sortedKeys = sortByLongestPrefix(Object.keys(paths));
24
29
  const sortedPaths = {};
@@ -29,45 +34,57 @@ export const createMatchPath = paths => {
29
34
  const found = Object.keys(sortedPaths).find(key => {
30
35
  return request.startsWith(key);
31
36
  });
37
+
32
38
  if (found) {
33
39
  let foundPaths = sortedPaths[found];
40
+
34
41
  if (!Array.isArray(foundPaths)) {
35
42
  foundPaths = [foundPaths];
36
43
  }
44
+
37
45
  foundPaths = foundPaths.filter(foundPath => path.isAbsolute(foundPath));
46
+
38
47
  for (const p of foundPaths) {
39
48
  const foundPath = request.replace(found, p);
49
+
40
50
  if (fs.existsSync(foundPath)) {
41
51
  return foundPath;
42
52
  }
43
53
  }
54
+
44
55
  return request.replace(found, foundPaths[0]);
45
56
  }
57
+
46
58
  return null;
47
59
  };
48
- };
60
+ }; // every path must be a absolute path;
49
61
 
50
- // every path must be a absolute path;
51
62
  export const registerPaths = paths => {
52
- const originalResolveFilename = Module._resolveFilename;
53
- // eslint-disable-next-line node/no-unsupported-features/node-builtins
63
+ const originalResolveFilename = Module._resolveFilename; // eslint-disable-next-line node/no-unsupported-features/node-builtins
64
+
54
65
  const {
55
66
  builtinModules
56
67
  } = Module;
57
68
  const matchPath = createMatchPath(paths);
69
+
58
70
  Module._resolveFilename = function (request, _parent) {
59
71
  const isCoreModule = builtinModules.includes(request);
72
+
60
73
  if (!isCoreModule) {
61
74
  const matched = matchPath(request);
75
+
62
76
  if (matched) {
63
77
  // eslint-disable-next-line prefer-rest-params
64
78
  const modifiedArguments = [matched, ...[].slice.call(arguments, 1)]; // Passes all arguments. Even those that is not specified above.
79
+
65
80
  return originalResolveFilename.apply(this, modifiedArguments);
66
81
  }
67
- }
68
- // eslint-disable-next-line prefer-rest-params
82
+ } // eslint-disable-next-line prefer-rest-params
83
+
84
+
69
85
  return originalResolveFilename.apply(this, arguments);
70
86
  };
87
+
71
88
  return () => {
72
89
  Module._resolveFilename = originalResolveFilename;
73
90
  };
@@ -1,14 +1,18 @@
1
1
  import * as ah from 'async_hooks';
2
+
2
3
  const createStorage = () => {
3
4
  let storage;
5
+
4
6
  if (typeof ah.AsyncLocalStorage !== 'undefined') {
5
7
  storage = new ah.AsyncLocalStorage();
6
8
  }
9
+
7
10
  const run = (context, cb) => {
8
11
  if (!storage) {
9
12
  throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
10
13
  `);
11
14
  }
15
+
12
16
  return new Promise((resolve, reject) => {
13
17
  storage.run(context, () => {
14
18
  try {
@@ -19,20 +23,26 @@ const createStorage = () => {
19
23
  });
20
24
  });
21
25
  };
26
+
22
27
  const useContext = () => {
23
28
  if (!storage) {
24
29
  throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
25
30
  `);
26
31
  }
32
+
27
33
  const context = storage.getStore();
34
+
28
35
  if (!context) {
29
36
  throw new Error(`Can't call useContext out of scope, it should be placed in the bff function`);
30
37
  }
38
+
31
39
  return context;
32
40
  };
41
+
33
42
  return {
34
43
  run,
35
44
  useContext
36
45
  };
37
46
  };
47
+
38
48
  export { createStorage };
@@ -1,14 +1,15 @@
1
- import util from 'util';
1
+ import util from 'util'; // fork from https://github.com/nodejs/node/blob/master/lib/internal/errors.js
2
2
 
3
- // fork from https://github.com/nodejs/node/blob/master/lib/internal/errors.js
4
3
  export const getTypeErrorMessage = actual => {
5
4
  let msg = '';
5
+
6
6
  if (actual == null) {
7
7
  msg += `. Received ${actual}`;
8
8
  } else if (typeof actual === 'function' && actual.name) {
9
9
  msg += `. Received function ${actual.name}`;
10
10
  } else if (typeof actual === 'object') {
11
11
  var _actual$constructor;
12
+
12
13
  if ((_actual$constructor = actual.constructor) !== null && _actual$constructor !== void 0 && _actual$constructor.name) {
13
14
  msg += `. Received an instance of ${actual.constructor.name}`;
14
15
  } else {
@@ -21,24 +22,28 @@ export const getTypeErrorMessage = actual => {
21
22
  let inspected = util.inspect(actual, {
22
23
  colors: false
23
24
  });
25
+
24
26
  if (inspected.length > 25) {
25
27
  inspected = `${inspected.slice(0, 25)}...`;
26
28
  }
29
+
27
30
  msg += `. Received type ${typeof actual} (${inspected})`;
28
31
  }
32
+
29
33
  return msg;
30
- };
34
+ }; // eslint-disable-next-line @typescript-eslint/naming-convention
31
35
 
32
- // eslint-disable-next-line @typescript-eslint/naming-convention
33
36
  export class ERR_INVALID_ARG_TYPE extends Error {
34
37
  constructor(funcName, expectedType, actual) {
35
38
  const message = `[ERR_INVALID_ARG_TYPE]: The '${funcName}' argument must be of type ${expectedType}${getTypeErrorMessage(actual)}`;
36
39
  super(message);
37
40
  }
41
+
38
42
  }
39
43
  export const validateFunction = (maybeFunc, name) => {
40
44
  if (typeof maybeFunc !== 'function') {
41
45
  throw new ERR_INVALID_ARG_TYPE(name, 'function', maybeFunc);
42
46
  }
47
+
43
48
  return true;
44
49
  };
@@ -4,10 +4,15 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.Api = Api;
7
+
7
8
  require("reflect-metadata");
9
+
8
10
  var _koaCompose = _interopRequireDefault(require("koa-compose"));
11
+
9
12
  var _utils = require("./utils");
13
+
10
14
  function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
15
+
11
16
  function Api(...args) {
12
17
  const handler = args.pop();
13
18
  (0, _utils.validateFunction)(handler, 'Apihandler');
@@ -16,27 +21,35 @@ function Api(...args) {
16
21
  getMetadata(key) {
17
22
  return Reflect.getMetadata(key, runner);
18
23
  },
24
+
19
25
  setMetadata(key, value) {
20
26
  return Reflect.defineMetadata(key, value, runner);
21
27
  }
28
+
22
29
  };
30
+
23
31
  for (const operator of operators) {
24
32
  if (operator.metadata) {
25
33
  operator.metadata(metadataHelper);
26
34
  }
27
35
  }
36
+
28
37
  const validateHandlers = operators.filter(operator => operator.validate).map(operator => operator.validate);
29
38
  const pipeHandlers = operators.filter(operator => operator.execute).map(operator => operator.execute);
39
+
30
40
  async function runner(inputs) {
31
41
  const executeHelper = {
32
42
  result: null,
43
+
33
44
  get inputs() {
34
45
  return inputs;
35
46
  },
47
+
36
48
  set inputs(val) {
37
49
  // eslint-disable-next-line no-param-reassign
38
50
  inputs = val;
39
51
  }
52
+
40
53
  };
41
54
  const stack = [...validateHandlers, ...pipeHandlers];
42
55
  stack.push(async (helper, next) => {
@@ -47,6 +60,7 @@ function Api(...args) {
47
60
  await (0, _koaCompose.default)(stack)(executeHelper);
48
61
  return executeHelper.result;
49
62
  }
63
+
50
64
  runner[_utils.HANDLER_WITH_META] = true;
51
65
  return runner;
52
66
  }
@@ -4,13 +4,20 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.generateClient = exports.DEFAULT_CLIENT_REQUEST_CREATOR = void 0;
7
+
7
8
  var path = _interopRequireWildcard(require("path"));
9
+
8
10
  var _router = require("../router");
11
+
9
12
  var _result = require("./result");
13
+
10
14
  function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function (nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }
15
+
11
16
  function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
17
+
12
18
  const DEFAULT_CLIENT_REQUEST_CREATOR = '@modern-js/create-request';
13
19
  exports.DEFAULT_CLIENT_REQUEST_CREATOR = DEFAULT_CLIENT_REQUEST_CREATOR;
20
+
14
21
  const generateClient = async ({
15
22
  resourcePath,
16
23
  apiDir,
@@ -27,21 +34,27 @@ const generateClient = async ({
27
34
  } else {
28
35
  // 这里约束传入的 requestCreator 包也必须有两个导出 client 和 server,因为目前的机制 client 和 server 要导出不同的 configure 函数;该 api 不对使用者暴露,后续可优化
29
36
  let resolvedPath = requestCreator;
37
+
30
38
  try {
31
39
  resolvedPath = path.dirname(_requireResolve(requestCreator));
32
- } catch (error) {}
33
- // eslint-disable-next-line no-param-reassign
40
+ } catch (error) {} // eslint-disable-next-line no-param-reassign
41
+
42
+
34
43
  requestCreator = `${resolvedPath}${target ? `/${target}` : ''}`.replace(/\\/g, '/');
35
44
  }
45
+
36
46
  const apiRouter = new _router.ApiRouter({
37
47
  apiDir,
38
48
  prefix
39
49
  });
40
50
  const handlerInfos = apiRouter.getSingleModuleHandlers(resourcePath);
51
+
41
52
  if (!handlerInfos) {
42
53
  return (0, _result.Err)(`generate client error: Cannot require module ${resourcePath}`);
43
54
  }
55
+
44
56
  let handlersCode = '';
57
+
45
58
  for (const handlerInfo of handlerInfos) {
46
59
  const {
47
60
  name,
@@ -49,16 +62,20 @@ const generateClient = async ({
49
62
  routePath
50
63
  } = handlerInfo;
51
64
  let exportStatement = `const ${name} =`;
65
+
52
66
  if (name.toLowerCase() === 'default') {
53
67
  exportStatement = 'default';
54
68
  }
69
+
55
70
  const upperHttpMethod = httpMethod.toUpperCase();
56
71
  const routeName = routePath;
57
72
  handlersCode += `export ${exportStatement} createRequest('${routeName}', '${upperHttpMethod}', process.env.PORT || ${String(port)}${fetcher ? `, fetch` : ''});
58
73
  `;
59
74
  }
75
+
60
76
  const importCode = `import { createRequest } from '${requestCreator}';
61
77
  ${fetcher ? `import { fetch } from '${fetcher}';\n` : ''}`;
62
78
  return (0, _result.Ok)(`${importCode}\n${handlersCode}`);
63
79
  };
80
+
64
81
  exports.generateClient = generateClient;
@@ -3,7 +3,9 @@
3
3
  Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
+
6
7
  var _generateClient = require("./generate-client");
8
+
7
9
  Object.keys(_generateClient).forEach(function (key) {
8
10
  if (key === "default" || key === "__esModule") return;
9
11
  if (key in exports && exports[key] === _generateClient[key]) return;
@@ -4,6 +4,7 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.Ok = exports.Err = void 0;
7
+
7
8
  // eslint-disable-next-line @typescript-eslint/no-redeclare
8
9
  const Err = value => {
9
10
  const err = {
@@ -13,10 +14,11 @@ const Err = value => {
13
14
  isOk: false
14
15
  };
15
16
  return err;
16
- };
17
+ }; // eslint-disable-next-line @typescript-eslint/no-redeclare
18
+
17
19
 
18
- // eslint-disable-next-line @typescript-eslint/no-redeclare
19
20
  exports.Err = Err;
21
+
20
22
  const Ok = value => {
21
23
  const ok = {
22
24
  kind: 'Ok',
@@ -26,4 +28,5 @@ const Ok = value => {
26
28
  };
27
29
  return ok;
28
30
  };
31
+
29
32
  exports.Ok = Ok;
@@ -4,20 +4,31 @@ Object.defineProperty(exports, "__esModule", {
4
4
  value: true
5
5
  });
6
6
  exports.ValidationError = exports.HttpError = void 0;
7
+
7
8
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
9
+
8
10
  class HttpError extends Error {
9
11
  constructor(status, message) {
10
12
  super(message);
13
+
11
14
  _defineProperty(this, "status", void 0);
15
+
12
16
  this.status = status;
13
17
  }
18
+
14
19
  }
20
+
15
21
  exports.HttpError = HttpError;
22
+
16
23
  class ValidationError extends HttpError {
17
24
  constructor(status, message) {
18
25
  super(status, message);
26
+
19
27
  _defineProperty(this, "code", void 0);
28
+
20
29
  this.code = 'VALIDATION_ERROR';
21
30
  }
31
+
22
32
  }
33
+
23
34
  exports.ValidationError = ValidationError;
@@ -61,9 +61,13 @@ Object.defineProperty(exports, "registerPaths", {
61
61
  return _utils.registerPaths;
62
62
  }
63
63
  });
64
+
64
65
  var _api = require("./api");
66
+
65
67
  var _http = require("./errors/http");
68
+
66
69
  var _router = require("./router");
70
+
67
71
  Object.keys(_router).forEach(function (key) {
68
72
  if (key === "default" || key === "__esModule") return;
69
73
  if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
@@ -75,7 +79,9 @@ Object.keys(_router).forEach(function (key) {
75
79
  }
76
80
  });
77
81
  });
82
+
78
83
  var _types = require("./types");
84
+
79
85
  Object.keys(_types).forEach(function (key) {
80
86
  if (key === "default" || key === "__esModule") return;
81
87
  if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
@@ -87,7 +93,9 @@ Object.keys(_types).forEach(function (key) {
87
93
  }
88
94
  });
89
95
  });
96
+
90
97
  var _client = require("./client");
98
+
91
99
  Object.keys(_client).forEach(function (key) {
92
100
  if (key === "default" || key === "__esModule") return;
93
101
  if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
@@ -99,7 +107,9 @@ Object.keys(_client).forEach(function (key) {
99
107
  }
100
108
  });
101
109
  });
110
+
102
111
  var _http2 = require("./operators/http");
112
+
103
113
  Object.keys(_http2).forEach(function (key) {
104
114
  if (key === "default" || key === "__esModule") return;
105
115
  if (Object.prototype.hasOwnProperty.call(_exportNames, key)) return;
@@ -111,4 +121,5 @@ Object.keys(_http2).forEach(function (key) {
111
121
  }
112
122
  });
113
123
  });
124
+
114
125
  var _utils = require("./utils");