@bleedingdev/modern-js-plugin-bff-build-extensions 0.0.0 → 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.
- package/LICENSE +21 -0
- package/dist/cjs/client-artifacts.js +106 -0
- package/dist/cjs/compile.js +63 -0
- package/dist/cjs/cross-project.js +92 -0
- package/dist/cjs/generated-entries.js +92 -0
- package/dist/cjs/hono-client-codegen.js +107 -0
- package/dist/cjs/index.js +133 -0
- package/dist/cjs/server-global-vars.js +113 -0
- package/dist/esm/client-artifacts.mjs +65 -0
- package/dist/esm/compile.mjs +25 -0
- package/dist/esm/cross-project.mjs +44 -0
- package/dist/esm/generated-entries.mjs +54 -0
- package/dist/esm/hono-client-codegen.mjs +59 -0
- package/dist/esm/index.mjs +93 -0
- package/dist/esm/server-global-vars.mjs +72 -0
- package/dist/esm-node/client-artifacts.mjs +66 -0
- package/dist/esm-node/compile.mjs +26 -0
- package/dist/esm-node/cross-project.mjs +45 -0
- package/dist/esm-node/generated-entries.mjs +56 -0
- package/dist/esm-node/hono-client-codegen.mjs +61 -0
- package/dist/esm-node/index.mjs +95 -0
- package/dist/esm-node/server-global-vars.mjs +73 -0
- package/dist/types/client-artifacts.d.ts +12 -0
- package/dist/types/compile.d.ts +3 -0
- package/dist/types/cross-project.d.ts +11 -0
- package/dist/types/generated-entries.d.ts +4 -0
- package/dist/types/hono-client-codegen.d.ts +2 -0
- package/dist/types/index.d.ts +4 -0
- package/dist/types/server-global-vars.d.ts +6 -0
- package/package.json +104 -8
- package/src/client-artifacts.ts +101 -0
- package/src/compile.ts +37 -0
- package/src/cross-project.ts +72 -0
- package/src/generated-entries.ts +100 -0
- package/src/hono-client-codegen.ts +83 -0
- package/src/index.ts +131 -0
- package/src/server-global-vars.ts +145 -0
- package/README.md +0 -3
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __webpack_require__ = {};
|
|
3
|
+
(()=>{
|
|
4
|
+
__webpack_require__.d = (exports1, getters, values)=>{
|
|
5
|
+
var define = (defs, kind)=>{
|
|
6
|
+
for(var key in defs)if (__webpack_require__.o(defs, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
|
|
7
|
+
enumerable: true,
|
|
8
|
+
[kind]: defs[key]
|
|
9
|
+
});
|
|
10
|
+
};
|
|
11
|
+
define(getters, "get");
|
|
12
|
+
define(values, "value");
|
|
13
|
+
};
|
|
14
|
+
})();
|
|
15
|
+
(()=>{
|
|
16
|
+
__webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
|
|
17
|
+
})();
|
|
18
|
+
(()=>{
|
|
19
|
+
__webpack_require__.r = (exports1)=>{
|
|
20
|
+
if ("u" > typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
|
|
21
|
+
value: 'Module'
|
|
22
|
+
});
|
|
23
|
+
Object.defineProperty(exports1, '__esModule', {
|
|
24
|
+
value: true
|
|
25
|
+
});
|
|
26
|
+
};
|
|
27
|
+
})();
|
|
28
|
+
var __webpack_exports__ = {};
|
|
29
|
+
__webpack_require__.r(__webpack_exports__);
|
|
30
|
+
__webpack_require__.d(__webpack_exports__, {
|
|
31
|
+
serializeServerGlobalVars: ()=>serializeServerGlobalVars,
|
|
32
|
+
transformServerGlobalVars: ()=>transformServerGlobalVars
|
|
33
|
+
});
|
|
34
|
+
const utils_namespaceObject = require("@modern-js/utils");
|
|
35
|
+
const core_namespaceObject = require("@swc/core");
|
|
36
|
+
const RELEASE_IDENTITY_GLOBAL_NAMES = [
|
|
37
|
+
'ULTRAMODERN_BUILD_MARKER',
|
|
38
|
+
'ULTRAMODERN_SOURCE_REVISION',
|
|
39
|
+
'ULTRAMODERN_RELEASE_VERSION'
|
|
40
|
+
];
|
|
41
|
+
const collectJavaScriptFiles = (directory)=>Promise.resolve().then(()=>utils_namespaceObject.fs.readdir(directory, {
|
|
42
|
+
withFileTypes: true
|
|
43
|
+
})).then((entries)=>Promise.all(entries.map((entry)=>{
|
|
44
|
+
const absolutePath = utils_namespaceObject.upath.join(directory, entry.name);
|
|
45
|
+
if (entry.isDirectory()) return collectJavaScriptFiles(absolutePath);
|
|
46
|
+
return /\.(?:c|m)?js$/u.test(entry.name) ? [
|
|
47
|
+
absolutePath
|
|
48
|
+
] : [];
|
|
49
|
+
})).then((nested)=>nested.flat()));
|
|
50
|
+
const serializeServerGlobalVars = (options)=>{
|
|
51
|
+
const globalVars = (0, utils_namespaceObject.applyOptionsChain)({}, options, {
|
|
52
|
+
env: 'server',
|
|
53
|
+
target: 'node'
|
|
54
|
+
});
|
|
55
|
+
return Object.fromEntries(Object.entries(globalVars).map(([key, value])=>{
|
|
56
|
+
let serialized;
|
|
57
|
+
try {
|
|
58
|
+
serialized = JSON.stringify(value);
|
|
59
|
+
} catch (error) {
|
|
60
|
+
throw new Error(`source.globalVars["${key}"] cannot be serialized exactly for BFF compilation.`, {
|
|
61
|
+
cause: error
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
if (void 0 === serialized) throw new Error(`source.globalVars["${key}"] cannot be serialized exactly for BFF compilation.`);
|
|
65
|
+
return [
|
|
66
|
+
key,
|
|
67
|
+
serialized
|
|
68
|
+
];
|
|
69
|
+
}));
|
|
70
|
+
};
|
|
71
|
+
const transformServerGlobalVars = (outputDirectories, globalVars)=>Promise.resolve().then(()=>{
|
|
72
|
+
if (0 === Object.keys(globalVars).length) return;
|
|
73
|
+
return Promise.all(outputDirectories.map((directory)=>utils_namespaceObject.fs.pathExists(directory).then((directoryExists)=>directoryExists ? directory : void 0))).then((existingDirectories)=>{
|
|
74
|
+
const filesPromise = Promise.all(existingDirectories.filter((directory)=>void 0 !== directory).map(collectJavaScriptFiles)).then((files)=>files.flat());
|
|
75
|
+
const releaseIdentityBanner = RELEASE_IDENTITY_GLOBAL_NAMES.every((name)=>Object.hasOwn(globalVars, name)) ? `${RELEASE_IDENTITY_GLOBAL_NAMES.map((name)=>`void ${globalVars[name]};`).join('')}\n` : '';
|
|
76
|
+
return filesPromise.then((files)=>Promise.all(files.map((filename)=>utils_namespaceObject.fs.readFile(filename, 'utf8').then((source)=>{
|
|
77
|
+
const sourceMapFilename = `${filename}.map`;
|
|
78
|
+
return utils_namespaceObject.fs.pathExists(sourceMapFilename).then((sourceMapExists)=>{
|
|
79
|
+
const inputSourceMapPromise = sourceMapExists ? utils_namespaceObject.fs.readFile(sourceMapFilename, 'utf8') : Promise.resolve(void 0);
|
|
80
|
+
return inputSourceMapPromise.then((inputSourceMap)=>(0, core_namespaceObject.transform)(`${releaseIdentityBanner}${source}`, {
|
|
81
|
+
filename,
|
|
82
|
+
inputSourceMap,
|
|
83
|
+
sourceMaps: sourceMapExists,
|
|
84
|
+
jsc: {
|
|
85
|
+
parser: {
|
|
86
|
+
syntax: "ecmascript"
|
|
87
|
+
},
|
|
88
|
+
preserveAllComments: true,
|
|
89
|
+
target: 'es2024',
|
|
90
|
+
transform: {
|
|
91
|
+
optimizer: {
|
|
92
|
+
globals: {
|
|
93
|
+
vars: globalVars
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}).then((result)=>utils_namespaceObject.fs.writeFile(filename, result.code).then(()=>{
|
|
99
|
+
if (sourceMapExists && void 0 !== result.map && result.map.length > 0) return utils_namespaceObject.fs.writeFile(sourceMapFilename, result.map);
|
|
100
|
+
})));
|
|
101
|
+
});
|
|
102
|
+
}))));
|
|
103
|
+
}).then(()=>void 0);
|
|
104
|
+
});
|
|
105
|
+
exports.serializeServerGlobalVars = __webpack_exports__.serializeServerGlobalVars;
|
|
106
|
+
exports.transformServerGlobalVars = __webpack_exports__.transformServerGlobalVars;
|
|
107
|
+
for(var __rspack_i in __webpack_exports__)if (-1 === [
|
|
108
|
+
"serializeServerGlobalVars",
|
|
109
|
+
"transformServerGlobalVars"
|
|
110
|
+
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
|
|
111
|
+
Object.defineProperty(exports, '__esModule', {
|
|
112
|
+
value: true
|
|
113
|
+
});
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { ApiRouter } from "@modern-js/bff-core";
|
|
2
|
+
import { buildOperationContractMap, deriveOperationVersion } from "@modern-js/server-runtime-extensions/bff-policy/node";
|
|
3
|
+
import { fs, upath } from "@modern-js/utils";
|
|
4
|
+
const BFF_REQUEST_RUNTIME = '@modern-js/runtime-extensions/request-policy';
|
|
5
|
+
function registerBffClientArtifacts(api, metadata) {
|
|
6
|
+
api.modifyBffClientArtifacts(async (context)=>{
|
|
7
|
+
const { generation } = context;
|
|
8
|
+
const config = api.getNormalizedConfig();
|
|
9
|
+
if ('effect' === api.getAppContext().bffRuntimeFramework) {
|
|
10
|
+
const { generateEffectClient, resolveEffectEntryPaths } = await import("@modern-js/plugin-bff-extensions/client-generator");
|
|
11
|
+
const { sourceEffectEntry, relativeEffectEntry } = resolveEffectEntryPaths({
|
|
12
|
+
appDir: generation.appDirectory,
|
|
13
|
+
apiDir: generation.apiDirectory,
|
|
14
|
+
effectEntry: config.bff?.effect?.entry
|
|
15
|
+
});
|
|
16
|
+
if (!sourceEffectEntry) throw new Error(`Cannot resolve Effect BFF entry in ${generation.apiDirectory}.`);
|
|
17
|
+
const artifacts = await generateEffectClient({
|
|
18
|
+
appDir: generation.appDirectory,
|
|
19
|
+
apiDir: generation.apiDirectory,
|
|
20
|
+
resourcePath: sourceEffectEntry,
|
|
21
|
+
prefix: generation.prefix,
|
|
22
|
+
port: Number(generation.port),
|
|
23
|
+
target: 'bundle',
|
|
24
|
+
requestId: generation.requestId,
|
|
25
|
+
requestCreator: generation.requestCreator || BFF_REQUEST_RUNTIME,
|
|
26
|
+
httpMethodDecider: generation.httpMethodDecider,
|
|
27
|
+
dataPlatformBatch: config.bff?.effect?.dataPlatform?.batch
|
|
28
|
+
});
|
|
29
|
+
if (!artifacts) throw new Error(`Effect cross-project client generation failed for ${sourceEffectEntry}.`);
|
|
30
|
+
context.additionalArtifacts.push({
|
|
31
|
+
sourcePath: upath.relative(generation.apiDirectory, sourceEffectEntry),
|
|
32
|
+
code: artifacts.code,
|
|
33
|
+
declaration: artifacts.declaration
|
|
34
|
+
});
|
|
35
|
+
metadata.set(generation, {
|
|
36
|
+
runtimeFramework: 'effect',
|
|
37
|
+
relativeEffectEntry,
|
|
38
|
+
operationContracts: artifacts.operationContracts,
|
|
39
|
+
effectArtifacts: artifacts
|
|
40
|
+
});
|
|
41
|
+
} else {
|
|
42
|
+
const router = new ApiRouter({
|
|
43
|
+
appDir: generation.appDirectory,
|
|
44
|
+
apiDir: generation.apiDirectory,
|
|
45
|
+
lambdaDir: generation.lambdaDirectory,
|
|
46
|
+
prefix: generation.prefix,
|
|
47
|
+
httpMethodDecider: generation.httpMethodDecider,
|
|
48
|
+
isBuild: true
|
|
49
|
+
});
|
|
50
|
+
const packageJson = await fs.readJSON(upath.join(generation.appDirectory, 'package.json'));
|
|
51
|
+
const operationContracts = generation.existLambda ? buildOperationContractMap({
|
|
52
|
+
handlers: await router.getApiHandlers(),
|
|
53
|
+
requestId: generation.requestId,
|
|
54
|
+
operationVersion: deriveOperationVersion(packageJson.version)
|
|
55
|
+
}) : {};
|
|
56
|
+
metadata.set(generation, {
|
|
57
|
+
runtimeFramework: 'hono',
|
|
58
|
+
relativeEffectEntry: '',
|
|
59
|
+
operationContracts
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
return context;
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
export { BFF_REQUEST_RUNTIME, registerBffClientArtifacts };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { serializeServerGlobalVars, transformServerGlobalVars } from "./server-global-vars.mjs";
|
|
2
|
+
function registerBffCompilation(api) {
|
|
3
|
+
const serialized = new WeakMap();
|
|
4
|
+
api.onBeforeBffCompile((context)=>{
|
|
5
|
+
serialized.set(context, serializeServerGlobalVars(api.getNormalizedConfig().source.globalVars));
|
|
6
|
+
});
|
|
7
|
+
api.onAfterBffCompile(async (context)=>{
|
|
8
|
+
const globals = serialized.get(context);
|
|
9
|
+
if (!globals) throw new Error('BFF compilation completed without its before hook.');
|
|
10
|
+
serialized.delete(context);
|
|
11
|
+
await transformServerGlobalVars([
|
|
12
|
+
...context.outputDirectories
|
|
13
|
+
], globals);
|
|
14
|
+
if ('effect' !== api.getAppContext().bffRuntimeFramework) return;
|
|
15
|
+
const { bundleBuiltEffectEntryForNode } = await import("@modern-js/plugin-bff-extensions/client-generator");
|
|
16
|
+
await bundleBuiltEffectEntryForNode({
|
|
17
|
+
appDir: context.appDirectory,
|
|
18
|
+
apiDir: context.apiDirectory,
|
|
19
|
+
distDir: context.distDirectory,
|
|
20
|
+
effectEntry: api.getNormalizedConfig().bff?.effect?.entry,
|
|
21
|
+
format: 'module' === context.moduleType ? 'esm' : 'cjs'
|
|
22
|
+
});
|
|
23
|
+
});
|
|
24
|
+
}
|
|
25
|
+
export { registerBffCompilation };
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import "@modern-js/server-runtime-extensions/server-config";
|
|
2
|
+
import node_path from "node:path";
|
|
3
|
+
import { createCrossProjectApiPlugin } from "@modern-js/plugin-bff/cross-project";
|
|
4
|
+
function createCrossProjectBffPlugin(descriptor) {
|
|
5
|
+
return createCrossProjectApiPlugin({
|
|
6
|
+
...descriptor.native,
|
|
7
|
+
modifyResolvedConfig: (resolvedConfig, { sdkDistDirectory, api })=>{
|
|
8
|
+
const config = api.getConfig();
|
|
9
|
+
const configuredRuntimeFramework = config?.bff?.runtimeFramework;
|
|
10
|
+
if (configuredRuntimeFramework && configuredRuntimeFramework !== descriptor.runtimeFramework) throw new Error(`[${descriptor.native.packageName}] Runtime framework mismatch for cross-project BFF. Detected "${configuredRuntimeFramework}", but producer SDK requires "${descriptor.runtimeFramework}".`);
|
|
11
|
+
const effectEntry = descriptor.relativeEffectEntry ? node_path.join(sdkDistDirectory, descriptor.relativeEffectEntry) : void 0;
|
|
12
|
+
api.updateAppContext({
|
|
13
|
+
...effectEntry ? {
|
|
14
|
+
apiDirectory: node_path.dirname(effectEntry)
|
|
15
|
+
} : {},
|
|
16
|
+
bffRuntimeFramework: descriptor.runtimeFramework
|
|
17
|
+
});
|
|
18
|
+
resolvedConfig.bff ??= {};
|
|
19
|
+
resolvedConfig.bff.runtimeFramework = descriptor.runtimeFramework;
|
|
20
|
+
if (effectEntry) resolvedConfig.bff.effect = {
|
|
21
|
+
...resolvedConfig.bff.effect,
|
|
22
|
+
entry: effectEntry
|
|
23
|
+
};
|
|
24
|
+
resolvedConfig.bff.requestId = resolvedConfig.bff.requestId || config?.bff?.requestId || descriptor.requestId || descriptor.native.packageName || 'default';
|
|
25
|
+
const policy = resolvedConfig.bff.crossProjectPolicy;
|
|
26
|
+
resolvedConfig.bff.crossProjectPolicy = {
|
|
27
|
+
...policy,
|
|
28
|
+
enabled: policy?.enabled ?? true,
|
|
29
|
+
requireEnvelope: policy?.requireEnvelope ?? true,
|
|
30
|
+
requireOperationContext: policy?.requireOperationContext ?? true,
|
|
31
|
+
requireOperationContextDetails: policy?.requireOperationContextDetails ?? true,
|
|
32
|
+
requireOperationSchemaHash: policy?.requireOperationSchemaHash ?? true,
|
|
33
|
+
requireOperationVersion: policy?.requireOperationVersion ?? true,
|
|
34
|
+
allowUnknownOperations: policy?.allowUnknownOperations ?? false,
|
|
35
|
+
expectedOperationContracts: {
|
|
36
|
+
...policy?.expectedOperationContracts,
|
|
37
|
+
...descriptor.operationContracts
|
|
38
|
+
}
|
|
39
|
+
};
|
|
40
|
+
return resolvedConfig;
|
|
41
|
+
}
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
export { createCrossProjectBffPlugin };
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { pathToFileURL } from "node:url";
|
|
2
|
+
import { fs, upath } from "@modern-js/utils";
|
|
3
|
+
import { BFF_REQUEST_RUNTIME } from "./client-artifacts.mjs";
|
|
4
|
+
function registerBffGeneratedEntries(api, metadata) {
|
|
5
|
+
api.modifyBffGeneratedEntries(async (entries)=>{
|
|
6
|
+
const { generation } = entries;
|
|
7
|
+
const details = metadata.get(generation);
|
|
8
|
+
if (!details) throw new Error('BFF entries require completed client artifact generation.');
|
|
9
|
+
metadata.delete(generation);
|
|
10
|
+
const packageJson = await fs.readJSON(upath.join(generation.appDirectory, 'package.json'));
|
|
11
|
+
const runtimeSpecifier = api.getNormalizedConfig().bff?.runtimeCreateRequest || BFF_REQUEST_RUNTIME;
|
|
12
|
+
const dependencies = [
|
|
13
|
+
'@modern-js/plugin-bff-build-extensions',
|
|
14
|
+
'@modern-js/plugin-bff-extensions'
|
|
15
|
+
];
|
|
16
|
+
const emitsClient = 'effect' === details.runtimeFramework || generation.apiFiles.length > 0;
|
|
17
|
+
if (runtimeSpecifier === BFF_REQUEST_RUNTIME || emitsClient && (generation.requestCreator || BFF_REQUEST_RUNTIME) === BFF_REQUEST_RUNTIME) dependencies.push('@modern-js/runtime-extensions');
|
|
18
|
+
for (const name of dependencies){
|
|
19
|
+
const specifier = packageJson.dependencies?.[name] || packageJson.devDependencies?.[name] || fs.readJSONSync(require.resolve(`${name}/package.json`)).version;
|
|
20
|
+
entries.packageDependencies[name] = specifier;
|
|
21
|
+
}
|
|
22
|
+
const descriptor = {
|
|
23
|
+
native: {
|
|
24
|
+
packageName: packageJson.name,
|
|
25
|
+
prefix: generation.prefix,
|
|
26
|
+
relativeDistPath: upath.normalize(generation.relativeDistPath),
|
|
27
|
+
relativeApiPath: upath.relative(generation.appDirectory, generation.apiDirectory),
|
|
28
|
+
relativeLambdaPath: upath.relative(generation.appDirectory, generation.lambdaDirectory)
|
|
29
|
+
},
|
|
30
|
+
runtimeFramework: details.runtimeFramework,
|
|
31
|
+
relativeEffectEntry: details.relativeEffectEntry,
|
|
32
|
+
requestId: generation.requestId,
|
|
33
|
+
operationContracts: details.operationContracts
|
|
34
|
+
};
|
|
35
|
+
const isModule = 'module' === api.getAppContext().moduleType || 'module' === packageJson.type;
|
|
36
|
+
entries.plugin = {
|
|
37
|
+
code: isModule ? `import { createCrossProjectBffPlugin } from '@modern-js/plugin-bff-build-extensions/cross-project';\nexport const crossProjectApiPlugin = () => createCrossProjectBffPlugin(${JSON.stringify(descriptor)});\n` : `'use strict';\nconst { createCrossProjectBffPlugin } = require('@modern-js/plugin-bff-build-extensions/cross-project');\nexports.crossProjectApiPlugin = () => createCrossProjectBffPlugin(${JSON.stringify(descriptor)});\n`,
|
|
38
|
+
declaration: `import type { AppTools, CliPlugin } from '@modern-js/app-tools';
|
|
39
|
+
export declare const crossProjectApiPlugin: () => CliPlugin<AppTools>;
|
|
40
|
+
`
|
|
41
|
+
};
|
|
42
|
+
const runtime = JSON.stringify(runtimeSpecifier);
|
|
43
|
+
const esmRuntime = JSON.stringify(upath.isAbsolute(runtimeSpecifier) ? pathToFileURL(runtimeSpecifier).href : runtimeSpecifier);
|
|
44
|
+
entries.runtime = {
|
|
45
|
+
code: isModule ? `import { configure as _configure } from ${esmRuntime};\nimport { createProducerClient } from '@modern-js/plugin-bff-extensions/producer-runtime';\nexport const configure = createProducerClient(_configure, { requestId: ${JSON.stringify(generation.requestId)} });\nexport const initProducerClient = configure;\n` : `'use strict';\nconst { configure: _configure } = require(${runtime});\nconst { createProducerClient } = require('@modern-js/plugin-bff-extensions/producer-runtime');\nconst configure = createProducerClient(_configure, { requestId: ${JSON.stringify(generation.requestId)} });\nexports.configure = configure;\nexports.initProducerClient = configure;\n`,
|
|
46
|
+
declaration: `type Runtime = typeof import(${runtime});
|
|
47
|
+
export declare const initProducerClient: (options?: Parameters<Runtime['configure']>[0]) => ReturnType<Runtime['configure']>;
|
|
48
|
+
export declare const configure: typeof initProducerClient;
|
|
49
|
+
`
|
|
50
|
+
};
|
|
51
|
+
return entries;
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
export { registerBffGeneratedEntries };
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import node_path from "node:path";
|
|
2
|
+
import { buildOperationContractMap, createOperationSchemaHash, deriveOperationVersion } from "@modern-js/server-runtime-extensions/bff-policy/node";
|
|
3
|
+
const REQUEST_RUNTIME = '@modern-js/runtime-extensions/request-policy';
|
|
4
|
+
const modifyClient = (draft, context)=>{
|
|
5
|
+
const { appDir, requestId } = context.options;
|
|
6
|
+
draft.requestCreator = context.options.requestCreator || REQUEST_RUNTIME;
|
|
7
|
+
let version;
|
|
8
|
+
try {
|
|
9
|
+
version = require(node_path.resolve(appDir, 'package.json')).version;
|
|
10
|
+
} catch {}
|
|
11
|
+
const operationVersion = deriveOperationVersion(version);
|
|
12
|
+
const normalizedRequestId = requestId || 'default';
|
|
13
|
+
const operationContracts = buildOperationContractMap({
|
|
14
|
+
handlers: [
|
|
15
|
+
...context.handlerInfos
|
|
16
|
+
],
|
|
17
|
+
requestId: normalizedRequestId,
|
|
18
|
+
operationVersion
|
|
19
|
+
});
|
|
20
|
+
const operationEntries = context.handlerInfos.map((handlerInfo)=>{
|
|
21
|
+
const httpMethod = handlerInfo.httpMethod.toUpperCase();
|
|
22
|
+
return {
|
|
23
|
+
name: handlerInfo.name,
|
|
24
|
+
httpMethod,
|
|
25
|
+
routePath: handlerInfo.routePath,
|
|
26
|
+
schemaHash: operationContracts[`${httpMethod}:${handlerInfo.routePath}`]?.schemaHash ?? ''
|
|
27
|
+
};
|
|
28
|
+
}).sort((a, b)=>`${a.routePath}:${a.httpMethod}:${a.name}`.localeCompare(`${b.routePath}:${b.httpMethod}:${b.name}`));
|
|
29
|
+
const schemaHash = createOperationSchemaHash(operationEntries, normalizedRequestId);
|
|
30
|
+
for (const { handlerInfo, optionProperties } of draft.handlers){
|
|
31
|
+
if ('upload' === handlerInfo.action && !requestId) continue;
|
|
32
|
+
const method = handlerInfo.httpMethod.toUpperCase();
|
|
33
|
+
const operationContext = {
|
|
34
|
+
operationId: handlerInfo.name,
|
|
35
|
+
routePath: handlerInfo.routePath,
|
|
36
|
+
method,
|
|
37
|
+
schemaHash: operationContracts[`${method}:${handlerInfo.routePath}`]?.schemaHash ?? '',
|
|
38
|
+
operationVersion
|
|
39
|
+
};
|
|
40
|
+
optionProperties.push(`operationContext: ${JSON.stringify(operationContext)}`);
|
|
41
|
+
}
|
|
42
|
+
if (requestId) {
|
|
43
|
+
draft.imports.push(`import * as requestRuntime from ${JSON.stringify(draft.requestCreator)};`, 'import { createProducerClient } from "@modern-js/plugin-bff-extensions/producer-runtime";');
|
|
44
|
+
draft.statements.push(`export const initProducerClient = (options = {}) => {
|
|
45
|
+
const configure = requestRuntime.configure;
|
|
46
|
+
if (typeof configure !== 'function') {
|
|
47
|
+
console.warn('[modernjs] Compatibility request creator path does not expose configure(); use default @modern-js/create-request or migrate the compatibility path.');
|
|
48
|
+
return undefined;
|
|
49
|
+
}
|
|
50
|
+
return createProducerClient(configure, { requestId: ${JSON.stringify(requestId)} })(options);
|
|
51
|
+
};`);
|
|
52
|
+
}
|
|
53
|
+
draft.statements.push(`export const operationVersion = ${String(operationVersion)};`, `export const operationSchemaHash = ${JSON.stringify(schemaHash)};`, `export const operationManifest = ${JSON.stringify({
|
|
54
|
+
operationVersion,
|
|
55
|
+
schemaHash,
|
|
56
|
+
operations: operationEntries
|
|
57
|
+
}, null, 2)};`);
|
|
58
|
+
};
|
|
59
|
+
export { modifyClient };
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import "@modern-js/server-runtime-extensions/server-config";
|
|
2
|
+
import { bffPlugin } from "@modern-js/plugin-bff";
|
|
3
|
+
import { fs, upath } from "@modern-js/utils";
|
|
4
|
+
import { BFF_REQUEST_RUNTIME, registerBffClientArtifacts } from "./client-artifacts.mjs";
|
|
5
|
+
import { registerBffCompilation } from "./compile.mjs";
|
|
6
|
+
import { registerBffGeneratedEntries } from "./generated-entries.mjs";
|
|
7
|
+
const src_bffPlugin = ()=>({
|
|
8
|
+
name: '@modern-js/plugin-bff-build-extensions',
|
|
9
|
+
usePlugins: [
|
|
10
|
+
bffPlugin()
|
|
11
|
+
],
|
|
12
|
+
pre: [
|
|
13
|
+
'@modern-js/plugin-bff'
|
|
14
|
+
],
|
|
15
|
+
setup: (api)=>{
|
|
16
|
+
const hooks = api.getHooks();
|
|
17
|
+
for (const name of [
|
|
18
|
+
'onBeforeBffCompile',
|
|
19
|
+
'onAfterBffCompile',
|
|
20
|
+
'modifyBffClientArtifacts',
|
|
21
|
+
'modifyBffGeneratedEntries'
|
|
22
|
+
])if ('function' != typeof hooks[name]?.tap) throw new Error(`Native BFF build hook ${name} is unavailable.`);
|
|
23
|
+
api.config(()=>({
|
|
24
|
+
bff: {
|
|
25
|
+
requestCreator: BFF_REQUEST_RUNTIME,
|
|
26
|
+
runtimeCreateRequest: BFF_REQUEST_RUNTIME,
|
|
27
|
+
clientCodegenPlugin: require.resolve('@modern-js/plugin-bff-build-extensions/hono-client-codegen')
|
|
28
|
+
}
|
|
29
|
+
}));
|
|
30
|
+
const runtimeFramework = api.getConfig()?.bff?.runtimeFramework;
|
|
31
|
+
if (void 0 !== runtimeFramework && 'hono' !== runtimeFramework && 'effect' !== runtimeFramework) throw new Error(`Unsupported Effect BFF runtime "${runtimeFramework}".`);
|
|
32
|
+
api.updateAppContext({
|
|
33
|
+
bffRuntimeFramework: runtimeFramework ?? 'effect'
|
|
34
|
+
});
|
|
35
|
+
api._internalServerPlugins(({ plugins })=>{
|
|
36
|
+
const nativePlugins = plugins.filter((plugin)=>'@modern-js/plugin-bff/server-plugin' === plugin.name);
|
|
37
|
+
if (1 !== nativePlugins.length) throw new Error('Expected exactly one native BFF server plugin.');
|
|
38
|
+
const native = nativePlugins[0];
|
|
39
|
+
const runtimeAdapters = native.options?.runtimeAdapters ?? {};
|
|
40
|
+
const effect = '@modern-js/plugin-bff-extensions/effect-adapter';
|
|
41
|
+
const honoRouteBinder = '@modern-js/plugin-bff-extensions/hono/node';
|
|
42
|
+
if (native.options?.honoRouteBinder !== void 0 && native.options.honoRouteBinder !== honoRouteBinder) throw new Error('The Hono BFF route binder is already configured.');
|
|
43
|
+
if (void 0 !== runtimeAdapters.effect && runtimeAdapters.effect !== effect) throw new Error('The Effect BFF runtime adapter is already configured.');
|
|
44
|
+
native.options = {
|
|
45
|
+
...native.options,
|
|
46
|
+
honoRouteBinder,
|
|
47
|
+
runtimeAdapters: {
|
|
48
|
+
...runtimeAdapters,
|
|
49
|
+
effect
|
|
50
|
+
}
|
|
51
|
+
};
|
|
52
|
+
return {
|
|
53
|
+
plugins
|
|
54
|
+
};
|
|
55
|
+
});
|
|
56
|
+
const metadata = new WeakMap();
|
|
57
|
+
registerBffCompilation(api);
|
|
58
|
+
registerBffClientArtifacts(api, metadata);
|
|
59
|
+
registerBffGeneratedEntries(api, metadata);
|
|
60
|
+
api.modifyBundlerChain(async (chain, { isServer, CHAIN_ID })=>{
|
|
61
|
+
if ('effect' !== api.getAppContext().bffRuntimeFramework) return;
|
|
62
|
+
const { appDirectory, apiDirectory, port } = api.getAppContext();
|
|
63
|
+
const bff = api.getNormalizedConfig().bff;
|
|
64
|
+
const { resolveEffectEntryFile } = await import("@modern-js/plugin-bff-extensions/client-generator");
|
|
65
|
+
const entry = resolveEffectEntryFile({
|
|
66
|
+
appDir: appDirectory,
|
|
67
|
+
apiDir: apiDirectory,
|
|
68
|
+
effectEntry: bff?.effect?.entry
|
|
69
|
+
});
|
|
70
|
+
if (!entry) throw new Error(`Cannot resolve Effect BFF entry in ${apiDirectory}.`);
|
|
71
|
+
const canonical = (file)=>upath.normalize(fs.existsSync(file) ? fs.realpathSync(file) : upath.resolve(file));
|
|
72
|
+
const entryPath = canonical(entry);
|
|
73
|
+
const isEntry = (resource)=>canonical(resource) === entryPath;
|
|
74
|
+
chain.module.rule(CHAIN_ID.RULE.JS).exclude.add(isEntry);
|
|
75
|
+
chain.module.rule('js-bff-api').exclude.add(isEntry);
|
|
76
|
+
chain.module.rule('js-bff-effect-entry').test(isEntry).use('effect-bff-loader').loader(require.resolve('@modern-js/plugin-bff-extensions/effect-source-loader/rspack-loader')).options({
|
|
77
|
+
appDir: appDirectory,
|
|
78
|
+
apiDir: apiDirectory,
|
|
79
|
+
effectEntry: entry,
|
|
80
|
+
prefix: Array.isArray(bff?.prefix) ? bff.prefix[0] : bff?.prefix || '/api',
|
|
81
|
+
port,
|
|
82
|
+
target: isServer ? 'server' : 'client',
|
|
83
|
+
requestId: bff?.requestId,
|
|
84
|
+
requestCreator: bff?.requestCreator || BFF_REQUEST_RUNTIME,
|
|
85
|
+
httpMethodDecider: bff?.httpMethodDecider,
|
|
86
|
+
effectDataPlatformBatch: bff?.effect?.dataPlatform?.batch
|
|
87
|
+
});
|
|
88
|
+
});
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
const src = src_bffPlugin;
|
|
92
|
+
export default src;
|
|
93
|
+
export { src_bffPlugin as bffPlugin };
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { applyOptionsChain, fs, upath } from "@modern-js/utils";
|
|
2
|
+
import { transform } from "@swc/core";
|
|
3
|
+
const RELEASE_IDENTITY_GLOBAL_NAMES = [
|
|
4
|
+
'ULTRAMODERN_BUILD_MARKER',
|
|
5
|
+
'ULTRAMODERN_SOURCE_REVISION',
|
|
6
|
+
'ULTRAMODERN_RELEASE_VERSION'
|
|
7
|
+
];
|
|
8
|
+
const collectJavaScriptFiles = (directory)=>Promise.resolve().then(()=>fs.readdir(directory, {
|
|
9
|
+
withFileTypes: true
|
|
10
|
+
})).then((entries)=>Promise.all(entries.map((entry)=>{
|
|
11
|
+
const absolutePath = upath.join(directory, entry.name);
|
|
12
|
+
if (entry.isDirectory()) return collectJavaScriptFiles(absolutePath);
|
|
13
|
+
return /\.(?:c|m)?js$/u.test(entry.name) ? [
|
|
14
|
+
absolutePath
|
|
15
|
+
] : [];
|
|
16
|
+
})).then((nested)=>nested.flat()));
|
|
17
|
+
const serializeServerGlobalVars = (options)=>{
|
|
18
|
+
const globalVars = applyOptionsChain({}, options, {
|
|
19
|
+
env: 'server',
|
|
20
|
+
target: 'node'
|
|
21
|
+
});
|
|
22
|
+
return Object.fromEntries(Object.entries(globalVars).map(([key, value])=>{
|
|
23
|
+
let serialized;
|
|
24
|
+
try {
|
|
25
|
+
serialized = JSON.stringify(value);
|
|
26
|
+
} catch (error) {
|
|
27
|
+
throw new Error(`source.globalVars["${key}"] cannot be serialized exactly for BFF compilation.`, {
|
|
28
|
+
cause: error
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
if (void 0 === serialized) throw new Error(`source.globalVars["${key}"] cannot be serialized exactly for BFF compilation.`);
|
|
32
|
+
return [
|
|
33
|
+
key,
|
|
34
|
+
serialized
|
|
35
|
+
];
|
|
36
|
+
}));
|
|
37
|
+
};
|
|
38
|
+
const transformServerGlobalVars = (outputDirectories, globalVars)=>Promise.resolve().then(()=>{
|
|
39
|
+
if (0 === Object.keys(globalVars).length) return;
|
|
40
|
+
return Promise.all(outputDirectories.map((directory)=>fs.pathExists(directory).then((directoryExists)=>directoryExists ? directory : void 0))).then((existingDirectories)=>{
|
|
41
|
+
const filesPromise = Promise.all(existingDirectories.filter((directory)=>void 0 !== directory).map(collectJavaScriptFiles)).then((files)=>files.flat());
|
|
42
|
+
const releaseIdentityBanner = RELEASE_IDENTITY_GLOBAL_NAMES.every((name)=>Object.hasOwn(globalVars, name)) ? `${RELEASE_IDENTITY_GLOBAL_NAMES.map((name)=>`void ${globalVars[name]};`).join('')}\n` : '';
|
|
43
|
+
return filesPromise.then((files)=>Promise.all(files.map((filename)=>fs.readFile(filename, 'utf8').then((source)=>{
|
|
44
|
+
const sourceMapFilename = `${filename}.map`;
|
|
45
|
+
return fs.pathExists(sourceMapFilename).then((sourceMapExists)=>{
|
|
46
|
+
const inputSourceMapPromise = sourceMapExists ? fs.readFile(sourceMapFilename, 'utf8') : Promise.resolve(void 0);
|
|
47
|
+
return inputSourceMapPromise.then((inputSourceMap)=>transform(`${releaseIdentityBanner}${source}`, {
|
|
48
|
+
filename,
|
|
49
|
+
inputSourceMap,
|
|
50
|
+
sourceMaps: sourceMapExists,
|
|
51
|
+
jsc: {
|
|
52
|
+
parser: {
|
|
53
|
+
syntax: "ecmascript"
|
|
54
|
+
},
|
|
55
|
+
preserveAllComments: true,
|
|
56
|
+
target: 'es2024',
|
|
57
|
+
transform: {
|
|
58
|
+
optimizer: {
|
|
59
|
+
globals: {
|
|
60
|
+
vars: globalVars
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
}).then((result)=>fs.writeFile(filename, result.code).then(()=>{
|
|
66
|
+
if (sourceMapExists && void 0 !== result.map && result.map.length > 0) return fs.writeFile(sourceMapFilename, result.map);
|
|
67
|
+
})));
|
|
68
|
+
});
|
|
69
|
+
}))));
|
|
70
|
+
}).then(()=>void 0);
|
|
71
|
+
});
|
|
72
|
+
export { serializeServerGlobalVars, transformServerGlobalVars };
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { ApiRouter } from "@modern-js/bff-core";
|
|
3
|
+
import { buildOperationContractMap, deriveOperationVersion } from "@modern-js/server-runtime-extensions/bff-policy/node";
|
|
4
|
+
import { fs, upath } from "@modern-js/utils";
|
|
5
|
+
const BFF_REQUEST_RUNTIME = '@modern-js/runtime-extensions/request-policy';
|
|
6
|
+
function registerBffClientArtifacts(api, metadata) {
|
|
7
|
+
api.modifyBffClientArtifacts(async (context)=>{
|
|
8
|
+
const { generation } = context;
|
|
9
|
+
const config = api.getNormalizedConfig();
|
|
10
|
+
if ('effect' === api.getAppContext().bffRuntimeFramework) {
|
|
11
|
+
const { generateEffectClient, resolveEffectEntryPaths } = await import("@modern-js/plugin-bff-extensions/client-generator");
|
|
12
|
+
const { sourceEffectEntry, relativeEffectEntry } = resolveEffectEntryPaths({
|
|
13
|
+
appDir: generation.appDirectory,
|
|
14
|
+
apiDir: generation.apiDirectory,
|
|
15
|
+
effectEntry: config.bff?.effect?.entry
|
|
16
|
+
});
|
|
17
|
+
if (!sourceEffectEntry) throw new Error(`Cannot resolve Effect BFF entry in ${generation.apiDirectory}.`);
|
|
18
|
+
const artifacts = await generateEffectClient({
|
|
19
|
+
appDir: generation.appDirectory,
|
|
20
|
+
apiDir: generation.apiDirectory,
|
|
21
|
+
resourcePath: sourceEffectEntry,
|
|
22
|
+
prefix: generation.prefix,
|
|
23
|
+
port: Number(generation.port),
|
|
24
|
+
target: 'bundle',
|
|
25
|
+
requestId: generation.requestId,
|
|
26
|
+
requestCreator: generation.requestCreator || BFF_REQUEST_RUNTIME,
|
|
27
|
+
httpMethodDecider: generation.httpMethodDecider,
|
|
28
|
+
dataPlatformBatch: config.bff?.effect?.dataPlatform?.batch
|
|
29
|
+
});
|
|
30
|
+
if (!artifacts) throw new Error(`Effect cross-project client generation failed for ${sourceEffectEntry}.`);
|
|
31
|
+
context.additionalArtifacts.push({
|
|
32
|
+
sourcePath: upath.relative(generation.apiDirectory, sourceEffectEntry),
|
|
33
|
+
code: artifacts.code,
|
|
34
|
+
declaration: artifacts.declaration
|
|
35
|
+
});
|
|
36
|
+
metadata.set(generation, {
|
|
37
|
+
runtimeFramework: 'effect',
|
|
38
|
+
relativeEffectEntry,
|
|
39
|
+
operationContracts: artifacts.operationContracts,
|
|
40
|
+
effectArtifacts: artifacts
|
|
41
|
+
});
|
|
42
|
+
} else {
|
|
43
|
+
const router = new ApiRouter({
|
|
44
|
+
appDir: generation.appDirectory,
|
|
45
|
+
apiDir: generation.apiDirectory,
|
|
46
|
+
lambdaDir: generation.lambdaDirectory,
|
|
47
|
+
prefix: generation.prefix,
|
|
48
|
+
httpMethodDecider: generation.httpMethodDecider,
|
|
49
|
+
isBuild: true
|
|
50
|
+
});
|
|
51
|
+
const packageJson = await fs.readJSON(upath.join(generation.appDirectory, 'package.json'));
|
|
52
|
+
const operationContracts = generation.existLambda ? buildOperationContractMap({
|
|
53
|
+
handlers: await router.getApiHandlers(),
|
|
54
|
+
requestId: generation.requestId,
|
|
55
|
+
operationVersion: deriveOperationVersion(packageJson.version)
|
|
56
|
+
}) : {};
|
|
57
|
+
metadata.set(generation, {
|
|
58
|
+
runtimeFramework: 'hono',
|
|
59
|
+
relativeEffectEntry: '',
|
|
60
|
+
operationContracts
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
return context;
|
|
64
|
+
});
|
|
65
|
+
}
|
|
66
|
+
export { BFF_REQUEST_RUNTIME, registerBffClientArtifacts };
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { serializeServerGlobalVars, transformServerGlobalVars } from "./server-global-vars.mjs";
|
|
3
|
+
function registerBffCompilation(api) {
|
|
4
|
+
const serialized = new WeakMap();
|
|
5
|
+
api.onBeforeBffCompile((context)=>{
|
|
6
|
+
serialized.set(context, serializeServerGlobalVars(api.getNormalizedConfig().source.globalVars));
|
|
7
|
+
});
|
|
8
|
+
api.onAfterBffCompile(async (context)=>{
|
|
9
|
+
const globals = serialized.get(context);
|
|
10
|
+
if (!globals) throw new Error('BFF compilation completed without its before hook.');
|
|
11
|
+
serialized.delete(context);
|
|
12
|
+
await transformServerGlobalVars([
|
|
13
|
+
...context.outputDirectories
|
|
14
|
+
], globals);
|
|
15
|
+
if ('effect' !== api.getAppContext().bffRuntimeFramework) return;
|
|
16
|
+
const { bundleBuiltEffectEntryForNode } = await import("@modern-js/plugin-bff-extensions/client-generator");
|
|
17
|
+
await bundleBuiltEffectEntryForNode({
|
|
18
|
+
appDir: context.appDirectory,
|
|
19
|
+
apiDir: context.apiDirectory,
|
|
20
|
+
distDir: context.distDirectory,
|
|
21
|
+
effectEntry: api.getNormalizedConfig().bff?.effect?.entry,
|
|
22
|
+
format: 'module' === context.moduleType ? 'esm' : 'cjs'
|
|
23
|
+
});
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
export { registerBffCompilation };
|