@bleedingdev/modern-js-plugin-bff-extensions 3.9.0-ultramodern.11 → 3.9.0-ultramodern.12

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 (45) hide show
  1. package/dist/cjs/backend-federation/identity.js +23 -22
  2. package/dist/cjs/backend-federation-manifest/validation.js +11 -7
  3. package/dist/cjs/cross-project-policy/node.js +8 -28
  4. package/dist/cjs/effect-adapter/cross-project-policy.js +2 -2
  5. package/dist/cjs/effect-adapter/entry.js +8 -44
  6. package/dist/cjs/effect-adapter/index.js +10 -2
  7. package/dist/cjs/effect-source-loader/built-entry.js +4 -5
  8. package/dist/cjs/effect-source-loader/loader.js +2 -1
  9. package/dist/cjs/effect-source-loader/operation-contracts.js +8 -31
  10. package/dist/cjs/effect-source-loader/paths.js +38 -10
  11. package/dist/esm/backend-federation/identity.mjs +18 -23
  12. package/dist/esm/backend-federation-manifest/validation.mjs +12 -8
  13. package/dist/esm/cross-project-policy/node.mjs +9 -19
  14. package/dist/esm/effect-adapter/cross-project-policy.mjs +2 -2
  15. package/dist/esm/effect-adapter/entry.mjs +9 -45
  16. package/dist/esm/effect-adapter/index.mjs +10 -2
  17. package/dist/esm/effect-source-loader/built-entry.mjs +5 -6
  18. package/dist/esm/effect-source-loader/loader.mjs +2 -1
  19. package/dist/esm/effect-source-loader/operation-contracts.mjs +10 -33
  20. package/dist/esm/effect-source-loader/paths.mjs +30 -11
  21. package/dist/esm-node/backend-federation/identity.mjs +18 -23
  22. package/dist/esm-node/backend-federation-manifest/validation.mjs +12 -8
  23. package/dist/esm-node/cross-project-policy/node.mjs +9 -19
  24. package/dist/esm-node/effect-adapter/cross-project-policy.mjs +2 -2
  25. package/dist/esm-node/effect-adapter/entry.mjs +9 -45
  26. package/dist/esm-node/effect-adapter/index.mjs +10 -2
  27. package/dist/esm-node/effect-source-loader/built-entry.mjs +5 -6
  28. package/dist/esm-node/effect-source-loader/loader.mjs +2 -1
  29. package/dist/esm-node/effect-source-loader/operation-contracts.mjs +10 -33
  30. package/dist/esm-node/effect-source-loader/paths.mjs +30 -11
  31. package/dist/types/backend-federation/identity.d.ts +3 -6
  32. package/dist/types/cross-project-policy/node.d.ts +2 -2
  33. package/dist/types/effect-adapter/cross-project-policy.d.ts +2 -1
  34. package/dist/types/effect-source-loader/paths.d.ts +20 -2
  35. package/package.json +10 -10
  36. package/src/backend-federation/identity.ts +39 -47
  37. package/src/backend-federation-manifest/validation.ts +22 -29
  38. package/src/cross-project-policy/node.ts +7 -38
  39. package/src/effect-adapter/cross-project-policy.ts +7 -1
  40. package/src/effect-adapter/entry.ts +10 -88
  41. package/src/effect-adapter/index.ts +7 -1
  42. package/src/effect-source-loader/built-entry.ts +11 -9
  43. package/src/effect-source-loader/loader.ts +10 -5
  44. package/src/effect-source-loader/operation-contracts.ts +7 -41
  45. package/src/effect-source-loader/paths.ts +55 -21
@@ -1,51 +1,15 @@
1
1
  import node_path from "node:path";
2
2
  import "@modern-js/server-runtime-extensions/server-config";
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
- }
3
+ import { API_DIR, isProd } from "@modern-js/utils";
4
+ import { resolveEffectEntry } from "../effect-source-loader/paths.mjs";
29
5
  function resolveEffectAdapterEntryFile(api) {
30
6
  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;
7
+ const appDir = node_path.resolve(appDirectory || process.cwd());
8
+ return resolveEffectEntry({
9
+ appDir,
10
+ apiDir: node_path.resolve(appDir, apiDirectory || API_DIR),
11
+ effectEntry: api.getServerConfig()?.bff?.effect?.entry,
12
+ distDir: isProd() && distDirectory ? node_path.resolve(distDirectory) : void 0
13
+ }).path;
50
14
  }
51
15
  export { resolveEffectAdapterEntryFile };
@@ -1,6 +1,7 @@
1
1
  import node_path from "node:path";
2
2
  import "@modern-js/server-runtime-extensions/server-config";
3
3
  import { dispatchEffectBffRequest, resolveEffectBffModuleHandler, useEffectContext } from "@modern-js/bff-effect/effect";
4
+ import { resolveOperationProducer } from "@modern-js/server-runtime-extensions/bff-policy/node";
4
5
  import { createDisposableServerRuntimeHandle, registerServerRuntimeDisposer } from "@modern-js/server-runtime-extensions/runtime-lifecycle";
5
6
  import { fs, isProd, logger } from "@modern-js/utils";
6
7
  import { checkCrossProjectPolicyForRequest } from "../cross-project-policy/evaluation.mjs";
@@ -20,9 +21,9 @@ class EffectAdapter {
20
21
  this.handler = null;
21
22
  return;
22
23
  }
24
+ const { appDirectory } = this.api.getServerContext();
23
25
  let mod;
24
26
  try {
25
- const { appDirectory } = this.api.getServerContext();
26
27
  mod = await (isProd() ? loadEffectBuiltModule(entryFile) : loadEffectSourceModule({
27
28
  resourcePath: entryFile,
28
29
  appDir: appDirectory || node_path.dirname(entryFile)
@@ -31,9 +32,16 @@ class EffectAdapter {
31
32
  logger.error(`[BFF][Effect] Failed to load Effect entry: ${entryFile}\n${String(error)}`);
32
33
  throw error;
33
34
  }
35
+ const producer = resolveOperationProducer({
36
+ directories: [
37
+ node_path.dirname(entryFile),
38
+ appDirectory
39
+ ],
40
+ requestId: this.api.getServerConfig()?.bff?.requestId
41
+ });
34
42
  const crossProjectPolicies = new Map(await Promise.all(this.prefixes.map(async (prefix)=>[
35
43
  prefix,
36
- await resolveEffectAdapterCrossProjectPolicy(this.api, prefix, mod)
44
+ await resolveEffectAdapterCrossProjectPolicy(this.api, prefix, mod, producer)
37
45
  ])));
38
46
  const effectConfig = this.api.getServerConfig()?.bff?.effect;
39
47
  const loaded = await resolveEffectBffModuleHandler(mod, {
@@ -1,11 +1,10 @@
1
1
  import { fs, upath } from "@modern-js/utils";
2
- import { resolveEffectEntryFile } from "./paths.mjs";
3
- const BUILT_ENTRY_EXT = /\.(?:[cm]?ts|tsx|jsx)$/u;
2
+ import { emittedEffectEntry, relativeEffectAppPath, resolveEffectEntryFile } from "./paths.mjs";
4
3
  function resolveBuiltEffectEntry(appDirectory, distDirectory, sourceEntry) {
5
4
  if (void 0 === sourceEntry || 0 === sourceEntry.length) return;
6
- const relativeEntry = upath.relative(appDirectory, sourceEntry);
7
- if ('..' === relativeEntry || relativeEntry.startsWith(`..${upath.sep}`)) throw new Error(`Effect BFF entry must be inside the application directory: ${sourceEntry}`);
8
- const builtEntry = upath.resolve(distDirectory, relativeEntry).replace(BUILT_ENTRY_EXT, '.js');
5
+ const relativeEntry = relativeEffectAppPath(appDirectory, sourceEntry);
6
+ if (void 0 === relativeEntry) throw new Error(`Effect BFF entry must be inside the application directory: ${sourceEntry}`);
7
+ const builtEntry = emittedEffectEntry(upath.resolve(distDirectory, relativeEntry));
9
8
  return fs.existsSync(builtEntry) ? builtEntry : void 0;
10
9
  }
11
10
  async function bundleBuiltEffectEntryForNode(options) {
@@ -31,7 +30,7 @@ function resolveEffectEntryPaths(options) {
31
30
  apiDir,
32
31
  effectEntry
33
32
  });
34
- const relativeEffectEntry = void 0 !== sourceEffectEntry && sourceEffectEntry.length > 0 ? upath.relative(appDir, sourceEffectEntry).replace(BUILT_ENTRY_EXT, '.js') : '';
33
+ const relativeEffectEntry = void 0 !== sourceEffectEntry && sourceEffectEntry.length > 0 ? emittedEffectEntry(upath.relative(appDir, sourceEffectEntry)) : '';
35
34
  return {
36
35
  sourceEffectEntry,
37
36
  relativeEffectEntry
@@ -130,7 +130,8 @@ function externalizeInstalledDependencies(options) {
130
130
  path: args.path
131
131
  };
132
132
  const realPath = await node_fs.promises.realpath(resolution.path).catch(()=>resolution.path);
133
- if (realPath.includes(`${node_path.sep}node_modules${node_path.sep}`)) {
133
+ const loader = SOURCE_LOADERS.get(node_path.extname(realPath).toLowerCase());
134
+ if (realPath.includes(`${node_path.sep}node_modules${node_path.sep}`) && 'ts' !== loader && 'tsx' !== loader && 'jsx' !== loader) {
134
135
  const runtimeResolution = await buildApi.resolve(args.path, {
135
136
  importer: '',
136
137
  kind: args.kind,
@@ -1,45 +1,22 @@
1
1
  import { collectEffectEndpoints, toOperationContractSources } from "@modern-js/bff-effect/effect";
2
- import { buildOperationContractMap, deriveOperationVersion } from "@modern-js/server-runtime-extensions/bff-policy/node";
3
- import { fs, upath } from "@modern-js/utils";
2
+ import { buildOperationContractMap, resolveOperationProducer } from "@modern-js/server-runtime-extensions/bff-policy/node";
3
+ import { upath } from "@modern-js/utils";
4
4
  import { getHttpApiRuntime, loadEffectApi } from "./http-api-runtime.mjs";
5
- function getPackageInfo(resourcePath, appDir, onDependency) {
6
- for (const startDir of [
7
- upath.dirname(resourcePath),
8
- appDir
9
- ]){
10
- let current = upath.resolve(startDir);
11
- for(let depth = 0; depth < 32; depth += 1){
12
- const packageJsonPath = upath.join(current, 'package.json');
13
- if (fs.existsSync(packageJsonPath)) {
14
- onDependency?.(packageJsonPath);
15
- try {
16
- const packageJson = fs.readJSONSync(packageJsonPath);
17
- return {
18
- name: packageJson.name,
19
- version: packageJson.version
20
- };
21
- } catch {
22
- return {};
23
- }
24
- }
25
- const parent = upath.dirname(current);
26
- if (parent === current) break;
27
- current = parent;
28
- }
29
- }
30
- return {};
31
- }
32
5
  async function resolveEffectOperationContracts(options) {
33
6
  const api = await loadEffectApi(options);
34
7
  if (null === api) return null;
35
8
  const runtime = await getHttpApiRuntime();
36
9
  const endpoints = collectEffectEndpoints(runtime.reflect, api, options.prefix);
37
- const packageInfo = getPackageInfo(options.resourcePath, options.appDir, options.onDependency);
38
- const requestId = options.requestId?.trim() || packageInfo.name || 'default';
39
10
  return buildOperationContractMap({
40
11
  handlers: toOperationContractSources(endpoints),
41
- requestId,
42
- operationVersion: deriveOperationVersion(packageInfo.version)
12
+ ...resolveOperationProducer({
13
+ directories: [
14
+ upath.dirname(options.resourcePath),
15
+ options.appDir
16
+ ],
17
+ requestId: options.requestId,
18
+ onDependency: options.onDependency
19
+ })
43
20
  });
44
21
  }
45
22
  export { resolveEffectOperationContracts };
@@ -9,16 +9,35 @@ const JS_OR_TS_EXTS = [
9
9
  '.cjs',
10
10
  '.cts'
11
11
  ];
12
- function resolveEffectEntryFile(options) {
13
- const { appDir, apiDir, effectEntry } = options;
14
- const resolveEntry = (entryWithoutExt)=>{
15
- if ('' !== upath.extname(entryWithoutExt)) return fs.existsSync(entryWithoutExt) ? entryWithoutExt : void 0;
16
- return findExists(JS_OR_TS_EXTS.map((ext)=>`${entryWithoutExt}${ext}`)) || void 0;
12
+ const emittedEffectEntry = (entry)=>entry.replace(/\.(?:[cm]?ts|tsx|jsx)$/u, '.js');
13
+ function relativeEffectAppPath(appDir, entry) {
14
+ const relative = upath.relative(appDir, entry);
15
+ return '..' === relative || relative.startsWith('../') || relative.split('/').includes('node_modules') ? void 0 : relative;
16
+ }
17
+ function existingEntry(entry) {
18
+ return upath.extname(entry) ? fs.existsSync(entry) ? entry : void 0 : findExists(JS_OR_TS_EXTS.map((ext)=>`${entry}${ext}`)) || void 0;
19
+ }
20
+ function resolveEffectEntry(options) {
21
+ const { appDir, apiDir, effectEntry, distDir } = options;
22
+ const entry = upath.resolve(appDir, effectEntry || upath.join(apiDir, 'index'));
23
+ if (distDir && void 0 !== relativeEffectAppPath(distDir, entry)) return {
24
+ kind: 'built-output',
25
+ path: existingEntry(emittedEffectEntry(entry))
26
+ };
27
+ const relative = relativeEffectAppPath(appDir, entry);
28
+ if (void 0 === relative) return {
29
+ kind: 'external-sdk',
30
+ path: existingEntry(entry)
17
31
  };
18
- if (void 0 !== effectEntry && '' !== effectEntry) {
19
- const entryWithoutExt = upath.isAbsolute(effectEntry) ? effectEntry : upath.resolve(appDir, effectEntry);
20
- return resolveEntry(entryWithoutExt);
21
- }
22
- return resolveEntry(upath.resolve(apiDir, 'index'));
32
+ return distDir ? {
33
+ kind: 'built-output',
34
+ path: existingEntry(emittedEffectEntry(upath.resolve(distDir, relative)))
35
+ } : {
36
+ kind: 'app-source',
37
+ path: existingEntry(entry)
38
+ };
39
+ }
40
+ function resolveEffectEntryFile(options) {
41
+ return resolveEffectEntry(options).path;
23
42
  }
24
- export { resolveEffectEntryFile };
43
+ export { emittedEffectEntry, relativeEffectAppPath, resolveEffectEntry, resolveEffectEntryFile };
@@ -1,36 +1,31 @@
1
1
  import "node:module";
2
2
  import { isRecord } from "./utils.mjs";
3
- function validateExpectedBackendFederationIdentity(loaded, expected) {
4
- const issues = [];
3
+ function backendFederationCompatibility(loaded) {
5
4
  const contract = isRecord(loaded) ? loaded.backendFederationContract : void 0;
6
5
  const compatibility = isRecord(contract) ? contract.compatibility : void 0;
7
- if (!isRecord(compatibility)) return [
6
+ return isRecord(compatibility) ? compatibility : void 0;
7
+ }
8
+ function validateBackendFederationCompatibility(compatibility, expected) {
9
+ return Object.entries(expected).flatMap(([field, value])=>void 0 === value || 'string' == typeof compatibility[field] && compatibility[field].length > 0 && compatibility[field] === value ? [] : [
10
+ {
11
+ path: `backendFederationContract.compatibility.${field}`,
12
+ message: `expected ${value}, received ${'string' == typeof compatibility[field] ? compatibility[field] : typeof compatibility[field]}`
13
+ }
14
+ ]);
15
+ }
16
+ function validateExpectedBackendFederationIdentity(loaded, expected) {
17
+ const compatibility = backendFederationCompatibility(loaded);
18
+ return compatibility ? validateBackendFederationCompatibility(compatibility, {
19
+ unitId: expected.unitId,
20
+ build: expected.buildMarker
21
+ }) : [
8
22
  {
9
23
  path: 'backendFederationContract.compatibility',
10
24
  message: 'loaded module declares no compatibility metadata; delivery-unit identity cannot be validated'
11
25
  }
12
26
  ];
13
- const unitId = compatibility.unitId;
14
- if ('string' != typeof unitId || 0 === unitId.length) issues.push({
15
- path: 'backendFederationContract.compatibility.unitId',
16
- message: `missing delivery-unit id; expected ${expected.unitId}`
17
- });
18
- else if (unitId !== expected.unitId) issues.push({
19
- path: 'backendFederationContract.compatibility.unitId',
20
- message: `expected ${expected.unitId}, received ${unitId}`
21
- });
22
- const build = compatibility.build;
23
- if ('string' != typeof build || 0 === build.length) issues.push({
24
- path: 'backendFederationContract.compatibility.build',
25
- message: `missing build marker; expected ${expected.buildMarker}`
26
- });
27
- else if (build !== expected.buildMarker) issues.push({
28
- path: 'backendFederationContract.compatibility.build',
29
- message: `expected ${expected.buildMarker}, received ${build}`
30
- });
31
- return issues;
32
27
  }
33
28
  function formatBackendFederationIdentityIssues(issues) {
34
29
  return issues.map((issue)=>`${issue.path}: ${issue.message}`).join('; ');
35
30
  }
36
- export { formatBackendFederationIdentityIssues, validateExpectedBackendFederationIdentity };
31
+ export { backendFederationCompatibility, formatBackendFederationIdentityIssues, validateBackendFederationCompatibility, validateExpectedBackendFederationIdentity };
@@ -1,8 +1,9 @@
1
1
  import "node:module";
2
2
  import { formatBackendFederationValidationErrors, validateBackendFederationManifest } from "@modern-js/backend-federation-contracts";
3
3
  import { BACKEND_FEDERATION_CONTRACT_VERSION, BACKEND_FEDERATION_NODE_ADAPTER_VERSION } from "../backend-federation/index.mjs";
4
+ import { backendFederationCompatibility, formatBackendFederationIdentityIssues, validateBackendFederationCompatibility } from "../backend-federation/identity.mjs";
4
5
  import { BackendFederationManifestAdapterError, assertConsistentValue, assertManifestAdapter, assertVersionValue } from "./errors.mjs";
5
- import { backendFederationMetadata, manifestDeliveryUnit, recordField, stringValue, versionBoundaryMetadata } from "./metadata.mjs";
6
+ import { backendFederationMetadata, manifestDeliveryUnit, stringValue, versionBoundaryMetadata } from "./metadata.mjs";
6
7
  function resolveExpectedBuildMarker(expected) {
7
8
  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
9
  label: 'expected.buildVersion/buildMarker',
@@ -43,19 +44,22 @@ function validateLoadedBackendFederationContract(loaded, manifest, remote) {
43
44
  const loadedContract = loaded.backendFederationContract;
44
45
  const backendFederation = backendFederationMetadata(manifest);
45
46
  const boundary = versionBoundaryMetadata(manifest);
46
- const compatibility = recordField(loadedContract, 'compatibility');
47
+ const compatibility = backendFederationCompatibility(loaded);
47
48
  assertManifestAdapter(compatibility, 'version_mismatch', `[BFF][Effect] Backend federation expose ${remote.name}/${remote.expose?.replace(/^\.\//u, '')} must declare compatibility metadata.`);
48
49
  assertVersionValue(stringValue(loadedContract?.role), 'microvertical-server', 'expose role');
49
50
  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
51
  const deliveryUnit = manifestDeliveryUnit(backendFederation, boundary);
55
52
  const manifestUnitId = stringValue(deliveryUnit.boundary?.unitId) ?? stringValue(deliveryUnit.top?.unitId);
56
53
  const manifestBuildMarker = stringValue(deliveryUnit.boundary?.buildMarker);
57
- assertVersionValue(stringValue(compatibility.unitId), manifestUnitId, 'deliveryUnit.unitId vs expose compatibility.unitId');
58
- assertVersionValue(stringValue(compatibility.build), manifestBuildMarker, 'deliveryUnit.buildMarker vs expose compatibility.build');
54
+ const issues = validateBackendFederationCompatibility(compatibility, {
55
+ contractVersion: stringValue(backendFederation?.contractVersion),
56
+ nodeAdapterVersion: stringValue(backendFederation?.nodeAdapterVersion),
57
+ packageName: stringValue(boundary?.packageName),
58
+ unitId: manifestUnitId,
59
+ build: manifestBuildMarker ?? stringValue(boundary?.buildVersion)
60
+ });
61
+ assertVersionValue(stringValue(compatibility.build), stringValue(boundary?.buildVersion), 'expose buildVersion');
62
+ assertManifestAdapter(0 === issues.length, 'version_mismatch', `[BFF][Effect] ${formatBackendFederationIdentityIssues(issues)}.`);
59
63
  }
60
64
  function classifyLoadError(error) {
61
65
  const message = error instanceof Error ? error.message : String(error);
@@ -1,30 +1,20 @@
1
1
  import "node:module";
2
- import { readFileSync } from "node:fs";
3
- import node_path from "node:path";
4
2
  import "@modern-js/server-runtime-extensions/server-config";
5
- import { deriveOperationVersion, resolveCrossProjectPolicy } from "@modern-js/server-runtime-extensions/bff-policy/node";
6
- const readNearestPackageVersion = (startDir)=>{
7
- if (!startDir) return;
8
- let current = node_path.resolve(startDir);
9
- for(let depth = 0; depth < 10; depth += 1){
10
- try {
11
- const packageJson = JSON.parse(readFileSync(node_path.join(current, 'package.json'), 'utf8'));
12
- if ('string' == typeof packageJson.version) return packageJson.version;
13
- } catch {}
14
- const parent = node_path.dirname(current);
15
- if (parent === current) break;
16
- current = parent;
17
- }
18
- };
19
- const resolveAdapterCrossProjectPolicy = (api, handlers)=>{
3
+ import { resolveCrossProjectPolicy, resolveOperationProducer } from "@modern-js/server-runtime-extensions/bff-policy/node";
4
+ const resolveAdapterCrossProjectPolicy = (api, handlers, producer)=>{
20
5
  const bff = api.getServerConfig()?.bff;
21
6
  const { apiDirectory, appDirectory } = api.getServerContext();
22
7
  return resolveCrossProjectPolicy({
23
8
  crossProjectPolicy: bff?.crossProjectPolicy,
24
9
  handlers,
25
- requestId: bff?.requestId,
26
10
  isCrossProjectServer: bff?.isCrossProjectServer,
27
- operationVersion: deriveOperationVersion(readNearestPackageVersion(apiDirectory) ?? readNearestPackageVersion(appDirectory))
11
+ ...producer ?? resolveOperationProducer({
12
+ directories: [
13
+ apiDirectory,
14
+ appDirectory
15
+ ],
16
+ requestId: bff?.requestId || 'default'
17
+ })
28
18
  });
29
19
  };
30
20
  export { resolveAdapterCrossProjectPolicy };
@@ -3,7 +3,7 @@ import { collectEffectEndpoints, extractHttpApiFromModule, toOperationContractSo
3
3
  import { logger } from "@modern-js/utils";
4
4
  import { HttpApi } from "effect/unstable/httpapi";
5
5
  import { resolveAdapterCrossProjectPolicy } from "../cross-project-policy/index.mjs";
6
- function resolveEffectAdapterCrossProjectPolicy(api, prefix, mod) {
6
+ function resolveEffectAdapterCrossProjectPolicy(api, prefix, mod, producer) {
7
7
  const contractSourcesPromise = null === mod ? Promise.resolve([]) : Promise.resolve().then(()=>extractHttpApiFromModule(mod, HttpApi.isHttpApi)).then((effectApi)=>{
8
8
  if (null === effectApi) return [];
9
9
  const reflect = (apiValue, handlers)=>{
@@ -19,7 +19,7 @@ function resolveEffectAdapterCrossProjectPolicy(api, prefix, mod) {
19
19
  return [];
20
20
  });
21
21
  return contractSourcesPromise.then((contractSources)=>{
22
- const policy = resolveAdapterCrossProjectPolicy(api, contractSources);
22
+ const policy = resolveAdapterCrossProjectPolicy(api, contractSources, producer);
23
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
24
  return policy;
25
25
  });
@@ -1,52 +1,16 @@
1
1
  import "node:module";
2
2
  import node_path from "node:path";
3
3
  import "@modern-js/server-runtime-extensions/server-config";
4
- import { API_DIR, findExists, fs, isProd } from "@modern-js/utils";
5
- const JS_OR_TS_EXTS = [
6
- '.js',
7
- '.jsx',
8
- '.ts',
9
- '.tsx',
10
- '.mjs',
11
- '.mts',
12
- '.cjs',
13
- '.cts'
14
- ];
15
- function resolveJsOrTsEntry(entryWithoutOrWithExt) {
16
- const extension = node_path.extname(entryWithoutOrWithExt);
17
- if (JS_OR_TS_EXTS.includes(extension)) return fs.existsSync(entryWithoutOrWithExt) ? entryWithoutOrWithExt : void 0;
18
- return findExists(JS_OR_TS_EXTS.map((ext)=>`${entryWithoutOrWithExt}${ext}`)) || void 0;
19
- }
20
- function builtEntryPath(entryPath) {
21
- return entryPath.replace(/\.(?:[cm]?ts|tsx|jsx)$/u, '.js');
22
- }
23
- function relativeAppPath(appDirectory, entryPath) {
24
- const relativePath = node_path.relative(appDirectory, entryPath);
25
- return '..' === relativePath || relativePath.startsWith(`..${node_path.sep}`) ? void 0 : relativePath;
26
- }
27
- function isDependencyPath(relativePath) {
28
- return relativePath?.split(/[\\/]/u).includes('node_modules') ?? false;
29
- }
4
+ import { API_DIR, isProd } from "@modern-js/utils";
5
+ import { resolveEffectEntry } from "../effect-source-loader/paths.mjs";
30
6
  function resolveEffectAdapterEntryFile(api) {
31
7
  const { appDirectory, apiDirectory, distDirectory } = api.getServerContext();
32
- const appRoot = node_path.resolve(appDirectory || process.cwd());
33
- const productionRoot = isProd() && distDirectory ? node_path.resolve(distDirectory) : void 0;
34
- const configuredEntry = api.getServerConfig()?.bff?.effect?.entry;
35
- if (configuredEntry) {
36
- const sourceEntry = node_path.isAbsolute(configuredEntry) ? configuredEntry : node_path.resolve(appRoot, configuredEntry);
37
- if (productionRoot) {
38
- const relativeEntry = relativeAppPath(appRoot, sourceEntry);
39
- if (void 0 === relativeEntry || isDependencyPath(relativeEntry)) return resolveJsOrTsEntry(sourceEntry);
40
- return relativeEntry ? resolveJsOrTsEntry(builtEntryPath(node_path.resolve(productionRoot, relativeEntry))) : void 0;
41
- }
42
- return resolveJsOrTsEntry(sourceEntry);
43
- }
44
- const resolvedApiDirectory = node_path.resolve(appRoot, apiDirectory || API_DIR);
45
- const productionApiDirectory = productionRoot ? void 0 !== relativeAppPath(productionRoot, resolvedApiDirectory) ? resolvedApiDirectory : (()=>{
46
- const relativeApiDirectory = relativeAppPath(appRoot, resolvedApiDirectory);
47
- if (isDependencyPath(relativeApiDirectory)) return resolvedApiDirectory;
48
- return relativeApiDirectory ? node_path.resolve(productionRoot, relativeApiDirectory) : void 0;
49
- })() : resolvedApiDirectory;
50
- return productionApiDirectory ? resolveJsOrTsEntry(node_path.resolve(productionApiDirectory, 'index')) : void 0;
8
+ const appDir = node_path.resolve(appDirectory || process.cwd());
9
+ return resolveEffectEntry({
10
+ appDir,
11
+ apiDir: node_path.resolve(appDir, apiDirectory || API_DIR),
12
+ effectEntry: api.getServerConfig()?.bff?.effect?.entry,
13
+ distDir: isProd() && distDirectory ? node_path.resolve(distDirectory) : void 0
14
+ }).path;
51
15
  }
52
16
  export { resolveEffectAdapterEntryFile };
@@ -2,6 +2,7 @@ import "node:module";
2
2
  import node_path from "node:path";
3
3
  import "@modern-js/server-runtime-extensions/server-config";
4
4
  import { dispatchEffectBffRequest, resolveEffectBffModuleHandler, useEffectContext } from "@modern-js/bff-effect/effect";
5
+ import { resolveOperationProducer } from "@modern-js/server-runtime-extensions/bff-policy/node";
5
6
  import { createDisposableServerRuntimeHandle, registerServerRuntimeDisposer } from "@modern-js/server-runtime-extensions/runtime-lifecycle";
6
7
  import { fs, isProd, logger } from "@modern-js/utils";
7
8
  import { checkCrossProjectPolicyForRequest } from "../cross-project-policy/evaluation.mjs";
@@ -21,9 +22,9 @@ class EffectAdapter {
21
22
  this.handler = null;
22
23
  return;
23
24
  }
25
+ const { appDirectory } = this.api.getServerContext();
24
26
  let mod;
25
27
  try {
26
- const { appDirectory } = this.api.getServerContext();
27
28
  mod = await (isProd() ? loadEffectBuiltModule(entryFile) : loadEffectSourceModule({
28
29
  resourcePath: entryFile,
29
30
  appDir: appDirectory || node_path.dirname(entryFile)
@@ -32,9 +33,16 @@ class EffectAdapter {
32
33
  logger.error(`[BFF][Effect] Failed to load Effect entry: ${entryFile}\n${String(error)}`);
33
34
  throw error;
34
35
  }
36
+ const producer = resolveOperationProducer({
37
+ directories: [
38
+ node_path.dirname(entryFile),
39
+ appDirectory
40
+ ],
41
+ requestId: this.api.getServerConfig()?.bff?.requestId
42
+ });
35
43
  const crossProjectPolicies = new Map(await Promise.all(this.prefixes.map(async (prefix)=>[
36
44
  prefix,
37
- await resolveEffectAdapterCrossProjectPolicy(this.api, prefix, mod)
45
+ await resolveEffectAdapterCrossProjectPolicy(this.api, prefix, mod, producer)
38
46
  ])));
39
47
  const effectConfig = this.api.getServerConfig()?.bff?.effect;
40
48
  const loaded = await resolveEffectBffModuleHandler(mod, {
@@ -1,12 +1,11 @@
1
1
  import "node:module";
2
2
  import { fs, upath } from "@modern-js/utils";
3
- import { resolveEffectEntryFile } from "./paths.mjs";
4
- const BUILT_ENTRY_EXT = /\.(?:[cm]?ts|tsx|jsx)$/u;
3
+ import { emittedEffectEntry, relativeEffectAppPath, resolveEffectEntryFile } from "./paths.mjs";
5
4
  function resolveBuiltEffectEntry(appDirectory, distDirectory, sourceEntry) {
6
5
  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');
6
+ const relativeEntry = relativeEffectAppPath(appDirectory, sourceEntry);
7
+ if (void 0 === relativeEntry) throw new Error(`Effect BFF entry must be inside the application directory: ${sourceEntry}`);
8
+ const builtEntry = emittedEffectEntry(upath.resolve(distDirectory, relativeEntry));
10
9
  return fs.existsSync(builtEntry) ? builtEntry : void 0;
11
10
  }
12
11
  async function bundleBuiltEffectEntryForNode(options) {
@@ -32,7 +31,7 @@ function resolveEffectEntryPaths(options) {
32
31
  apiDir,
33
32
  effectEntry
34
33
  });
35
- const relativeEffectEntry = void 0 !== sourceEffectEntry && sourceEffectEntry.length > 0 ? upath.relative(appDir, sourceEffectEntry).replace(BUILT_ENTRY_EXT, '.js') : '';
34
+ const relativeEffectEntry = void 0 !== sourceEffectEntry && sourceEffectEntry.length > 0 ? emittedEffectEntry(upath.relative(appDir, sourceEffectEntry)) : '';
36
35
  return {
37
36
  sourceEffectEntry,
38
37
  relativeEffectEntry
@@ -131,7 +131,8 @@ function externalizeInstalledDependencies(options) {
131
131
  path: args.path
132
132
  };
133
133
  const realPath = await node_fs.promises.realpath(resolution.path).catch(()=>resolution.path);
134
- if (realPath.includes(`${node_path.sep}node_modules${node_path.sep}`)) {
134
+ const loader = SOURCE_LOADERS.get(node_path.extname(realPath).toLowerCase());
135
+ if (realPath.includes(`${node_path.sep}node_modules${node_path.sep}`) && 'ts' !== loader && 'tsx' !== loader && 'jsx' !== loader) {
135
136
  const runtimeResolution = await buildApi.resolve(args.path, {
136
137
  importer: '',
137
138
  kind: args.kind,
@@ -1,46 +1,23 @@
1
1
  import "node:module";
2
2
  import { collectEffectEndpoints, toOperationContractSources } from "@modern-js/bff-effect/effect";
3
- import { buildOperationContractMap, deriveOperationVersion } from "@modern-js/server-runtime-extensions/bff-policy/node";
4
- import { fs, upath } from "@modern-js/utils";
3
+ import { buildOperationContractMap, resolveOperationProducer } from "@modern-js/server-runtime-extensions/bff-policy/node";
4
+ import { upath } from "@modern-js/utils";
5
5
  import { getHttpApiRuntime, loadEffectApi } from "./http-api-runtime.mjs";
6
- function getPackageInfo(resourcePath, appDir, onDependency) {
7
- for (const startDir of [
8
- upath.dirname(resourcePath),
9
- appDir
10
- ]){
11
- let current = upath.resolve(startDir);
12
- for(let depth = 0; depth < 32; depth += 1){
13
- const packageJsonPath = upath.join(current, 'package.json');
14
- if (fs.existsSync(packageJsonPath)) {
15
- onDependency?.(packageJsonPath);
16
- try {
17
- const packageJson = fs.readJSONSync(packageJsonPath);
18
- return {
19
- name: packageJson.name,
20
- version: packageJson.version
21
- };
22
- } catch {
23
- return {};
24
- }
25
- }
26
- const parent = upath.dirname(current);
27
- if (parent === current) break;
28
- current = parent;
29
- }
30
- }
31
- return {};
32
- }
33
6
  async function resolveEffectOperationContracts(options) {
34
7
  const api = await loadEffectApi(options);
35
8
  if (null === api) return null;
36
9
  const runtime = await getHttpApiRuntime();
37
10
  const endpoints = collectEffectEndpoints(runtime.reflect, api, options.prefix);
38
- const packageInfo = getPackageInfo(options.resourcePath, options.appDir, options.onDependency);
39
- const requestId = options.requestId?.trim() || packageInfo.name || 'default';
40
11
  return buildOperationContractMap({
41
12
  handlers: toOperationContractSources(endpoints),
42
- requestId,
43
- operationVersion: deriveOperationVersion(packageInfo.version)
13
+ ...resolveOperationProducer({
14
+ directories: [
15
+ upath.dirname(options.resourcePath),
16
+ options.appDir
17
+ ],
18
+ requestId: options.requestId,
19
+ onDependency: options.onDependency
20
+ })
44
21
  });
45
22
  }
46
23
  export { resolveEffectOperationContracts };