@modern-js/bff-core 2.6.1-alpha.1 → 2.7.1-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 (48) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/cjs/client/generateClient.js +3 -3
  3. package/dist/cjs/operators/http.js +3 -3
  4. package/dist/cjs/router/index.js +2 -2
  5. package/dist/cjs/types.js +1 -1
  6. package/dist/esm/client/generateClient.js +3 -3
  7. package/dist/esm/operators/http.js +2 -2
  8. package/dist/esm/router/index.js +2 -2
  9. package/dist/esm/types.js +1 -1
  10. package/dist/js/modern/api.js +69 -0
  11. package/dist/js/modern/client/generate-client.js +79 -0
  12. package/dist/js/modern/client/index.js +1 -0
  13. package/dist/js/modern/client/result.js +22 -0
  14. package/dist/js/modern/errors/http.js +16 -0
  15. package/dist/js/modern/index.js +23 -0
  16. package/dist/js/modern/operators/http.js +210 -0
  17. package/dist/js/modern/router/constants.js +32 -0
  18. package/dist/js/modern/router/index.js +236 -0
  19. package/dist/js/modern/router/types.js +0 -0
  20. package/dist/js/modern/router/utils.js +83 -0
  21. package/dist/js/modern/types.js +45 -0
  22. package/dist/js/modern/utils/alias.js +76 -0
  23. package/dist/js/modern/utils/debug.js +5 -0
  24. package/dist/js/modern/utils/index.js +8 -0
  25. package/dist/js/modern/utils/meta.js +8 -0
  26. package/dist/js/modern/utils/storage.js +42 -0
  27. package/dist/js/modern/utils/validate.js +43 -0
  28. package/dist/js/node/api.js +98 -0
  29. package/dist/js/node/client/generate-client.js +109 -0
  30. package/dist/js/node/client/index.js +17 -0
  31. package/dist/js/node/client/result.js +46 -0
  32. package/dist/js/node/errors/http.js +40 -0
  33. package/dist/js/node/index.js +48 -0
  34. package/dist/js/node/operators/http.js +241 -0
  35. package/dist/js/node/router/constants.js +61 -0
  36. package/dist/js/node/router/index.js +256 -0
  37. package/dist/js/node/router/types.js +15 -0
  38. package/dist/js/node/router/utils.js +116 -0
  39. package/dist/js/node/types.js +73 -0
  40. package/dist/js/node/utils/alias.js +107 -0
  41. package/dist/js/node/utils/debug.js +28 -0
  42. package/dist/js/node/utils/index.js +32 -0
  43. package/dist/js/node/utils/meta.js +32 -0
  44. package/dist/js/node/utils/storage.js +71 -0
  45. package/dist/js/node/utils/validate.js +74 -0
  46. package/dist/types/operators/http.d.ts +1 -1
  47. package/dist/types/types.d.ts +2 -2
  48. package/package.json +6 -6
@@ -0,0 +1,236 @@
1
+ import path from "path";
2
+ import { fs, logger } from "@modern-js/utils";
3
+ import "reflect-metadata";
4
+ import { HttpMethod, httpMethods, OperatorType, TriggerType } from "../types";
5
+ import { debug } from "../utils";
6
+ import {
7
+ APIMode,
8
+ FRAMEWORK_MODE_LAMBDA_DIR,
9
+ API_FILE_RULES,
10
+ FRAMEWORK_MODE_APP_DIR
11
+ } from "./constants";
12
+ import {
13
+ getFiles,
14
+ getPathFromFilename,
15
+ requireHandlerModule,
16
+ sortRoutes
17
+ } from "./utils";
18
+ export * from "./types";
19
+ export * from "./constants";
20
+ class ApiRouter {
21
+ constructor({
22
+ apiDir,
23
+ lambdaDir,
24
+ prefix
25
+ }) {
26
+ this.apiFiles = [];
27
+ this.getExactApiMode = (apiDir) => {
28
+ const exist = this.createExistChecker(apiDir);
29
+ const existLambdaDir = exist(FRAMEWORK_MODE_LAMBDA_DIR);
30
+ const existAppDir = exist(FRAMEWORK_MODE_APP_DIR);
31
+ const existAppFile = exist("app.ts") || exist("app.js");
32
+ if (existLambdaDir || existAppDir || existAppFile) {
33
+ return APIMode.FARMEWORK;
34
+ }
35
+ return APIMode.FUNCTION;
36
+ };
37
+ this.createExistChecker = (base) => (target) => fs.pathExistsSync(path.resolve(base, target));
38
+ this.getExactLambdaDir = (apiDir) => {
39
+ if (this.lambdaDir) {
40
+ return this.lambdaDir;
41
+ }
42
+ const lambdaDir = this.apiMode === APIMode.FARMEWORK ? path.join(apiDir, FRAMEWORK_MODE_LAMBDA_DIR) : apiDir;
43
+ return lambdaDir;
44
+ };
45
+ this.validateAbsolute(apiDir, "apiDir");
46
+ this.validateAbsolute(lambdaDir, "lambdaDir");
47
+ this.prefix = this.initPrefix(prefix);
48
+ this.apiDir = apiDir;
49
+ this.apiMode = this.getExactApiMode(apiDir);
50
+ this.lambdaDir = lambdaDir || this.getExactLambdaDir(this.apiDir);
51
+ this.existLambdaDir = fs.existsSync(this.lambdaDir);
52
+ }
53
+ isExistLambda() {
54
+ return this.existLambdaDir;
55
+ }
56
+ getApiMode() {
57
+ return this.apiMode;
58
+ }
59
+ getLambdaDir() {
60
+ return this.lambdaDir;
61
+ }
62
+ isApiFile(filename) {
63
+ if (this.existLambdaDir) {
64
+ return false;
65
+ }
66
+ if (!this.apiFiles.includes(filename)) {
67
+ return false;
68
+ }
69
+ return true;
70
+ }
71
+ getSingleModuleHandlers(filename) {
72
+ const moduleInfo = this.getModuleInfo(filename);
73
+ if (moduleInfo) {
74
+ return this.getModuleHandlerInfos(moduleInfo);
75
+ }
76
+ return null;
77
+ }
78
+ getHandlerInfo(filename, originFuncName, handler) {
79
+ const httpMethod = this.getHttpMethod(originFuncName, handler);
80
+ const routeName = this.getRouteName(filename, handler);
81
+ if (httpMethod && routeName) {
82
+ return {
83
+ handler,
84
+ name: originFuncName,
85
+ httpMethod,
86
+ routeName,
87
+ filename,
88
+ routePath: this.getRoutePath(this.prefix, routeName)
89
+ };
90
+ }
91
+ return null;
92
+ }
93
+ getSafeRoutePath(filename, handler) {
94
+ this.loadApiFiles();
95
+ this.validateValidApifile(filename);
96
+ return this.getRouteName(filename, handler);
97
+ }
98
+ getRouteName(filename, handler) {
99
+ if (handler) {
100
+ const trigger = Reflect.getMetadata(OperatorType.Trigger, handler);
101
+ if (trigger && trigger.type === TriggerType.Http) {
102
+ if (!trigger.path) {
103
+ throw new Error(
104
+ `The http trigger ${trigger.name} needs to specify a path`
105
+ );
106
+ }
107
+ return trigger.path;
108
+ }
109
+ }
110
+ const routePath = getPathFromFilename(this.lambdaDir, filename);
111
+ return routePath;
112
+ }
113
+ getHttpMethod(originHandlerName, handler) {
114
+ if (handler) {
115
+ const trigger = Reflect.getMetadata(OperatorType.Trigger, handler);
116
+ if (trigger && httpMethods.includes(trigger.method)) {
117
+ return trigger.method;
118
+ }
119
+ }
120
+ const upperName = originHandlerName.toUpperCase();
121
+ switch (upperName) {
122
+ case "GET":
123
+ return HttpMethod.Get;
124
+ case "POST":
125
+ return HttpMethod.Post;
126
+ case "PUT":
127
+ return HttpMethod.Put;
128
+ case "DELETE":
129
+ case "DEL":
130
+ return HttpMethod.Delete;
131
+ case "CONNECT":
132
+ return HttpMethod.Connect;
133
+ case "TRACE":
134
+ return HttpMethod.Trace;
135
+ case "PATCH":
136
+ return HttpMethod.Patch;
137
+ case "OPTION":
138
+ return HttpMethod.Option;
139
+ case "DEFAULT": {
140
+ return HttpMethod.Get;
141
+ }
142
+ default:
143
+ logger.warn(
144
+ `Only api handlers are allowd to be exported, please remove the function ${originHandlerName} from exports`
145
+ );
146
+ return null;
147
+ }
148
+ }
149
+ loadApiFiles() {
150
+ if (!this.existLambdaDir) {
151
+ return [];
152
+ }
153
+ const apiFiles = this.apiFiles = getFiles(this.lambdaDir, API_FILE_RULES);
154
+ return apiFiles;
155
+ }
156
+ getApiFiles() {
157
+ if (!this.existLambdaDir) {
158
+ return [];
159
+ }
160
+ if (this.apiFiles.length > 0) {
161
+ return this.apiFiles;
162
+ }
163
+ return this.loadApiFiles();
164
+ }
165
+ getApiHandlers() {
166
+ const filenames = this.getApiFiles();
167
+ const moduleInfos = this.getModuleInfos(filenames);
168
+ const apiHandlers = this.getHandlerInfos(moduleInfos);
169
+ debug("apiHandlers", apiHandlers.length, apiHandlers);
170
+ return apiHandlers;
171
+ }
172
+ initPrefix(prefix) {
173
+ if (prefix === "/") {
174
+ return "";
175
+ }
176
+ return prefix || "/api";
177
+ }
178
+ validateAbsolute(filename, paramsName) {
179
+ if (typeof filename === "string" && !path.isAbsolute(filename)) {
180
+ throw new Error(`The ${paramsName} ${filename} is not a abolute path`);
181
+ }
182
+ }
183
+ getModuleInfos(filenames) {
184
+ return filenames.map((filename) => this.getModuleInfo(filename)).filter((moduleInfo) => Boolean(moduleInfo));
185
+ }
186
+ getModuleInfo(filename) {
187
+ try {
188
+ const module = requireHandlerModule(filename);
189
+ return {
190
+ filename,
191
+ module
192
+ };
193
+ } catch (err) {
194
+ if (process.env.NODE_ENV === "production") {
195
+ throw err;
196
+ } else {
197
+ console.error(err);
198
+ return null;
199
+ }
200
+ }
201
+ }
202
+ getHandlerInfos(moduleInfos) {
203
+ let apiHandlers = [];
204
+ moduleInfos.forEach((moduleInfo) => {
205
+ const handlerInfos = this.getModuleHandlerInfos(moduleInfo);
206
+ if (handlerInfos) {
207
+ apiHandlers = apiHandlers.concat(handlerInfos);
208
+ }
209
+ });
210
+ const sortedHandlers = sortRoutes(apiHandlers);
211
+ return sortedHandlers;
212
+ }
213
+ getModuleHandlerInfos(moduleInfo) {
214
+ const { module, filename } = moduleInfo;
215
+ return Object.entries(module).filter(([, handler]) => typeof handler === "function").map(([key]) => {
216
+ const handler = module[key];
217
+ const handlerInfo = this.getHandlerInfo(filename, key, handler);
218
+ return handlerInfo;
219
+ }).filter((handlerInfo) => Boolean(handlerInfo));
220
+ }
221
+ validateValidApifile(filename) {
222
+ if (!this.apiFiles.includes(filename)) {
223
+ throw new Error(`The ${filename} is not a valid api file.`);
224
+ }
225
+ }
226
+ getRoutePath(prefix, routeName) {
227
+ const finalRouteName = routeName === "/" ? "" : routeName;
228
+ if (prefix === "" && finalRouteName === "") {
229
+ return "/";
230
+ }
231
+ return `${prefix}${finalRouteName}`;
232
+ }
233
+ }
234
+ export {
235
+ ApiRouter
236
+ };
File without changes
@@ -0,0 +1,83 @@
1
+ import path from "path";
2
+ import { 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 enableRegister = (requireFn) => {
35
+ let existTsLoader = false;
36
+ let firstCall = true;
37
+ return (modulePath) => {
38
+ if (firstCall) {
39
+ existTsLoader = Boolean(require.extensions[".ts"]);
40
+ firstCall = false;
41
+ }
42
+ if (!existTsLoader) {
43
+ const {
44
+ register
45
+ } = require("esbuild-register/dist/node");
46
+ const { unregister } = register({
47
+ extensions: [".ts"]
48
+ });
49
+ const requiredModule2 = requireFn(modulePath);
50
+ unregister();
51
+ return requiredModule2;
52
+ }
53
+ const requiredModule = requireFn(modulePath);
54
+ return requiredModule;
55
+ };
56
+ };
57
+ const isFunction = (input) => input && {}.toString.call(input) === "[object Function]";
58
+ const requireHandlerModule = enableRegister((modulePath) => {
59
+ const originRequire = process.env.NODE_ENV === "test" ? jest.requireActual : require;
60
+ const module = originRequire(modulePath);
61
+ if (isFunction(module)) {
62
+ return { default: module };
63
+ }
64
+ return module;
65
+ });
66
+ const routeValue = (routePath) => {
67
+ if (routePath.includes(":")) {
68
+ return 11;
69
+ }
70
+ return 1;
71
+ };
72
+ const sortRoutes = (apiHandlers) => {
73
+ return apiHandlers.sort((handlerA, handlerB) => {
74
+ return routeValue(handlerA.routeName) - routeValue(handlerB.routeName);
75
+ });
76
+ };
77
+ export {
78
+ getFiles,
79
+ getPathFromFilename,
80
+ isHandler,
81
+ requireHandlerModule,
82
+ sortRoutes
83
+ };
@@ -0,0 +1,45 @@
1
+ var OperatorType = /* @__PURE__ */ ((OperatorType2) => {
2
+ OperatorType2[OperatorType2["Trigger"] = 0] = "Trigger";
3
+ OperatorType2[OperatorType2["Middleware"] = 1] = "Middleware";
4
+ return OperatorType2;
5
+ })(OperatorType || {});
6
+ var TriggerType = /* @__PURE__ */ ((TriggerType2) => {
7
+ TriggerType2[TriggerType2["Http"] = 0] = "Http";
8
+ return TriggerType2;
9
+ })(TriggerType || {});
10
+ var HttpMetadata = /* @__PURE__ */ ((HttpMetadata2) => {
11
+ HttpMetadata2["Method"] = "METHOD";
12
+ HttpMetadata2["Data"] = "DATA";
13
+ HttpMetadata2["Query"] = "QUERY";
14
+ HttpMetadata2["Params"] = "PARAMS";
15
+ HttpMetadata2["Headers"] = "HEADERS";
16
+ HttpMetadata2["Response"] = "RESPONSE";
17
+ return HttpMetadata2;
18
+ })(HttpMetadata || {});
19
+ var ResponseMetaType = /* @__PURE__ */ ((ResponseMetaType2) => {
20
+ ResponseMetaType2[ResponseMetaType2["StatusCode"] = 0] = "StatusCode";
21
+ ResponseMetaType2[ResponseMetaType2["Redirect"] = 1] = "Redirect";
22
+ ResponseMetaType2[ResponseMetaType2["Headers"] = 2] = "Headers";
23
+ return ResponseMetaType2;
24
+ })(ResponseMetaType || {});
25
+ var HttpMethod = /* @__PURE__ */ ((HttpMethod2) => {
26
+ HttpMethod2["Get"] = "GET";
27
+ HttpMethod2["Post"] = "POST";
28
+ HttpMethod2["Put"] = "PUT";
29
+ HttpMethod2["Delete"] = "DELETE";
30
+ HttpMethod2["Connect"] = "CONNECT";
31
+ HttpMethod2["Trace"] = "TRACE";
32
+ HttpMethod2["Patch"] = "PATCH";
33
+ HttpMethod2["Option"] = "OPTION";
34
+ HttpMethod2["Head"] = "HEAD";
35
+ return HttpMethod2;
36
+ })(HttpMethod || {});
37
+ const httpMethods = Object.values(HttpMethod);
38
+ export {
39
+ HttpMetadata,
40
+ HttpMethod,
41
+ OperatorType,
42
+ ResponseMetaType,
43
+ TriggerType,
44
+ httpMethods
45
+ };
@@ -0,0 +1,76 @@
1
+ import * as path from "path";
2
+ import * as os from "os";
3
+ import fs from "fs";
4
+ import Module from "module";
5
+ const getRelativeRuntimePath = (appDirectory, serverRuntimePath) => {
6
+ let relativeRuntimePath = "";
7
+ if (os.platform() === "win32") {
8
+ relativeRuntimePath = `../${path.relative(
9
+ appDirectory,
10
+ serverRuntimePath
11
+ )}`;
12
+ } else {
13
+ relativeRuntimePath = path.join(
14
+ "../",
15
+ path.relative(appDirectory, serverRuntimePath)
16
+ );
17
+ }
18
+ if (process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test") {
19
+ relativeRuntimePath = `./${path.relative(appDirectory, serverRuntimePath)}`;
20
+ }
21
+ return relativeRuntimePath;
22
+ };
23
+ const sortByLongestPrefix = (arr) => {
24
+ return arr.concat().sort((a, b) => b.length - a.length);
25
+ };
26
+ const createMatchPath = (paths) => {
27
+ const sortedKeys = sortByLongestPrefix(Object.keys(paths));
28
+ const sortedPaths = {};
29
+ sortedKeys.forEach((key) => {
30
+ sortedPaths[key] = paths[key];
31
+ });
32
+ return (request) => {
33
+ const found = Object.keys(sortedPaths).find((key) => {
34
+ return request.startsWith(key);
35
+ });
36
+ if (found) {
37
+ let foundPaths = sortedPaths[found];
38
+ if (!Array.isArray(foundPaths)) {
39
+ foundPaths = [foundPaths];
40
+ }
41
+ foundPaths = foundPaths.filter((foundPath) => path.isAbsolute(foundPath));
42
+ for (const p of foundPaths) {
43
+ const foundPath = request.replace(found, p);
44
+ if (fs.existsSync(foundPath)) {
45
+ return foundPath;
46
+ }
47
+ }
48
+ return request.replace(found, foundPaths[0]);
49
+ }
50
+ return null;
51
+ };
52
+ };
53
+ const registerPaths = (paths) => {
54
+ const originalResolveFilename = Module._resolveFilename;
55
+ const { builtinModules } = Module;
56
+ const matchPath = createMatchPath(paths);
57
+ Module._resolveFilename = function(request, _parent) {
58
+ const isCoreModule = builtinModules.includes(request);
59
+ if (!isCoreModule) {
60
+ const matched = matchPath(request);
61
+ if (matched) {
62
+ const modifiedArguments = [matched, ...[].slice.call(arguments, 1)];
63
+ return originalResolveFilename.apply(this, modifiedArguments);
64
+ }
65
+ }
66
+ return originalResolveFilename.apply(this, arguments);
67
+ };
68
+ return () => {
69
+ Module._resolveFilename = originalResolveFilename;
70
+ };
71
+ };
72
+ export {
73
+ createMatchPath,
74
+ getRelativeRuntimePath,
75
+ registerPaths
76
+ };
@@ -0,0 +1,5 @@
1
+ import { createDebugger } from "@modern-js/utils";
2
+ const debug = createDebugger("bff");
3
+ export {
4
+ debug
5
+ };
@@ -0,0 +1,8 @@
1
+ export * from "./storage";
2
+ export * from "./alias";
3
+ import { debug } from "./debug";
4
+ export * from "./meta";
5
+ export * from "./validate";
6
+ export {
7
+ debug
8
+ };
@@ -0,0 +1,8 @@
1
+ const HANDLER_WITH_META = "HANDLER_WITH_META";
2
+ const isWithMetaHandler = (handler) => {
3
+ return typeof handler === "function" && handler[HANDLER_WITH_META];
4
+ };
5
+ export {
6
+ HANDLER_WITH_META,
7
+ isWithMetaHandler
8
+ };
@@ -0,0 +1,42 @@
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(
30
+ `Can't call useContext out of scope, it should be placed in the bff function`
31
+ );
32
+ }
33
+ return context;
34
+ };
35
+ return {
36
+ run,
37
+ useContext
38
+ };
39
+ };
40
+ export {
41
+ createStorage
42
+ };
@@ -0,0 +1,43 @@
1
+ import util from "util";
2
+ const getTypeErrorMessage = (actual) => {
3
+ var _a;
4
+ let msg = "";
5
+ if (actual == null) {
6
+ msg += `. Received ${actual}`;
7
+ } else if (typeof actual === "function" && actual.name) {
8
+ msg += `. Received function ${actual.name}`;
9
+ } else if (typeof actual === "object") {
10
+ if ((_a = actual.constructor) == null ? void 0 : _a.name) {
11
+ msg += `. Received an instance of ${actual.constructor.name}`;
12
+ } else {
13
+ const inspected = util.inspect(actual, { depth: -1 });
14
+ msg += `. Received ${inspected}`;
15
+ }
16
+ } else {
17
+ let inspected = util.inspect(actual, { colors: false });
18
+ if (inspected.length > 25) {
19
+ inspected = `${inspected.slice(0, 25)}...`;
20
+ }
21
+ msg += `. Received type ${typeof actual} (${inspected})`;
22
+ }
23
+ return msg;
24
+ };
25
+ class ERR_INVALID_ARG_TYPE extends Error {
26
+ constructor(funcName, expectedType, actual) {
27
+ const message = `[ERR_INVALID_ARG_TYPE]: The '${funcName}' argument must be of type ${expectedType}${getTypeErrorMessage(
28
+ actual
29
+ )}`;
30
+ super(message);
31
+ }
32
+ }
33
+ const validateFunction = (maybeFunc, name) => {
34
+ if (typeof maybeFunc !== "function") {
35
+ throw new ERR_INVALID_ARG_TYPE(name, "function", maybeFunc);
36
+ }
37
+ return true;
38
+ };
39
+ export {
40
+ ERR_INVALID_ARG_TYPE,
41
+ getTypeErrorMessage,
42
+ validateFunction
43
+ };
@@ -0,0 +1,98 @@
1
+ var __create = Object.create;
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
+ var __getOwnPropNames = Object.getOwnPropertyNames;
5
+ var __getProtoOf = Object.getPrototypeOf;
6
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
7
+ var __export = (target, all) => {
8
+ for (var name in all)
9
+ __defProp(target, name, { get: all[name], enumerable: true });
10
+ };
11
+ var __copyProps = (to, from, except, desc) => {
12
+ if (from && typeof from === "object" || typeof from === "function") {
13
+ for (let key of __getOwnPropNames(from))
14
+ if (!__hasOwnProp.call(to, key) && key !== except)
15
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
16
+ }
17
+ return to;
18
+ };
19
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
20
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
21
+ mod
22
+ ));
23
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
24
+ var __async = (__this, __arguments, generator) => {
25
+ return new Promise((resolve, reject) => {
26
+ var fulfilled = (value) => {
27
+ try {
28
+ step(generator.next(value));
29
+ } catch (e) {
30
+ reject(e);
31
+ }
32
+ };
33
+ var rejected = (value) => {
34
+ try {
35
+ step(generator.throw(value));
36
+ } catch (e) {
37
+ reject(e);
38
+ }
39
+ };
40
+ var step = (x) => x.done ? resolve(x.value) : Promise.resolve(x.value).then(fulfilled, rejected);
41
+ step((generator = generator.apply(__this, __arguments)).next());
42
+ });
43
+ };
44
+ var api_exports = {};
45
+ __export(api_exports, {
46
+ Api: () => Api
47
+ });
48
+ module.exports = __toCommonJS(api_exports);
49
+ var import_reflect_metadata = require("reflect-metadata");
50
+ var import_koa_compose = __toESM(require("koa-compose"));
51
+ var import_utils = require("./utils");
52
+ function Api(...args) {
53
+ const handler = args.pop();
54
+ (0, import_utils.validateFunction)(handler, "Apihandler");
55
+ const operators = args;
56
+ const metadataHelper = {
57
+ getMetadata(key) {
58
+ return Reflect.getMetadata(key, runner);
59
+ },
60
+ setMetadata(key, value) {
61
+ return Reflect.defineMetadata(key, value, runner);
62
+ }
63
+ };
64
+ for (const operator of operators) {
65
+ if (operator.metadata) {
66
+ operator.metadata(metadataHelper);
67
+ }
68
+ }
69
+ const validateHandlers = operators.filter((operator) => operator.validate).map((operator) => operator.validate);
70
+ const pipeHandlers = operators.filter((operator) => operator.execute).map((operator) => operator.execute);
71
+ function runner(inputs) {
72
+ return __async(this, null, function* () {
73
+ const executeHelper = {
74
+ result: null,
75
+ get inputs() {
76
+ return inputs;
77
+ },
78
+ set inputs(val) {
79
+ inputs = val;
80
+ }
81
+ };
82
+ const stack = [...validateHandlers, ...pipeHandlers];
83
+ stack.push((helper, next) => __async(this, null, function* () {
84
+ const res = yield handler(helper.inputs);
85
+ helper.result = res;
86
+ return next();
87
+ }));
88
+ yield (0, import_koa_compose.default)(stack)(executeHelper);
89
+ return executeHelper.result;
90
+ });
91
+ }
92
+ runner[import_utils.HANDLER_WITH_META] = true;
93
+ return runner;
94
+ }
95
+ // Annotate the CommonJS export names for ESM import in node:
96
+ 0 && (module.exports = {
97
+ Api
98
+ });