@bleedingdev/modern-js-plugin-bff 3.9.0-ultramodern.3 → 3.9.0-ultramodern.5

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 (75) hide show
  1. package/dist/cjs/cli/generator.js +118 -117
  2. package/dist/cjs/cli.js +11 -6
  3. package/dist/cjs/loader.js +9 -65
  4. package/dist/cjs/runtime/create-request/index.js +0 -6
  5. package/dist/cjs/runtime/hono/adapter.js +8 -12
  6. package/dist/cjs/server.js +26 -18
  7. package/dist/cjs/utils/client-generator/files.js +1 -1
  8. package/dist/cjs/utils/client-generator/generate.js +46 -45
  9. package/dist/cjs/utils/client-generator/write-package.js +10 -1
  10. package/dist/cjs/utils/crossProjectApiPlugin.js +26 -83
  11. package/dist/cjs/utils/pluginGenerator.js +26 -26
  12. package/dist/cjs/utils/runtimeGenerator.js +25 -75
  13. package/dist/esm/cli/generator.mjs +121 -120
  14. package/dist/esm/cli.mjs +11 -6
  15. package/dist/esm/loader.mjs +9 -55
  16. package/dist/esm/runtime/create-request/index.mjs +1 -1
  17. package/dist/esm/runtime/hono/adapter.mjs +8 -12
  18. package/dist/esm/server.mjs +27 -19
  19. package/dist/esm/utils/client-generator/files.mjs +1 -1
  20. package/dist/esm/utils/client-generator/generate.mjs +47 -46
  21. package/dist/esm/utils/client-generator/write-package.mjs +10 -1
  22. package/dist/esm/utils/crossProjectApiPlugin.mjs +24 -54
  23. package/dist/esm/utils/pluginGenerator.mjs +23 -25
  24. package/dist/esm/utils/runtimeGenerator.mjs +22 -74
  25. package/dist/esm-node/cli/generator.mjs +121 -120
  26. package/dist/esm-node/cli.mjs +11 -6
  27. package/dist/esm-node/loader.mjs +9 -55
  28. package/dist/esm-node/runtime/create-request/index.mjs +1 -1
  29. package/dist/esm-node/runtime/hono/adapter.mjs +8 -12
  30. package/dist/esm-node/server.mjs +27 -19
  31. package/dist/esm-node/utils/client-generator/files.mjs +1 -1
  32. package/dist/esm-node/utils/client-generator/generate.mjs +47 -46
  33. package/dist/esm-node/utils/client-generator/write-package.mjs +10 -1
  34. package/dist/esm-node/utils/crossProjectApiPlugin.mjs +24 -54
  35. package/dist/esm-node/utils/pluginGenerator.mjs +23 -28
  36. package/dist/esm-node/utils/runtimeGenerator.mjs +23 -76
  37. package/dist/types/cli/generator.d.ts +2 -2
  38. package/dist/types/loader.d.ts +1 -11
  39. package/dist/types/runtime/create-request/index.d.ts +1 -3
  40. package/dist/types/runtime/hono/adapter.d.ts +9 -2
  41. package/dist/types/server.d.ts +9 -2
  42. package/dist/types/utils/client-generator/generate.d.ts +8 -12
  43. package/dist/types/utils/client-generator/write-package.d.ts +1 -1
  44. package/dist/types/utils/crossProjectApiPlugin.d.ts +18 -12
  45. package/dist/types/utils/pluginGenerator.d.ts +6 -7
  46. package/dist/types/utils/runtimeGenerator.d.ts +6 -3
  47. package/package.json +25 -118
  48. package/dist/cjs/cli/serverGlobalVars.js +0 -113
  49. package/dist/cjs/runtime/data-platform/index.js +0 -62
  50. package/dist/cjs/runtime/effect/edge-dispatcher.js +0 -62
  51. package/dist/cjs/runtime/effect/edge.js +0 -69
  52. package/dist/cjs/runtime/effect/index.js +0 -305
  53. package/dist/cjs/runtime/effect-client/index.js +0 -62
  54. package/dist/cjs/runtime/effect-client/runtime.js +0 -62
  55. package/dist/esm/cli/serverGlobalVars.mjs +0 -72
  56. package/dist/esm/runtime/data-platform/index.mjs +0 -1
  57. package/dist/esm/runtime/effect/edge-dispatcher.mjs +0 -1
  58. package/dist/esm/runtime/effect/edge.mjs +0 -2
  59. package/dist/esm/runtime/effect/index.mjs +0 -16
  60. package/dist/esm/runtime/effect-client/index.mjs +0 -1
  61. package/dist/esm/runtime/effect-client/runtime.mjs +0 -1
  62. package/dist/esm-node/cli/serverGlobalVars.mjs +0 -73
  63. package/dist/esm-node/runtime/data-platform/index.mjs +0 -2
  64. package/dist/esm-node/runtime/effect/edge-dispatcher.mjs +0 -2
  65. package/dist/esm-node/runtime/effect/edge.mjs +0 -3
  66. package/dist/esm-node/runtime/effect/index.mjs +0 -17
  67. package/dist/esm-node/runtime/effect-client/index.mjs +0 -2
  68. package/dist/esm-node/runtime/effect-client/runtime.mjs +0 -2
  69. package/dist/types/cli/serverGlobalVars.d.ts +0 -6
  70. package/dist/types/runtime/data-platform/index.d.ts +0 -1
  71. package/dist/types/runtime/effect/edge-dispatcher.d.ts +0 -1
  72. package/dist/types/runtime/effect/edge.d.ts +0 -2
  73. package/dist/types/runtime/effect/index.d.ts +0 -15
  74. package/dist/types/runtime/effect-client/index.d.ts +0 -1
  75. package/dist/types/runtime/effect-client/runtime.d.ts +0 -1
@@ -1,132 +1,133 @@
1
- import { ApiRouter, buildOperationContractMap, deriveOperationVersion } from "@modern-js/bff-core";
1
+ import { ApiRouter } from "@modern-js/bff-core";
2
2
  import { compile } from "@modern-js/server-utils";
3
3
  import { API_DIR, SHARED_DIR, fs, resolveServerTsconfig, upath } from "@modern-js/utils";
4
4
  import clientGenerator from "../utils/clientGenerator.mjs";
5
- import pluginGenerator from "../utils/pluginGenerator.mjs";
6
- import runtimeGenerator from "../utils/runtimeGenerator.mjs";
5
+ import pluginGenerator, { renderBffPlugin } from "../utils/pluginGenerator.mjs";
6
+ import runtimeGenerator, { renderBffRuntime } from "../utils/runtimeGenerator.mjs";
7
7
  import { getPrimaryPrefix } from "./prefix.mjs";
8
- import { serializeServerGlobalVars, transformServerGlobalVars } from "./serverGlobalVars.mjs";
9
8
  const RUNTIME_CREATE_REQUEST = '@modern-js/plugin-bff/client';
10
9
  const createBffGenerator = (api)=>{
11
- const compileApi = ()=>Promise.resolve().then(()=>{
12
- const { appDirectory, distDirectory, apiDirectory, bffRuntimeFramework, sharedDirectory, moduleType } = api.getAppContext();
13
- const modernConfig = api.getNormalizedConfig();
14
- const distDir = upath.resolve(distDirectory);
15
- const apiDir = apiDirectory || upath.resolve(appDirectory, API_DIR);
16
- const sharedDir = sharedDirectory || upath.resolve(appDirectory, SHARED_DIR);
17
- const tsconfigPath = resolveServerTsconfig(appDirectory, modernConfig?.server?.tsconfigPath);
18
- const sourceDirs = [];
19
- return fs.pathExists(apiDir).then((apiDirectoryExists)=>{
20
- if (apiDirectoryExists) sourceDirs.push(apiDir);
21
- return fs.pathExists(sharedDir);
22
- }).then((sharedDirectoryExists)=>{
23
- if (sharedDirectoryExists) sourceDirs.push(sharedDir);
24
- if (0 === sourceDirs.length) return;
25
- const { alias, globalVars } = modernConfig.source;
26
- const { alias: resolveAlias } = modernConfig.resolve;
27
- const combinedAlias = [].concat(alias ?? []).concat(resolveAlias ?? []);
28
- const serializedGlobalVars = serializeServerGlobalVars(globalVars);
29
- return compile(appDirectory, {
30
- alias: combinedAlias
31
- }, {
32
- sourceDirs,
33
- distDir,
34
- tsconfigPath,
35
- moduleType,
36
- throwErrorInsteadOfExit: true
37
- }).then(()=>transformServerGlobalVars(sourceDirs.map((sourceDir)=>upath.resolve(distDir, upath.relative(appDirectory, sourceDir))), serializedGlobalVars)).then(async ()=>{
38
- if ('effect' !== bffRuntimeFramework) return;
39
- const { bundleBuiltEffectEntryForNode } = await import("@modern-js/plugin-bff-extensions/client-generator");
40
- return bundleBuiltEffectEntryForNode({
41
- appDir: appDirectory,
42
- apiDir,
43
- distDir,
44
- effectEntry: modernConfig.bff?.effect?.entry,
45
- format: 'module' === moduleType ? 'esm' : 'cjs'
46
- });
47
- });
48
- });
10
+ const compileApi = async ()=>{
11
+ const { appDirectory, distDirectory, apiDirectory, sharedDirectory, moduleType } = api.getAppContext();
12
+ const config = api.getNormalizedConfig();
13
+ const distDir = upath.resolve(distDirectory);
14
+ const apiDir = apiDirectory || upath.resolve(appDirectory, API_DIR);
15
+ const sharedDir = sharedDirectory || upath.resolve(appDirectory, SHARED_DIR);
16
+ const tsconfigPath = resolveServerTsconfig(appDirectory, config.server?.tsconfigPath);
17
+ const sourceDirs = [];
18
+ for (const directory of [
19
+ apiDir,
20
+ sharedDir
21
+ ])if (await fs.pathExists(directory)) sourceDirs.push(directory);
22
+ if (0 === sourceDirs.length) return;
23
+ const combinedAlias = [].concat(config.source.alias ?? []).concat(config.resolve.alias ?? []);
24
+ const context = {
25
+ appDirectory,
26
+ apiDirectory: apiDir,
27
+ sourceDirectories: sourceDirs,
28
+ outputDirectories: sourceDirs.map((directory)=>upath.resolve(distDir, upath.relative(appDirectory, directory))),
29
+ distDirectory: distDir,
30
+ tsconfigPath,
31
+ moduleType
32
+ };
33
+ const hooks = api.getHooks();
34
+ await hooks.onBeforeBffCompile.call(context);
35
+ await compile(appDirectory, {
36
+ alias: combinedAlias
37
+ }, {
38
+ sourceDirs,
39
+ distDir,
40
+ tsconfigPath,
41
+ moduleType,
42
+ excludeFiles: api.getAppContext().serverCompileExcludedFiles,
43
+ throwErrorInsteadOfExit: true
49
44
  });
50
- const generate = ()=>Promise.resolve().then(async ()=>{
51
- const { appDirectory, apiDirectory, lambdaDirectory, port, bffRuntimeFramework, packageName } = api.getAppContext();
52
- const modernConfig = api.getNormalizedConfig();
53
- const relativeDistPath = modernConfig?.output?.distPath?.root || 'dist';
54
- const { bff } = modernConfig || {};
55
- const prefix = getPrimaryPrefix(bff?.prefix);
56
- const httpMethodDecider = bff?.httpMethodDecider;
57
- const apiRouter = new ApiRouter({
58
- apiDir: apiDirectory,
59
- appDir: appDirectory,
60
- lambdaDir: lambdaDirectory,
61
- prefix,
62
- httpMethodDecider,
63
- isBuild: true
64
- });
65
- const lambdaDir = apiRouter.getLambdaDir();
66
- const existLambda = apiRouter.isExistLambda();
67
- const packageJson = fs.readJSONSync(upath.resolve(appDirectory, 'package.json'));
68
- const requestId = bff?.requestId || packageJson.name || packageName || 'default';
69
- const operationContractsPromise = 'effect' !== bffRuntimeFramework && existLambda ? apiRouter.getApiHandlers().then((handlers)=>buildOperationContractMap({
70
- handlers,
71
- requestId,
72
- operationVersion: deriveOperationVersion(packageJson.version)
73
- })) : Promise.resolve({});
74
- const runtime = bff?.runtimeCreateRequest || RUNTIME_CREATE_REQUEST;
75
- const relativeApiPath = upath.relative(appDirectory, apiDirectory);
76
- const relativeLambdaPath = upath.relative(appDirectory, lambdaDir);
77
- const { sourceEffectEntry, relativeEffectEntry } = 'effect' === bffRuntimeFramework ? (await import("@modern-js/plugin-bff-extensions/client-generator")).resolveEffectEntryPaths({
78
- appDir: appDirectory,
79
- apiDir: apiDirectory,
80
- effectEntry: bff?.effect?.entry
81
- }) : {
82
- sourceEffectEntry: void 0,
83
- relativeEffectEntry: ''
84
- };
85
- const clientGenerationPromise = clientGenerator({
86
- prefix,
87
- appDir: appDirectory,
88
- apiDir: apiDirectory,
89
- lambdaDir,
90
- existLambda,
91
- port,
92
- requestId,
93
- requestCreator: bff?.requestCreator,
94
- httpMethodDecider,
95
- relativeDistPath,
96
- relativeApiPath,
97
- apiFiles: apiRouter.getApiFiles(),
98
- bffRuntimeFramework,
99
- effectEntry: bff?.effect?.entry,
100
- effectDataPlatformBatch: bff?.effect?.dataPlatform?.batch
101
- });
102
- return Promise.all([
103
- operationContractsPromise,
104
- clientGenerationPromise
105
- ]).then(([lambdaContracts, generatedEffectClient])=>{
106
- if ('effect' === bffRuntimeFramework && null === generatedEffectClient) throw new Error(`Effect cross-project client generation failed for ${sourceEffectEntry ?? apiDirectory}.`);
107
- const operationContracts = 'effect' === bffRuntimeFramework ? generatedEffectClient?.operationContracts ?? {} : lambdaContracts;
108
- return pluginGenerator({
109
- prefix,
110
- appDirectory,
111
- requestId,
112
- relativeDistPath,
113
- relativeApiPath,
114
- relativeLambdaPath,
115
- runtimeFramework: 'hono' === bffRuntimeFramework ? 'hono' : 'effect',
116
- relativeEffectEntry,
117
- operationContracts
118
- }).then(()=>runtimeGenerator({
119
- runtime,
120
- appDirectory,
121
- relativeDistPath
122
- }));
123
- });
45
+ await hooks.onAfterBffCompile.call(context);
46
+ };
47
+ const generate = async ()=>{
48
+ const { appDirectory, apiDirectory, lambdaDirectory, port, packageName } = api.getAppContext();
49
+ const config = api.getNormalizedConfig();
50
+ const relativeDistPath = config.output?.distPath?.root || 'dist';
51
+ const bff = config.bff;
52
+ const prefix = getPrimaryPrefix(bff?.prefix);
53
+ const apiRouter = new ApiRouter({
54
+ apiDir: apiDirectory,
55
+ appDir: appDirectory,
56
+ lambdaDir: lambdaDirectory,
57
+ prefix,
58
+ httpMethodDecider: bff?.httpMethodDecider,
59
+ isBuild: true
124
60
  });
125
- const handleCrossProjectInvocation = (isBuild = false)=>Promise.resolve().then(()=>{
126
- const { bff } = api.getNormalizedConfig();
127
- if (bff?.crossProject !== true) return;
128
- return isBuild ? generate() : compileApi().then(()=>generate());
61
+ const lambdaDir = apiRouter.getLambdaDir();
62
+ const packageJson = await fs.readJSON(upath.resolve(appDirectory, 'package.json'));
63
+ const generation = {
64
+ appDirectory,
65
+ apiDirectory,
66
+ lambdaDirectory: lambdaDir,
67
+ existLambda: apiRouter.isExistLambda(),
68
+ apiFiles: apiRouter.getApiFiles(),
69
+ relativeDistPath,
70
+ prefix,
71
+ port,
72
+ requestId: bff?.requestId || packageJson.name || packageName || 'default',
73
+ requestCreator: bff?.requestCreator,
74
+ httpMethodDecider: bff?.httpMethodDecider
75
+ };
76
+ const pluginOptions = {
77
+ prefix,
78
+ appDirectory,
79
+ relativeDistPath,
80
+ relativeApiPath: upath.relative(appDirectory, apiDirectory),
81
+ relativeLambdaPath: upath.relative(appDirectory, lambdaDir)
82
+ };
83
+ const runtimeOptions = {
84
+ runtime: bff?.runtimeCreateRequest || RUNTIME_CREATE_REQUEST,
85
+ appDirectory,
86
+ relativeDistPath
87
+ };
88
+ const hooks = api.getHooks();
89
+ await clientGenerator({
90
+ prefix,
91
+ appDir: appDirectory,
92
+ apiDir: apiDirectory,
93
+ lambdaDir,
94
+ existLambda: generation.existLambda,
95
+ apiFiles: [
96
+ ...generation.apiFiles
97
+ ],
98
+ port,
99
+ requestId: generation.requestId,
100
+ requestCreator: generation.requestCreator,
101
+ clientCodegenPlugin: bff?.clientCodegenPlugin,
102
+ httpMethodDecider: generation.httpMethodDecider,
103
+ relativeDistPath,
104
+ relativeApiPath: pluginOptions.relativeApiPath
105
+ }, {
106
+ generation,
107
+ modifyArtifacts: async (context)=>{
108
+ const result = await hooks.modifyBffClientArtifacts.call(context);
109
+ if (result.generation !== generation) throw new Error('modifyBffClientArtifacts must preserve generation identity.');
110
+ return result;
111
+ },
112
+ beforePublish: async ()=>{
113
+ const entries = await hooks.modifyBffGeneratedEntries.call({
114
+ generation,
115
+ plugin: await renderBffPlugin(pluginOptions),
116
+ runtime: renderBffRuntime(runtimeOptions),
117
+ packageDependencies: {}
118
+ });
119
+ if (entries.generation !== generation) throw new Error('modifyBffGeneratedEntries must preserve generation identity.');
120
+ await pluginGenerator(pluginOptions, entries.plugin);
121
+ await runtimeGenerator(runtimeOptions, entries.runtime);
122
+ return entries.packageDependencies;
123
+ }
129
124
  });
125
+ };
126
+ const handleCrossProjectInvocation = async (isBuild = false)=>{
127
+ if (api.getNormalizedConfig().bff?.crossProject !== true) return;
128
+ if (!isBuild) await compileApi();
129
+ await generate();
130
+ };
130
131
  return {
131
132
  compileApi,
132
133
  generate,
package/dist/esm/cli.mjs CHANGED
@@ -1,4 +1,5 @@
1
1
  import { ApiRouter } from "@modern-js/bff-core";
2
+ import { createAsyncHook } from "@modern-js/plugin";
2
3
  import { normalizeOutputPath } from "@modern-js/utils";
3
4
  import path from "path";
4
5
  import { createCompressConfig } from "./cli/compress.mjs";
@@ -7,13 +8,19 @@ import { getPrimaryPrefix } from "./cli/prefix.mjs";
7
8
  import { isWatchableBffFile } from "./cli/watch.mjs";
8
9
  const bffPlugin = ()=>({
9
10
  name: '@modern-js/plugin-bff',
11
+ registryHooks: {
12
+ onBeforeBffCompile: createAsyncHook(),
13
+ onAfterBffCompile: createAsyncHook(),
14
+ modifyBffClientArtifacts: createAsyncHook(),
15
+ modifyBffGeneratedEntries: createAsyncHook()
16
+ },
10
17
  setup: (api)=>{
11
18
  {
12
19
  const appContext = api.getAppContext();
13
20
  const userRuntimeFramework = api.getConfig()?.bff?.runtimeFramework;
14
21
  api.updateAppContext({
15
22
  ...appContext,
16
- bffRuntimeFramework: 'hono' === userRuntimeFramework ? 'hono' : 'effect'
23
+ bffRuntimeFramework: userRuntimeFramework ?? 'hono'
17
24
  });
18
25
  }
19
26
  const { compileApi, handleCrossProjectInvocation } = createBffGenerator(api);
@@ -31,7 +38,7 @@ const bffPlugin = ()=>({
31
38
  compress
32
39
  },
33
40
  bundlerChain: (chain, { CHAIN_ID, isServer })=>{
34
- const { port, appDirectory, apiDirectory, lambdaDirectory, bffRuntimeFramework } = api.getAppContext();
41
+ const { port, appDirectory, apiDirectory, lambdaDirectory } = api.getAppContext();
35
42
  const modernConfig = api.getNormalizedConfig();
36
43
  const { bff } = modernConfig || {};
37
44
  const prefix = getPrimaryPrefix(bff?.prefix);
@@ -61,10 +68,8 @@ const bffPlugin = ()=>({
61
68
  requestId: bff?.requestId,
62
69
  target: name,
63
70
  requestCreator: bff?.requestCreator,
64
- httpMethodDecider,
65
- bffRuntimeFramework,
66
- effectEntry: bff?.effect?.entry,
67
- effectDataPlatformBatch: bff?.effect?.dataPlatform?.batch
71
+ clientCodegenPlugin: bff?.clientCodegenPlugin,
72
+ httpMethodDecider
68
73
  });
69
74
  }
70
75
  }
@@ -1,64 +1,12 @@
1
1
  import { generateClient } from "@modern-js/bff-core";
2
- import { generateEffectClientCode, generateEffectWorkerRuntimeWrapper, resolveEffectEntryFile } from "@modern-js/plugin-bff-extensions/effect-source-loader";
3
2
  import { logger } from "@modern-js/utils";
4
- import path from "path";
5
- const EFFECT_BFF_WORKER_RUNTIME_QUERY = 'modern-bff-runtime';
6
- const EFFECT_BFF_WORKER_RUNTIME_SOURCE_QUERY = 'modern-bff-runtime-source';
7
3
  const createErrorModule = (message)=>`throw new Error(${JSON.stringify(message)});`;
8
- async function transformEffectRuntimeSource(source, filename) {
9
- const swc = await import("@swc/core");
10
- const result = await swc.transform(source, {
11
- filename,
12
- sourceMaps: false,
13
- jsc: {
14
- parser: {
15
- syntax: "typescript",
16
- tsx: filename.endsWith('.tsx') || filename.endsWith('.jsx')
17
- },
18
- target: 'es2024'
19
- },
20
- module: {
21
- type: 'es6'
22
- }
23
- });
24
- return result.code;
25
- }
26
4
  async function loader(source) {
27
5
  this.cacheable();
28
6
  const { resourcePath } = this;
29
7
  delete require.cache[resourcePath];
30
8
  const callback = this.async();
31
9
  const draftOptions = this.getOptions();
32
- const resourceQueries = new URLSearchParams(this.resourceQuery);
33
- const effectEntryFile = resolveEffectEntryFile({
34
- appDir: draftOptions.appDir,
35
- apiDir: draftOptions.apiDir,
36
- effectEntry: draftOptions.effectEntry
37
- });
38
- if ('effect' === draftOptions.bffRuntimeFramework && effectEntryFile && path.resolve(effectEntryFile) === path.resolve(resourcePath) && resourceQueries.has(EFFECT_BFF_WORKER_RUNTIME_SOURCE_QUERY)) {
39
- const code = await transformEffectRuntimeSource(source, resourcePath);
40
- callback(void 0, code);
41
- return;
42
- }
43
- if ('effect' === draftOptions.bffRuntimeFramework && effectEntryFile && path.resolve(effectEntryFile) === path.resolve(resourcePath) && resourceQueries.has(EFFECT_BFF_WORKER_RUNTIME_QUERY)) return void callback(void 0, await generateEffectWorkerRuntimeWrapper(this, draftOptions, resourcePath));
44
- if ('effect' === draftOptions.bffRuntimeFramework && effectEntryFile && path.resolve(effectEntryFile) === path.resolve(resourcePath)) {
45
- const code = await generateEffectClientCode({
46
- appDir: draftOptions.appDir,
47
- apiDir: draftOptions.apiDir,
48
- resourcePath,
49
- prefix: Array.isArray(draftOptions.prefix) ? draftOptions.prefix[0] : draftOptions.prefix,
50
- port: Number(draftOptions.port),
51
- target: draftOptions.target,
52
- requestId: draftOptions.requestId,
53
- requestCreator: draftOptions.requestCreator,
54
- httpMethodDecider: draftOptions.httpMethodDecider,
55
- dataPlatformBatch: draftOptions.effectDataPlatformBatch,
56
- onDependency: (dependency)=>this.addDependency(dependency)
57
- });
58
- if (code) return void callback(void 0, code);
59
- callback(new Error(`Failed to generate Effect client for ${resourcePath}`));
60
- return;
61
- }
62
10
  const warning = `The file ${resourcePath} is not allowed to be imported in src directory, only API definition files are allowed.`;
63
11
  if (!draftOptions.existLambda) {
64
12
  logger.warn(warning);
@@ -74,7 +22,9 @@ async function loader(source) {
74
22
  port: Number(draftOptions.port),
75
23
  source,
76
24
  resourcePath,
77
- httpMethodDecider: draftOptions.httpMethodDecider
25
+ httpMethodDecider: draftOptions.httpMethodDecider,
26
+ clientCodegenPlugin: draftOptions.clientCodegenPlugin,
27
+ requestId: draftOptions.requestId
78
28
  };
79
29
  const { lambdaDir } = draftOptions;
80
30
  if (!resourcePath.startsWith(lambdaDir)) {
@@ -85,8 +35,12 @@ async function loader(source) {
85
35
  if (draftOptions.fetcher) options.fetcher = draftOptions.fetcher;
86
36
  if (draftOptions.requestCreator) options.requestCreator = draftOptions.requestCreator;
87
37
  options.requireResolve = require.resolve;
88
- const result = await generateClient(options);
89
- callback(void 0, result.isOk ? result.value : createErrorModule(result.value));
38
+ try {
39
+ const result = await generateClient(options);
40
+ callback(void 0, result.isOk ? result.value : createErrorModule(result.value));
41
+ } catch (error) {
42
+ callback(error instanceof Error ? error : new Error(String(error)));
43
+ }
90
44
  }
91
45
  const src_loader = loader;
92
46
  export default src_loader;
@@ -1 +1 @@
1
- export { configure, createRequest, createRequestContextHeaders, createRequestContextSnapshot, createUploader } from "@modern-js/create-request";
1
+ export { configure, createRequest, createUploader } from "@modern-js/create-request";
@@ -1,6 +1,3 @@
1
- import { resolveAdapterCrossProjectPolicy } from "@modern-js/plugin-bff-extensions/cross-project-policy";
2
- import { bindHonoRouteHandlers } from "@modern-js/plugin-bff-extensions/hono";
3
- import { logger } from "@modern-js/utils";
4
1
  import createHonoRoutes from "../../utils/createHonoRoutes.mjs";
5
2
  const before = [
6
3
  'custom-server-hook',
@@ -8,7 +5,8 @@ const before = [
8
5
  'render'
9
6
  ];
10
7
  class HonoAdapter {
11
- constructor(api){
8
+ constructor(api, createRouteBinder){
9
+ this.createRouteBinder = createRouteBinder;
12
10
  this.apiMiddleware = [];
13
11
  this.isHono = true;
14
12
  this.setHandlers = async ()=>{
@@ -16,25 +14,23 @@ class HonoAdapter {
16
14
  const { apiHandlerInfos } = this.api.getServerContext();
17
15
  const handlers = apiHandlerInfos ?? [];
18
16
  const honoHandlers = createHonoRoutes(handlers);
19
- const policy = resolveAdapterCrossProjectPolicy(this.api, handlers);
17
+ const bindRoute = this.createRouteBinder?.(this.api, handlers);
18
+ if (this.createRouteBinder && 'function' != typeof bindRoute) throw new TypeError('Hono route binder factory must return a function.');
20
19
  this.apiMiddleware = honoHandlers.map(({ path, method, handler })=>({
21
20
  name: 'hono-bff-api',
22
21
  path,
23
22
  method,
24
- handler: bindHonoRouteHandlers({
23
+ handler: bindRoute ? bindRoute({
25
24
  handler,
26
- policy,
27
- routePath: path,
28
- onError: this.api.getServerConfig()?.onError,
29
- reportError: (error)=>logger.error(error)
30
- }),
25
+ routePath: path
26
+ }) : handler,
31
27
  order: 'post',
32
28
  before: before
33
29
  }));
34
30
  };
35
31
  this.registerMiddleware = async (_options)=>{
36
32
  const { bffRuntimeFramework } = this.api.getServerContext();
37
- if ('hono' !== bffRuntimeFramework) {
33
+ if (void 0 !== bffRuntimeFramework && 'hono' !== bffRuntimeFramework) {
38
34
  this.isHono = false;
39
35
  return;
40
36
  }
@@ -1,18 +1,16 @@
1
1
  import { ApiRouter } from "@modern-js/bff-core";
2
- import { API_DIR, isFunction, isWebOnly } from "@modern-js/utils";
2
+ import { API_DIR, compatibleRequire, isFunction, isWebOnly, tryResolve } from "@modern-js/utils";
3
3
  import path from "path";
4
4
  import { HonoAdapter } from "./runtime/hono/adapter.mjs";
5
- const RUNTIME_ADAPTER_LOADERS = {
6
- hono: async (api)=>[
7
- new HonoAdapter(api)
8
- ],
9
- effect: async (api)=>{
10
- const { EffectAdapter } = await import("@modern-js/plugin-bff-extensions/effect-adapter");
11
- return [
12
- new EffectAdapter(api)
13
- ];
14
- }
15
- };
5
+ async function loadRuntimeAdapters(specifier, api) {
6
+ if ('string' != typeof specifier || '' === specifier.trim()) throw new Error('The BFF runtime adapter must be a module specifier.');
7
+ const context = api.getServerContext();
8
+ const module = await compatibleRequire(tryResolve(specifier, context.appDirectory || context.distDirectory || process.cwd()), false);
9
+ if (!module || 'function' != typeof module.createRuntimeAdapters) throw new Error(`BFF runtime adapter module "${specifier}" must export createRuntimeAdapters.`);
10
+ const adapters = await module.createRuntimeAdapters(api);
11
+ if (!Array.isArray(adapters) || 0 === adapters.length || adapters.some((adapter)=>!adapter || 'function' != typeof adapter.registerMiddleware)) throw new Error(`BFF runtime adapter module "${specifier}" returned invalid adapters.`);
12
+ return adapters;
13
+ }
16
14
  const normalizePrefixList = (prefix)=>{
17
15
  if (Array.isArray(prefix)) return prefix.filter(Boolean);
18
16
  return [
@@ -20,21 +18,21 @@ const normalizePrefixList = (prefix)=>{
20
18
  ];
21
19
  };
22
20
  const getPrimaryPrefix = (prefix)=>normalizePrefixList(prefix)[0] || '/api';
23
- function resolveRuntimeFramework(runtimeFramework) {
24
- return 'hono' === runtimeFramework ? 'hono' : 'effect';
25
- }
26
21
  class Storage {
27
22
  constructor(){
28
23
  this.middlewares = [];
29
24
  }
30
25
  }
31
- const server = ()=>({
26
+ const server = (options = {})=>({
32
27
  name: '@modern-js/plugin-bff',
33
28
  setup: (api)=>{
34
29
  const storage = new Storage();
35
30
  let apiRouter = null;
36
31
  const appContext = api.getServerContext();
37
- const runtimeFramework = resolveRuntimeFramework(appContext.bffRuntimeFramework);
32
+ const runtimeFramework = appContext.bffRuntimeFramework ?? 'hono';
33
+ if (options.runtimeAdapters && Object.hasOwn(options.runtimeAdapters, 'hono')) throw new Error('The native Hono BFF adapter cannot be overridden.');
34
+ const adapterModule = options.runtimeAdapters?.[runtimeFramework];
35
+ if ('hono' !== runtimeFramework && (!options.runtimeAdapters || !Object.hasOwn(options.runtimeAdapters, runtimeFramework) || 'string' != typeof adapterModule || '' === adapterModule.trim())) throw new Error(`No BFF runtime adapter is registered for "${runtimeFramework}".`);
38
36
  api.onPrepare(async ()=>{
39
37
  const appContext = api.getServerContext();
40
38
  const { render } = appContext;
@@ -80,9 +78,19 @@ const server = ()=>({
80
78
  ]
81
79
  });
82
80
  }
83
- const runtimeAdapters = await RUNTIME_ADAPTER_LOADERS[runtimeFramework](api);
81
+ let createHonoRouteBinder;
82
+ if ('hono' === runtimeFramework && void 0 !== options.honoRouteBinder) {
83
+ if ('string' != typeof options.honoRouteBinder || '' === options.honoRouteBinder.trim()) throw new Error('The Hono BFF route binder must be a module specifier.');
84
+ const context = api.getServerContext();
85
+ const module = await compatibleRequire(tryResolve(options.honoRouteBinder, context.appDirectory || context.distDirectory || process.cwd()), false);
86
+ if (!module || 'function' != typeof module.createHonoRouteBinder) throw new Error(`BFF route binder module "${options.honoRouteBinder}" must export createHonoRouteBinder.`);
87
+ createHonoRouteBinder = module.createHonoRouteBinder;
88
+ }
89
+ const runtimeAdapters = 'hono' === runtimeFramework ? [
90
+ new HonoAdapter(api, createHonoRouteBinder)
91
+ ] : await loadRuntimeAdapters(adapterModule, api);
84
92
  await Promise.all(runtimeAdapters.map((adapter)=>adapter.registerMiddleware({
85
- prefix: 'effect' === runtimeFramework ? prefixList : prefix,
93
+ prefix: 'hono' === runtimeFramework ? prefix : prefixList,
86
94
  enableHandleWeb
87
95
  })));
88
96
  });
@@ -18,7 +18,7 @@ function createFileDetails(options) {
18
18
  const relativePath = path.relative(baseDirectory, resourcePath);
19
19
  const parsedPath = path.parse(relativePath);
20
20
  const targetDir = posixJoin(`./${relativeDistPath}/${CLIENT_DIR}`, parsedPath.dir, `${parsedPath.name}.js`);
21
- const absTargetDir = path.resolve(targetDir);
21
+ const absTargetDir = path.resolve(appDirectory, targetDir);
22
22
  const relativePathFromAppDirectory = path.relative(appDirectory, path.dirname(resourcePath));
23
23
  const typesFilePath = posixJoin(`./${relativeDistPath}`, relativePathFromAppDirectory, `${parsedPath.name}.d.ts`);
24
24
  return {