@modern-js/bff-core 2.69.4 → 3.0.0-alpha.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.
Files changed (77) hide show
  1. package/dist/cjs/api.js +82 -78
  2. package/dist/cjs/client/generateClient.js +90 -76
  3. package/dist/cjs/client/index.js +55 -19
  4. package/dist/cjs/client/result.js +51 -42
  5. package/dist/cjs/compatible.js +17 -15
  6. package/dist/cjs/errors/http.js +43 -34
  7. package/dist/cjs/index.js +169 -54
  8. package/dist/cjs/operators/http.js +213 -212
  9. package/dist/cjs/router/constants.js +63 -57
  10. package/dist/cjs/router/index.js +271 -291
  11. package/dist/cjs/router/types.js +17 -15
  12. package/dist/cjs/router/utils.js +90 -92
  13. package/dist/cjs/types.js +84 -71
  14. package/dist/cjs/utils/alias.js +100 -103
  15. package/dist/cjs/utils/debug.js +34 -26
  16. package/dist/cjs/utils/index.js +98 -34
  17. package/dist/cjs/utils/meta.js +45 -38
  18. package/dist/cjs/utils/storage.js +58 -68
  19. package/dist/cjs/utils/validate.js +73 -72
  20. package/dist/esm/api.mjs +44 -0
  21. package/dist/esm/client/generateClient.mjs +60 -0
  22. package/dist/esm/client/result.mjs +19 -0
  23. package/dist/esm/compatible.mjs +0 -0
  24. package/dist/esm/errors/http.mjs +13 -0
  25. package/dist/esm/index.mjs +8 -0
  26. package/dist/esm/operators/http.mjs +135 -0
  27. package/dist/esm/router/constants.mjs +19 -0
  28. package/dist/esm/router/index.mjs +186 -0
  29. package/dist/esm/router/types.mjs +0 -0
  30. package/dist/esm/router/utils.mjs +42 -0
  31. package/dist/esm/types.mjs +39 -0
  32. package/dist/esm/utils/alias.mjs +57 -0
  33. package/dist/esm/utils/debug.mjs +3 -0
  34. package/dist/esm/utils/{index.js → index.mjs} +2 -4
  35. package/dist/esm/utils/meta.mjs +5 -0
  36. package/dist/esm/utils/storage.mjs +30 -0
  37. package/dist/esm/utils/validate.mjs +32 -0
  38. package/dist/esm-node/api.mjs +44 -0
  39. package/dist/esm-node/client/generateClient.mjs +60 -0
  40. package/dist/esm-node/client/index.mjs +1 -0
  41. package/dist/esm-node/client/result.mjs +19 -0
  42. package/dist/esm-node/errors/http.mjs +13 -0
  43. package/dist/esm-node/index.mjs +8 -0
  44. package/dist/esm-node/operators/http.mjs +135 -0
  45. package/dist/esm-node/router/constants.mjs +19 -0
  46. package/dist/esm-node/router/index.mjs +186 -0
  47. package/dist/esm-node/router/utils.mjs +42 -0
  48. package/dist/esm-node/types.mjs +39 -0
  49. package/dist/esm-node/utils/alias.mjs +57 -0
  50. package/dist/esm-node/utils/debug.mjs +3 -0
  51. package/dist/esm-node/utils/index.mjs +6 -0
  52. package/dist/esm-node/utils/meta.mjs +5 -0
  53. package/dist/esm-node/utils/storage.mjs +30 -0
  54. package/dist/esm-node/utils/validate.mjs +32 -0
  55. package/dist/types/client/generateClient.d.ts +1 -1
  56. package/dist/types/router/constants.d.ts +0 -10
  57. package/dist/types/router/index.d.ts +0 -5
  58. package/package.json +18 -18
  59. package/rslib.config.mts +4 -0
  60. package/dist/esm/api.js +0 -50
  61. package/dist/esm/client/generateClient.js +0 -60
  62. package/dist/esm/client/result.js +0 -22
  63. package/dist/esm/errors/http.js +0 -16
  64. package/dist/esm/index.js +0 -19
  65. package/dist/esm/operators/http.js +0 -178
  66. package/dist/esm/router/constants.js +0 -32
  67. package/dist/esm/router/index.js +0 -261
  68. package/dist/esm/router/utils.js +0 -62
  69. package/dist/esm/types.js +0 -46
  70. package/dist/esm/utils/alias.js +0 -75
  71. package/dist/esm/utils/debug.js +0 -5
  72. package/dist/esm/utils/meta.js +0 -14
  73. package/dist/esm/utils/storage.js +0 -40
  74. package/dist/esm/utils/validate.js +0 -45
  75. /package/dist/esm/client/{index.js → index.mjs} +0 -0
  76. /package/dist/{esm/compatible.js → esm-node/compatible.mjs} +0 -0
  77. /package/dist/{esm/router/types.js → esm-node/router/types.mjs} +0 -0
@@ -1,261 +0,0 @@
1
- import path from "path";
2
- import { fs, logger } from "@modern-js/utils";
3
- import "reflect-metadata";
4
- import { HttpMethod, OperatorType, TriggerType, httpMethods } from "../types";
5
- import { INPUT_PARAMS_DECIDER, debug } from "../utils";
6
- import { APIMode, API_FILE_RULES, FRAMEWORK_MODE_APP_DIR, FRAMEWORK_MODE_LAMBDA_DIR } from "./constants";
7
- import { getFiles, getPathFromFilename, requireHandlerModule, sortRoutes } from "./utils";
8
- export * from "./types";
9
- export * from "./constants";
10
- class ApiRouter {
11
- isExistLambda() {
12
- return this.existLambdaDir;
13
- }
14
- getApiMode() {
15
- return this.apiMode;
16
- }
17
- getLambdaDir() {
18
- return this.lambdaDir;
19
- }
20
- isApiFile(filename) {
21
- if (this.apiFiles.includes(filename)) {
22
- return true;
23
- }
24
- return false;
25
- }
26
- async getSingleModuleHandlers(filename) {
27
- const moduleInfo = await this.getModuleInfo(filename);
28
- if (moduleInfo) {
29
- return this.getModuleHandlerInfos(moduleInfo);
30
- }
31
- return null;
32
- }
33
- getHandlerInfo(filename, originFuncName, handler) {
34
- const httpMethod = this.getHttpMethod(originFuncName, handler);
35
- const routeName = this.getRouteName(filename, handler);
36
- const action = this.getAction(handler);
37
- const responseObj = {
38
- handler,
39
- name: originFuncName,
40
- httpMethod,
41
- routeName,
42
- filename,
43
- routePath: this.getRoutePath(this.prefix, routeName)
44
- };
45
- if (action) {
46
- responseObj.action = action;
47
- }
48
- if (httpMethod && routeName) {
49
- return responseObj;
50
- }
51
- return null;
52
- }
53
- // TODO: 性能提升,开发环境,判断下 lambda 目录修改时间
54
- getSafeRoutePath(filename, handler) {
55
- this.loadApiFiles();
56
- this.validateValidApifile(filename);
57
- return this.getRouteName(filename, handler);
58
- }
59
- getRouteName(filename, handler) {
60
- if (handler) {
61
- const trigger = Reflect.getMetadata(OperatorType.Trigger, handler);
62
- if (trigger && trigger.type === TriggerType.Http) {
63
- if (!trigger.path) {
64
- throw new Error(`The http trigger ${trigger.name} needs to specify a path`);
65
- }
66
- return trigger.path;
67
- }
68
- }
69
- let routePath = getPathFromFilename(this.lambdaDir, filename);
70
- if (this.httpMethodDecider === "inputParams") {
71
- if (routePath.endsWith("/")) {
72
- routePath += `${handler === null || handler === void 0 ? void 0 : handler.name}`;
73
- } else {
74
- routePath += `/${handler === null || handler === void 0 ? void 0 : handler.name}`;
75
- }
76
- }
77
- return routePath;
78
- }
79
- getHttpMethod(originHandlerName, handler) {
80
- if (handler) {
81
- const trigger = Reflect.getMetadata(OperatorType.Trigger, handler);
82
- if (trigger && httpMethods.includes(trigger.method)) {
83
- return trigger.method;
84
- }
85
- }
86
- if (this.httpMethodDecider === "functionName") {
87
- const upperName = originHandlerName.toUpperCase();
88
- switch (upperName) {
89
- case "GET":
90
- return HttpMethod.Get;
91
- case "POST":
92
- return HttpMethod.Post;
93
- case "PUT":
94
- return HttpMethod.Put;
95
- case "DELETE":
96
- case "DEL":
97
- return HttpMethod.Delete;
98
- case "CONNECT":
99
- return HttpMethod.Connect;
100
- case "TRACE":
101
- return HttpMethod.Trace;
102
- case "PATCH":
103
- return HttpMethod.Patch;
104
- case "OPTIONS":
105
- return HttpMethod.Options;
106
- case "DEFAULT": {
107
- return HttpMethod.Get;
108
- }
109
- default:
110
- if (process.env.NODE_ENV !== "test") {
111
- logger.warn(`Only api handlers are allowd to be exported, please remove the function ${originHandlerName} from exports`);
112
- }
113
- return null;
114
- }
115
- } else {
116
- if (!handler) {
117
- return null;
118
- }
119
- if (typeof handler === "function" && handler.length > 0) {
120
- return HttpMethod.Post;
121
- }
122
- return HttpMethod.Get;
123
- }
124
- }
125
- getAction(handler) {
126
- if (handler) {
127
- const trigger = Reflect.getMetadata(OperatorType.Trigger, handler);
128
- if (trigger === null || trigger === void 0 ? void 0 : trigger.action) {
129
- return trigger.action;
130
- }
131
- }
132
- }
133
- loadApiFiles() {
134
- if (!this.existLambdaDir) {
135
- return [];
136
- }
137
- const apiFiles = this.apiFiles = getFiles(this.lambdaDir, API_FILE_RULES);
138
- return apiFiles;
139
- }
140
- getApiFiles() {
141
- if (!this.existLambdaDir) {
142
- return [];
143
- }
144
- if (this.apiFiles.length > 0) {
145
- return this.apiFiles;
146
- }
147
- return this.loadApiFiles();
148
- }
149
- async getApiHandlers() {
150
- const filenames = this.getApiFiles();
151
- const moduleInfos = await this.getModuleInfos(filenames);
152
- const apiHandlers = this.getHandlerInfos(moduleInfos);
153
- debug("apiHandlers", apiHandlers.length, apiHandlers);
154
- return apiHandlers;
155
- }
156
- /**
157
- * 如果用户未传入或传入空串,默认为 /api
158
- * 如果传入 /,则 prefix 为 /
159
- */
160
- initPrefix(prefix) {
161
- if (prefix === "/") {
162
- return "";
163
- }
164
- return prefix || "/api";
165
- }
166
- validateAbsolute(filename, paramsName) {
167
- if (typeof filename === "string" && !path.isAbsolute(filename)) {
168
- throw new Error(`The ${paramsName} ${filename} is not a abolute path`);
169
- }
170
- }
171
- async getModuleInfos(filenames) {
172
- return Promise.all(filenames.map((filename) => this.getModuleInfo(filename)).filter((moduleInfo) => Boolean(moduleInfo)));
173
- }
174
- async getModuleInfo(filename) {
175
- try {
176
- const module = await requireHandlerModule(filename);
177
- return {
178
- filename,
179
- module
180
- };
181
- } catch (err) {
182
- if (process.env.NODE_ENV === "production") {
183
- throw err;
184
- } else {
185
- console.error(err);
186
- return null;
187
- }
188
- }
189
- }
190
- getHandlerInfos(moduleInfos) {
191
- let apiHandlers = [];
192
- moduleInfos.forEach((moduleInfo) => {
193
- const handlerInfos = this.getModuleHandlerInfos(moduleInfo);
194
- if (handlerInfos) {
195
- apiHandlers = apiHandlers.concat(handlerInfos);
196
- }
197
- });
198
- const sortedHandlers = sortRoutes(apiHandlers);
199
- return sortedHandlers;
200
- }
201
- getModuleHandlerInfos(moduleInfo) {
202
- const { module, filename } = moduleInfo;
203
- const { httpMethodDecider } = this;
204
- return Object.entries(module).filter(([, handler]) => typeof handler === "function").map(([key]) => {
205
- const handler = module[key];
206
- if (httpMethodDecider === "inputParams") {
207
- Object.assign(handler, {
208
- [INPUT_PARAMS_DECIDER]: true
209
- });
210
- }
211
- const handlerInfo = this.getHandlerInfo(filename, key, handler);
212
- return handlerInfo;
213
- }).filter((handlerInfo) => Boolean(handlerInfo));
214
- }
215
- validateValidApifile(filename) {
216
- if (!this.apiFiles.includes(filename)) {
217
- throw new Error(`The ${filename} is not a valid api file.`);
218
- }
219
- }
220
- getRoutePath(prefix, routeName) {
221
- const finalRouteName = routeName === "/" ? "" : routeName;
222
- if (prefix === "" && finalRouteName === "") {
223
- return "/";
224
- }
225
- return `${prefix}${finalRouteName}`;
226
- }
227
- constructor({ appDir, apiDir, lambdaDir, prefix, isBuild, httpMethodDecider = "functionName" }) {
228
- this.apiFiles = [];
229
- this.getExactApiMode = (apiDir2, lambdaDir2) => {
230
- const exist = this.createExistChecker(apiDir2);
231
- const existLambdaDir = lambdaDir2 && fs.pathExistsSync(lambdaDir2) || exist(FRAMEWORK_MODE_LAMBDA_DIR);
232
- const existAppDir = exist(FRAMEWORK_MODE_APP_DIR);
233
- const existAppFile = exist("app.ts") || exist("app.js");
234
- if (existLambdaDir || existAppDir || existAppFile) {
235
- return APIMode.FARMEWORK;
236
- }
237
- return APIMode.FUNCTION;
238
- };
239
- this.createExistChecker = (base) => (target) => fs.pathExistsSync(path.resolve(base, target));
240
- this.getExactLambdaDir = (apiDir2, originLambdaDir) => {
241
- if (this.apiMode === APIMode.FUNCTION) {
242
- return apiDir2;
243
- }
244
- return originLambdaDir || path.join(apiDir2, FRAMEWORK_MODE_LAMBDA_DIR);
245
- };
246
- this.validateAbsolute(apiDir, "apiDir");
247
- this.validateAbsolute(lambdaDir, "lambdaDir");
248
- this.prefix = this.initPrefix(prefix);
249
- this.appDir = appDir;
250
- this.apiDir = apiDir;
251
- this.httpMethodDecider = httpMethodDecider;
252
- this.isBuild = isBuild;
253
- this.apiMode = this.getExactApiMode(apiDir, lambdaDir);
254
- this.lambdaDir = this.getExactLambdaDir(this.apiDir, lambdaDir);
255
- this.existLambdaDir = fs.existsSync(this.lambdaDir);
256
- debug(`apiDir:`, this.apiDir, `lambdaDir:`, this.lambdaDir);
257
- }
258
- }
259
- export {
260
- ApiRouter
261
- };
@@ -1,62 +0,0 @@
1
- import path from "path";
2
- import { compatibleRequire, globby } from "@modern-js/utils";
3
- import { INDEX_SUFFIX } from "./constants";
4
- const getFiles = (lambdaDir, rules) => globby.sync(rules, {
5
- cwd: lambdaDir,
6
- gitignore: true
7
- }).map((file) => path.resolve(lambdaDir, file));
8
- const getPathFromFilename = (baseDir, filename) => {
9
- const relativeName = filename.substring(baseDir.length);
10
- const relativePath = relativeName.split(".").slice(0, -1).join(".");
11
- const nameSplit = relativePath.split(path.sep).map((item) => {
12
- if (item.length > 2) {
13
- if (item.startsWith("[") && item.endsWith("]")) {
14
- return `:${item.substring(1, item.length - 1)}`;
15
- }
16
- }
17
- return item;
18
- });
19
- const name = nameSplit.join("/");
20
- const finalName = name.endsWith(INDEX_SUFFIX) ? name.substring(0, name.length - INDEX_SUFFIX.length) : name;
21
- return clearRouteName(finalName);
22
- };
23
- const clearRouteName = (routeName) => {
24
- let finalRouteName = routeName.trim();
25
- if (!finalRouteName.startsWith("/")) {
26
- finalRouteName = `/${finalRouteName}`;
27
- }
28
- if (finalRouteName.length > 1 && finalRouteName.endsWith("/")) {
29
- finalRouteName = finalRouteName.substring(0, finalRouteName.length - 1);
30
- }
31
- return finalRouteName;
32
- };
33
- const isHandler = (input) => input && typeof input === "function";
34
- const isFunction = (input) => input && {}.toString.call(input) === "[object Function]";
35
- const requireHandlerModule = async (modulePath) => {
36
- const originRequire = process.env.NODE_ENV === "test" ? jest.requireActual : compatibleRequire;
37
- const module = await originRequire(modulePath, false);
38
- if (isFunction(module)) {
39
- return {
40
- default: module
41
- };
42
- }
43
- return module;
44
- };
45
- const routeValue = (routePath) => {
46
- if (routePath.includes(":")) {
47
- return 11;
48
- }
49
- return 1;
50
- };
51
- const sortRoutes = (apiHandlers) => {
52
- return apiHandlers.sort((handlerA, handlerB) => {
53
- return routeValue(handlerA.routeName) - routeValue(handlerB.routeName);
54
- });
55
- };
56
- export {
57
- getFiles,
58
- getPathFromFilename,
59
- isHandler,
60
- requireHandlerModule,
61
- sortRoutes
62
- };
package/dist/esm/types.js DELETED
@@ -1,46 +0,0 @@
1
- var OperatorType;
2
- (function(OperatorType2) {
3
- OperatorType2[OperatorType2["Trigger"] = 0] = "Trigger";
4
- OperatorType2[OperatorType2["Middleware"] = 1] = "Middleware";
5
- })(OperatorType || (OperatorType = {}));
6
- var TriggerType;
7
- (function(TriggerType2) {
8
- TriggerType2[TriggerType2["Http"] = 0] = "Http";
9
- })(TriggerType || (TriggerType = {}));
10
- var HttpMetadata;
11
- (function(HttpMetadata2) {
12
- HttpMetadata2["Method"] = "METHOD";
13
- HttpMetadata2["Data"] = "DATA";
14
- HttpMetadata2["Query"] = "QUERY";
15
- HttpMetadata2["Params"] = "PARAMS";
16
- HttpMetadata2["Headers"] = "HEADERS";
17
- HttpMetadata2["Response"] = "RESPONSE";
18
- HttpMetadata2["Files"] = "Files";
19
- })(HttpMetadata || (HttpMetadata = {}));
20
- var ResponseMetaType;
21
- (function(ResponseMetaType2) {
22
- ResponseMetaType2[ResponseMetaType2["StatusCode"] = 0] = "StatusCode";
23
- ResponseMetaType2[ResponseMetaType2["Redirect"] = 1] = "Redirect";
24
- ResponseMetaType2[ResponseMetaType2["Headers"] = 2] = "Headers";
25
- })(ResponseMetaType || (ResponseMetaType = {}));
26
- var HttpMethod;
27
- (function(HttpMethod2) {
28
- HttpMethod2["Get"] = "GET";
29
- HttpMethod2["Post"] = "POST";
30
- HttpMethod2["Put"] = "PUT";
31
- HttpMethod2["Delete"] = "DELETE";
32
- HttpMethod2["Connect"] = "CONNECT";
33
- HttpMethod2["Trace"] = "TRACE";
34
- HttpMethod2["Patch"] = "PATCH";
35
- HttpMethod2["Options"] = "OPTIONS";
36
- HttpMethod2["Head"] = "HEAD";
37
- })(HttpMethod || (HttpMethod = {}));
38
- const httpMethods = Object.values(HttpMethod);
39
- export {
40
- HttpMetadata,
41
- HttpMethod,
42
- OperatorType,
43
- ResponseMetaType,
44
- TriggerType,
45
- httpMethods
46
- };
@@ -1,75 +0,0 @@
1
- import fs from "fs";
2
- import Module from "module";
3
- import * as os from "os";
4
- import * as path from "path";
5
- const getRelativeRuntimePath = (appDirectory, serverRuntimePath) => {
6
- let relativeRuntimePath = "";
7
- if (os.platform() === "win32") {
8
- relativeRuntimePath = `../${path.relative(appDirectory, serverRuntimePath)}`;
9
- } else {
10
- relativeRuntimePath = path.join("../", path.relative(appDirectory, serverRuntimePath));
11
- }
12
- if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
13
- relativeRuntimePath = `./${path.relative(appDirectory, serverRuntimePath)}`;
14
- }
15
- return relativeRuntimePath;
16
- };
17
- const sortByLongestPrefix = (arr) => {
18
- return arr.concat().sort((a, b) => b.length - a.length);
19
- };
20
- const createMatchPath = (paths) => {
21
- const sortedKeys = sortByLongestPrefix(Object.keys(paths));
22
- const sortedPaths = {};
23
- sortedKeys.forEach((key) => {
24
- sortedPaths[key] = paths[key];
25
- });
26
- return (request) => {
27
- const found = Object.keys(sortedPaths).find((key) => {
28
- return request.startsWith(key);
29
- });
30
- if (found) {
31
- let foundPaths = sortedPaths[found];
32
- if (!Array.isArray(foundPaths)) {
33
- foundPaths = [
34
- foundPaths
35
- ];
36
- }
37
- foundPaths = foundPaths.filter((foundPath) => path.isAbsolute(foundPath));
38
- for (const p of foundPaths) {
39
- const foundPath = request.replace(found, p);
40
- if (fs.existsSync(foundPath)) {
41
- return foundPath;
42
- }
43
- }
44
- return request.replace(found, foundPaths[0]);
45
- }
46
- return null;
47
- };
48
- };
49
- const registerPaths = (paths) => {
50
- const originalResolveFilename = Module._resolveFilename;
51
- const { builtinModules } = Module;
52
- const matchPath = createMatchPath(paths);
53
- Module._resolveFilename = function(request, _parent) {
54
- const isCoreModule = builtinModules.includes(request);
55
- if (!isCoreModule) {
56
- const matched = matchPath(request);
57
- if (matched) {
58
- const modifiedArguments = [
59
- matched,
60
- ...[].slice.call(arguments, 1)
61
- ];
62
- return originalResolveFilename.apply(this, modifiedArguments);
63
- }
64
- }
65
- return originalResolveFilename.apply(this, arguments);
66
- };
67
- return () => {
68
- Module._resolveFilename = originalResolveFilename;
69
- };
70
- };
71
- export {
72
- createMatchPath,
73
- getRelativeRuntimePath,
74
- registerPaths
75
- };
@@ -1,5 +0,0 @@
1
- import { createDebugger } from "@modern-js/utils";
2
- const debug = createDebugger("bff");
3
- export {
4
- debug
5
- };
@@ -1,14 +0,0 @@
1
- const HANDLER_WITH_META = "HANDLER_WITH_META";
2
- const INPUT_PARAMS_DECIDER = "INPUT_PARAMS_DECIDER";
3
- const isWithMetaHandler = (handler) => {
4
- return typeof handler === "function" && handler[HANDLER_WITH_META];
5
- };
6
- const isInputParamsDeciderHandler = (handler) => {
7
- return typeof handler === "function" && handler[INPUT_PARAMS_DECIDER];
8
- };
9
- export {
10
- HANDLER_WITH_META,
11
- INPUT_PARAMS_DECIDER,
12
- isInputParamsDeciderHandler,
13
- isWithMetaHandler
14
- };
@@ -1,40 +0,0 @@
1
- import * as ah from "async_hooks";
2
- const createStorage = () => {
3
- let storage;
4
- if (typeof ah.AsyncLocalStorage !== "undefined") {
5
- storage = new ah.AsyncLocalStorage();
6
- }
7
- const run = (context, cb) => {
8
- if (!storage) {
9
- throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
10
- `);
11
- }
12
- return new Promise((resolve, reject) => {
13
- storage.run(context, () => {
14
- try {
15
- return resolve(cb());
16
- } catch (error) {
17
- return reject(error);
18
- }
19
- });
20
- });
21
- };
22
- const useContext = () => {
23
- if (!storage) {
24
- throw new Error(`Unable to use async_hook, please confirm the node version >= 12.17
25
- `);
26
- }
27
- const context = storage.getStore();
28
- if (!context) {
29
- throw new Error(`Can't call useContext out of scope, it should be placed in the bff function`);
30
- }
31
- return context;
32
- };
33
- return {
34
- run,
35
- useContext
36
- };
37
- };
38
- export {
39
- createStorage
40
- };
@@ -1,45 +0,0 @@
1
- import util from "util";
2
- const getTypeErrorMessage = (actual) => {
3
- let msg = "";
4
- if (actual == null) {
5
- msg += `. Received ${actual}`;
6
- } else if (typeof actual === "function" && actual.name) {
7
- msg += `. Received function ${actual.name}`;
8
- } else if (typeof actual === "object") {
9
- var _actual_constructor;
10
- if ((_actual_constructor = actual.constructor) === null || _actual_constructor === void 0 ? void 0 : _actual_constructor.name) {
11
- msg += `. Received an instance of ${actual.constructor.name}`;
12
- } else {
13
- const inspected = util.inspect(actual, {
14
- depth: -1
15
- });
16
- msg += `. Received ${inspected}`;
17
- }
18
- } else {
19
- let inspected = util.inspect(actual, {
20
- colors: false
21
- });
22
- if (inspected.length > 25) {
23
- inspected = `${inspected.slice(0, 25)}...`;
24
- }
25
- msg += `. Received type ${typeof actual} (${inspected})`;
26
- }
27
- return msg;
28
- };
29
- class ERR_INVALID_ARG_TYPE extends Error {
30
- constructor(funcName, expectedType, actual) {
31
- const message = `[ERR_INVALID_ARG_TYPE]: The '${funcName}' argument must be of type ${expectedType}${getTypeErrorMessage(actual)}`;
32
- super(message);
33
- }
34
- }
35
- const validateFunction = (maybeFunc, name) => {
36
- if (typeof maybeFunc !== "function") {
37
- throw new ERR_INVALID_ARG_TYPE(name, "function", maybeFunc);
38
- }
39
- return true;
40
- };
41
- export {
42
- ERR_INVALID_ARG_TYPE,
43
- getTypeErrorMessage,
44
- validateFunction
45
- };
File without changes