@modern-js/plugin-bff 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 (76) hide show
  1. package/dist/cjs/cli.js +256 -272
  2. package/dist/cjs/constants.js +43 -34
  3. package/dist/cjs/index.js +55 -19
  4. package/dist/cjs/loader.js +69 -65
  5. package/dist/cjs/runtime/create-request/index.js +39 -29
  6. package/dist/cjs/runtime/hono/adapter.js +128 -126
  7. package/dist/cjs/runtime/hono/index.js +78 -30
  8. package/dist/cjs/runtime/hono/operators.js +64 -67
  9. package/dist/cjs/server.js +159 -165
  10. package/dist/cjs/utils/clientGenerator.js +204 -206
  11. package/dist/cjs/utils/createHonoRoutes.js +128 -144
  12. package/dist/cjs/utils/crossProjectApiPlugin.js +91 -81
  13. package/dist/cjs/utils/pluginGenerator.js +66 -54
  14. package/dist/cjs/utils/runtimeGenerator.js +67 -45
  15. package/dist/esm/cli.mjs +214 -0
  16. package/dist/esm/constants.mjs +11 -0
  17. package/dist/esm/loader.mjs +39 -0
  18. package/dist/esm/runtime/create-request/{index.js → index.mjs} +1 -5
  19. package/dist/esm/runtime/hono/adapter.mjs +95 -0
  20. package/dist/{esm-node/runtime/hono/index.js → esm/runtime/hono/index.mjs} +2 -4
  21. package/dist/esm/runtime/hono/operators.mjs +31 -0
  22. package/dist/esm/server.mjs +122 -0
  23. package/dist/esm/utils/clientGenerator.mjs +175 -0
  24. package/dist/esm/utils/createHonoRoutes.mjs +91 -0
  25. package/dist/esm/utils/crossProjectApiPlugin.mjs +34 -0
  26. package/dist/esm/utils/pluginGenerator.mjs +29 -0
  27. package/dist/esm/utils/runtimeGenerator.mjs +43 -0
  28. package/dist/esm-node/cli.mjs +214 -0
  29. package/dist/esm-node/constants.mjs +11 -0
  30. package/dist/esm-node/index.mjs +1 -0
  31. package/dist/esm-node/loader.mjs +39 -0
  32. package/dist/esm-node/runtime/create-request/{index.js → index.mjs} +1 -5
  33. package/dist/esm-node/runtime/hono/adapter.mjs +95 -0
  34. package/dist/{esm/runtime/hono/index.js → esm-node/runtime/hono/index.mjs} +3 -5
  35. package/dist/esm-node/runtime/hono/operators.mjs +31 -0
  36. package/dist/esm-node/server.mjs +122 -0
  37. package/dist/esm-node/utils/clientGenerator.mjs +175 -0
  38. package/dist/esm-node/utils/createHonoRoutes.mjs +91 -0
  39. package/dist/esm-node/utils/crossProjectApiPlugin.mjs +34 -0
  40. package/dist/esm-node/utils/pluginGenerator.mjs +29 -0
  41. package/dist/esm-node/utils/runtimeGenerator.mjs +43 -0
  42. package/dist/types/loader.d.ts +2 -2
  43. package/dist/types/runtime/hono/adapter.d.ts +3 -3
  44. package/dist/types/server.d.ts +2 -2
  45. package/dist/types/utils/runtimeGenerator.d.ts +2 -1
  46. package/package.json +54 -32
  47. package/rslib.config.mts +4 -0
  48. package/dist/cjs/helper.js +0 -48
  49. package/dist/esm/cli.js +0 -425
  50. package/dist/esm/constants.js +0 -14
  51. package/dist/esm/helper.js +0 -13
  52. package/dist/esm/index.js +0 -1
  53. package/dist/esm/loader.js +0 -75
  54. package/dist/esm/runtime/hono/adapter.js +0 -243
  55. package/dist/esm/runtime/hono/operators.js +0 -79
  56. package/dist/esm/server.js +0 -258
  57. package/dist/esm/utils/clientGenerator.js +0 -517
  58. package/dist/esm/utils/createHonoRoutes.js +0 -319
  59. package/dist/esm/utils/crossProjectApiPlugin.js +0 -49
  60. package/dist/esm/utils/pluginGenerator.js +0 -94
  61. package/dist/esm/utils/runtimeGenerator.js +0 -55
  62. package/dist/esm-node/cli.js +0 -246
  63. package/dist/esm-node/constants.js +0 -14
  64. package/dist/esm-node/helper.js +0 -14
  65. package/dist/esm-node/loader.js +0 -49
  66. package/dist/esm-node/runtime/hono/adapter.js +0 -103
  67. package/dist/esm-node/runtime/hono/operators.js +0 -46
  68. package/dist/esm-node/server.js +0 -142
  69. package/dist/esm-node/utils/clientGenerator.js +0 -192
  70. package/dist/esm-node/utils/createHonoRoutes.js +0 -120
  71. package/dist/esm-node/utils/crossProjectApiPlugin.js +0 -47
  72. package/dist/esm-node/utils/pluginGenerator.js +0 -31
  73. package/dist/esm-node/utils/runtimeGenerator.js +0 -35
  74. package/dist/types/helper.d.ts +0 -2
  75. package/types.d.ts +0 -3
  76. /package/dist/{esm-node/index.js → esm/index.mjs} +0 -0
@@ -1,246 +0,0 @@
1
- import path from "path";
2
- import { ApiRouter } from "@modern-js/bff-core";
3
- import { compile } from "@modern-js/server-utils";
4
- import { fs, API_DIR, DEFAULT_API_PREFIX, SHARED_DIR, normalizeOutputPath } from "@modern-js/utils";
5
- import clientGenerator from "./utils/clientGenerator";
6
- import pluginGenerator from "./utils/pluginGenerator";
7
- import runtimeGenerator from "./utils/runtimeGenerator";
8
- const TS_CONFIG_FILENAME = "tsconfig.json";
9
- const RUNTIME_CREATE_REQUEST = "@modern-js/plugin-bff/runtime/create-request";
10
- const RUNTIME_HONO = "@modern-js/plugin-bff/hono";
11
- const bffPlugin = () => ({
12
- name: "@modern-js/plugin-bff",
13
- setup: (api) => {
14
- const compileApi = async () => {
15
- const { appDirectory, distDirectory, apiDirectory, sharedDirectory, moduleType } = api.useAppContext();
16
- const modernConfig = api.useResolvedConfigContext();
17
- const distDir = path.resolve(distDirectory);
18
- const apiDir = apiDirectory || path.resolve(appDirectory, API_DIR);
19
- const sharedDir = sharedDirectory || path.resolve(appDirectory, SHARED_DIR);
20
- const tsconfigPath = path.resolve(appDirectory, TS_CONFIG_FILENAME);
21
- const sourceDirs = [];
22
- if (await fs.pathExists(apiDir)) {
23
- sourceDirs.push(apiDir);
24
- }
25
- if (await fs.pathExists(sharedDir)) {
26
- sourceDirs.push(sharedDir);
27
- }
28
- const { server } = modernConfig;
29
- const { alias } = modernConfig.source;
30
- const { alias: resolveAlias } = modernConfig.resolve;
31
- const { babel } = modernConfig.tools;
32
- if (sourceDirs.length > 0) {
33
- const combinedAlias = [].concat(alias !== null && alias !== void 0 ? alias : []).concat(resolveAlias !== null && resolveAlias !== void 0 ? resolveAlias : []);
34
- await compile(appDirectory, {
35
- server,
36
- alias: combinedAlias,
37
- babelConfig: babel
38
- }, {
39
- sourceDirs,
40
- distDir,
41
- tsconfigPath,
42
- moduleType,
43
- throwErrorInsteadOfExit: true
44
- });
45
- }
46
- };
47
- const generator = async () => {
48
- var _modernConfig_output_distPath, _modernConfig_output;
49
- const { appDirectory, apiDirectory, lambdaDirectory, port } = api.useAppContext();
50
- const modernConfig = api.useResolvedConfigContext();
51
- const relativeDistPath = (modernConfig === null || modernConfig === void 0 ? void 0 : (_modernConfig_output = modernConfig.output) === null || _modernConfig_output === void 0 ? void 0 : (_modernConfig_output_distPath = _modernConfig_output.distPath) === null || _modernConfig_output_distPath === void 0 ? void 0 : _modernConfig_output_distPath.root) || "dist";
52
- const { bff } = modernConfig || {};
53
- const prefix = (bff === null || bff === void 0 ? void 0 : bff.prefix) || DEFAULT_API_PREFIX;
54
- const httpMethodDecider = bff === null || bff === void 0 ? void 0 : bff.httpMethodDecider;
55
- const apiRouter = new ApiRouter({
56
- apiDir: apiDirectory,
57
- appDir: appDirectory,
58
- lambdaDir: lambdaDirectory,
59
- prefix,
60
- httpMethodDecider,
61
- isBuild: true
62
- });
63
- const lambdaDir = apiRouter.getLambdaDir();
64
- const existLambda = apiRouter.isExistLambda();
65
- const runtime = (bff === null || bff === void 0 ? void 0 : bff.runtimeCreateRequest) || RUNTIME_CREATE_REQUEST;
66
- const relativeApiPath = path.relative(appDirectory, apiDirectory);
67
- const relativeLambdaPath = path.relative(appDirectory, lambdaDir);
68
- await pluginGenerator({
69
- prefix,
70
- appDirectory,
71
- relativeDistPath,
72
- relativeApiPath,
73
- relativeLambdaPath
74
- });
75
- await clientGenerator({
76
- prefix,
77
- appDir: appDirectory,
78
- apiDir: apiDirectory,
79
- lambdaDir,
80
- existLambda,
81
- port,
82
- requestCreator: bff === null || bff === void 0 ? void 0 : bff.requestCreator,
83
- httpMethodDecider,
84
- relativeDistPath,
85
- relativeApiPath
86
- });
87
- await runtimeGenerator({
88
- runtime,
89
- appDirectory,
90
- relativeDistPath
91
- });
92
- };
93
- const handleCrossProjectInvocation = async (isBuild = false) => {
94
- const { bff } = api.useResolvedConfigContext();
95
- if (bff === null || bff === void 0 ? void 0 : bff.crossProject) {
96
- if (!isBuild) {
97
- await compileApi();
98
- }
99
- await generator();
100
- }
101
- };
102
- const isHono = () => {
103
- const { bffRuntimeFramework } = api.useAppContext();
104
- return bffRuntimeFramework === "hono";
105
- };
106
- return {
107
- config() {
108
- var _api_useConfigContext_tools, _api_useConfigContext, _api_useConfigContext_bff, _api_useConfigContext1;
109
- const honoRuntimePath = isHono() ? {
110
- [RUNTIME_HONO]: RUNTIME_HONO
111
- } : void 0;
112
- const devServer = (_api_useConfigContext = api.useConfigContext()) === null || _api_useConfigContext === void 0 ? void 0 : (_api_useConfigContext_tools = _api_useConfigContext.tools) === null || _api_useConfigContext_tools === void 0 ? void 0 : _api_useConfigContext_tools.devServer;
113
- const prefix = ((_api_useConfigContext1 = api.useConfigContext()) === null || _api_useConfigContext1 === void 0 ? void 0 : (_api_useConfigContext_bff = _api_useConfigContext1.bff) === null || _api_useConfigContext_bff === void 0 ? void 0 : _api_useConfigContext_bff.prefix) || DEFAULT_API_PREFIX;
114
- if (typeof devServer === "object" && devServer !== null && !Array.isArray(devServer)) {
115
- const compress = devServer.compress;
116
- if (typeof compress === "undefined" || compress === true) {
117
- devServer.compress = {
118
- filter: (req) => {
119
- var _req_url;
120
- return !((_req_url = req.url) === null || _req_url === void 0 ? void 0 : _req_url.includes(prefix));
121
- }
122
- };
123
- }
124
- }
125
- return {
126
- tools: {
127
- bundlerChain: (chain, { CHAIN_ID, isServer }) => {
128
- const { port, appDirectory, apiDirectory, lambdaDirectory } = api.useAppContext();
129
- const modernConfig = api.useResolvedConfigContext();
130
- const { bff } = modernConfig || {};
131
- const prefix2 = (bff === null || bff === void 0 ? void 0 : bff.prefix) || DEFAULT_API_PREFIX;
132
- const httpMethodDecider = bff === null || bff === void 0 ? void 0 : bff.httpMethodDecider;
133
- const apiRouter = new ApiRouter({
134
- apiDir: apiDirectory,
135
- appDir: appDirectory,
136
- lambdaDir: lambdaDirectory,
137
- prefix: prefix2,
138
- httpMethodDecider,
139
- isBuild: true
140
- });
141
- const lambdaDir = apiRouter.getLambdaDir();
142
- const existLambda = apiRouter.isExistLambda();
143
- const apiRegexp = new RegExp(normalizeOutputPath(`${apiDirectory}${path.sep}.*(.[tj]s)$`));
144
- const name = isServer ? "server" : "client";
145
- chain.module.rule(CHAIN_ID.RULE.JS).exclude.add(apiRegexp);
146
- chain.module.rule("js-bff-api").test(apiRegexp).use("custom-loader").loader(require.resolve("./loader").replace(/\\/g, "/")).options({
147
- prefix: prefix2,
148
- appDir: appDirectory,
149
- apiDir: apiDirectory,
150
- lambdaDir,
151
- existLambda,
152
- port,
153
- target: name,
154
- // Internal field
155
- requestCreator: bff === null || bff === void 0 ? void 0 : bff.requestCreator,
156
- httpMethodDecider
157
- });
158
- chain.resolve.alias.set("@api", apiDirectory);
159
- chain.resolve.alias.set("@modern-js/runtime/bff", RUNTIME_CREATE_REQUEST);
160
- }
161
- },
162
- source: {
163
- moduleScopes: [
164
- `./${API_DIR}`,
165
- /create-request/
166
- ]
167
- },
168
- output: {
169
- externals: honoRuntimePath
170
- }
171
- };
172
- },
173
- modifyServerRoutes({ routes }) {
174
- const modernConfig = api.useResolvedConfigContext();
175
- const { bff } = modernConfig || {};
176
- const prefix = (bff === null || bff === void 0 ? void 0 : bff.prefix) || "/api";
177
- const prefixList = [];
178
- if (Array.isArray(prefix)) {
179
- prefixList.push(...prefix);
180
- } else {
181
- prefixList.push(prefix);
182
- }
183
- const apiServerRoutes = prefixList.map((pre) => ({
184
- urlPath: pre,
185
- isApi: true,
186
- entryPath: "",
187
- isSPA: false,
188
- isSSR: false
189
- }));
190
- if (!isHono() && (bff === null || bff === void 0 ? void 0 : bff.enableHandleWeb)) {
191
- return {
192
- routes: routes.map((route) => {
193
- return {
194
- ...route,
195
- isApi: true
196
- };
197
- }).concat(apiServerRoutes)
198
- };
199
- }
200
- return {
201
- routes: routes.concat(apiServerRoutes)
202
- };
203
- },
204
- _internalServerPlugins({ plugins }) {
205
- plugins.push({
206
- name: "@modern-js/plugin-bff/server"
207
- });
208
- return {
209
- plugins
210
- };
211
- },
212
- async beforeDev() {
213
- await handleCrossProjectInvocation();
214
- },
215
- async afterBuild() {
216
- await compileApi();
217
- await handleCrossProjectInvocation(true);
218
- },
219
- async watchFiles() {
220
- var _config_bff;
221
- const appContext = api.useAppContext();
222
- const config = api.useResolvedConfigContext();
223
- if (config === null || config === void 0 ? void 0 : (_config_bff = config.bff) === null || _config_bff === void 0 ? void 0 : _config_bff.crossProject) {
224
- return [
225
- appContext.apiDirectory
226
- ];
227
- } else {
228
- return [];
229
- }
230
- },
231
- async fileChange(e) {
232
- const { filename, eventType, isPrivate } = e;
233
- const { appDirectory, apiDirectory } = api.useAppContext();
234
- const relativeApiPath = path.relative(appDirectory, apiDirectory);
235
- if (!isPrivate && (eventType === "change" || eventType === "unlink") && filename.startsWith(`${relativeApiPath}/`) && (filename.endsWith(".ts") || filename.endsWith(".js"))) {
236
- await handleCrossProjectInvocation();
237
- }
238
- }
239
- };
240
- }
241
- });
242
- var cli_default = bffPlugin;
243
- export {
244
- bffPlugin,
245
- cli_default as default
246
- };
@@ -1,14 +0,0 @@
1
- const API_APP_NAME = "_app";
2
- const BUILD_FILES = [
3
- "**/*.[tj]sx?",
4
- "!**/*.test.jsx?",
5
- "!**/*.test.tsx?",
6
- "!**/*.spec.jsx?",
7
- "!**/*.spec.tsx?",
8
- "!__tests__/*.tsx?",
9
- "!__tests__/*.jsx?"
10
- ];
11
- export {
12
- API_APP_NAME,
13
- BUILD_FILES
14
- };
@@ -1,14 +0,0 @@
1
- import * as path from "path";
2
- import { registerPaths } from "@modern-js/bff-core";
3
- const serverRuntimeAlias = "@modern-js/runtime/server";
4
- const serverRuntimePath = ".runtime-exports/server";
5
- const registerModernRuntimePath = (internalDirectory) => {
6
- const paths = {
7
- [serverRuntimeAlias]: path.join(internalDirectory, serverRuntimePath)
8
- };
9
- const unRegister = registerPaths(paths);
10
- return unRegister;
11
- };
12
- export {
13
- registerModernRuntimePath
14
- };
@@ -1,49 +0,0 @@
1
- import { generateClient } from "@modern-js/bff-core";
2
- import { logger } from "@modern-js/utils";
3
- async function loader(source) {
4
- this.cacheable();
5
- const { resourcePath } = this;
6
- delete require.cache[resourcePath];
7
- const callback = this.async();
8
- const draftOptions = this.getOptions();
9
- const warning = `The file ${resourcePath} is not allowd to be imported in src directory, only API definition files are allowed.`;
10
- if (!draftOptions.existLambda) {
11
- logger.warn(warning);
12
- callback(null, `throw new Error('${warning}')`);
13
- return;
14
- }
15
- const options = {
16
- prefix: Array.isArray(draftOptions.prefix) ? draftOptions.prefix[0] : draftOptions.prefix,
17
- appDir: draftOptions.appDir,
18
- apiDir: draftOptions.apiDir,
19
- lambdaDir: draftOptions.lambdaDir,
20
- target: draftOptions.target,
21
- port: Number(draftOptions.port),
22
- source,
23
- resourcePath,
24
- httpMethodDecider: draftOptions.httpMethodDecider
25
- };
26
- const { lambdaDir } = draftOptions;
27
- if (!resourcePath.startsWith(lambdaDir)) {
28
- logger.warn(warning);
29
- callback(null, `throw new Error('${warning}')`);
30
- return;
31
- }
32
- if (draftOptions.fetcher) {
33
- options.fetcher = draftOptions.fetcher;
34
- }
35
- if (draftOptions.requestCreator) {
36
- options.requestCreator = draftOptions.requestCreator;
37
- }
38
- options.requireResolve = require.resolve;
39
- const result = await generateClient(options);
40
- if (result.isOk) {
41
- callback(void 0, result.value);
42
- } else {
43
- callback(void 0, `throw new Error('${result.value}')`);
44
- }
45
- }
46
- var loader_default = loader;
47
- export {
48
- loader_default as default
49
- };
@@ -1,103 +0,0 @@
1
- import { Hono } from "@modern-js/server-core";
2
- import { isProd, logger } from "@modern-js/utils";
3
- import createHonoRoutes from "../../utils/createHonoRoutes";
4
- const before = [
5
- "custom-server-hook",
6
- "custom-server-middleware",
7
- "render"
8
- ];
9
- class HonoAdapter {
10
- wrapInArray(handler) {
11
- if (Array.isArray(handler)) {
12
- return handler;
13
- } else {
14
- return [
15
- handler
16
- ];
17
- }
18
- }
19
- constructor(api) {
20
- this.apiMiddleware = [];
21
- this.apiServer = null;
22
- this.isHono = true;
23
- this.setHandlers = async () => {
24
- if (!this.isHono) {
25
- return;
26
- }
27
- const { apiHandlerInfos } = this.api.useAppContext();
28
- const honoHandlers = createHonoRoutes(apiHandlerInfos);
29
- this.apiMiddleware = honoHandlers.map(({ path, method, handler }) => ({
30
- name: "hono-bff-api",
31
- path,
32
- method,
33
- handler,
34
- order: "post",
35
- before
36
- }));
37
- };
38
- this.registerApiRoutes = async () => {
39
- if (!this.isHono) {
40
- return;
41
- }
42
- this.apiServer = new Hono();
43
- this.apiMiddleware.forEach(({ path = "*", method = "all", handler }) => {
44
- var _this_apiServer;
45
- const handlers = this.wrapInArray(handler);
46
- (_this_apiServer = this.apiServer) === null || _this_apiServer === void 0 ? void 0 : _this_apiServer[method](path, ...handlers);
47
- });
48
- this.apiServer.onError(async (err, c) => {
49
- try {
50
- const serverConfig = this.api.useConfigContext();
51
- const onErrorHandler = serverConfig === null || serverConfig === void 0 ? void 0 : serverConfig.onError;
52
- if (onErrorHandler) {
53
- const result = await onErrorHandler(err, c);
54
- if (result instanceof Response) {
55
- return result;
56
- }
57
- }
58
- } catch (configError) {
59
- logger.error(`Error in serverConfig.onError handler: ${configError}`);
60
- }
61
- return c.json({
62
- message: (err === null || err === void 0 ? void 0 : err.message) || "[BFF] Internal Server Error"
63
- }, (err === null || err === void 0 ? void 0 : err.status) || 500);
64
- });
65
- };
66
- this.registerMiddleware = async (options) => {
67
- const { prefix } = options;
68
- const { bffRuntimeFramework } = this.api.useAppContext();
69
- if (bffRuntimeFramework !== "hono") {
70
- this.isHono = false;
71
- return;
72
- }
73
- const { middlewares: globalMiddlewares } = this.api.useAppContext();
74
- await this.setHandlers();
75
- if (isProd()) {
76
- globalMiddlewares.push(...this.apiMiddleware);
77
- } else {
78
- await this.registerApiRoutes();
79
- const dynamicApiMiddleware = {
80
- name: "dynamic-bff-handler",
81
- path: `${prefix}/*`,
82
- method: "all",
83
- order: "post",
84
- before,
85
- handler: async (c, next) => {
86
- if (this.apiServer) {
87
- const response = await this.apiServer.fetch(c.req, c.env);
88
- if (response.status !== 404) {
89
- return new Response(response.body, response);
90
- }
91
- }
92
- await next();
93
- }
94
- };
95
- globalMiddlewares.push(dynamicApiMiddleware);
96
- }
97
- };
98
- this.api = api;
99
- }
100
- }
101
- export {
102
- HonoAdapter
103
- };
@@ -1,46 +0,0 @@
1
- import { useHonoContext } from "@modern-js/server-core";
2
- const Pipe = (func) => {
3
- return {
4
- name: "pipe",
5
- async execute(executeHelper, next) {
6
- const { inputs } = executeHelper;
7
- const ctx = useHonoContext();
8
- const { res } = ctx;
9
- if (typeof func === "function") {
10
- let isPiped = true;
11
- const end = (value) => {
12
- isPiped = false;
13
- if (typeof value === "function") {
14
- value(res);
15
- return;
16
- }
17
- return value;
18
- };
19
- const output = await func(inputs, end);
20
- if (!isPiped) {
21
- if (output) {
22
- return executeHelper.result = output;
23
- } else {
24
- return;
25
- }
26
- }
27
- executeHelper.inputs = output;
28
- await next();
29
- }
30
- }
31
- };
32
- };
33
- const Middleware = (middleware) => {
34
- return {
35
- name: "middleware",
36
- metadata(helper) {
37
- const middlewares = helper.getMetadata("pipe") || [];
38
- middlewares.push(middleware);
39
- helper.setMetadata("middleware", middlewares);
40
- }
41
- };
42
- };
43
- export {
44
- Middleware,
45
- Pipe
46
- };
@@ -1,142 +0,0 @@
1
- import path from "path";
2
- import { ApiRouter } from "@modern-js/bff-core";
3
- import { API_DIR, isProd, isWebOnly, requireExistModule } from "@modern-js/utils";
4
- import { isFunction } from "@modern-js/utils";
5
- import { API_APP_NAME } from "./constants";
6
- import { HonoAdapter } from "./runtime/hono/adapter";
7
- class Storage {
8
- reset() {
9
- this.middlewares = [];
10
- }
11
- constructor() {
12
- this.middlewares = [];
13
- }
14
- }
15
- const createTransformAPI = (storage) => ({
16
- addMiddleware(fn) {
17
- storage.middlewares.push(fn);
18
- }
19
- });
20
- var server_default = () => ({
21
- name: "@modern-js/plugin-bff",
22
- setup: (api) => {
23
- const storage = new Storage();
24
- const transformAPI = createTransformAPI(storage);
25
- let apiAppPath = "";
26
- let apiRouter;
27
- const honoAdapter = new HonoAdapter(api);
28
- return {
29
- async prepare() {
30
- var _config_bff, _config_bff1, _config_bff2;
31
- const appContext = api.useAppContext();
32
- const { appDirectory, distDirectory, render } = appContext;
33
- const root = isProd() ? distDirectory : appDirectory;
34
- const apiPath = path.resolve(root || process.cwd(), API_DIR);
35
- apiAppPath = path.resolve(apiPath, API_APP_NAME);
36
- const apiMod = await requireExistModule(apiAppPath);
37
- if (apiMod && typeof apiMod === "function") {
38
- apiMod(transformAPI);
39
- }
40
- const { middlewares } = storage;
41
- api.setAppContext({
42
- ...appContext,
43
- apiMiddlewares: middlewares
44
- });
45
- const config = api.useConfigContext();
46
- const prefix = (config === null || config === void 0 ? void 0 : (_config_bff = config.bff) === null || _config_bff === void 0 ? void 0 : _config_bff.prefix) || "/api";
47
- const enableHandleWeb = config === null || config === void 0 ? void 0 : (_config_bff1 = config.bff) === null || _config_bff1 === void 0 ? void 0 : _config_bff1.enableHandleWeb;
48
- const httpMethodDecider = config === null || config === void 0 ? void 0 : (_config_bff2 = config.bff) === null || _config_bff2 === void 0 ? void 0 : _config_bff2.httpMethodDecider;
49
- const { distDirectory: pwd, middlewares: globalMiddlewares } = api.useAppContext();
50
- const webOnly = await isWebOnly();
51
- let handler;
52
- if (webOnly) {
53
- handler = async (c, next) => {
54
- c.body("");
55
- await next();
56
- };
57
- } else {
58
- const runner = api.useHookRunners();
59
- const renderHandler = enableHandleWeb ? render : null;
60
- handler = await runner.prepareApiServer({
61
- pwd,
62
- prefix,
63
- render: renderHandler,
64
- httpMethodDecider
65
- }, {
66
- onLast: () => null
67
- });
68
- }
69
- if (handler && isFunction(handler)) {
70
- globalMiddlewares.push({
71
- name: "bind-bff",
72
- handler: (c, next) => {
73
- if (!c.req.path.startsWith(prefix) && !enableHandleWeb) {
74
- return next();
75
- } else {
76
- return handler(c, next);
77
- }
78
- },
79
- order: "post",
80
- before: [
81
- "custom-server-hook",
82
- "custom-server-middleware",
83
- "render"
84
- ]
85
- });
86
- }
87
- honoAdapter.registerMiddleware({
88
- prefix,
89
- enableHandleWeb
90
- });
91
- },
92
- async reset({ event }) {
93
- storage.reset();
94
- const appContext = api.useAppContext();
95
- const newApiModule = await requireExistModule(apiAppPath);
96
- if (newApiModule && typeof newApiModule === "function") {
97
- newApiModule(transformAPI);
98
- }
99
- const { middlewares } = storage;
100
- api.setAppContext({
101
- ...appContext,
102
- apiMiddlewares: middlewares
103
- });
104
- if (event.type === "file-change") {
105
- const apiHandlerInfos = await apiRouter.getApiHandlers();
106
- const appContext2 = api.useAppContext();
107
- api.setAppContext({
108
- ...appContext2,
109
- apiHandlerInfos
110
- });
111
- await honoAdapter.setHandlers();
112
- await honoAdapter.registerApiRoutes();
113
- }
114
- },
115
- async prepareApiServer(props, next) {
116
- const { pwd, prefix, httpMethodDecider } = props;
117
- const apiDir = path.resolve(pwd, API_DIR);
118
- const appContext = api.useAppContext();
119
- const { apiDirectory, lambdaDirectory } = appContext;
120
- apiRouter = new ApiRouter({
121
- appDir: pwd,
122
- apiDir: apiDirectory || apiDir,
123
- lambdaDir: lambdaDirectory,
124
- prefix,
125
- httpMethodDecider
126
- });
127
- const apiMode = apiRouter.getApiMode();
128
- const apiHandlerInfos = await apiRouter.getApiHandlers();
129
- api.setAppContext({
130
- ...appContext,
131
- apiRouter,
132
- apiHandlerInfos,
133
- apiMode
134
- });
135
- return next(props);
136
- }
137
- };
138
- }
139
- });
140
- export {
141
- server_default as default
142
- };