@bleedingdev/modern-js-plugin-bff-extensions 3.8.3-ultramodern.2
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 +22 -0
- package/README.md +29 -0
- package/dist/cjs/backend-federation/edge-runtime.js +230 -0
- package/dist/cjs/backend-federation/edge.js +80 -0
- package/dist/cjs/backend-federation/entry.js +94 -0
- package/dist/cjs/backend-federation/identity.js +82 -0
- package/dist/cjs/backend-federation/index.js +61 -0
- package/dist/cjs/backend-federation/legacy-warning.js +40 -0
- package/dist/cjs/backend-federation/load.js +72 -0
- package/dist/cjs/backend-federation/node.js +50 -0
- package/dist/cjs/backend-federation/plugin.js +63 -0
- package/dist/cjs/backend-federation/remotes.js +51 -0
- package/dist/cjs/backend-federation/runtime.js +128 -0
- package/dist/cjs/backend-federation/types.js +18 -0
- package/dist/cjs/backend-federation/utils.js +48 -0
- package/dist/cjs/backend-federation/validate-loaded.js +56 -0
- package/dist/cjs/backend-federation-manifest/errors.js +83 -0
- package/dist/cjs/backend-federation-manifest/index.js +48 -0
- package/dist/cjs/backend-federation-manifest/load.js +173 -0
- package/dist/cjs/backend-federation-manifest/metadata.js +101 -0
- package/dist/cjs/backend-federation-manifest/node.js +50 -0
- package/dist/cjs/backend-federation-manifest/reference.js +132 -0
- package/dist/cjs/backend-federation-manifest/remote.js +81 -0
- package/dist/cjs/backend-federation-manifest/types.js +18 -0
- package/dist/cjs/backend-federation-manifest/validation.js +110 -0
- package/dist/cjs/client-generator/built-entry.js +84 -0
- package/dist/cjs/client-generator/generator.js +73 -0
- package/dist/cjs/client-generator/index.js +54 -0
- package/dist/cjs/client-generator/paths.js +62 -0
- package/dist/cjs/client-generator/rendering.js +253 -0
- package/dist/cjs/client-generator/runtime.js +68 -0
- package/dist/cjs/client-generator/types.js +18 -0
- package/dist/cjs/cross-project-generation/index.js +40 -0
- package/dist/cjs/cross-project-generation/render.js +53 -0
- package/dist/cjs/cross-project-policy/evaluation.js +75 -0
- package/dist/cjs/cross-project-policy/index.js +40 -0
- package/dist/cjs/cross-project-policy/node.js +76 -0
- package/dist/cjs/effect-adapter/cross-project-policy.js +64 -0
- package/dist/cjs/effect-adapter/entry.js +98 -0
- package/dist/cjs/effect-adapter/error-response.js +75 -0
- package/dist/cjs/effect-adapter/index.js +187 -0
- package/dist/cjs/effect-source-loader/index.js +51 -0
- package/dist/cjs/effect-source-loader/loader.js +341 -0
- package/dist/cjs/effect-source-loader/worker-runtime-wrapper.js +97 -0
- package/dist/cjs/hono/bind-route-handlers.js +76 -0
- package/dist/cjs/hono/cross-project-policy.js +48 -0
- package/dist/cjs/hono/index.js +40 -0
- package/dist/esm/backend-federation/edge-runtime.mjs +186 -0
- package/dist/esm/backend-federation/edge.mjs +21 -0
- package/dist/esm/backend-federation/entry.mjs +56 -0
- package/dist/esm/backend-federation/identity.mjs +41 -0
- package/dist/esm/backend-federation/index.mjs +4 -0
- package/dist/esm/backend-federation/legacy-warning.mjs +2 -0
- package/dist/esm/backend-federation/load.mjs +34 -0
- package/dist/esm/backend-federation/node.mjs +12 -0
- package/dist/esm/backend-federation/plugin.mjs +25 -0
- package/dist/esm/backend-federation/remotes.mjs +13 -0
- package/dist/esm/backend-federation/runtime.mjs +90 -0
- package/dist/esm/backend-federation/types.mjs +0 -0
- package/dist/esm/backend-federation/utils.mjs +7 -0
- package/dist/esm/backend-federation/validate-loaded.mjs +18 -0
- package/dist/esm/backend-federation-manifest/errors.mjs +32 -0
- package/dist/esm/backend-federation-manifest/index.mjs +3 -0
- package/dist/esm/backend-federation-manifest/load.mjs +135 -0
- package/dist/esm/backend-federation-manifest/metadata.mjs +42 -0
- package/dist/esm/backend-federation-manifest/node.mjs +12 -0
- package/dist/esm/backend-federation-manifest/reference.mjs +88 -0
- package/dist/esm/backend-federation-manifest/remote.mjs +43 -0
- package/dist/esm/backend-federation-manifest/types.mjs +0 -0
- package/dist/esm/backend-federation-manifest/validation.mjs +66 -0
- package/dist/esm/client-generator/built-entry.mjs +40 -0
- package/dist/esm/client-generator/generator.mjs +32 -0
- package/dist/esm/client-generator/index.mjs +3 -0
- package/dist/esm/client-generator/paths.mjs +24 -0
- package/dist/esm/client-generator/rendering.mjs +209 -0
- package/dist/esm/client-generator/runtime.mjs +27 -0
- package/dist/esm/client-generator/types.mjs +0 -0
- package/dist/esm/cross-project-generation/index.mjs +1 -0
- package/dist/esm/cross-project-generation/render.mjs +15 -0
- package/dist/esm/cross-project-policy/evaluation.mjs +34 -0
- package/dist/esm/cross-project-policy/index.mjs +1 -0
- package/dist/esm/cross-project-policy/node.mjs +28 -0
- package/dist/esm/effect-adapter/cross-project-policy.mjs +26 -0
- package/dist/esm/effect-adapter/entry.mjs +50 -0
- package/dist/esm/effect-adapter/error-response.mjs +37 -0
- package/dist/esm/effect-adapter/index.mjs +139 -0
- package/dist/esm/effect-source-loader/index.mjs +3 -0
- package/dist/esm/effect-source-loader/loader.mjs +285 -0
- package/dist/esm/effect-source-loader/worker-runtime-wrapper.mjs +56 -0
- package/dist/esm/hono/bind-route-handlers.mjs +38 -0
- package/dist/esm/hono/cross-project-policy.mjs +10 -0
- package/dist/esm/hono/index.mjs +1 -0
- package/dist/esm-node/backend-federation/edge-runtime.mjs +187 -0
- package/dist/esm-node/backend-federation/edge.mjs +22 -0
- package/dist/esm-node/backend-federation/entry.mjs +57 -0
- package/dist/esm-node/backend-federation/identity.mjs +42 -0
- package/dist/esm-node/backend-federation/index.mjs +5 -0
- package/dist/esm-node/backend-federation/legacy-warning.mjs +3 -0
- package/dist/esm-node/backend-federation/load.mjs +35 -0
- package/dist/esm-node/backend-federation/node.mjs +13 -0
- package/dist/esm-node/backend-federation/plugin.mjs +26 -0
- package/dist/esm-node/backend-federation/remotes.mjs +14 -0
- package/dist/esm-node/backend-federation/runtime.mjs +91 -0
- package/dist/esm-node/backend-federation/types.mjs +1 -0
- package/dist/esm-node/backend-federation/utils.mjs +8 -0
- package/dist/esm-node/backend-federation/validate-loaded.mjs +19 -0
- package/dist/esm-node/backend-federation-manifest/errors.mjs +33 -0
- package/dist/esm-node/backend-federation-manifest/index.mjs +4 -0
- package/dist/esm-node/backend-federation-manifest/load.mjs +136 -0
- package/dist/esm-node/backend-federation-manifest/metadata.mjs +43 -0
- package/dist/esm-node/backend-federation-manifest/node.mjs +13 -0
- package/dist/esm-node/backend-federation-manifest/reference.mjs +89 -0
- package/dist/esm-node/backend-federation-manifest/remote.mjs +44 -0
- package/dist/esm-node/backend-federation-manifest/types.mjs +1 -0
- package/dist/esm-node/backend-federation-manifest/validation.mjs +67 -0
- package/dist/esm-node/client-generator/built-entry.mjs +41 -0
- package/dist/esm-node/client-generator/generator.mjs +33 -0
- package/dist/esm-node/client-generator/index.mjs +4 -0
- package/dist/esm-node/client-generator/paths.mjs +25 -0
- package/dist/esm-node/client-generator/rendering.mjs +210 -0
- package/dist/esm-node/client-generator/runtime.mjs +29 -0
- package/dist/esm-node/client-generator/types.mjs +1 -0
- package/dist/esm-node/cross-project-generation/index.mjs +2 -0
- package/dist/esm-node/cross-project-generation/render.mjs +16 -0
- package/dist/esm-node/cross-project-policy/evaluation.mjs +35 -0
- package/dist/esm-node/cross-project-policy/index.mjs +2 -0
- package/dist/esm-node/cross-project-policy/node.mjs +29 -0
- package/dist/esm-node/effect-adapter/cross-project-policy.mjs +27 -0
- package/dist/esm-node/effect-adapter/entry.mjs +51 -0
- package/dist/esm-node/effect-adapter/error-response.mjs +38 -0
- package/dist/esm-node/effect-adapter/index.mjs +140 -0
- package/dist/esm-node/effect-source-loader/index.mjs +4 -0
- package/dist/esm-node/effect-source-loader/loader.mjs +286 -0
- package/dist/esm-node/effect-source-loader/worker-runtime-wrapper.mjs +57 -0
- package/dist/esm-node/hono/bind-route-handlers.mjs +39 -0
- package/dist/esm-node/hono/cross-project-policy.mjs +11 -0
- package/dist/esm-node/hono/index.mjs +2 -0
- package/dist/types/backend-federation/edge-runtime.d.ts +46 -0
- package/dist/types/backend-federation/edge.d.ts +28 -0
- package/dist/types/backend-federation/entry.d.ts +2 -0
- package/dist/types/backend-federation/identity.d.ts +30 -0
- package/dist/types/backend-federation/index.d.ts +6 -0
- package/dist/types/backend-federation/legacy-warning.d.ts +1 -0
- package/dist/types/backend-federation/load.d.ts +13 -0
- package/dist/types/backend-federation/node.d.ts +4 -0
- package/dist/types/backend-federation/plugin.d.ts +3 -0
- package/dist/types/backend-federation/remotes.d.ts +2 -0
- package/dist/types/backend-federation/runtime.d.ts +3 -0
- package/dist/types/backend-federation/types.d.ts +76 -0
- package/dist/types/backend-federation/utils.d.ts +2 -0
- package/dist/types/backend-federation/validate-loaded.d.ts +8 -0
- package/dist/types/backend-federation-manifest/errors.d.ts +11 -0
- package/dist/types/backend-federation-manifest/index.d.ts +5 -0
- package/dist/types/backend-federation-manifest/load.d.ts +3 -0
- package/dist/types/backend-federation-manifest/metadata.d.ts +18 -0
- package/dist/types/backend-federation-manifest/node.d.ts +3 -0
- package/dist/types/backend-federation-manifest/reference.d.ts +4 -0
- package/dist/types/backend-federation-manifest/remote.d.ts +3 -0
- package/dist/types/backend-federation-manifest/types.d.ts +49 -0
- package/dist/types/backend-federation-manifest/validation.d.ts +5 -0
- package/dist/types/client-generator/built-entry.d.ts +16 -0
- package/dist/types/client-generator/generator.d.ts +3 -0
- package/dist/types/client-generator/index.d.ts +4 -0
- package/dist/types/client-generator/paths.d.ts +5 -0
- package/dist/types/client-generator/rendering.d.ts +24 -0
- package/dist/types/client-generator/runtime.d.ts +12 -0
- package/dist/types/client-generator/types.d.ts +33 -0
- package/dist/types/cross-project-generation/index.d.ts +1 -0
- package/dist/types/cross-project-generation/render.d.ts +1 -0
- package/dist/types/cross-project-policy/evaluation.d.ts +4 -0
- package/dist/types/cross-project-policy/index.d.ts +1 -0
- package/dist/types/cross-project-policy/node.d.ts +4 -0
- package/dist/types/effect-adapter/cross-project-policy.d.ts +4 -0
- package/dist/types/effect-adapter/entry.d.ts +2 -0
- package/dist/types/effect-adapter/error-response.d.ts +2 -0
- package/dist/types/effect-adapter/index.d.ts +19 -0
- package/dist/types/effect-source-loader/index.d.ts +3 -0
- package/dist/types/effect-source-loader/loader.d.ts +17 -0
- package/dist/types/effect-source-loader/worker-runtime-wrapper.d.ts +25 -0
- package/dist/types/hono/bind-route-handlers.d.ts +10 -0
- package/dist/types/hono/cross-project-policy.d.ts +3 -0
- package/dist/types/hono/index.d.ts +1 -0
- package/package.json +213 -0
- package/src/backend-federation/edge-runtime.ts +258 -0
- package/src/backend-federation/edge.ts +128 -0
- package/src/backend-federation/entry.ts +125 -0
- package/src/backend-federation/identity.ts +97 -0
- package/src/backend-federation/index.ts +30 -0
- package/src/backend-federation/legacy-warning.ts +2 -0
- package/src/backend-federation/load.ts +102 -0
- package/src/backend-federation/node.ts +33 -0
- package/src/backend-federation/plugin.ts +35 -0
- package/src/backend-federation/remotes.ts +17 -0
- package/src/backend-federation/runtime.ts +99 -0
- package/src/backend-federation/types.ts +103 -0
- package/src/backend-federation/utils.ts +7 -0
- package/src/backend-federation/validate-loaded.ts +72 -0
- package/src/backend-federation-manifest/errors.ts +85 -0
- package/src/backend-federation-manifest/index.ts +11 -0
- package/src/backend-federation-manifest/load.ts +266 -0
- package/src/backend-federation-manifest/metadata.ts +73 -0
- package/src/backend-federation-manifest/node.ts +19 -0
- package/src/backend-federation-manifest/reference.ts +240 -0
- package/src/backend-federation-manifest/remote.ts +102 -0
- package/src/backend-federation-manifest/types.ts +73 -0
- package/src/backend-federation-manifest/validation.ts +255 -0
- package/src/client-generator/built-entry.ts +70 -0
- package/src/client-generator/generator.ts +52 -0
- package/src/client-generator/index.ts +10 -0
- package/src/client-generator/paths.ts +40 -0
- package/src/client-generator/rendering.ts +307 -0
- package/src/client-generator/runtime.ts +69 -0
- package/src/client-generator/types.ts +35 -0
- package/src/cross-project-generation/index.ts +1 -0
- package/src/cross-project-generation/render.ts +14 -0
- package/src/cross-project-policy/evaluation.ts +70 -0
- package/src/cross-project-policy/index.ts +1 -0
- package/src/cross-project-policy/node.ts +63 -0
- package/src/effect-adapter/cross-project-policy.ts +63 -0
- package/src/effect-adapter/entry.ts +95 -0
- package/src/effect-adapter/error-response.ts +68 -0
- package/src/effect-adapter/index.ts +246 -0
- package/src/effect-source-loader/index.ts +6 -0
- package/src/effect-source-loader/loader.ts +397 -0
- package/src/effect-source-loader/worker-runtime-wrapper.ts +90 -0
- package/src/hono/bind-route-handlers.ts +62 -0
- package/src/hono/cross-project-policy.ts +26 -0
- package/src/hono/index.ts +4 -0
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { formatBackendFederationValidationErrors, validateBackendFederationManifest } from "@modern-js/utils/universal";
|
|
3
|
+
import { BACKEND_FEDERATION_CONTRACT_VERSION, BACKEND_FEDERATION_NODE_ADAPTER_VERSION } from "../backend-federation/index.mjs";
|
|
4
|
+
import { BackendFederationManifestAdapterError, assertConsistentValue, assertManifestAdapter, assertVersionValue } from "./errors.mjs";
|
|
5
|
+
import { backendFederationMetadata, manifestDeliveryUnit, recordField, stringValue, versionBoundaryMetadata } from "./metadata.mjs";
|
|
6
|
+
function resolveExpectedBuildMarker(expected) {
|
|
7
|
+
if (void 0 !== expected.buildVersion && void 0 !== expected.buildMarker && expected.buildVersion !== expected.buildMarker) throw new BackendFederationManifestAdapterError('version_mismatch', `[BFF][Effect] Backend federation expected buildVersion/buildMarker mismatch: buildVersion ${expected.buildVersion}, buildMarker ${expected.buildMarker}.`, void 0, {
|
|
8
|
+
label: 'expected.buildVersion/buildMarker',
|
|
9
|
+
expected: expected.buildVersion,
|
|
10
|
+
received: expected.buildMarker
|
|
11
|
+
});
|
|
12
|
+
return expected.buildMarker;
|
|
13
|
+
}
|
|
14
|
+
function validation_validateBackendFederationManifest(manifest, expected = {}) {
|
|
15
|
+
const expectedBuildMarker = resolveExpectedBuildMarker(expected);
|
|
16
|
+
const backendFederation = backendFederationMetadata(manifest);
|
|
17
|
+
assertManifestAdapter(backendFederation, 'manifest_invalid', '[BFF][Effect] Backend federation manifest must declare backendFederation metadata.');
|
|
18
|
+
const manifestShape = validateBackendFederationManifest(manifest, {
|
|
19
|
+
expectedContractVersion: false,
|
|
20
|
+
expectedNodeAdapterVersion: false,
|
|
21
|
+
validateDeliveryUnit: false
|
|
22
|
+
});
|
|
23
|
+
assertManifestAdapter(manifestShape.ok, 'manifest_invalid', `[BFF][Effect] Backend federation manifest schema invalid: ${formatBackendFederationValidationErrors(manifestShape.errors)}.`);
|
|
24
|
+
assertManifestAdapter('effect' === backendFederation.runtimeFramework, 'strict_effect_required', '[BFF][Effect] Backend federation manifest must declare runtimeFramework: "effect".');
|
|
25
|
+
assertManifestAdapter(true === backendFederation.strictEffectApproach, 'strict_effect_required', '[BFF][Effect] Backend federation manifest must declare strictEffectApproach: true.');
|
|
26
|
+
assertVersionValue(stringValue(backendFederation.contractVersion), expected.contractVersion ?? BACKEND_FEDERATION_CONTRACT_VERSION, 'manifest contractVersion');
|
|
27
|
+
assertVersionValue(stringValue(backendFederation.nodeAdapterVersion), expected.nodeAdapterVersion ?? BACKEND_FEDERATION_NODE_ADAPTER_VERSION, 'manifest nodeAdapterVersion');
|
|
28
|
+
const boundary = versionBoundaryMetadata(manifest);
|
|
29
|
+
assertVersionValue(stringValue(backendFederation.name) ?? stringValue(manifest.name) ?? stringValue(manifest.id), expected.remoteName, 'manifest remoteName');
|
|
30
|
+
assertVersionValue(stringValue(boundary?.packageName), expected.packageName, 'versionBoundary.packageName');
|
|
31
|
+
assertVersionValue(stringValue(boundary?.version), expected.version, 'versionBoundary.version');
|
|
32
|
+
assertVersionValue(stringValue(boundary?.buildVersion), expected.buildVersion, 'versionBoundary.buildVersion');
|
|
33
|
+
assertConsistentValue(stringValue(manifest.version), stringValue(boundary?.version), 'manifest versionBoundary.version');
|
|
34
|
+
assertConsistentValue(stringValue(manifest.buildVersion), stringValue(boundary?.buildVersion), 'manifest versionBoundary.buildVersion');
|
|
35
|
+
const deliveryUnit = manifestDeliveryUnit(backendFederation, boundary);
|
|
36
|
+
assertConsistentValue(stringValue(deliveryUnit.boundary?.buildMarker), stringValue(boundary?.buildVersion), 'versionBoundary.deliveryUnit.buildMarker vs versionBoundary.buildVersion');
|
|
37
|
+
assertConsistentValue(stringValue(deliveryUnit.top?.unitId), stringValue(deliveryUnit.boundary?.unitId), 'backendFederation.deliveryUnit.unitId vs versionBoundary.deliveryUnit.unitId');
|
|
38
|
+
const manifestUnitId = stringValue(deliveryUnit.boundary?.unitId) ?? stringValue(deliveryUnit.top?.unitId);
|
|
39
|
+
assertVersionValue(manifestUnitId, expected.unitId, 'deliveryUnit.unitId');
|
|
40
|
+
assertVersionValue(stringValue(deliveryUnit.boundary?.buildMarker), expectedBuildMarker, 'deliveryUnit.buildMarker');
|
|
41
|
+
}
|
|
42
|
+
function validateLoadedBackendFederationContract(loaded, manifest, remote) {
|
|
43
|
+
const loadedContract = loaded.backendFederationContract;
|
|
44
|
+
const backendFederation = backendFederationMetadata(manifest);
|
|
45
|
+
const boundary = versionBoundaryMetadata(manifest);
|
|
46
|
+
const compatibility = recordField(loadedContract, 'compatibility');
|
|
47
|
+
assertManifestAdapter(compatibility, 'version_mismatch', `[BFF][Effect] Backend federation expose ${remote.name}/${remote.expose?.replace(/^\.\//u, '')} must declare compatibility metadata.`);
|
|
48
|
+
assertVersionValue(stringValue(loadedContract?.role), 'microvertical-server', 'expose role');
|
|
49
|
+
assertVersionValue(stringValue(loadedContract?.name), remote.name, 'expose name');
|
|
50
|
+
assertVersionValue(stringValue(compatibility.contractVersion), stringValue(backendFederation?.contractVersion), 'expose contractVersion');
|
|
51
|
+
assertVersionValue(stringValue(compatibility.nodeAdapterVersion), stringValue(backendFederation?.nodeAdapterVersion), 'expose nodeAdapterVersion');
|
|
52
|
+
assertVersionValue(stringValue(compatibility.packageName), stringValue(boundary?.packageName), 'expose packageName');
|
|
53
|
+
assertVersionValue(stringValue(compatibility.build), stringValue(boundary?.buildVersion), 'expose buildVersion');
|
|
54
|
+
const deliveryUnit = manifestDeliveryUnit(backendFederation, boundary);
|
|
55
|
+
const manifestUnitId = stringValue(deliveryUnit.boundary?.unitId) ?? stringValue(deliveryUnit.top?.unitId);
|
|
56
|
+
const manifestBuildMarker = stringValue(deliveryUnit.boundary?.buildMarker);
|
|
57
|
+
assertConsistentValue(manifestUnitId, stringValue(compatibility.unitId), 'deliveryUnit.unitId vs expose compatibility.unitId');
|
|
58
|
+
assertConsistentValue(manifestBuildMarker, stringValue(compatibility.build), 'deliveryUnit.buildMarker vs expose compatibility.build');
|
|
59
|
+
}
|
|
60
|
+
function classifyLoadError(error) {
|
|
61
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
62
|
+
if ('object' == typeof error && null !== error && 'code' in error && 'timeout' === error.code || /timed out/iu.test(message)) return 'timeout';
|
|
63
|
+
if (message.includes('delivery-unit identity mismatch')) return 'version_mismatch';
|
|
64
|
+
if (message.includes('strictEffectApproach') || message.includes('runtimeFramework')) return 'strict_effect_required';
|
|
65
|
+
return 'remote_unavailable';
|
|
66
|
+
}
|
|
67
|
+
export { classifyLoadError, validateLoadedBackendFederationContract, validation_validateBackendFederationManifest as validateBackendFederationManifest };
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { fs, upath } from "@modern-js/utils";
|
|
3
|
+
import { resolveEffectEntryFile } from "./paths.mjs";
|
|
4
|
+
const BUILT_ENTRY_EXT = /\.(?:[cm]?ts|tsx|jsx)$/u;
|
|
5
|
+
function resolveBuiltEffectEntry(appDirectory, distDirectory, sourceEntry) {
|
|
6
|
+
if (void 0 === sourceEntry || 0 === sourceEntry.length) return;
|
|
7
|
+
const relativeEntry = upath.relative(appDirectory, sourceEntry);
|
|
8
|
+
if ('..' === relativeEntry || relativeEntry.startsWith(`..${upath.sep}`)) throw new Error(`Effect BFF entry must be inside the application directory: ${sourceEntry}`);
|
|
9
|
+
const builtEntry = upath.resolve(distDirectory, relativeEntry).replace(BUILT_ENTRY_EXT, '.js');
|
|
10
|
+
return fs.existsSync(builtEntry) ? builtEntry : void 0;
|
|
11
|
+
}
|
|
12
|
+
async function bundleBuiltEffectEntryForNode(options) {
|
|
13
|
+
const { appDir, apiDir, distDir, effectEntry, format } = options;
|
|
14
|
+
const sourceEntry = resolveEffectEntryFile({
|
|
15
|
+
appDir,
|
|
16
|
+
apiDir,
|
|
17
|
+
effectEntry
|
|
18
|
+
});
|
|
19
|
+
const builtEntry = resolveBuiltEffectEntry(appDir, distDir, sourceEntry);
|
|
20
|
+
if (void 0 === builtEntry || 0 === builtEntry.length) throw new Error(`Effect BFF entry was not emitted into ${distDir}: ${sourceEntry ?? upath.resolve(apiDir, 'index')}`);
|
|
21
|
+
const { bundleEffectEntryForNode } = await import("../effect-source-loader/loader.mjs");
|
|
22
|
+
return bundleEffectEntryForNode({
|
|
23
|
+
appDir,
|
|
24
|
+
entryPath: builtEntry,
|
|
25
|
+
format
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
function resolveEffectEntryPaths(options) {
|
|
29
|
+
const { appDir, apiDir, effectEntry } = options;
|
|
30
|
+
const sourceEffectEntry = resolveEffectEntryFile({
|
|
31
|
+
appDir,
|
|
32
|
+
apiDir,
|
|
33
|
+
effectEntry
|
|
34
|
+
});
|
|
35
|
+
const relativeEffectEntry = void 0 !== sourceEffectEntry && sourceEffectEntry.length > 0 ? upath.relative(appDir, sourceEffectEntry).replace(BUILT_ENTRY_EXT, '.js') : '';
|
|
36
|
+
return {
|
|
37
|
+
sourceEffectEntry,
|
|
38
|
+
relativeEffectEntry
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export { bundleBuiltEffectEntryForNode, resolveBuiltEffectEntry, resolveEffectEntryPaths };
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { collectEffectEndpoints } from "@modern-js/bff-effect/effect";
|
|
3
|
+
import { logger } from "@modern-js/utils";
|
|
4
|
+
import { createEffectClientGeneration, renderEffectClientCode, renderEffectClientDeclaration } from "./rendering.mjs";
|
|
5
|
+
import { getHttpApiRuntime, loadEffectApi } from "./runtime.mjs";
|
|
6
|
+
function generateEffectClient(options) {
|
|
7
|
+
return loadEffectApi({
|
|
8
|
+
appDir: options.appDir,
|
|
9
|
+
resourcePath: options.resourcePath,
|
|
10
|
+
onDependency: options.onDependency
|
|
11
|
+
}).then((api)=>{
|
|
12
|
+
if (null === api) {
|
|
13
|
+
logger.warn(`[BFF][Effect] Failed to generate client for ${options.resourcePath}: unable to resolve exported HttpApi.`);
|
|
14
|
+
return null;
|
|
15
|
+
}
|
|
16
|
+
return getHttpApiRuntime().then((httpApiRuntime)=>{
|
|
17
|
+
const endpoints = collectEffectEndpoints(httpApiRuntime.reflect, api, options.prefix);
|
|
18
|
+
const generation = createEffectClientGeneration(endpoints, options);
|
|
19
|
+
return {
|
|
20
|
+
code: renderEffectClientCode(generation),
|
|
21
|
+
declaration: renderEffectClientDeclaration(endpoints),
|
|
22
|
+
endpoints,
|
|
23
|
+
operationContracts: generation.operationContracts,
|
|
24
|
+
operationVersion: generation.operationVersion,
|
|
25
|
+
requestId: generation.requestId
|
|
26
|
+
};
|
|
27
|
+
});
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
function generateEffectClientCode(options) {
|
|
31
|
+
return generateEffectClient(options).then((artifacts)=>null === artifacts ? null : artifacts.code);
|
|
32
|
+
}
|
|
33
|
+
export { generateEffectClient, generateEffectClientCode };
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { findExists, fs, upath } from "@modern-js/utils";
|
|
3
|
+
const JS_OR_TS_EXTS = [
|
|
4
|
+
'.js',
|
|
5
|
+
'.jsx',
|
|
6
|
+
'.ts',
|
|
7
|
+
'.tsx',
|
|
8
|
+
'.mjs',
|
|
9
|
+
'.mts',
|
|
10
|
+
'.cjs',
|
|
11
|
+
'.cts'
|
|
12
|
+
];
|
|
13
|
+
function resolveEffectEntryFile(options) {
|
|
14
|
+
const { appDir, apiDir, effectEntry } = options;
|
|
15
|
+
const resolveEntry = (entryWithoutExt)=>{
|
|
16
|
+
if ('' !== upath.extname(entryWithoutExt)) return fs.existsSync(entryWithoutExt) ? entryWithoutExt : void 0;
|
|
17
|
+
return findExists(JS_OR_TS_EXTS.map((ext)=>`${entryWithoutExt}${ext}`)) || void 0;
|
|
18
|
+
};
|
|
19
|
+
if (void 0 !== effectEntry && '' !== effectEntry) {
|
|
20
|
+
const entryWithoutExt = upath.isAbsolute(effectEntry) ? effectEntry : upath.resolve(appDir, effectEntry);
|
|
21
|
+
return resolveEntry(entryWithoutExt);
|
|
22
|
+
}
|
|
23
|
+
return resolveEntry(upath.resolve(apiDir, 'index'));
|
|
24
|
+
}
|
|
25
|
+
export { resolveEffectEntryFile };
|
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { buildOperationContractMap, deriveOperationVersion } from "@modern-js/bff-core";
|
|
3
|
+
import { createEffectEndpointContractHash, ensureLeadingSlash, normalizeEffectPrefix, toOperationContractSources } from "@modern-js/bff-effect/effect";
|
|
4
|
+
import { fs, upath } from "@modern-js/utils";
|
|
5
|
+
const DEFAULT_REQUEST_CREATOR = '@modern-js/plugin-bff/client';
|
|
6
|
+
const EFFECT_CLIENT_RUNTIME_IMPORT = '@modern-js/plugin-bff/effect-client-runtime';
|
|
7
|
+
function isAbsoluteUrl(value) {
|
|
8
|
+
try {
|
|
9
|
+
new URL(value);
|
|
10
|
+
return true;
|
|
11
|
+
} catch {
|
|
12
|
+
return false;
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
function resolveBatchEndpoint(prefix, endpoint) {
|
|
16
|
+
const value = void 0 === endpoint || '' === endpoint ? '/_data/batch' : endpoint;
|
|
17
|
+
if (isAbsoluteUrl(value)) return value;
|
|
18
|
+
const normalizedPrefix = normalizeEffectPrefix(prefix);
|
|
19
|
+
const normalizedEndpoint = ensureLeadingSlash(value);
|
|
20
|
+
if ('' === normalizedPrefix) return normalizedEndpoint;
|
|
21
|
+
if (normalizedEndpoint === normalizedPrefix || normalizedEndpoint.startsWith(`${normalizedPrefix}/`)) return normalizedEndpoint;
|
|
22
|
+
return `${normalizedPrefix}${'/' === normalizedEndpoint ? '' : normalizedEndpoint}`;
|
|
23
|
+
}
|
|
24
|
+
function getPackageInfo(resourcePath, appDir, onDependency) {
|
|
25
|
+
for (const startDir of [
|
|
26
|
+
upath.dirname(resourcePath),
|
|
27
|
+
appDir
|
|
28
|
+
]){
|
|
29
|
+
let current = upath.resolve(startDir);
|
|
30
|
+
for(let depth = 0; depth < 32; depth += 1){
|
|
31
|
+
const packageJsonPath = upath.join(current, 'package.json');
|
|
32
|
+
if (fs.existsSync(packageJsonPath)) {
|
|
33
|
+
onDependency?.(packageJsonPath);
|
|
34
|
+
try {
|
|
35
|
+
const packageJson = fs.readJSONSync(packageJsonPath);
|
|
36
|
+
return {
|
|
37
|
+
name: packageJson.name,
|
|
38
|
+
version: packageJson.version
|
|
39
|
+
};
|
|
40
|
+
} catch {
|
|
41
|
+
return {};
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const parent = upath.dirname(current);
|
|
45
|
+
if (parent === current) break;
|
|
46
|
+
current = parent;
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return {};
|
|
50
|
+
}
|
|
51
|
+
function renderEffectClientCode(generation) {
|
|
52
|
+
const { config, manifest } = generation;
|
|
53
|
+
return `import * as __requestRuntime from ${JSON.stringify(generation.requestCreator)};
|
|
54
|
+
import { createGeneratedEffectClient } from ${JSON.stringify(EFFECT_CLIENT_RUNTIME_IMPORT)};
|
|
55
|
+
|
|
56
|
+
const __manifest = ${JSON.stringify(manifest, null, 2)};
|
|
57
|
+
|
|
58
|
+
const __config = ${JSON.stringify(config, null, 2)};
|
|
59
|
+
|
|
60
|
+
const __generated = createGeneratedEffectClient(__manifest, __config, __requestRuntime);
|
|
61
|
+
|
|
62
|
+
const client = __generated.client;
|
|
63
|
+
const operationManifest = __generated.operationManifest;
|
|
64
|
+
const createEffectRequestContext = __generated.createEffectRequestContext;
|
|
65
|
+
const apiModule = {
|
|
66
|
+
client,
|
|
67
|
+
operationManifest,
|
|
68
|
+
createEffectRequestContext,
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
export { client, createEffectRequestContext, operationManifest };
|
|
72
|
+
export default apiModule;
|
|
73
|
+
`;
|
|
74
|
+
}
|
|
75
|
+
function createEffectClientGeneration(endpoints, options) {
|
|
76
|
+
const requestCreator = options.requestCreator || DEFAULT_REQUEST_CREATOR;
|
|
77
|
+
const httpMethodDecider = options.httpMethodDecider || 'functionName';
|
|
78
|
+
const packageInfo = getPackageInfo(options.resourcePath, options.appDir, options.onDependency);
|
|
79
|
+
const packageName = packageInfo.name;
|
|
80
|
+
const dataPlatformAppNamespace = void 0 === packageName || '' === packageName ? 'unknown-app' : packageName;
|
|
81
|
+
const requestId = 'bundle' === options.target ? void 0 !== options.requestId && '' !== options.requestId.trim() ? options.requestId.trim() : void 0 !== packageName && '' !== packageName ? packageName : void 0 : void 0;
|
|
82
|
+
const normalizedRequestId = void 0 === requestId || '' === requestId ? 'default' : requestId;
|
|
83
|
+
const operationVersion = deriveOperationVersion(packageInfo.version);
|
|
84
|
+
const batchConfig = options.dataPlatformBatch;
|
|
85
|
+
const batchEndpoint = resolveBatchEndpoint(options.prefix, batchConfig?.endpoint);
|
|
86
|
+
const manifest = {
|
|
87
|
+
endpoints: endpoints.map((endpoint)=>({
|
|
88
|
+
apiId: endpoint.apiId,
|
|
89
|
+
group: endpoint.groupName,
|
|
90
|
+
endpoint: endpoint.endpointName,
|
|
91
|
+
method: endpoint.method,
|
|
92
|
+
routePath: endpoint.routePath,
|
|
93
|
+
schemaHash: createEffectEndpointContractHash(endpoint, normalizedRequestId),
|
|
94
|
+
operationVersion
|
|
95
|
+
}))
|
|
96
|
+
};
|
|
97
|
+
const config = {
|
|
98
|
+
appNamespace: dataPlatformAppNamespace,
|
|
99
|
+
...void 0 !== requestId && '' !== requestId ? {
|
|
100
|
+
requestId
|
|
101
|
+
} : {},
|
|
102
|
+
port: options.port,
|
|
103
|
+
useEnvPort: 'server' === options.target,
|
|
104
|
+
defaultOrigin: `http://localhost:${String(options.port)}`,
|
|
105
|
+
httpMethodDecider,
|
|
106
|
+
batch: {
|
|
107
|
+
enabled: batchConfig?.enabled ?? true,
|
|
108
|
+
endpoint: batchEndpoint,
|
|
109
|
+
flushIntervalMs: batchConfig?.flushIntervalMs ?? 8,
|
|
110
|
+
maxBatchSize: batchConfig?.maxBatchSize ?? 16,
|
|
111
|
+
maxBatchBytes: batchConfig?.maxBatchBytes ?? 65536,
|
|
112
|
+
requestTimeoutMs: batchConfig?.requestTimeoutMs ?? 10000,
|
|
113
|
+
allowedMethods: batchConfig?.allowedMethods !== void 0 && batchConfig.allowedMethods.length > 0 ? batchConfig.allowedMethods : [
|
|
114
|
+
'GET'
|
|
115
|
+
]
|
|
116
|
+
}
|
|
117
|
+
};
|
|
118
|
+
return {
|
|
119
|
+
config,
|
|
120
|
+
manifest,
|
|
121
|
+
operationContracts: buildOperationContractMap({
|
|
122
|
+
handlers: toOperationContractSources(endpoints),
|
|
123
|
+
requestId: normalizedRequestId,
|
|
124
|
+
operationVersion
|
|
125
|
+
}),
|
|
126
|
+
operationVersion,
|
|
127
|
+
requestCreator,
|
|
128
|
+
requestId: normalizedRequestId
|
|
129
|
+
};
|
|
130
|
+
}
|
|
131
|
+
function renderClientShape(endpoints, valueType) {
|
|
132
|
+
if (0 === endpoints.length) return `Record<string, Record<string, ${valueType}>>`;
|
|
133
|
+
const groups = new Map();
|
|
134
|
+
for (const endpoint of endpoints){
|
|
135
|
+
const group = groups.get(endpoint.groupName) || [];
|
|
136
|
+
group.push(endpoint.endpointName);
|
|
137
|
+
groups.set(endpoint.groupName, group);
|
|
138
|
+
}
|
|
139
|
+
const groupEntries = [
|
|
140
|
+
...groups.entries()
|
|
141
|
+
].map(([groupName, names])=>{
|
|
142
|
+
const endpointEntries = names.map((name)=>` ${JSON.stringify(name)}: ${valueType};`).join('\n');
|
|
143
|
+
return ` ${JSON.stringify(groupName)}: {\n${endpointEntries}\n };`;
|
|
144
|
+
});
|
|
145
|
+
return `{\n${groupEntries.join('\n')}\n}`;
|
|
146
|
+
}
|
|
147
|
+
function renderEffectClientDeclaration(endpoints = []) {
|
|
148
|
+
return `export type EffectClientOperation = (
|
|
149
|
+
request?: unknown,
|
|
150
|
+
) => Promise<unknown>;
|
|
151
|
+
export type EffectClientGroup = Record<string, EffectClientOperation>;
|
|
152
|
+
export type EffectClient = Record<string, EffectClientGroup>;
|
|
153
|
+
export type EffectOperationDescriptor = {
|
|
154
|
+
appNamespace: string;
|
|
155
|
+
apiId: string;
|
|
156
|
+
group: string;
|
|
157
|
+
endpoint: string;
|
|
158
|
+
operationId: string;
|
|
159
|
+
routePath: string;
|
|
160
|
+
method: string;
|
|
161
|
+
operationVersion: number;
|
|
162
|
+
schemaHash: string;
|
|
163
|
+
version: number;
|
|
164
|
+
};
|
|
165
|
+
export type EffectOperationManifest = Record<
|
|
166
|
+
string,
|
|
167
|
+
Record<string, EffectOperationDescriptor>
|
|
168
|
+
>;
|
|
169
|
+
export type EffectOperationContext = {
|
|
170
|
+
requestId?: string;
|
|
171
|
+
operationId?: string;
|
|
172
|
+
routePath?: string;
|
|
173
|
+
method?: string;
|
|
174
|
+
schemaHash?: string;
|
|
175
|
+
operationVersion?: number;
|
|
176
|
+
locale?: string;
|
|
177
|
+
traceparent?: string;
|
|
178
|
+
traceId?: string;
|
|
179
|
+
spanId?: string;
|
|
180
|
+
source?: string;
|
|
181
|
+
scope?: Record<string, unknown>;
|
|
182
|
+
sessionClaims?: Record<string, unknown>;
|
|
183
|
+
attributes?: Record<string, unknown>;
|
|
184
|
+
};
|
|
185
|
+
export type EffectRequestContext = {
|
|
186
|
+
headers?: Record<string, string>;
|
|
187
|
+
locale?: string;
|
|
188
|
+
operationContext?: EffectOperationContext;
|
|
189
|
+
traceparent?: string;
|
|
190
|
+
traceId?: string;
|
|
191
|
+
spanId?: string;
|
|
192
|
+
};
|
|
193
|
+
export type GeneratedEffectClient = ${renderClientShape(endpoints, 'EffectClientOperation')};
|
|
194
|
+
export type GeneratedEffectOperationManifest = ${renderClientShape(endpoints, "EffectOperationDescriptor")};
|
|
195
|
+
|
|
196
|
+
export declare const client: GeneratedEffectClient;
|
|
197
|
+
export declare const createEffectRequestContext: (
|
|
198
|
+
requestContext: Record<string, unknown>,
|
|
199
|
+
) => EffectRequestContext;
|
|
200
|
+
export declare const operationManifest: GeneratedEffectOperationManifest;
|
|
201
|
+
declare const apiModule: {
|
|
202
|
+
client: GeneratedEffectClient;
|
|
203
|
+
createEffectRequestContext: typeof createEffectRequestContext;
|
|
204
|
+
operationManifest: GeneratedEffectOperationManifest;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
export default apiModule;
|
|
208
|
+
`;
|
|
209
|
+
}
|
|
210
|
+
export { createEffectClientGeneration, renderEffectClientCode, renderEffectClientDeclaration };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import __rslib_shim_module__ from "node:module";
|
|
2
|
+
const require = /*#__PURE__*/ __rslib_shim_module__.createRequire(/*#__PURE__*/ (()=>import.meta.url)());
|
|
3
|
+
import { extractHttpApiFromModule } from "@modern-js/bff-effect/effect";
|
|
4
|
+
import { compatibleRequire, upath } from "@modern-js/utils";
|
|
5
|
+
import { loadEffectSourceModule } from "../effect-source-loader/loader.mjs";
|
|
6
|
+
let httpApiRuntimePromise;
|
|
7
|
+
function isRecord(value) {
|
|
8
|
+
return 'object' == typeof value && null !== value;
|
|
9
|
+
}
|
|
10
|
+
function isHttpApiRuntime(value) {
|
|
11
|
+
return isRecord(value) && 'function' == typeof value.isHttpApi && 'function' == typeof value.reflect;
|
|
12
|
+
}
|
|
13
|
+
function getHttpApiRuntime() {
|
|
14
|
+
if (void 0 === httpApiRuntimePromise) httpApiRuntimePromise = compatibleRequire('effect/unstable/httpapi', false).catch((error)=>{
|
|
15
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
16
|
+
if (!message.includes("Cannot find module 'effect/unstable/httpapi'")) throw error;
|
|
17
|
+
const effectPackageJson = require.resolve('effect/package.json');
|
|
18
|
+
const effectHttpApiRuntimePath = upath.join(upath.dirname(effectPackageJson), 'dist', 'unstable', 'httpapi', 'index.js');
|
|
19
|
+
return compatibleRequire(effectHttpApiRuntimePath, false);
|
|
20
|
+
}).then((mod)=>{
|
|
21
|
+
if (isRecord(mod) && isHttpApiRuntime(mod.HttpApi)) return mod.HttpApi;
|
|
22
|
+
throw new Error('[BFF][Effect] Unable to resolve HttpApi runtime from effect/unstable/httpapi.');
|
|
23
|
+
});
|
|
24
|
+
return httpApiRuntimePromise;
|
|
25
|
+
}
|
|
26
|
+
function loadEffectApi(options) {
|
|
27
|
+
return getHttpApiRuntime().then((httpApiRuntime)=>loadEffectSourceModule(options).then((mod)=>extractHttpApiFromModule(mod, httpApiRuntime.isHttpApi)));
|
|
28
|
+
}
|
|
29
|
+
export { getHttpApiRuntime, loadEffectApi };
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import "node:module";
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
const renderProducerRuntimeDefaults = (requestIdValue)=>`{
|
|
3
|
+
requestId: ${requestIdValue},
|
|
4
|
+
requireEnvelope: true,
|
|
5
|
+
identityBinding: {
|
|
6
|
+
enabled: true,
|
|
7
|
+
strict: true,
|
|
8
|
+
},
|
|
9
|
+
operationContract: {
|
|
10
|
+
enabled: true,
|
|
11
|
+
strict: true,
|
|
12
|
+
requireSchemaHash: true,
|
|
13
|
+
requireOperationVersion: true,
|
|
14
|
+
},
|
|
15
|
+
}`;
|
|
16
|
+
export { renderProducerRuntimeDefaults };
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { evaluateCrossProjectPolicy, resolveCrossProjectRequestObservation } from "@modern-js/bff-core/security/cross-project-policy";
|
|
3
|
+
const DENIAL_HEADERS = {
|
|
4
|
+
'content-type': 'application/json; charset=utf-8'
|
|
5
|
+
};
|
|
6
|
+
const checkCrossProjectPolicyResponse = (headers, policy, observedRequest)=>{
|
|
7
|
+
if (!policy?.enabled) return null;
|
|
8
|
+
const violation = evaluateCrossProjectPolicy(headers, policy, observedRequest);
|
|
9
|
+
if (!violation) return null;
|
|
10
|
+
return new Response(JSON.stringify({
|
|
11
|
+
code: violation.code,
|
|
12
|
+
reason: violation.reason,
|
|
13
|
+
message: violation.message
|
|
14
|
+
}), {
|
|
15
|
+
status: violation.status,
|
|
16
|
+
headers: DENIAL_HEADERS
|
|
17
|
+
});
|
|
18
|
+
};
|
|
19
|
+
const checkCrossProjectPolicyForRequest = (request, policy)=>{
|
|
20
|
+
if (!policy?.enabled) return null;
|
|
21
|
+
const requestTarget = {
|
|
22
|
+
method: request.method,
|
|
23
|
+
pathname: new URL(request.url).pathname
|
|
24
|
+
};
|
|
25
|
+
const observedRequest = resolveCrossProjectRequestObservation(requestTarget, policy) ?? {
|
|
26
|
+
method: requestTarget.method,
|
|
27
|
+
routePath: requestTarget.pathname
|
|
28
|
+
};
|
|
29
|
+
const headers = {};
|
|
30
|
+
request.headers.forEach((value, key)=>{
|
|
31
|
+
headers[key] = value;
|
|
32
|
+
});
|
|
33
|
+
return checkCrossProjectPolicyResponse(headers, policy, observedRequest);
|
|
34
|
+
};
|
|
35
|
+
export { checkCrossProjectPolicyForRequest, checkCrossProjectPolicyResponse };
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { readFileSync } from "node:fs";
|
|
3
|
+
import node_path from "node:path";
|
|
4
|
+
import { deriveOperationVersion, resolveCrossProjectPolicy } from "@modern-js/bff-core";
|
|
5
|
+
const readNearestPackageVersion = (startDir)=>{
|
|
6
|
+
if (!startDir) return;
|
|
7
|
+
let current = node_path.resolve(startDir);
|
|
8
|
+
for(let depth = 0; depth < 10; depth += 1){
|
|
9
|
+
try {
|
|
10
|
+
const packageJson = JSON.parse(readFileSync(node_path.join(current, 'package.json'), 'utf8'));
|
|
11
|
+
if ('string' == typeof packageJson.version) return packageJson.version;
|
|
12
|
+
} catch {}
|
|
13
|
+
const parent = node_path.dirname(current);
|
|
14
|
+
if (parent === current) break;
|
|
15
|
+
current = parent;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
const resolveAdapterCrossProjectPolicy = (api, handlers)=>{
|
|
19
|
+
const bff = api.getServerConfig()?.bff;
|
|
20
|
+
const { apiDirectory, appDirectory } = api.getServerContext();
|
|
21
|
+
return resolveCrossProjectPolicy({
|
|
22
|
+
crossProjectPolicy: bff?.crossProjectPolicy,
|
|
23
|
+
handlers,
|
|
24
|
+
requestId: bff?.requestId,
|
|
25
|
+
isCrossProjectServer: bff?.isCrossProjectServer,
|
|
26
|
+
operationVersion: deriveOperationVersion(readNearestPackageVersion(apiDirectory) ?? readNearestPackageVersion(appDirectory))
|
|
27
|
+
});
|
|
28
|
+
};
|
|
29
|
+
export { resolveAdapterCrossProjectPolicy };
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { collectEffectEndpoints, extractHttpApiFromModule, toOperationContractSources } from "@modern-js/bff-effect/effect";
|
|
3
|
+
import { logger } from "@modern-js/utils";
|
|
4
|
+
import { HttpApi } from "effect/unstable/httpapi";
|
|
5
|
+
import { resolveAdapterCrossProjectPolicy } from "../cross-project-policy/index.mjs";
|
|
6
|
+
function resolveEffectAdapterCrossProjectPolicy(api, prefix, mod) {
|
|
7
|
+
const contractSourcesPromise = null === mod ? Promise.resolve([]) : Promise.resolve().then(()=>extractHttpApiFromModule(mod, HttpApi.isHttpApi)).then((effectApi)=>{
|
|
8
|
+
if (null === effectApi) return [];
|
|
9
|
+
const reflect = (apiValue, handlers)=>{
|
|
10
|
+
if (!HttpApi.isHttpApi(apiValue)) throw new Error('[BFF][Effect] Endpoint reflection received a non-HttpApi value.');
|
|
11
|
+
HttpApi.reflect(apiValue, {
|
|
12
|
+
onGroup: handlers.onGroup ?? (()=>{}),
|
|
13
|
+
onEndpoint: handlers.onEndpoint
|
|
14
|
+
});
|
|
15
|
+
};
|
|
16
|
+
return toOperationContractSources(collectEffectEndpoints(reflect, effectApi, prefix));
|
|
17
|
+
}).catch((error)=>{
|
|
18
|
+
logger.warn(`[BFF][Effect] Failed reflect HttpApi endpoints cross-project policy: ${String(error)}`);
|
|
19
|
+
return [];
|
|
20
|
+
});
|
|
21
|
+
return contractSourcesPromise.then((contractSources)=>{
|
|
22
|
+
const policy = resolveAdapterCrossProjectPolicy(api, contractSources);
|
|
23
|
+
if (policy?.enabled === true && 0 === contractSources.length) logger.warn('[BFF][Effect] Cross-project policy enabled but no HttpApi endpoints could be reflected; requests fail operation-contract matching unless allowUnknownOperations is enabled.');
|
|
24
|
+
return policy;
|
|
25
|
+
});
|
|
26
|
+
}
|
|
27
|
+
export { resolveEffectAdapterCrossProjectPolicy };
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import node_path from "node:path";
|
|
3
|
+
import { API_DIR, findExists, fs, isProd } from "@modern-js/utils";
|
|
4
|
+
const JS_OR_TS_EXTS = [
|
|
5
|
+
'.js',
|
|
6
|
+
'.jsx',
|
|
7
|
+
'.ts',
|
|
8
|
+
'.tsx',
|
|
9
|
+
'.mjs',
|
|
10
|
+
'.mts',
|
|
11
|
+
'.cjs',
|
|
12
|
+
'.cts'
|
|
13
|
+
];
|
|
14
|
+
function resolveJsOrTsEntry(entryWithoutOrWithExt) {
|
|
15
|
+
const extension = node_path.extname(entryWithoutOrWithExt);
|
|
16
|
+
if (JS_OR_TS_EXTS.includes(extension)) return fs.existsSync(entryWithoutOrWithExt) ? entryWithoutOrWithExt : void 0;
|
|
17
|
+
return findExists(JS_OR_TS_EXTS.map((ext)=>`${entryWithoutOrWithExt}${ext}`)) || void 0;
|
|
18
|
+
}
|
|
19
|
+
function builtEntryPath(entryPath) {
|
|
20
|
+
return entryPath.replace(/\.(?:[cm]?ts|tsx|jsx)$/u, '.js');
|
|
21
|
+
}
|
|
22
|
+
function relativeAppPath(appDirectory, entryPath) {
|
|
23
|
+
const relativePath = node_path.relative(appDirectory, entryPath);
|
|
24
|
+
return '..' === relativePath || relativePath.startsWith(`..${node_path.sep}`) ? void 0 : relativePath;
|
|
25
|
+
}
|
|
26
|
+
function isDependencyPath(relativePath) {
|
|
27
|
+
return relativePath?.split(/[\\/]/u).includes('node_modules') ?? false;
|
|
28
|
+
}
|
|
29
|
+
function resolveEffectAdapterEntryFile(api) {
|
|
30
|
+
const { appDirectory, apiDirectory, distDirectory } = api.getServerContext();
|
|
31
|
+
const appRoot = node_path.resolve(appDirectory || process.cwd());
|
|
32
|
+
const productionRoot = isProd() && distDirectory ? node_path.resolve(distDirectory) : void 0;
|
|
33
|
+
const configuredEntry = api.getServerConfig()?.bff?.effect?.entry;
|
|
34
|
+
if (configuredEntry) {
|
|
35
|
+
const sourceEntry = node_path.isAbsolute(configuredEntry) ? configuredEntry : node_path.resolve(appRoot, configuredEntry);
|
|
36
|
+
if (productionRoot) {
|
|
37
|
+
const relativeEntry = relativeAppPath(appRoot, sourceEntry);
|
|
38
|
+
if (void 0 === relativeEntry || isDependencyPath(relativeEntry)) return resolveJsOrTsEntry(sourceEntry);
|
|
39
|
+
return relativeEntry ? resolveJsOrTsEntry(builtEntryPath(node_path.resolve(productionRoot, relativeEntry))) : void 0;
|
|
40
|
+
}
|
|
41
|
+
return resolveJsOrTsEntry(sourceEntry);
|
|
42
|
+
}
|
|
43
|
+
const resolvedApiDirectory = node_path.resolve(appRoot, apiDirectory || API_DIR);
|
|
44
|
+
const productionApiDirectory = productionRoot ? void 0 !== relativeAppPath(productionRoot, resolvedApiDirectory) ? resolvedApiDirectory : (()=>{
|
|
45
|
+
const relativeApiDirectory = relativeAppPath(appRoot, resolvedApiDirectory);
|
|
46
|
+
if (isDependencyPath(relativeApiDirectory)) return resolvedApiDirectory;
|
|
47
|
+
return relativeApiDirectory ? node_path.resolve(productionRoot, relativeApiDirectory) : void 0;
|
|
48
|
+
})() : resolvedApiDirectory;
|
|
49
|
+
return productionApiDirectory ? resolveJsOrTsEntry(node_path.resolve(productionApiDirectory, 'index')) : void 0;
|
|
50
|
+
}
|
|
51
|
+
export { resolveEffectAdapterEntryFile };
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import "node:module";
|
|
2
|
+
import { createSafeFailureResponse } from "@modern-js/runtime-extensions/safe-failure";
|
|
3
|
+
import { logger } from "@modern-js/utils";
|
|
4
|
+
function createEffectAdapterRuntimeErrorResponse(api, error, context) {
|
|
5
|
+
try {
|
|
6
|
+
const onError = api.getServerConfig()?.onError;
|
|
7
|
+
if (void 0 !== onError) return Promise.resolve(onError(error instanceof Error ? error : new Error(String(error)), ensureJsonContext(context))).then((result)=>result instanceof Response ? result : createSafeFailureResponse(error)).catch((configError)=>{
|
|
8
|
+
logger.error(`Error in serverConfig.onError handler: ${String(configError)}`);
|
|
9
|
+
return createSafeFailureResponse(error);
|
|
10
|
+
});
|
|
11
|
+
logger.error(error instanceof Error ? error : new Error(String(error)));
|
|
12
|
+
} catch (configError) {
|
|
13
|
+
logger.error(`Error in serverConfig.onError handler: ${configError}`);
|
|
14
|
+
}
|
|
15
|
+
return Promise.resolve(createSafeFailureResponse(error));
|
|
16
|
+
}
|
|
17
|
+
function ensureJsonContext(context) {
|
|
18
|
+
if ('json' in context && 'function' == typeof context.json) return context;
|
|
19
|
+
return Object.assign({}, context, {
|
|
20
|
+
json (data, statusOrInit = 200, extraHeaders) {
|
|
21
|
+
const responseInit = 'number' == typeof statusOrInit ? {
|
|
22
|
+
status: statusOrInit,
|
|
23
|
+
headers: extraHeaders
|
|
24
|
+
} : statusOrInit;
|
|
25
|
+
const responseHeaders = new Headers({
|
|
26
|
+
'content-type': 'application/json; charset=utf-8'
|
|
27
|
+
});
|
|
28
|
+
if (void 0 !== responseInit.headers) new Headers(responseInit.headers).forEach((value, key)=>{
|
|
29
|
+
responseHeaders.set(key, value);
|
|
30
|
+
});
|
|
31
|
+
return new Response(JSON.stringify(data), {
|
|
32
|
+
...responseInit,
|
|
33
|
+
headers: responseHeaders
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
}
|
|
38
|
+
export { createEffectAdapterRuntimeErrorResponse };
|