@bleedingdev/modern-js-app-tools 3.9.0-ultramodern.2 → 3.9.0-ultramodern.20

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 (138) hide show
  1. package/dist/cjs/builder/generator/createCopyPattern.js +2 -1
  2. package/dist/cjs/builder/generator/index.js +0 -1
  3. package/dist/cjs/builder/shared/builderPlugins/adapterHtml.js +2 -1
  4. package/dist/cjs/builder/shared/builderPlugins/index.js +4 -11
  5. package/dist/cjs/builder/shared/lazyCompilation.js +26 -0
  6. package/dist/cjs/commands/index.js +6 -2
  7. package/dist/cjs/compat/hooks.js +1 -1
  8. package/dist/cjs/config/index.js +4 -11
  9. package/dist/cjs/index.js +70 -87
  10. package/dist/cjs/plugins/analyze/getFileSystemEntry.js +1 -1
  11. package/dist/cjs/plugins/analyze/getServerRoutes.js +1 -1
  12. package/dist/cjs/plugins/analyze/utils.js +2 -2
  13. package/dist/cjs/plugins/deploy/index.js +7 -28
  14. package/dist/cjs/plugins/deploy/platforms/netlify.js +2 -1
  15. package/dist/cjs/plugins/deploy/platforms/node.js +12 -16
  16. package/dist/cjs/plugins/deploy/platforms/vercel.js +2 -1
  17. package/dist/cjs/plugins/deploy/utils/generator.js +1 -1
  18. package/dist/cjs/plugins/deploy/utils/index.js +15 -12
  19. package/dist/cjs/plugins/initialize/index.js +3 -1
  20. package/dist/cjs/plugins/serverBuild.js +2 -3
  21. package/dist/cjs/{plugins/backendFederationBuild.js → server-plugin.js} +4 -7
  22. package/dist/cjs/utils/loadPlugins.js +1 -6
  23. package/dist/esm/builder/generator/createCopyPattern.mjs +2 -1
  24. package/dist/esm/builder/generator/index.mjs +1 -2
  25. package/dist/esm/builder/shared/builderPlugins/adapterHtml.mjs +2 -1
  26. package/dist/esm/builder/shared/builderPlugins/index.mjs +0 -1
  27. package/dist/esm/builder/shared/lazyCompilation.mjs +14 -1
  28. package/dist/esm/commands/index.mjs +6 -2
  29. package/dist/esm/compat/hooks.mjs +1 -1
  30. package/dist/esm/config/index.mjs +0 -1
  31. package/dist/esm/index.mjs +9 -6
  32. package/dist/esm/plugins/analyze/getFileSystemEntry.mjs +1 -1
  33. package/dist/esm/plugins/analyze/getServerRoutes.mjs +1 -1
  34. package/dist/esm/plugins/analyze/utils.mjs +2 -2
  35. package/dist/esm/plugins/deploy/index.mjs +5 -21
  36. package/dist/esm/plugins/deploy/platforms/netlify.mjs +2 -1
  37. package/dist/esm/plugins/deploy/platforms/node.mjs +12 -16
  38. package/dist/esm/plugins/deploy/platforms/vercel.mjs +2 -1
  39. package/dist/esm/plugins/deploy/utils/generator.mjs +1 -1
  40. package/dist/esm/plugins/deploy/utils/index.mjs +17 -14
  41. package/dist/esm/plugins/initialize/index.mjs +3 -1
  42. package/dist/esm/plugins/serverBuild.mjs +2 -3
  43. package/dist/esm/server-plugin.mjs +1 -0
  44. package/dist/esm/utils/loadPlugins.mjs +2 -7
  45. package/dist/esm-node/builder/generator/createCopyPattern.mjs +2 -1
  46. package/dist/esm-node/builder/generator/index.mjs +1 -2
  47. package/dist/esm-node/builder/shared/builderPlugins/adapterHtml.mjs +2 -1
  48. package/dist/esm-node/builder/shared/builderPlugins/index.mjs +0 -1
  49. package/dist/esm-node/builder/shared/lazyCompilation.mjs +14 -1
  50. package/dist/esm-node/commands/index.mjs +6 -2
  51. package/dist/esm-node/compat/hooks.mjs +1 -1
  52. package/dist/esm-node/config/index.mjs +0 -1
  53. package/dist/esm-node/index.mjs +9 -6
  54. package/dist/esm-node/plugins/analyze/getFileSystemEntry.mjs +1 -1
  55. package/dist/esm-node/plugins/analyze/getServerRoutes.mjs +1 -1
  56. package/dist/esm-node/plugins/analyze/utils.mjs +2 -2
  57. package/dist/esm-node/plugins/deploy/index.mjs +5 -21
  58. package/dist/esm-node/plugins/deploy/platforms/netlify.mjs +2 -1
  59. package/dist/esm-node/plugins/deploy/platforms/node.mjs +12 -16
  60. package/dist/esm-node/plugins/deploy/platforms/vercel.mjs +2 -1
  61. package/dist/esm-node/plugins/deploy/utils/generator.mjs +1 -1
  62. package/dist/esm-node/plugins/deploy/utils/index.mjs +17 -15
  63. package/dist/esm-node/plugins/initialize/index.mjs +3 -1
  64. package/dist/esm-node/plugins/serverBuild.mjs +2 -3
  65. package/dist/esm-node/server-plugin.mjs +2 -0
  66. package/dist/esm-node/utils/loadPlugins.mjs +2 -7
  67. package/dist/types/builder/shared/builderPlugins/index.d.ts +0 -1
  68. package/dist/types/builder/shared/lazyCompilation.d.ts +15 -0
  69. package/dist/types/config/index.d.ts +0 -1
  70. package/dist/types/index.d.ts +2 -2
  71. package/dist/types/plugins/deploy/index.d.ts +1 -4
  72. package/dist/types/plugins/deploy/utils/generator.d.ts +1 -1
  73. package/dist/types/plugins/deploy/utils/index.d.ts +1 -1
  74. package/dist/types/server-plugin.d.ts +10 -0
  75. package/dist/types/types/config/output.d.ts +0 -9
  76. package/dist/types/types/index.d.ts +1 -1
  77. package/dist/types/types/plugin.d.ts +58 -2
  78. package/dist/types/utils/initAppContext.d.ts +3 -2
  79. package/docs/apis/app/commands.md +1 -0
  80. package/docs/configure/app/bff/effect.md +34 -36
  81. package/docs/configure/app/source/react-compiler.md +2 -0
  82. package/docs/guides/advanced-features/bff/data-platform.md +2 -2
  83. package/docs/guides/advanced-features/bff/frameworks.md +36 -24
  84. package/docs/guides/advanced-features/bff/function.md +2 -2
  85. package/docs/guides/advanced-features/bff/operators.md +17 -17
  86. package/docs/guides/basic-features/render/ssr-cache.md +14 -1
  87. package/docs/guides/get-started/quick-start.md +2 -6
  88. package/docs/guides/get-started/ultramodern.md +14 -97
  89. package/docs/llms.txt +3 -3
  90. package/docs/plugin/server-plugins/api.md +1 -0
  91. package/package.json +38 -36
  92. package/dist/cjs/builder/shared/builderPlugins/adapterPrecompress.js +0 -125
  93. package/dist/cjs/config/build-environment.js +0 -268
  94. package/dist/cjs/config/public.js +0 -46
  95. package/dist/cjs/plugins/backend-federation/codegen.js +0 -256
  96. package/dist/cjs/plugins/backend-federation/config.js +0 -204
  97. package/dist/cjs/plugins/backend-federation/emit.js +0 -150
  98. package/dist/cjs/plugins/deploy/platforms/cloudflare-output-verifier/index.js +0 -62
  99. package/dist/cjs/plugins/deploy/utils/npmAliases.js +0 -226
  100. package/dist/cjs/plugins/ultramodernReleaseEnvelope.js +0 -44
  101. package/dist/cjs/presetUltramodern.js +0 -168
  102. package/dist/cjs/types/config/precompress.js +0 -18
  103. package/dist/esm/builder/shared/builderPlugins/adapterPrecompress.mjs +0 -77
  104. package/dist/esm/config/build-environment.mjs +0 -224
  105. package/dist/esm/config/public.mjs +0 -1
  106. package/dist/esm/plugins/backend-federation/codegen.mjs +0 -205
  107. package/dist/esm/plugins/backend-federation/config.mjs +0 -128
  108. package/dist/esm/plugins/backend-federation/emit.mjs +0 -99
  109. package/dist/esm/plugins/backendFederationBuild.mjs +0 -1
  110. package/dist/esm/plugins/deploy/platforms/cloudflare-output-verifier/index.mjs +0 -1
  111. package/dist/esm/plugins/deploy/utils/npmAliases.mjs +0 -174
  112. package/dist/esm/plugins/ultramodernReleaseEnvelope.mjs +0 -6
  113. package/dist/esm/presetUltramodern.mjs +0 -112
  114. package/dist/esm/types/config/precompress.mjs +0 -0
  115. package/dist/esm-node/builder/shared/builderPlugins/adapterPrecompress.mjs +0 -78
  116. package/dist/esm-node/config/build-environment.mjs +0 -225
  117. package/dist/esm-node/config/public.mjs +0 -2
  118. package/dist/esm-node/plugins/backend-federation/codegen.mjs +0 -206
  119. package/dist/esm-node/plugins/backend-federation/config.mjs +0 -129
  120. package/dist/esm-node/plugins/backend-federation/emit.mjs +0 -100
  121. package/dist/esm-node/plugins/backendFederationBuild.mjs +0 -2
  122. package/dist/esm-node/plugins/deploy/platforms/cloudflare-output-verifier/index.mjs +0 -2
  123. package/dist/esm-node/plugins/deploy/utils/npmAliases.mjs +0 -175
  124. package/dist/esm-node/plugins/ultramodernReleaseEnvelope.mjs +0 -7
  125. package/dist/esm-node/presetUltramodern.mjs +0 -113
  126. package/dist/esm-node/types/config/precompress.mjs +0 -1
  127. package/dist/types/builder/shared/builderPlugins/adapterPrecompress.d.ts +0 -3
  128. package/dist/types/config/build-environment.d.ts +0 -22
  129. package/dist/types/config/public.d.ts +0 -2
  130. package/dist/types/plugins/backend-federation/codegen.d.ts +0 -86
  131. package/dist/types/plugins/backend-federation/config.d.ts +0 -103
  132. package/dist/types/plugins/backend-federation/emit.d.ts +0 -13
  133. package/dist/types/plugins/backendFederationBuild.d.ts +0 -2
  134. package/dist/types/plugins/deploy/platforms/cloudflare-output-verifier/index.d.ts +0 -1
  135. package/dist/types/plugins/deploy/utils/npmAliases.d.ts +0 -14
  136. package/dist/types/plugins/ultramodernReleaseEnvelope.d.ts +0 -3
  137. package/dist/types/presetUltramodern.d.ts +0 -87
  138. package/dist/types/types/config/precompress.d.ts +0 -20
@@ -1,112 +0,0 @@
1
- import node_fs from "node:fs";
2
- import node_path from "node:path";
3
- import { resolveUltramodernReleaseIdentity } from "@modern-js/app-tools-extensions/release-identity";
4
- import { mergeConfig } from "@modern-js/plugin/cli";
5
- import { rspack } from "@rsbuild/core";
6
- const DEFAULT_OTLP_ENDPOINT = 'http://127.0.0.1:4318/v1/logs';
7
- const DEFAULT_VICTORIA_METRICS_ENDPOINT = 'http://127.0.0.1:8428/api/v1/import/prometheus';
8
- const resolveReactRouterPackageDir = (appDirectory)=>{
9
- const resolveNodeModulePackageJson = (packageName, fromDirectory)=>{
10
- let currentDirectory = node_path.resolve(fromDirectory);
11
- while(true){
12
- const packageJson = node_path.join(currentDirectory, 'node_modules', packageName, 'package.json');
13
- if (node_fs.existsSync(packageJson)) return node_fs.realpathSync(packageJson);
14
- const parentDirectory = node_path.dirname(currentDirectory);
15
- if (parentDirectory === currentDirectory) return;
16
- currentDirectory = parentDirectory;
17
- }
18
- };
19
- const reactRouterPackageJson = resolveNodeModulePackageJson('react-router', appDirectory);
20
- if (reactRouterPackageJson) return node_path.dirname(reactRouterPackageJson);
21
- const reactRouterDomPackageJson = resolveNodeModulePackageJson('react-router-dom', appDirectory);
22
- if (!reactRouterDomPackageJson) return;
23
- const nestedReactRouterPackageJson = resolveNodeModulePackageJson('react-router', node_path.dirname(reactRouterDomPackageJson));
24
- if (nestedReactRouterPackageJson) return node_path.dirname(nestedReactRouterPackageJson);
25
- };
26
- const setReactRouterBridgeSafeAliases = (chain, { isProd })=>{
27
- const chainContext = chain.get('context');
28
- const appDirectory = 'string' == typeof chainContext && chainContext.length > 0 ? chainContext : process.cwd();
29
- const reactRouterPackageDir = resolveReactRouterPackageDir(appDirectory);
30
- if (!reactRouterPackageDir) return;
31
- const productionEntry = node_path.join(reactRouterPackageDir, 'dist/production/index.mjs');
32
- const developmentEntry = node_path.join(reactRouterPackageDir, 'dist/development/index.mjs');
33
- chain.resolve.alias.set('react-router$', isProd ? productionEntry : developmentEntry);
34
- chain.resolve.alias.set('react-router/dist/production/index.js', productionEntry);
35
- chain.resolve.alias.set('react-router/dist/development/index.js', developmentEntry);
36
- };
37
- const createPresetUltramodernConfig = (options = {})=>{
38
- const { appId = 'app', deliveryUnit, enableBffRequestId = true, enableTelemetry = true, enableTelemetryExporters, otlpEndpoint = process.env.MODERN_TELEMETRY_OTLP_ENDPOINT, victoriaMetricsEndpoint = process.env.MODERN_TELEMETRY_VICTORIA_ENDPOINT, telemetryFailLoudStartup = false, enableModuleFederationSSR = true } = options;
39
- const server = {};
40
- const releaseIdentity = deliveryUnit ? resolveUltramodernReleaseIdentity({
41
- generationBuildMarker: deliveryUnit.buildMarker,
42
- unitId: deliveryUnit.unitId
43
- }) : void 0;
44
- const bundledReleaseIdentity = releaseIdentity ? {
45
- ...releaseIdentity,
46
- releaseVersion: deliveryUnit.version
47
- } : void 0;
48
- if (enableTelemetry) {
49
- server.telemetry = {
50
- enabled: true,
51
- failLoudStartup: telemetryFailLoudStartup
52
- };
53
- if (false !== enableTelemetryExporters) {
54
- const exporters = {};
55
- if (true === enableTelemetryExporters || otlpEndpoint) exporters.otlp = {
56
- enabled: true,
57
- endpoint: otlpEndpoint || DEFAULT_OTLP_ENDPOINT
58
- };
59
- if (true === enableTelemetryExporters || victoriaMetricsEndpoint) exporters.victoriaMetrics = {
60
- enabled: true,
61
- endpoint: victoriaMetricsEndpoint || DEFAULT_VICTORIA_METRICS_ENDPOINT
62
- };
63
- if (Object.keys(exporters).length > 0) server.telemetry.exporters = exporters;
64
- }
65
- }
66
- if (enableModuleFederationSSR) server.ssr = {
67
- mode: 'stream',
68
- moduleFederationAppSSR: true
69
- };
70
- const presetConfig = {
71
- output: {
72
- precompress: true
73
- },
74
- server,
75
- source: {
76
- reactCompiler: true,
77
- ...deliveryUnit ? {
78
- globalVars: {
79
- ULTRAMODERN_BUILD_MARKER: releaseIdentity?.buildMarker,
80
- ULTRAMODERN_RELEASE_VERSION: deliveryUnit.version,
81
- ULTRAMODERN_SOURCE_REVISION: releaseIdentity?.sourceRevision
82
- }
83
- } : {}
84
- },
85
- tools: {
86
- bundlerChain: setReactRouterBridgeSafeAliases,
87
- lightningcssLoader: true,
88
- ...bundledReleaseIdentity ? {
89
- rspack: (config)=>{
90
- config.plugins ??= [];
91
- config.plugins.push(new rspack.BannerPlugin({
92
- banner: `void ${JSON.stringify(bundledReleaseIdentity.buildMarker)};void ${JSON.stringify(bundledReleaseIdentity.sourceRevision)};void ${JSON.stringify(bundledReleaseIdentity.releaseVersion)};`,
93
- raw: true,
94
- stage: rspack.Compilation.PROCESS_ASSETS_STAGE_SUMMARIZE,
95
- test: /\.(?:c|m)?js$/u
96
- }));
97
- return config;
98
- }
99
- } : {}
100
- }
101
- };
102
- if (enableBffRequestId) presetConfig.bff = {
103
- requestId: appId
104
- };
105
- return presetConfig;
106
- };
107
- const presetUltramodern = (config, options = {})=>mergeConfig([
108
- createPresetUltramodernConfig(options),
109
- config
110
- ]);
111
- export { default as ultramodernReleaseEnvelopePlugin } from "./plugins/ultramodernReleaseEnvelope.mjs";
112
- export { createPresetUltramodernConfig, presetUltramodern };
File without changes
@@ -1,78 +0,0 @@
1
- import "node:module";
2
- import { constants } from "node:zlib";
3
- import compression_webpack_plugin from "compression-webpack-plugin";
4
- const DEFAULT_PRECOMPRESS_TEST = /\.(js|mjs|cjs|css|html|svg|json|map)$/i;
5
- const DEFAULT_PRECOMPRESS_THRESHOLD = 10240;
6
- const DEFAULT_PRECOMPRESS_MIN_RATIO = 0.8;
7
- const createDefaultGzipOptions = ()=>({
8
- algorithm: 'gzip',
9
- filename: '[path][base].gz',
10
- test: DEFAULT_PRECOMPRESS_TEST,
11
- threshold: DEFAULT_PRECOMPRESS_THRESHOLD,
12
- minRatio: DEFAULT_PRECOMPRESS_MIN_RATIO,
13
- compressionOptions: {
14
- level: 6
15
- }
16
- });
17
- const createDefaultBrotliOptions = ()=>({
18
- algorithm: 'brotliCompress',
19
- filename: '[path][base].br',
20
- test: DEFAULT_PRECOMPRESS_TEST,
21
- threshold: DEFAULT_PRECOMPRESS_THRESHOLD,
22
- minRatio: DEFAULT_PRECOMPRESS_MIN_RATIO,
23
- compressionOptions: {
24
- params: {
25
- [constants.BROTLI_PARAM_QUALITY]: 9
26
- }
27
- }
28
- });
29
- const mergeCompressionOptions = (base, next)=>{
30
- const merged = {
31
- ...base,
32
- ...next
33
- };
34
- if (base.compressionOptions || next.compressionOptions) {
35
- const baseCompressionOptions = base.compressionOptions;
36
- const nextCompressionOptions = next.compressionOptions;
37
- const mergedCompressionOptions = {
38
- ...baseCompressionOptions,
39
- ...nextCompressionOptions
40
- };
41
- if (baseCompressionOptions?.params || nextCompressionOptions?.params) mergedCompressionOptions.params = {
42
- ...baseCompressionOptions?.params,
43
- ...nextCompressionOptions?.params
44
- };
45
- merged.compressionOptions = mergedCompressionOptions;
46
- }
47
- return merged;
48
- };
49
- const resolveCodecOptions = (codecConfig, createDefaultOptions)=>{
50
- if (false === codecConfig) return null;
51
- if (void 0 === codecConfig || true === codecConfig) return createDefaultOptions();
52
- return mergeCompressionOptions(createDefaultOptions(), codecConfig);
53
- };
54
- const resolvePrecompressConfig = (normalizedConfig)=>{
55
- const precompress = normalizedConfig.output.precompress;
56
- if (false === precompress || void 0 === precompress) return false;
57
- if (true === precompress) return {};
58
- return precompress;
59
- };
60
- const builderPluginAdapterPrecompress = (options)=>({
61
- name: 'builder-plugin-adapter-modern-precompress',
62
- setup (api) {
63
- api.modifyBundlerChain((chain, { isProd, target })=>{
64
- if (!isProd || 'web' !== target) return;
65
- const precompressConfig = resolvePrecompressConfig(options.normalizedConfig);
66
- if (false === precompressConfig) return;
67
- const gzipOptions = resolveCodecOptions(precompressConfig.gzip, createDefaultGzipOptions);
68
- if (gzipOptions) chain.plugin('modern-precompress-gzip').use(compression_webpack_plugin, [
69
- gzipOptions
70
- ]);
71
- const brotliOptions = resolveCodecOptions(precompressConfig.brotli, createDefaultBrotliOptions);
72
- if (brotliOptions) chain.plugin('modern-precompress-brotli').use(compression_webpack_plugin, [
73
- brotliOptions
74
- ]);
75
- });
76
- }
77
- });
78
- export { builderPluginAdapterPrecompress };
@@ -1,225 +0,0 @@
1
- import "node:module";
2
- import { execFileSync } from "node:child_process";
3
- import { createHash } from "node:crypto";
4
- import { accessSync, chmodSync, constants, lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from "node:fs";
5
- import { createRequire } from "node:module";
6
- import { tmpdir } from "node:os";
7
- import { basename, dirname, join, resolve } from "node:path";
8
- const EFFECT_TSGO_PACKAGE = '@effect/tsgo';
9
- const EFFECT_TSGO_BIN = 'effect-tsgo';
10
- const EFFECT_TSGO_RESOLUTION_ERROR = 'Unable to resolve the Effect TS-Go compiler. Install "@effect/tsgo" and a native TypeScript backend for this build config, or set EFFECT_TSGO_BIN.';
11
- const executableEffectTsgoCompilers = new Map();
12
- const BUILD_CONFIG_ENVIRONMENT_PLUGIN = 'ModernJsBuildConfigEnvironmentLeasePlugin';
13
- const ENVIRONMENT_LEASE_REGISTRY_KEY = Symbol.for('@modern-js/app-tools/build-config-environment-lease-registry/v1');
14
- const ENVIRONMENT_LEASE_REGISTRY_BRAND = Symbol.for('@modern-js/app-tools/build-config-environment-lease-registry-brand/v1');
15
- const LIFECYCLE_HOOK_NAMES = [
16
- 'run',
17
- 'watchRun',
18
- 'afterDone',
19
- 'failed',
20
- 'shutdown',
21
- 'watchClose'
22
- ];
23
- function restoreEnvironment(name, value) {
24
- if (void 0 === value) delete process.env[name];
25
- else process.env[name] = value;
26
- }
27
- function createEnvironmentLeaseRegistry() {
28
- const environmentLeases = new Map();
29
- return Object.freeze({
30
- acquire (name, value) {
31
- let lease = environmentLeases.get(name);
32
- if (lease) {
33
- if (lease.value !== value) throw new Error(`Build config environment "${name}" already has an active lease for a different value.`);
34
- if (process.env[name] !== lease.value) throw new Error(`Build config environment lease for "${name}" lost ownership before another lease was acquired.`);
35
- } else {
36
- lease = {
37
- originalValue: process.env[name],
38
- owners: new Set(),
39
- value
40
- };
41
- process.env[name] = value;
42
- environmentLeases.set(name, lease);
43
- }
44
- const owner = Symbol(name);
45
- lease.owners.add(owner);
46
- let released = false;
47
- return ()=>{
48
- if (released) return;
49
- if (environmentLeases.get(name) !== lease || !lease.owners.has(owner)) throw new Error(`Build config environment lease for "${name}" cannot be restored because its ownership record was lost.`);
50
- released = true;
51
- const lostOwnership = process.env[name] !== lease.value;
52
- lease.owners.delete(owner);
53
- if (0 === lease.owners.size) {
54
- environmentLeases.delete(name);
55
- restoreEnvironment(name, lease.originalValue);
56
- } else if (lostOwnership) process.env[name] = lease.value;
57
- if (lostOwnership) throw new Error(`Build config environment lease for "${name}" lost ownership before restoration.`);
58
- };
59
- },
60
- brand: ENVIRONMENT_LEASE_REGISTRY_BRAND
61
- });
62
- }
63
- function getEnvironmentLeaseRegistry() {
64
- const descriptor = Object.getOwnPropertyDescriptor(process, ENVIRONMENT_LEASE_REGISTRY_KEY);
65
- if (descriptor) {
66
- const registry = descriptor.value;
67
- if (descriptor.configurable || descriptor.enumerable || descriptor.writable || registry?.brand !== ENVIRONMENT_LEASE_REGISTRY_BRAND || 'function' != typeof registry.acquire) throw new Error('The process-global build config environment lease registry is occupied by an incompatible value.');
68
- return registry;
69
- }
70
- const registry = createEnvironmentLeaseRegistry();
71
- Object.defineProperty(process, ENVIRONMENT_LEASE_REGISTRY_KEY, {
72
- configurable: false,
73
- enumerable: false,
74
- value: registry,
75
- writable: false
76
- });
77
- return registry;
78
- }
79
- function acquireEnvironmentLease(name, value) {
80
- return getEnvironmentLeaseRegistry().acquire(name, value);
81
- }
82
- function releaseAfterFailure(release, originalError) {
83
- try {
84
- release();
85
- } catch (restorationError) {
86
- throw new AggregateError([
87
- originalError,
88
- restorationError
89
- ], 'Build config environment setup and restoration both failed.');
90
- }
91
- throw originalError;
92
- }
93
- class BuildConfigEnvironmentLeasePlugin {
94
- apply(compiler) {
95
- const hooks = compiler.hooks;
96
- try {
97
- const lifecycleHooks = {};
98
- for (const hookName of LIFECYCLE_HOOK_NAMES){
99
- const hook = hooks[hookName];
100
- if (!hook || 'function' != typeof hook.tap) throw new Error(`Rspack does not expose the "${hookName}" lifecycle hook required to restore build config environment leases.`);
101
- lifecycleHooks[hookName] = hook;
102
- }
103
- let mode = 'pending';
104
- const modeTap = {
105
- name: BUILD_CONFIG_ENVIRONMENT_PLUGIN,
106
- stage: Number.MIN_SAFE_INTEGER
107
- };
108
- const releaseTap = {
109
- name: BUILD_CONFIG_ENVIRONMENT_PLUGIN,
110
- stage: Number.MAX_SAFE_INTEGER
111
- };
112
- const releaseAfterOneShot = ()=>{
113
- if ('watch' !== mode && true !== compiler.watchMode) this.release();
114
- };
115
- lifecycleHooks.run.tap(modeTap, ()=>{
116
- mode = 'run';
117
- });
118
- lifecycleHooks.watchRun.tap(modeTap, ()=>{
119
- mode = 'watch';
120
- });
121
- lifecycleHooks.afterDone.tap(releaseTap, releaseAfterOneShot);
122
- lifecycleHooks.failed.tap(releaseTap, releaseAfterOneShot);
123
- lifecycleHooks.shutdown.tap(releaseTap, this.release);
124
- lifecycleHooks.watchClose.tap(releaseTap, this.release);
125
- } catch (error) {
126
- releaseAfterFailure(this.release, error);
127
- }
128
- }
129
- constructor(release){
130
- this.release = release;
131
- }
132
- }
133
- function resolveEffectTsgoCli(from) {
134
- const projectRequire = createRequire(from);
135
- const packageJsonPath = projectRequire.resolve(`${EFFECT_TSGO_PACKAGE}/package.json`);
136
- const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
137
- const bin = 'string' == typeof packageJson.bin ? packageJson.bin : packageJson.bin?.[EFFECT_TSGO_BIN];
138
- if (!bin) throw new Error(EFFECT_TSGO_RESOLUTION_ERROR);
139
- return resolve(dirname(packageJsonPath), bin);
140
- }
141
- function resolveExecutableEffectTsgoCompiler(compilerPath) {
142
- if ('win32' === process.platform) return compilerPath;
143
- const sourcePath = realpathSync(compilerPath);
144
- const source = lstatSync(sourcePath);
145
- if (!source.isFile()) throw new Error(EFFECT_TSGO_RESOLUTION_ERROR);
146
- try {
147
- accessSync(sourcePath, constants.X_OK);
148
- return compilerPath;
149
- } catch {}
150
- const cachedCompiler = executableEffectTsgoCompilers.get(sourcePath);
151
- if (cachedCompiler) try {
152
- accessSync(cachedCompiler, constants.X_OK);
153
- return cachedCompiler;
154
- } catch {
155
- executableEffectTsgoCompilers.delete(sourcePath);
156
- }
157
- const compilerBytes = readFileSync(sourcePath);
158
- const compilerDigest = createHash('sha256').update(compilerBytes).digest('hex');
159
- const compilerDirectory = join(tmpdir(), 'modern-js', 'effect-tsgo', compilerDigest);
160
- mkdirSync(compilerDirectory, {
161
- recursive: true,
162
- mode: 448
163
- });
164
- const executableCompiler = join(compilerDirectory, basename(sourcePath));
165
- try {
166
- accessSync(executableCompiler, constants.X_OK);
167
- } catch {
168
- const temporaryCompiler = join(compilerDirectory, `.${basename(sourcePath)}.${process.pid}.tmp`);
169
- rmSync(temporaryCompiler, {
170
- force: true
171
- });
172
- try {
173
- writeFileSync(temporaryCompiler, compilerBytes, {
174
- flag: 'wx',
175
- mode: 448
176
- });
177
- chmodSync(temporaryCompiler, 448);
178
- renameSync(temporaryCompiler, executableCompiler);
179
- } finally{
180
- rmSync(temporaryCompiler, {
181
- force: true
182
- });
183
- }
184
- }
185
- accessSync(executableCompiler, constants.X_OK);
186
- executableEffectTsgoCompilers.set(sourcePath, executableCompiler);
187
- return executableCompiler;
188
- }
189
- function getBuildConfigEnvironment(name) {
190
- return process.env[name];
191
- }
192
- function withBuildConfigEnvironment(name, value, setup) {
193
- return async (config, ...args)=>{
194
- const release = acquireEnvironmentLease(name, value);
195
- try {
196
- const configured = await setup(config, ...args) ?? config;
197
- configured.plugins = [
198
- ...configured.plugins ?? [],
199
- new BuildConfigEnvironmentLeasePlugin(release)
200
- ];
201
- return configured;
202
- } catch (error) {
203
- releaseAfterFailure(release, error);
204
- }
205
- };
206
- }
207
- function resolveEffectTsgoCompiler(options) {
208
- const configuredCompiler = getBuildConfigEnvironment('EFFECT_TSGO_BIN')?.trim();
209
- if (configuredCompiler) try {
210
- return resolveExecutableEffectTsgoCompiler(configuredCompiler);
211
- } catch {
212
- throw new Error(EFFECT_TSGO_RESOLUTION_ERROR);
213
- }
214
- try {
215
- const compiler = execFileSync(process.execPath, [
216
- resolveEffectTsgoCli(options.from),
217
- 'get-exe-path'
218
- ], {
219
- encoding: 'utf-8'
220
- }).trim();
221
- if (compiler) return resolveExecutableEffectTsgoCompiler(compiler);
222
- } catch {}
223
- throw new Error(EFFECT_TSGO_RESOLUTION_ERROR);
224
- }
225
- export { getBuildConfigEnvironment, resolveEffectTsgoCompiler, withBuildConfigEnvironment };
@@ -1,2 +0,0 @@
1
- import "node:module";
2
- export { getBuildConfigEnvironment, resolveEffectTsgoCompiler, withBuildConfigEnvironment } from "./build-environment.mjs";
@@ -1,206 +0,0 @@
1
- import "node:module";
2
- import node_path from "node:path";
3
- import { BACKEND_FEDERATION_CONTRACT_VERSION, BACKEND_FEDERATION_EFFECT_EXPOSE, BACKEND_FEDERATION_NODE_ADAPTER_VERSION, BACKEND_FEDERATION_REMOTE_ENTRY_FILE, formatBackendFederationValidationErrors, validateBackendFederationManifest } from "@modern-js/utils/universal";
4
- import { build } from "esbuild";
5
- import { normalizeRelativePath } from "./config.mjs";
6
- const createRelativeImportSpecifier = (fromDirectory, toFile)=>{
7
- const relativePath = normalizeRelativePath(node_path.relative(fromDirectory, toFile));
8
- return relativePath.startsWith('.') ? relativePath : `./${relativePath}`;
9
- };
10
- const createPublicPath = (containerEntry, fallbackPort)=>{
11
- try {
12
- return new URL('.', containerEntry).href;
13
- } catch {
14
- const slashIndex = containerEntry.lastIndexOf('/');
15
- if (slashIndex >= 0) return containerEntry.slice(0, slashIndex + 1);
16
- return `http://localhost:${fallbackPort}/`;
17
- }
18
- };
19
- const createBackendRemoteEntrySource = async (workspaceRoot, app, effectApiPath, entryPath)=>{
20
- const effectApiSpecifier = createRelativeImportSpecifier(node_path.dirname(effectApiPath), effectApiPath);
21
- const containerMetadata = {
22
- buildVersion: app.buildVersion,
23
- expose: BACKEND_FEDERATION_EFFECT_EXPOSE,
24
- name: app.backendName,
25
- packageName: app.packageName,
26
- remoteType: app.remoteType,
27
- source: normalizeRelativePath(node_path.relative(workspaceRoot, effectApiPath)),
28
- version: app.version,
29
- ...app.unitId ? {
30
- unitId: app.unitId
31
- } : {},
32
- ...app.sourceRevision ? {
33
- sourceRevision: app.sourceRevision
34
- } : {}
35
- };
36
- const compatibility = {
37
- build: app.buildVersion,
38
- contractVersion: BACKEND_FEDERATION_CONTRACT_VERSION,
39
- nodeAdapterVersion: BACKEND_FEDERATION_NODE_ADAPTER_VERSION,
40
- packageName: app.packageName,
41
- ...app.unitId ? {
42
- unitId: app.unitId
43
- } : {},
44
- ...app.sourceRevision ? {
45
- sourceRevision: app.sourceRevision
46
- } : {}
47
- };
48
- const source = `// Generated by Modern.js backend federation build.
49
- import * as exposedNamespace from ${JSON.stringify(effectApiSpecifier)};
50
-
51
- const exposedModule = {
52
- ...exposedNamespace,
53
- backendFederationContract: {
54
- ...(exposedNamespace.backendFederationContract ?? {}),
55
- compatibility: {
56
- ...(exposedNamespace.backendFederationContract?.compatibility ?? {}),
57
- ...${JSON.stringify(compatibility)},
58
- },
59
- name: ${JSON.stringify(app.backendName)},
60
- role: 'microvertical-server',
61
- runtimeFramework: 'effect',
62
- strictEffectApproach: true,
63
- },
64
- };
65
- const exposedModules = {
66
- ${JSON.stringify(BACKEND_FEDERATION_EFFECT_EXPOSE)}: () => Promise.resolve(exposedModule),
67
- };
68
- const __modernjsBackendFederation = ${JSON.stringify(containerMetadata)};
69
-
70
- function init() {}
71
-
72
- function get(id) {
73
- const load = exposedModules[id];
74
- if (!load) {
75
- throw new Error(\`Unexpected backend federation expose: \${id}\`);
76
- }
77
-
78
- return async () => load();
79
- }
80
-
81
- module.exports = { __modernjsBackendFederation, get, init };
82
- `;
83
- const result = await build({
84
- absWorkingDir: node_path.dirname(effectApiPath),
85
- bundle: true,
86
- format: 'cjs',
87
- logLevel: 'silent',
88
- platform: 'node',
89
- stdin: {
90
- contents: source,
91
- loader: 'ts',
92
- resolveDir: node_path.dirname(effectApiPath),
93
- sourcefile: node_path.basename(entryPath)
94
- },
95
- target: 'node20',
96
- write: false
97
- });
98
- const output = result.outputFiles[0];
99
- if (!output) throw new Error('[backend-federation-build] CommonJS backend federation container emitted no output.');
100
- return output.text;
101
- };
102
- const createBackendManifest = (workspaceRoot, distDirectory, app, entryIntegrity)=>{
103
- const sourceModule = `${app.directory}/api/effect-api.ts`;
104
- const publicPath = createPublicPath(app.containerEntry, app.port);
105
- const manifest = {
106
- schemaVersion: 1,
107
- id: app.backendName,
108
- name: app.backendName,
109
- version: app.version,
110
- buildVersion: app.buildVersion,
111
- metaData: {
112
- name: app.backendName,
113
- type: 'backend',
114
- buildInfo: {
115
- buildVersion: app.buildVersion,
116
- buildName: app.packageName
117
- },
118
- remoteEntry: {
119
- name: BACKEND_FEDERATION_REMOTE_ENTRY_FILE,
120
- path: '',
121
- type: app.remoteType
122
- },
123
- globalName: app.backendName,
124
- publicPath,
125
- ssrRemoteEntry: {
126
- name: BACKEND_FEDERATION_REMOTE_ENTRY_FILE,
127
- path: '',
128
- type: app.remoteType
129
- },
130
- ssrPublicPath: publicPath
131
- },
132
- entry: {
133
- ...entryIntegrity,
134
- file: BACKEND_FEDERATION_REMOTE_ENTRY_FILE,
135
- path: normalizeRelativePath(node_path.relative(workspaceRoot, node_path.join(distDirectory, BACKEND_FEDERATION_REMOTE_ENTRY_FILE))),
136
- type: app.remoteType,
137
- url: app.containerEntry
138
- },
139
- exposes: [
140
- {
141
- id: `${app.backendName}:${BACKEND_FEDERATION_EFFECT_EXPOSE}`,
142
- name: BACKEND_FEDERATION_EFFECT_EXPOSE,
143
- path: '',
144
- assets: {
145
- js: {
146
- async: [],
147
- sync: [
148
- BACKEND_FEDERATION_REMOTE_ENTRY_FILE
149
- ]
150
- },
151
- css: {
152
- async: [],
153
- sync: []
154
- }
155
- }
156
- }
157
- ],
158
- shared: [],
159
- backendFederation: {
160
- role: 'microvertical-server',
161
- appId: app.id,
162
- name: app.backendName,
163
- runtimeFramework: 'effect',
164
- strictEffectApproach: true,
165
- contractVersion: BACKEND_FEDERATION_CONTRACT_VERSION,
166
- nodeAdapterVersion: BACKEND_FEDERATION_NODE_ADAPTER_VERSION,
167
- remoteType: app.remoteType,
168
- expose: BACKEND_FEDERATION_EFFECT_EXPOSE,
169
- manifestUrl: app.manifestUrl,
170
- containerEntry: app.containerEntry,
171
- source: {
172
- module: sourceModule
173
- },
174
- readinessPath: `${app.apiPrefix}/${app.apiStem}/readiness`,
175
- openapiPath: `${app.apiPrefix}/openapi.json`,
176
- ...app.deliveryUnit ? {
177
- deliveryUnit: app.deliveryUnit
178
- } : {},
179
- versionBoundary: {
180
- invariant: 'web-and-api-same-build',
181
- packageName: app.packageName,
182
- version: app.version,
183
- buildVersion: app.buildVersion,
184
- ...app.uiManifestUrl ? {
185
- uiManifestUrl: app.uiManifestUrl
186
- } : {},
187
- ...app.deliveryUnit ? {
188
- deliveryUnit: {
189
- unitId: app.deliveryUnit.unitId,
190
- buildMarker: app.deliveryUnit.buildMarker,
191
- sourceRevision: app.deliveryUnit.sourceRevision
192
- }
193
- } : {}
194
- }
195
- }
196
- };
197
- const validation = validateBackendFederationManifest(manifest, {
198
- path: 'backendFederationManifest',
199
- requireEffectExpose: true,
200
- requireEffectRuntime: true,
201
- requireVersionFields: true
202
- });
203
- if (!validation.ok) throw new Error(`[backend-federation-build] Invalid backend federation manifest: ${formatBackendFederationValidationErrors(validation.errors)}.`);
204
- return manifest;
205
- };
206
- export { createBackendManifest, createBackendRemoteEntrySource };