@nx/webpack 20.2.0-beta.2 → 20.2.0-beta.4

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 (34) hide show
  1. package/index.d.ts +0 -1
  2. package/index.js +0 -1
  3. package/package.json +3 -7
  4. package/src/generators/configuration/configuration.js +0 -2
  5. package/src/generators/init/init.js +0 -2
  6. package/src/plugins/nx-webpack-plugin/lib/apply-base-config.js +1 -0
  7. package/src/utils/module-federation/dependencies.d.ts +0 -6
  8. package/src/utils/module-federation/dependencies.js +0 -56
  9. package/src/utils/module-federation/get-remotes-for-host.d.ts +0 -16
  10. package/src/utils/module-federation/get-remotes-for-host.js +0 -97
  11. package/src/utils/module-federation/index.d.ts +0 -6
  12. package/src/utils/module-federation/index.js +0 -9
  13. package/src/utils/module-federation/models/index.d.ts +0 -47
  14. package/src/utils/module-federation/models/index.js +0 -2
  15. package/src/utils/module-federation/package-json.d.ts +0 -8
  16. package/src/utils/module-federation/package-json.js +0 -12
  17. package/src/utils/module-federation/parse-static-remotes-config.d.ts +0 -13
  18. package/src/utils/module-federation/parse-static-remotes-config.js +0 -34
  19. package/src/utils/module-federation/plugins/runtime-library-control.plugin.d.ts +0 -3
  20. package/src/utils/module-federation/plugins/runtime-library-control.plugin.js +0 -54
  21. package/src/utils/module-federation/public-api.d.ts +0 -6
  22. package/src/utils/module-federation/public-api.js +0 -16
  23. package/src/utils/module-federation/remotes.d.ts +0 -19
  24. package/src/utils/module-federation/remotes.js +0 -89
  25. package/src/utils/module-federation/secondary-entry-points.d.ts +0 -12
  26. package/src/utils/module-federation/secondary-entry-points.js +0 -125
  27. package/src/utils/module-federation/share.d.ts +0 -48
  28. package/src/utils/module-federation/share.js +0 -240
  29. package/src/utils/module-federation/start-remote-proxies.d.ts +0 -5
  30. package/src/utils/module-federation/start-remote-proxies.js +0 -38
  31. package/src/utils/module-federation/start-ssr-remote-proxies.d.ts +0 -5
  32. package/src/utils/module-federation/start-ssr-remote-proxies.js +0 -52
  33. package/src/utils/module-federation/typescript.d.ts +0 -4
  34. package/src/utils/module-federation/typescript.js +0 -53
package/index.d.ts CHANGED
@@ -21,5 +21,4 @@ export * from './src/executors/webpack/webpack.impl';
21
21
  export * from './src/utils/get-css-module-local-ident';
22
22
  export * from './src/utils/with-nx';
23
23
  export * from './src/utils/with-web';
24
- export * from './src/utils/module-federation/public-api';
25
24
  export * from './src/utils/e2e-web-server-info-utils';
package/index.js CHANGED
@@ -28,5 +28,4 @@ tslib_1.__exportStar(require("./src/executors/webpack/webpack.impl"), exports);
28
28
  tslib_1.__exportStar(require("./src/utils/get-css-module-local-ident"), exports);
29
29
  tslib_1.__exportStar(require("./src/utils/with-nx"), exports);
30
30
  tslib_1.__exportStar(require("./src/utils/with-web"), exports);
31
- tslib_1.__exportStar(require("./src/utils/module-federation/public-api"), exports);
32
31
  tslib_1.__exportStar(require("./src/utils/e2e-web-server-info-utils"), exports);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nx/webpack",
3
- "version": "20.2.0-beta.2",
3
+ "version": "20.2.0-beta.4",
4
4
  "private": false,
5
5
  "description": "The Nx Plugin for Webpack contains executors and generators that support building applications using Webpack.",
6
6
  "repository": {
@@ -32,8 +32,6 @@
32
32
  "dependencies": {
33
33
  "@babel/core": "^7.23.2",
34
34
  "@phenomnomnominal/tsquery": "~5.0.1",
35
- "@module-federation/sdk": "^0.6.0",
36
- "@module-federation/enhanced": "^0.6.0",
37
35
  "ajv": "^8.12.0",
38
36
  "autoprefixer": "^10.4.9",
39
37
  "babel-loader": "^9.1.2",
@@ -42,9 +40,7 @@
42
40
  "copy-webpack-plugin": "^10.2.4",
43
41
  "css-loader": "^6.4.0",
44
42
  "css-minimizer-webpack-plugin": "^5.0.0",
45
- "express": "^4.19.2",
46
43
  "fork-ts-checker-webpack-plugin": "7.2.13",
47
- "http-proxy-middleware": "^3.0.3",
48
44
  "less": "4.1.3",
49
45
  "less-loader": "11.1.0",
50
46
  "license-webpack-plugin": "^4.0.2",
@@ -69,8 +65,8 @@
69
65
  "webpack-dev-server": "^5.0.4",
70
66
  "webpack-node-externals": "^3.0.0",
71
67
  "webpack-subresource-integrity": "^5.1.0",
72
- "@nx/devkit": "20.2.0-beta.2",
73
- "@nx/js": "20.2.0-beta.2"
68
+ "@nx/devkit": "20.2.0-beta.4",
69
+ "@nx/js": "20.2.0-beta.4"
74
70
  },
75
71
  "publishConfig": {
76
72
  "access": "public"
@@ -7,12 +7,10 @@ const init_1 = require("../init/init");
7
7
  const has_plugin_1 = require("../../utils/has-plugin");
8
8
  const target_defaults_utils_1 = require("@nx/devkit/src/generators/target-defaults-utils");
9
9
  const ensure_dependencies_1 = require("../../utils/ensure-dependencies");
10
- const ts_solution_setup_1 = require("@nx/js/src/utils/typescript/ts-solution-setup");
11
10
  function configurationGenerator(tree, options) {
12
11
  return configurationGeneratorInternal(tree, { addPlugin: false, ...options });
13
12
  }
14
13
  async function configurationGeneratorInternal(tree, options) {
15
- (0, ts_solution_setup_1.assertNotUsingTsSolutionSetup)(tree, 'webpack', 'configuration');
16
14
  const tasks = [];
17
15
  const nxJson = (0, devkit_1.readNxJson)(tree);
18
16
  const addPluginDefault = process.env.NX_ADD_PLUGINS !== 'false' &&
@@ -4,14 +4,12 @@ exports.webpackInitGenerator = webpackInitGenerator;
4
4
  exports.webpackInitGeneratorInternal = webpackInitGeneratorInternal;
5
5
  const devkit_1 = require("@nx/devkit");
6
6
  const add_plugin_1 = require("@nx/devkit/src/utils/add-plugin");
7
- const ts_solution_setup_1 = require("@nx/js/src/utils/typescript/ts-solution-setup");
8
7
  const plugin_1 = require("../../plugins/plugin");
9
8
  const versions_1 = require("../../utils/versions");
10
9
  function webpackInitGenerator(tree, schema) {
11
10
  return webpackInitGeneratorInternal(tree, { addPlugin: false, ...schema });
12
11
  }
13
12
  async function webpackInitGeneratorInternal(tree, schema) {
14
- (0, ts_solution_setup_1.assertNotUsingTsSolutionSetup)(tree, 'webpack', 'init');
15
13
  const nxJson = (0, devkit_1.readNxJson)(tree);
16
14
  const addPluginDefault = process.env.NX_ADD_PLUGINS !== 'false' &&
17
15
  nxJson.useInferencePlugins !== false;
@@ -96,6 +96,7 @@ function applyNxIndependentConfig(options, config) {
96
96
  config.experiments = { ...config.experiments, cacheUnaffected: true };
97
97
  config.ignoreWarnings = [
98
98
  (x) => IGNORED_WEBPACK_WARNINGS.some((r) => typeof x === 'string' ? r.test(x) : r.test(x.message)),
99
+ ...(config.ignoreWarnings ?? []),
99
100
  ];
100
101
  config.optimization = {
101
102
  ...config.optimization,
@@ -1,6 +0,0 @@
1
- import type { ProjectGraph } from '@nx/devkit';
2
- import type { WorkspaceLibrary } from './models';
3
- export declare function getDependentPackagesForProject(projectGraph: ProjectGraph, name: string): {
4
- workspaceLibraries: WorkspaceLibrary[];
5
- npmPackages: string[];
6
- };
@@ -1,56 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getDependentPackagesForProject = getDependentPackagesForProject;
4
- const typescript_1 = require("./typescript");
5
- const devkit_1 = require("@nx/devkit");
6
- function getDependentPackagesForProject(projectGraph, name) {
7
- const { npmPackages, workspaceLibraries } = collectDependencies(projectGraph, name);
8
- return {
9
- workspaceLibraries: [...workspaceLibraries.values()],
10
- npmPackages: [...npmPackages],
11
- };
12
- }
13
- function collectDependencies(projectGraph, name, dependencies = {
14
- workspaceLibraries: new Map(),
15
- npmPackages: new Set(),
16
- }, seen = new Set()) {
17
- if (seen.has(name)) {
18
- return dependencies;
19
- }
20
- seen.add(name);
21
- (projectGraph.dependencies[name] ?? []).forEach((dependency) => {
22
- if (dependency.target.startsWith('npm:')) {
23
- dependencies.npmPackages.add(dependency.target.replace('npm:', ''));
24
- }
25
- else {
26
- dependencies.workspaceLibraries.set(dependency.target, {
27
- name: dependency.target,
28
- root: projectGraph.nodes[dependency.target].data.root,
29
- importKey: getLibraryImportPath(dependency.target, projectGraph),
30
- });
31
- collectDependencies(projectGraph, dependency.target, dependencies, seen);
32
- }
33
- });
34
- return dependencies;
35
- }
36
- function getLibraryImportPath(library, projectGraph) {
37
- let buildLibsFromSource = true;
38
- if (process.env.NX_BUILD_LIBS_FROM_SOURCE) {
39
- buildLibsFromSource = process.env.NX_BUILD_LIBS_FROM_SOURCE === 'true';
40
- }
41
- const libraryNode = projectGraph.nodes[library];
42
- let sourceRoots = [libraryNode.data.sourceRoot];
43
- if (!buildLibsFromSource && process.env.NX_BUILD_TARGET) {
44
- const buildTarget = (0, devkit_1.parseTargetString)(process.env.NX_BUILD_TARGET, projectGraph);
45
- sourceRoots = (0, devkit_1.getOutputsForTargetAndConfiguration)(buildTarget, {}, libraryNode);
46
- }
47
- const tsConfigPathMappings = (0, typescript_1.readTsPathMappings)();
48
- for (const [key, value] of Object.entries(tsConfigPathMappings)) {
49
- for (const src of sourceRoots) {
50
- if (value.find((path) => path.startsWith(src))) {
51
- return key;
52
- }
53
- }
54
- }
55
- return undefined;
56
- }
@@ -1,16 +0,0 @@
1
- import { type ProjectGraph } from '@nx/devkit';
2
- import { ModuleFederationConfig } from './models/index';
3
- interface ModuleFederationExecutorContext {
4
- projectName: string;
5
- projectGraph: ProjectGraph;
6
- root: string;
7
- }
8
- export declare function getRemotes(devRemotes: string[], skipRemotes: string[], config: ModuleFederationConfig, context: ModuleFederationExecutorContext, pathToManifestFile?: string): {
9
- staticRemotes: string[];
10
- devRemotes: any[];
11
- dynamicRemotes: any[];
12
- remotePorts: any[];
13
- staticRemotePort: number;
14
- };
15
- export declare function getModuleFederationConfig(tsconfigPath: string, workspaceRoot: string, projectRoot: string, pluginName?: 'react' | 'angular'): any;
16
- export {};
@@ -1,97 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.getRemotes = getRemotes;
4
- exports.getModuleFederationConfig = getModuleFederationConfig;
5
- const devkit_1 = require("@nx/devkit");
6
- const internal_1 = require("@nx/js/src/internal");
7
- const find_matching_projects_1 = require("nx/src/utils/find-matching-projects");
8
- const pc = require("picocolors");
9
- const path_1 = require("path");
10
- const fs_1 = require("fs");
11
- function extractRemoteProjectsFromConfig(config, pathToManifestFile) {
12
- const remotes = [];
13
- const dynamicRemotes = [];
14
- if (pathToManifestFile && (0, fs_1.existsSync)(pathToManifestFile)) {
15
- const moduleFederationManifestJson = (0, fs_1.readFileSync)(pathToManifestFile, 'utf-8');
16
- if (moduleFederationManifestJson) {
17
- // This should have shape of
18
- // {
19
- // "remoteName": "remoteLocation",
20
- // }
21
- const parsedManifest = JSON.parse(moduleFederationManifestJson);
22
- if (Object.keys(parsedManifest).every((key) => typeof key === 'string' && typeof parsedManifest[key] === 'string')) {
23
- dynamicRemotes.push(...Object.keys(parsedManifest));
24
- }
25
- }
26
- }
27
- const staticRemotes = config.remotes?.map((r) => (Array.isArray(r) ? r[0] : r)) ?? [];
28
- remotes.push(...staticRemotes);
29
- return { remotes, dynamicRemotes };
30
- }
31
- function collectRemoteProjects(remote, collected, context) {
32
- const remoteProject = context.projectGraph.nodes[remote]?.data;
33
- if (!context.projectGraph.nodes[remote] || collected.has(remote)) {
34
- return;
35
- }
36
- collected.add(remote);
37
- const remoteProjectRoot = remoteProject.root;
38
- const remoteProjectTsConfig = remoteProject.targets['build'].options.tsConfig;
39
- const remoteProjectConfig = getModuleFederationConfig(remoteProjectTsConfig, context.root, remoteProjectRoot);
40
- const { remotes: remoteProjectRemotes } = extractRemoteProjectsFromConfig(remoteProjectConfig);
41
- remoteProjectRemotes.forEach((r) => collectRemoteProjects(r, collected, context));
42
- }
43
- function getRemotes(devRemotes, skipRemotes, config, context, pathToManifestFile) {
44
- const collectedRemotes = new Set();
45
- const { remotes, dynamicRemotes } = extractRemoteProjectsFromConfig(config, pathToManifestFile);
46
- remotes.forEach((r) => collectRemoteProjects(r, collectedRemotes, context));
47
- const remotesToSkip = new Set((0, find_matching_projects_1.findMatchingProjects)(skipRemotes, context.projectGraph.nodes) ?? []);
48
- if (remotesToSkip.size > 0) {
49
- devkit_1.logger.info(`Remotes not served automatically: ${[...remotesToSkip.values()].join(', ')}`);
50
- }
51
- const knownRemotes = Array.from(collectedRemotes).filter((r) => !remotesToSkip.has(r));
52
- const knownDynamicRemotes = dynamicRemotes.filter((r) => !remotesToSkip.has(r) && context.projectGraph.nodes[r]);
53
- devkit_1.logger.info(`NX Starting module federation dev-server for ${pc.bold(context.projectName)} with ${[...knownRemotes, ...knownDynamicRemotes].length} remotes`);
54
- const devServeApps = new Set(!devRemotes
55
- ? []
56
- : Array.isArray(devRemotes)
57
- ? (0, find_matching_projects_1.findMatchingProjects)(devRemotes, context.projectGraph.nodes)
58
- : (0, find_matching_projects_1.findMatchingProjects)([devRemotes], context.projectGraph.nodes));
59
- const staticRemotes = knownRemotes.filter((r) => !devServeApps.has(r));
60
- const devServeRemotes = [...knownRemotes, ...knownDynamicRemotes].filter((r) => devServeApps.has(r));
61
- const staticDynamicRemotes = knownDynamicRemotes.filter((r) => !devServeApps.has(r));
62
- const remotePorts = [...devServeRemotes, ...staticDynamicRemotes].map((r) => context.projectGraph.nodes[r].data.targets['serve'].options.port);
63
- const staticRemotePort = Math.max(...[
64
- ...remotePorts,
65
- ...staticRemotes.map((r) => context.projectGraph.nodes[r].data.targets['serve'].options.port),
66
- ]) +
67
- (remotesToSkip.size + 1);
68
- return {
69
- staticRemotes,
70
- devRemotes: devServeRemotes,
71
- dynamicRemotes: staticDynamicRemotes,
72
- remotePorts,
73
- staticRemotePort,
74
- };
75
- }
76
- function getModuleFederationConfig(tsconfigPath, workspaceRoot, projectRoot, pluginName = 'react') {
77
- const moduleFederationConfigPathJS = (0, path_1.join)(workspaceRoot, projectRoot, 'module-federation.config.js');
78
- const moduleFederationConfigPathTS = (0, path_1.join)(workspaceRoot, projectRoot, 'module-federation.config.ts');
79
- let moduleFederationConfigPath = moduleFederationConfigPathJS;
80
- // create a no-op so this can be called with issue
81
- const fullTSconfigPath = tsconfigPath.startsWith(workspaceRoot)
82
- ? tsconfigPath
83
- : (0, path_1.join)(workspaceRoot, tsconfigPath);
84
- let cleanupTranspiler = () => { };
85
- if ((0, fs_1.existsSync)(moduleFederationConfigPathTS)) {
86
- cleanupTranspiler = (0, internal_1.registerTsProject)(fullTSconfigPath);
87
- moduleFederationConfigPath = moduleFederationConfigPathTS;
88
- }
89
- try {
90
- const config = require(moduleFederationConfigPath);
91
- cleanupTranspiler();
92
- return config.default || config;
93
- }
94
- catch {
95
- throw new Error(`Could not load ${moduleFederationConfigPath}. Was this project generated with "@nx/${pluginName}:host"?\nSee: https://nx.dev/concepts/more-concepts/faster-builds-with-module-federation`);
96
- }
97
- }
@@ -1,6 +0,0 @@
1
- export * from './share';
2
- export * from './dependencies';
3
- export * from './package-json';
4
- export * from './remotes';
5
- export * from './models';
6
- export * from './get-remotes-for-host';
@@ -1,9 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const tslib_1 = require("tslib");
4
- tslib_1.__exportStar(require("./share"), exports);
5
- tslib_1.__exportStar(require("./dependencies"), exports);
6
- tslib_1.__exportStar(require("./package-json"), exports);
7
- tslib_1.__exportStar(require("./remotes"), exports);
8
- tslib_1.__exportStar(require("./models"), exports);
9
- tslib_1.__exportStar(require("./get-remotes-for-host"), exports);
@@ -1,47 +0,0 @@
1
- import type { NormalModuleReplacementPlugin } from 'webpack';
2
- import type { moduleFederationPlugin } from '@module-federation/sdk';
3
- export type ModuleFederationLibrary = {
4
- type: string;
5
- name: string;
6
- };
7
- export type WorkspaceLibrary = {
8
- name: string;
9
- root: string;
10
- importKey: string | undefined;
11
- };
12
- export type SharedWorkspaceLibraryConfig = {
13
- getAliases: () => Record<string, string>;
14
- getLibraries: (projectRoot: string, eager?: boolean) => Record<string, SharedLibraryConfig>;
15
- getReplacementPlugin: () => NormalModuleReplacementPlugin;
16
- };
17
- export type Remotes = Array<string | [remoteName: string, remoteUrl: string]>;
18
- export interface SharedLibraryConfig {
19
- singleton?: boolean;
20
- strictVersion?: boolean;
21
- requiredVersion?: false | string;
22
- eager?: boolean;
23
- }
24
- export type SharedFunction = (libraryName: string, sharedConfig: SharedLibraryConfig) => undefined | false | SharedLibraryConfig;
25
- export type AdditionalSharedConfig = Array<string | [libraryName: string, sharedConfig: SharedLibraryConfig] | {
26
- libraryName: string;
27
- sharedConfig: SharedLibraryConfig;
28
- }>;
29
- export interface ModuleFederationConfig {
30
- name: string;
31
- remotes?: Remotes;
32
- library?: ModuleFederationLibrary;
33
- exposes?: Record<string, string>;
34
- shared?: SharedFunction;
35
- additionalShared?: AdditionalSharedConfig;
36
- /**
37
- * `nxRuntimeLibraryControlPlugin` is a runtime module federation plugin to ensure
38
- * that shared libraries are resolved from a remote with live reload capabilities.
39
- * If you run into any issues with loading shared libraries, try disabling this option.
40
- */
41
- disableNxRuntimeLibraryControlPlugin?: boolean;
42
- }
43
- export type NxModuleFederationConfigOverride = Omit<moduleFederationPlugin.ModuleFederationPluginOptions, 'exposes' | 'remotes' | 'name' | 'library' | 'shared' | 'filename' | 'remoteType'>;
44
- export type WorkspaceLibrarySecondaryEntryPoint = {
45
- name: string;
46
- path: string;
47
- };
@@ -1,2 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
@@ -1,8 +0,0 @@
1
- export declare function readRootPackageJson(): {
2
- dependencies?: {
3
- [key: string]: string;
4
- };
5
- devDependencies?: {
6
- [key: string]: string;
7
- };
8
- };
@@ -1,12 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.readRootPackageJson = readRootPackageJson;
4
- const fs_1 = require("fs");
5
- const devkit_1 = require("@nx/devkit");
6
- function readRootPackageJson() {
7
- const pkgJsonPath = (0, devkit_1.joinPathFragments)(devkit_1.workspaceRoot, 'package.json');
8
- if (!(0, fs_1.existsSync)(pkgJsonPath)) {
9
- throw new Error('NX MF: Could not find root package.json to determine dependency versions.');
10
- }
11
- return (0, devkit_1.readJsonFile)(pkgJsonPath);
12
- }
@@ -1,13 +0,0 @@
1
- import type { ExecutorContext } from '@nx/devkit';
2
- export type StaticRemoteConfig = {
3
- basePath: string;
4
- outputPath: string;
5
- urlSegment: string;
6
- port: number;
7
- };
8
- export type StaticRemotesConfig = {
9
- remotes: string[];
10
- config: Record<string, StaticRemoteConfig> | undefined;
11
- };
12
- export declare function parseStaticRemotesConfig(staticRemotes: string[] | undefined, context: ExecutorContext): StaticRemotesConfig;
13
- export declare function parseStaticSsrRemotesConfig(staticRemotes: string[] | undefined, context: ExecutorContext): StaticRemotesConfig;
@@ -1,34 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.parseStaticRemotesConfig = parseStaticRemotesConfig;
4
- exports.parseStaticSsrRemotesConfig = parseStaticSsrRemotesConfig;
5
- const path_1 = require("path");
6
- function parseStaticRemotesConfig(staticRemotes, context) {
7
- if (!staticRemotes?.length) {
8
- return { remotes: [], config: undefined };
9
- }
10
- const config = {};
11
- for (const app of staticRemotes) {
12
- const outputPath = context.projectGraph.nodes[app].data.targets['build'].options.outputPath;
13
- const basePath = (0, path_1.dirname)(outputPath);
14
- const urlSegment = (0, path_1.basename)(outputPath);
15
- const port = context.projectGraph.nodes[app].data.targets['serve'].options.port;
16
- config[app] = { basePath, outputPath, urlSegment, port };
17
- }
18
- return { remotes: staticRemotes, config };
19
- }
20
- function parseStaticSsrRemotesConfig(staticRemotes, context) {
21
- if (!staticRemotes?.length) {
22
- return { remotes: [], config: undefined };
23
- }
24
- const config = {};
25
- for (const app of staticRemotes) {
26
- const outputPath = (0, path_1.dirname)(context.projectGraph.nodes[app].data.targets['build'].options.outputPath // dist/checkout/browser -> checkout
27
- );
28
- const basePath = (0, path_1.dirname)(outputPath); // dist/checkout -> dist
29
- const urlSegment = (0, path_1.basename)(outputPath); // dist/checkout -> checkout
30
- const port = context.projectGraph.nodes[app].data.targets['serve'].options.port;
31
- config[app] = { basePath, outputPath, urlSegment, port };
32
- }
33
- return { remotes: staticRemotes, config };
34
- }
@@ -1,3 +0,0 @@
1
- import type { FederationRuntimePlugin } from '@module-federation/enhanced/runtime';
2
- declare const nxRuntimeLibraryControlPlugin: () => FederationRuntimePlugin;
3
- export default nxRuntimeLibraryControlPlugin;
@@ -1,54 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- const runtimeStore = {
4
- sharedPackagesFromDev: {},
5
- };
6
- if (process.env.NX_MF_DEV_REMOTES) {
7
- // process.env.NX_MF_DEV_REMOTES is replaced by an array value via DefinePlugin, even though the original value is a stringified array.
8
- runtimeStore.devRemotes = process.env
9
- .NX_MF_DEV_REMOTES;
10
- }
11
- const nxRuntimeLibraryControlPlugin = function () {
12
- return {
13
- name: 'nx-runtime-library-control-plugin',
14
- beforeInit(args) {
15
- runtimeStore.name = args.options.name;
16
- return args;
17
- },
18
- resolveShare: (args) => {
19
- const { shareScopeMap, scope, pkgName, version, GlobalFederation } = args;
20
- const originalResolver = args.resolver;
21
- args.resolver = function () {
22
- if (!runtimeStore.sharedPackagesFromDev[pkgName]) {
23
- if (!GlobalFederation.__INSTANCES__) {
24
- return originalResolver();
25
- }
26
- else if (!runtimeStore.devRemotes) {
27
- return originalResolver();
28
- }
29
- const devRemoteInstanceToUse = GlobalFederation.__INSTANCES__.find((instance) => instance.options.shared[pkgName] &&
30
- runtimeStore.devRemotes.find((dr) => instance.name === dr));
31
- if (!devRemoteInstanceToUse) {
32
- return originalResolver();
33
- }
34
- runtimeStore.sharedPackagesFromDev[pkgName] =
35
- devRemoteInstanceToUse.name;
36
- }
37
- const remoteInstanceName = runtimeStore.sharedPackagesFromDev[pkgName];
38
- const remoteInstance = GlobalFederation.__INSTANCES__.find((instance) => instance.name === remoteInstanceName);
39
- try {
40
- const remotePkgInfo = remoteInstance.options.shared[pkgName].find((shared) => shared.from === remoteInstanceName);
41
- remotePkgInfo.useIn.push(runtimeStore.name);
42
- remotePkgInfo.useIn = Array.from(new Set(remotePkgInfo.useIn));
43
- shareScopeMap[scope][pkgName][version] = remotePkgInfo;
44
- return remotePkgInfo;
45
- }
46
- catch {
47
- return originalResolver();
48
- }
49
- };
50
- return args;
51
- },
52
- };
53
- };
54
- exports.default = nxRuntimeLibraryControlPlugin;
@@ -1,6 +0,0 @@
1
- import { AdditionalSharedConfig, ModuleFederationConfig, ModuleFederationLibrary, Remotes, SharedFunction, SharedLibraryConfig, SharedWorkspaceLibraryConfig, WorkspaceLibrary, WorkspaceLibrarySecondaryEntryPoint } from './models';
2
- import { applyAdditionalShared, applySharedFunction, getNpmPackageSharedConfig, sharePackages, shareWorkspaceLibraries } from './share';
3
- import { mapRemotes, mapRemotesForSSR } from './remotes';
4
- import { getDependentPackagesForProject } from './dependencies';
5
- import { readRootPackageJson } from './package-json';
6
- export { ModuleFederationConfig, SharedLibraryConfig, SharedWorkspaceLibraryConfig, AdditionalSharedConfig, WorkspaceLibrary, SharedFunction, WorkspaceLibrarySecondaryEntryPoint, Remotes, ModuleFederationLibrary, applySharedFunction, applyAdditionalShared, getNpmPackageSharedConfig, shareWorkspaceLibraries, sharePackages, mapRemotes, mapRemotesForSSR, getDependentPackagesForProject, readRootPackageJson, };
@@ -1,16 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.readRootPackageJson = exports.getDependentPackagesForProject = exports.mapRemotesForSSR = exports.mapRemotes = exports.sharePackages = exports.shareWorkspaceLibraries = exports.getNpmPackageSharedConfig = exports.applyAdditionalShared = exports.applySharedFunction = void 0;
4
- const share_1 = require("./share");
5
- Object.defineProperty(exports, "applyAdditionalShared", { enumerable: true, get: function () { return share_1.applyAdditionalShared; } });
6
- Object.defineProperty(exports, "applySharedFunction", { enumerable: true, get: function () { return share_1.applySharedFunction; } });
7
- Object.defineProperty(exports, "getNpmPackageSharedConfig", { enumerable: true, get: function () { return share_1.getNpmPackageSharedConfig; } });
8
- Object.defineProperty(exports, "sharePackages", { enumerable: true, get: function () { return share_1.sharePackages; } });
9
- Object.defineProperty(exports, "shareWorkspaceLibraries", { enumerable: true, get: function () { return share_1.shareWorkspaceLibraries; } });
10
- const remotes_1 = require("./remotes");
11
- Object.defineProperty(exports, "mapRemotes", { enumerable: true, get: function () { return remotes_1.mapRemotes; } });
12
- Object.defineProperty(exports, "mapRemotesForSSR", { enumerable: true, get: function () { return remotes_1.mapRemotesForSSR; } });
13
- const dependencies_1 = require("./dependencies");
14
- Object.defineProperty(exports, "getDependentPackagesForProject", { enumerable: true, get: function () { return dependencies_1.getDependentPackagesForProject; } });
15
- const package_json_1 = require("./package-json");
16
- Object.defineProperty(exports, "readRootPackageJson", { enumerable: true, get: function () { return package_json_1.readRootPackageJson; } });
@@ -1,19 +0,0 @@
1
- import { Remotes } from './models';
2
- /**
3
- * Map remote names to a format that can be understood and used by Module
4
- * Federation.
5
- *
6
- * @param remotes - The remotes to map
7
- * @param remoteEntryExt - The file extension of the remoteEntry file
8
- * @param determineRemoteUrl - The function used to lookup the URL of the served remote
9
- */
10
- export declare function mapRemotes(remotes: Remotes, remoteEntryExt: 'js' | 'mjs', determineRemoteUrl: (remote: string) => string, isRemoteGlobal?: boolean): Record<string, string>;
11
- /**
12
- * Map remote names to a format that can be understood and used by Module
13
- * Federation.
14
- *
15
- * @param remotes - The remotes to map
16
- * @param remoteEntryExt - The file extension of the remoteEntry file
17
- * @param determineRemoteUrl - The function used to lookup the URL of the served remote
18
- */
19
- export declare function mapRemotesForSSR(remotes: Remotes, remoteEntryExt: 'js' | 'mjs', determineRemoteUrl: (remote: string) => string): Record<string, string>;
@@ -1,89 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.mapRemotes = mapRemotes;
4
- exports.mapRemotesForSSR = mapRemotesForSSR;
5
- const path_1 = require("path");
6
- /**
7
- * Map remote names to a format that can be understood and used by Module
8
- * Federation.
9
- *
10
- * @param remotes - The remotes to map
11
- * @param remoteEntryExt - The file extension of the remoteEntry file
12
- * @param determineRemoteUrl - The function used to lookup the URL of the served remote
13
- */
14
- function mapRemotes(remotes, remoteEntryExt, determineRemoteUrl, isRemoteGlobal = false) {
15
- const mappedRemotes = {};
16
- for (const nxRemoteProjectName of remotes) {
17
- if (Array.isArray(nxRemoteProjectName)) {
18
- const mfRemoteName = normalizeRemoteName(nxRemoteProjectName[0]);
19
- mappedRemotes[mfRemoteName] = handleArrayRemote(nxRemoteProjectName, remoteEntryExt, isRemoteGlobal);
20
- }
21
- else if (typeof nxRemoteProjectName === 'string') {
22
- const mfRemoteName = normalizeRemoteName(nxRemoteProjectName);
23
- mappedRemotes[mfRemoteName] = handleStringRemote(nxRemoteProjectName, determineRemoteUrl, isRemoteGlobal);
24
- }
25
- }
26
- return mappedRemotes;
27
- }
28
- // Helper function to deal with remotes that are arrays
29
- function handleArrayRemote(remote, remoteEntryExt, isRemoteGlobal) {
30
- let [nxRemoteProjectName, remoteLocation] = remote;
31
- const mfRemoteName = normalizeRemoteName(nxRemoteProjectName);
32
- const remoteLocationExt = (0, path_1.extname)(remoteLocation);
33
- // If remote location already has .js or .mjs extension
34
- if (['.js', '.mjs', '.json'].includes(remoteLocationExt)) {
35
- return remoteLocation;
36
- }
37
- const baseRemote = remoteLocation.endsWith('/')
38
- ? remoteLocation.slice(0, -1)
39
- : remoteLocation;
40
- const globalPrefix = isRemoteGlobal
41
- ? `${normalizeRemoteName(nxRemoteProjectName)}@`
42
- : '';
43
- // if the remote is defined with anything other than http then we assume it's a promise based remote
44
- // In that case we should use what the user provides as the remote location
45
- if (!remoteLocation.startsWith('promise new Promise')) {
46
- return `${globalPrefix}${baseRemote}/remoteEntry.${remoteEntryExt}`;
47
- }
48
- else {
49
- return remoteLocation;
50
- }
51
- }
52
- // Helper function to deal with remotes that are strings
53
- function handleStringRemote(nxRemoteProjectName, determineRemoteUrl, isRemoteGlobal) {
54
- const globalPrefix = isRemoteGlobal
55
- ? `${normalizeRemoteName(nxRemoteProjectName)}@`
56
- : '';
57
- return `${globalPrefix}${determineRemoteUrl(nxRemoteProjectName)}`;
58
- }
59
- /**
60
- * Map remote names to a format that can be understood and used by Module
61
- * Federation.
62
- *
63
- * @param remotes - The remotes to map
64
- * @param remoteEntryExt - The file extension of the remoteEntry file
65
- * @param determineRemoteUrl - The function used to lookup the URL of the served remote
66
- */
67
- function mapRemotesForSSR(remotes, remoteEntryExt, determineRemoteUrl) {
68
- const mappedRemotes = {};
69
- for (const remote of remotes) {
70
- if (Array.isArray(remote)) {
71
- let [nxRemoteProjectName, remoteLocation] = remote;
72
- const mfRemoteName = normalizeRemoteName(nxRemoteProjectName);
73
- const remoteLocationExt = (0, path_1.extname)(remoteLocation);
74
- mappedRemotes[mfRemoteName] = `${mfRemoteName}@${['.js', '.mjs', '.json'].includes(remoteLocationExt)
75
- ? remoteLocation
76
- : `${remoteLocation.endsWith('/')
77
- ? remoteLocation.slice(0, -1)
78
- : remoteLocation}/remoteEntry.${remoteEntryExt}`}`;
79
- }
80
- else if (typeof remote === 'string') {
81
- const mfRemoteName = normalizeRemoteName(remote);
82
- mappedRemotes[mfRemoteName] = `${mfRemoteName}@${determineRemoteUrl(remote)}`;
83
- }
84
- }
85
- return mappedRemotes;
86
- }
87
- function normalizeRemoteName(remote) {
88
- return remote.replace(/-/g, '_');
89
- }
@@ -1,12 +0,0 @@
1
- import type { WorkspaceLibrary } from './models';
2
- import { WorkspaceLibrarySecondaryEntryPoint } from './models';
3
- export declare function collectWorkspaceLibrarySecondaryEntryPoints(library: WorkspaceLibrary, tsconfigPathAliases: Record<string, string[]>): WorkspaceLibrarySecondaryEntryPoint[];
4
- export declare function getNonNodeModulesSubDirs(directory: string): string[];
5
- export declare function recursivelyCollectSecondaryEntryPointsFromDirectory(pkgName: string, pkgVersion: string, pkgRoot: string, mainEntryPointExports: any | undefined, directories: string[], collectedPackages: {
6
- name: string;
7
- version: string;
8
- }[]): void;
9
- export declare function collectPackageSecondaryEntryPoints(pkgName: string, pkgVersion: string, collectedPackages: {
10
- name: string;
11
- version: string;
12
- }[]): void;
@@ -1,125 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.collectWorkspaceLibrarySecondaryEntryPoints = collectWorkspaceLibrarySecondaryEntryPoints;
4
- exports.getNonNodeModulesSubDirs = getNonNodeModulesSubDirs;
5
- exports.recursivelyCollectSecondaryEntryPointsFromDirectory = recursivelyCollectSecondaryEntryPointsFromDirectory;
6
- exports.collectPackageSecondaryEntryPoints = collectPackageSecondaryEntryPoints;
7
- const path_1 = require("path");
8
- const fs_1 = require("fs");
9
- const devkit_1 = require("@nx/devkit");
10
- const package_json_1 = require("nx/src/utils/package-json");
11
- function collectWorkspaceLibrarySecondaryEntryPoints(library, tsconfigPathAliases) {
12
- const libraryRoot = (0, path_1.join)(devkit_1.workspaceRoot, library.root);
13
- const needsSecondaryEntryPointsCollected = (0, fs_1.existsSync)((0, path_1.join)(libraryRoot, 'ng-package.json'));
14
- const secondaryEntryPoints = [];
15
- if (needsSecondaryEntryPointsCollected) {
16
- const tsConfigAliasesForLibWithSecondaryEntryPoints = Object.entries(tsconfigPathAliases).reduce((acc, [tsKey, tsPaths]) => {
17
- if (!tsKey.startsWith(library.importKey)) {
18
- return { ...acc };
19
- }
20
- if (tsPaths.some((path) => path.startsWith(`${library.root}/`))) {
21
- acc = { ...acc, [tsKey]: tsPaths };
22
- }
23
- return acc;
24
- }, {});
25
- for (const [alias] of Object.entries(tsConfigAliasesForLibWithSecondaryEntryPoints)) {
26
- const pathToLib = (0, path_1.dirname)((0, path_1.join)(devkit_1.workspaceRoot, tsconfigPathAliases[alias][0]));
27
- let searchDir = pathToLib;
28
- while (searchDir !== libraryRoot) {
29
- if ((0, fs_1.existsSync)((0, path_1.join)(searchDir, 'ng-package.json'))) {
30
- secondaryEntryPoints.push({ name: alias, path: pathToLib });
31
- break;
32
- }
33
- searchDir = (0, path_1.dirname)(searchDir);
34
- }
35
- }
36
- }
37
- return secondaryEntryPoints;
38
- }
39
- function getNonNodeModulesSubDirs(directory) {
40
- return (0, fs_1.readdirSync)(directory)
41
- .filter((file) => file !== 'node_modules')
42
- .map((file) => (0, path_1.join)(directory, file))
43
- .filter((file) => (0, fs_1.lstatSync)(file).isDirectory());
44
- }
45
- function recursivelyCollectSecondaryEntryPointsFromDirectory(pkgName, pkgVersion, pkgRoot, mainEntryPointExports, directories, collectedPackages) {
46
- for (const directory of directories) {
47
- const packageJsonPath = (0, path_1.join)(directory, 'package.json');
48
- const relativeEntryPointPath = (0, path_1.relative)(pkgRoot, directory);
49
- const entryPointName = (0, devkit_1.joinPathFragments)(pkgName, relativeEntryPointPath);
50
- if ((0, fs_1.existsSync)(packageJsonPath)) {
51
- try {
52
- // require the secondary entry point to try to rule out sample code
53
- require.resolve(entryPointName, { paths: [devkit_1.workspaceRoot] });
54
- const { name } = (0, devkit_1.readJsonFile)(packageJsonPath);
55
- // further check to make sure what we were able to require is the
56
- // same as the package name
57
- if (name === entryPointName) {
58
- collectedPackages.push({ name, version: pkgVersion });
59
- }
60
- }
61
- catch { }
62
- }
63
- else if (mainEntryPointExports) {
64
- // if the package.json doesn't exist, check if the directory is
65
- // exported by the main entry point
66
- const entryPointExportKey = `./${relativeEntryPointPath}`;
67
- const entryPointInfo = mainEntryPointExports[entryPointExportKey];
68
- if (entryPointInfo) {
69
- collectedPackages.push({
70
- name: entryPointName,
71
- version: pkgVersion,
72
- });
73
- }
74
- }
75
- const subDirs = getNonNodeModulesSubDirs(directory);
76
- recursivelyCollectSecondaryEntryPointsFromDirectory(pkgName, pkgVersion, pkgRoot, mainEntryPointExports, subDirs, collectedPackages);
77
- }
78
- }
79
- function collectPackagesFromExports(pkgName, pkgVersion, exports, collectedPackages) {
80
- for (const [relativeEntryPoint, exportOptions] of Object.entries(exports)) {
81
- const defaultExportOptions = typeof exportOptions?.['default'] === 'string'
82
- ? exportOptions?.['default']
83
- : exportOptions?.['default']?.['default'];
84
- if (defaultExportOptions?.search(/\.(js|mjs|cjs)$/)) {
85
- let entryPointName = (0, devkit_1.joinPathFragments)(pkgName, relativeEntryPoint);
86
- if (entryPointName.endsWith('.json')) {
87
- entryPointName = (0, path_1.dirname)(entryPointName);
88
- }
89
- if (entryPointName === '.') {
90
- continue;
91
- }
92
- if (collectedPackages.find((p) => p.name === entryPointName)) {
93
- continue;
94
- }
95
- collectedPackages.push({ name: entryPointName, version: pkgVersion });
96
- }
97
- }
98
- }
99
- function collectPackageSecondaryEntryPoints(pkgName, pkgVersion, collectedPackages) {
100
- let pathToPackage;
101
- let packageJsonPath;
102
- let packageJson;
103
- try {
104
- ({ path: packageJsonPath, packageJson } = (0, package_json_1.readModulePackageJson)(pkgName));
105
- pathToPackage = (0, path_1.dirname)(packageJsonPath);
106
- }
107
- catch {
108
- // the package.json might not resolve if the package has the "exports"
109
- // entry and is not exporting the package.json file, fall back to trying
110
- // to find it from the top-level node_modules
111
- pathToPackage = (0, path_1.join)(devkit_1.workspaceRoot, 'node_modules', pkgName);
112
- packageJsonPath = (0, path_1.join)(pathToPackage, 'package.json');
113
- if (!(0, fs_1.existsSync)(packageJsonPath)) {
114
- // might not exist if it's nested in another package, just return here
115
- return;
116
- }
117
- packageJson = (0, devkit_1.readJsonFile)(packageJsonPath);
118
- }
119
- const { exports } = packageJson;
120
- if (exports) {
121
- collectPackagesFromExports(pkgName, pkgVersion, exports, collectedPackages);
122
- }
123
- const subDirs = getNonNodeModulesSubDirs(pathToPackage);
124
- recursivelyCollectSecondaryEntryPointsFromDirectory(pkgName, pkgVersion, pathToPackage, exports, subDirs, collectedPackages);
125
- }
@@ -1,48 +0,0 @@
1
- import type { SharedLibraryConfig, SharedWorkspaceLibraryConfig, WorkspaceLibrary } from './models';
2
- import { AdditionalSharedConfig, SharedFunction } from './models';
3
- import { type ProjectGraph } from '@nx/devkit';
4
- /**
5
- * Build an object of functions to be used with the ModuleFederationPlugin to
6
- * share Nx Workspace Libraries between Hosts and Remotes.
7
- *
8
- * @param workspaceLibs - The Nx Workspace Libraries to share
9
- * @param tsConfigPath - The path to TS Config File that contains the Path Mappings for the Libraries
10
- */
11
- export declare function shareWorkspaceLibraries(workspaceLibs: WorkspaceLibrary[], tsConfigPath?: string): SharedWorkspaceLibraryConfig;
12
- /**
13
- * Build the Module Federation Share Config for a specific package and the
14
- * specified version of that package.
15
- * @param pkgName - Name of the package to share
16
- * @param version - Version of the package to require by other apps in the Module Federation setup
17
- */
18
- export declare function getNpmPackageSharedConfig(pkgName: string, version: string): SharedLibraryConfig | undefined;
19
- /**
20
- * Create a dictionary of packages and their Module Federation Shared Config
21
- * from an array of package names.
22
- *
23
- * Lookup the versions of the packages from the root package.json file in the
24
- * workspace.
25
- * @param packages - Array of package names as strings
26
- */
27
- export declare function sharePackages(packages: string[]): Record<string, SharedLibraryConfig>;
28
- /**
29
- * Apply a custom function provided by the user that will modify the Shared Config
30
- * of the dependencies for the Module Federation build.
31
- *
32
- * @param sharedConfig - The original Shared Config to be modified
33
- * @param sharedFn - The custom function to run
34
- */
35
- export declare function applySharedFunction(sharedConfig: Record<string, SharedLibraryConfig>, sharedFn: SharedFunction | undefined): void;
36
- /**
37
- * Add additional dependencies to the shared package that may not have been
38
- * discovered by the project graph.
39
- *
40
- * This can be useful for applications that use a Dependency Injection system
41
- * that expects certain Singleton values to be present in the shared injection
42
- * hierarchy.
43
- *
44
- * @param sharedConfig - The original Shared Config
45
- * @param additionalShared - The additional dependencies to add
46
- * @param projectGraph - The Nx project graph
47
- */
48
- export declare function applyAdditionalShared(sharedConfig: Record<string, SharedLibraryConfig>, additionalShared: AdditionalSharedConfig | undefined, projectGraph: ProjectGraph): void;
@@ -1,240 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.shareWorkspaceLibraries = shareWorkspaceLibraries;
4
- exports.getNpmPackageSharedConfig = getNpmPackageSharedConfig;
5
- exports.sharePackages = sharePackages;
6
- exports.applySharedFunction = applySharedFunction;
7
- exports.applyAdditionalShared = applyAdditionalShared;
8
- const path_1 = require("path");
9
- const package_json_1 = require("./package-json");
10
- const typescript_1 = require("./typescript");
11
- const secondary_entry_points_1 = require("./secondary-entry-points");
12
- const devkit_1 = require("@nx/devkit");
13
- const fs_1 = require("fs");
14
- /**
15
- * Build an object of functions to be used with the ModuleFederationPlugin to
16
- * share Nx Workspace Libraries between Hosts and Remotes.
17
- *
18
- * @param workspaceLibs - The Nx Workspace Libraries to share
19
- * @param tsConfigPath - The path to TS Config File that contains the Path Mappings for the Libraries
20
- */
21
- function shareWorkspaceLibraries(workspaceLibs, tsConfigPath = process.env.NX_TSCONFIG_PATH ?? (0, typescript_1.getRootTsConfigPath)()) {
22
- if (!workspaceLibs) {
23
- return getEmptySharedLibrariesConfig();
24
- }
25
- const tsconfigPathAliases = (0, typescript_1.readTsPathMappings)(tsConfigPath);
26
- if (!Object.keys(tsconfigPathAliases).length) {
27
- return getEmptySharedLibrariesConfig();
28
- }
29
- // Nested projects must come first, sort them as such
30
- const sortedTsConfigPathAliases = {};
31
- Object.keys(tsconfigPathAliases)
32
- .sort((a, b) => {
33
- return b.split('/').length - a.split('/').length;
34
- })
35
- .forEach((key) => (sortedTsConfigPathAliases[key] = tsconfigPathAliases[key]));
36
- const pathMappings = [];
37
- for (const [key, paths] of Object.entries(sortedTsConfigPathAliases)) {
38
- const library = workspaceLibs.find((lib) => lib.importKey === key);
39
- if (!library) {
40
- continue;
41
- }
42
- // This is for Angular Projects that use ng-package.json
43
- // It will do nothing for React Projects
44
- (0, secondary_entry_points_1.collectWorkspaceLibrarySecondaryEntryPoints)(library, sortedTsConfigPathAliases).forEach(({ name, path }) => pathMappings.push({
45
- name,
46
- path,
47
- }));
48
- pathMappings.push({
49
- name: key,
50
- path: (0, path_1.normalize)((0, path_1.join)(devkit_1.workspaceRoot, paths[0])),
51
- });
52
- }
53
- const webpack = require('webpack');
54
- return {
55
- getAliases: () => pathMappings.reduce((aliases, library) => ({
56
- ...aliases,
57
- // If the library path ends in a wildcard, remove it as webpack can't handle this in resolve.alias
58
- // e.g. path/to/my/lib/* -> path/to/my/lib
59
- [library.name]: library.path.replace(/\/\*$/, ''),
60
- }), {}),
61
- getLibraries: (projectRoot, eager) => {
62
- let pkgJson = null;
63
- if (projectRoot &&
64
- (0, fs_1.existsSync)((0, devkit_1.joinPathFragments)(devkit_1.workspaceRoot, projectRoot, 'package.json'))) {
65
- pkgJson = (0, devkit_1.readJsonFile)((0, devkit_1.joinPathFragments)(devkit_1.workspaceRoot, projectRoot, 'package.json'));
66
- }
67
- return pathMappings.reduce((libraries, library) => {
68
- // Check to see if the library version is declared in the app's package.json
69
- let version = pkgJson?.dependencies?.[library.name];
70
- if (!version && workspaceLibs.length > 0) {
71
- const workspaceLib = workspaceLibs.find((lib) => lib.importKey === library.name);
72
- const libPackageJsonPath = workspaceLib
73
- ? (0, path_1.join)(workspaceLib.root, 'package.json')
74
- : null;
75
- if (libPackageJsonPath && (0, fs_1.existsSync)(libPackageJsonPath)) {
76
- pkgJson = (0, devkit_1.readJsonFile)(libPackageJsonPath);
77
- if (pkgJson) {
78
- version = pkgJson.version;
79
- }
80
- }
81
- }
82
- return {
83
- ...libraries,
84
- [library.name]: {
85
- ...(version
86
- ? {
87
- requiredVersion: version,
88
- singleton: true,
89
- }
90
- : { requiredVersion: false }),
91
- eager,
92
- },
93
- };
94
- }, {});
95
- },
96
- getReplacementPlugin: () => new webpack.NormalModuleReplacementPlugin(/./, (req) => {
97
- if (!req.request.startsWith('.')) {
98
- return;
99
- }
100
- const from = req.context;
101
- const to = (0, path_1.normalize)((0, path_1.join)(req.context, req.request));
102
- for (const library of pathMappings) {
103
- const libFolder = (0, path_1.normalize)((0, path_1.dirname)(library.path));
104
- if (!from.startsWith(libFolder) && to.startsWith(libFolder)) {
105
- const newReq = library.name.endsWith('/*')
106
- ? /**
107
- * req usually is in the form of "../../../path/to/file"
108
- * library.path is usually in the form of "/Users/username/path/to/Workspace/path/to/library"
109
- *
110
- * When a wildcard is used in the TS path mappings, we want to get everything after the import to
111
- * re-route the request correctly inline with the webpack resolve.alias
112
- */
113
- (0, path_1.join)(library.name, req.request.split(library.path.replace(devkit_1.workspaceRoot, '').replace('/*', ''))[1])
114
- : library.name;
115
- req.request = newReq;
116
- }
117
- }
118
- }),
119
- };
120
- }
121
- /**
122
- * Build the Module Federation Share Config for a specific package and the
123
- * specified version of that package.
124
- * @param pkgName - Name of the package to share
125
- * @param version - Version of the package to require by other apps in the Module Federation setup
126
- */
127
- function getNpmPackageSharedConfig(pkgName, version) {
128
- if (!version) {
129
- devkit_1.logger.warn(`Could not find a version for "${pkgName}" in the root "package.json" ` +
130
- 'when collecting shared packages for the Module Federation setup. ' +
131
- 'The package will not be shared.');
132
- return undefined;
133
- }
134
- return { singleton: true, strictVersion: true, requiredVersion: version };
135
- }
136
- /**
137
- * Create a dictionary of packages and their Module Federation Shared Config
138
- * from an array of package names.
139
- *
140
- * Lookup the versions of the packages from the root package.json file in the
141
- * workspace.
142
- * @param packages - Array of package names as strings
143
- */
144
- function sharePackages(packages) {
145
- const pkgJson = (0, package_json_1.readRootPackageJson)();
146
- const allPackages = [];
147
- packages.forEach((pkg) => {
148
- const pkgVersion = pkgJson.dependencies?.[pkg] ?? pkgJson.devDependencies?.[pkg];
149
- allPackages.push({ name: pkg, version: pkgVersion });
150
- (0, secondary_entry_points_1.collectPackageSecondaryEntryPoints)(pkg, pkgVersion, allPackages);
151
- });
152
- return allPackages.reduce((shared, pkg) => {
153
- const config = getNpmPackageSharedConfig(pkg.name, pkg.version);
154
- if (config) {
155
- shared[pkg.name] = config;
156
- }
157
- return shared;
158
- }, {});
159
- }
160
- /**
161
- * Apply a custom function provided by the user that will modify the Shared Config
162
- * of the dependencies for the Module Federation build.
163
- *
164
- * @param sharedConfig - The original Shared Config to be modified
165
- * @param sharedFn - The custom function to run
166
- */
167
- function applySharedFunction(sharedConfig, sharedFn) {
168
- if (!sharedFn) {
169
- return;
170
- }
171
- for (const [libraryName, library] of Object.entries(sharedConfig)) {
172
- const mappedDependency = sharedFn(libraryName, library);
173
- if (mappedDependency === false) {
174
- delete sharedConfig[libraryName];
175
- continue;
176
- }
177
- else if (!mappedDependency) {
178
- continue;
179
- }
180
- sharedConfig[libraryName] = mappedDependency;
181
- }
182
- }
183
- /**
184
- * Add additional dependencies to the shared package that may not have been
185
- * discovered by the project graph.
186
- *
187
- * This can be useful for applications that use a Dependency Injection system
188
- * that expects certain Singleton values to be present in the shared injection
189
- * hierarchy.
190
- *
191
- * @param sharedConfig - The original Shared Config
192
- * @param additionalShared - The additional dependencies to add
193
- * @param projectGraph - The Nx project graph
194
- */
195
- function applyAdditionalShared(sharedConfig, additionalShared, projectGraph) {
196
- if (!additionalShared) {
197
- return;
198
- }
199
- for (const shared of additionalShared) {
200
- if (typeof shared === 'string') {
201
- addStringDependencyToSharedConfig(sharedConfig, shared, projectGraph);
202
- }
203
- else if (Array.isArray(shared)) {
204
- sharedConfig[shared[0]] = shared[1];
205
- }
206
- else if (typeof shared === 'object') {
207
- sharedConfig[shared.libraryName] = shared.sharedConfig;
208
- }
209
- }
210
- }
211
- function addStringDependencyToSharedConfig(sharedConfig, dependency, projectGraph) {
212
- if (projectGraph.nodes[dependency]) {
213
- sharedConfig[dependency] = { requiredVersion: false };
214
- }
215
- else if (projectGraph.externalNodes?.[`npm:${dependency}`]) {
216
- const pkgJson = (0, package_json_1.readRootPackageJson)();
217
- const config = getNpmPackageSharedConfig(dependency, pkgJson.dependencies?.[dependency] ??
218
- pkgJson.devDependencies?.[dependency]);
219
- if (!config) {
220
- return;
221
- }
222
- sharedConfig[dependency] = config;
223
- }
224
- else {
225
- const pkgJsonPath = require.resolve(`${dependency}/package.json`);
226
- if (!pkgJsonPath) {
227
- throw new Error(`Could not find package ${dependency} when applying it as a shared package. Are you sure it has been installed?`);
228
- }
229
- const pkgJson = (0, devkit_1.readJsonFile)(pkgJsonPath);
230
- const config = getNpmPackageSharedConfig(dependency, pkgJson.version);
231
- }
232
- }
233
- function getEmptySharedLibrariesConfig() {
234
- const webpack = require('webpack');
235
- return {
236
- getAliases: () => ({}),
237
- getLibraries: () => ({}),
238
- getReplacementPlugin: () => new webpack.NormalModuleReplacementPlugin(/./, () => { }),
239
- };
240
- }
@@ -1,5 +0,0 @@
1
- import { StaticRemotesConfig } from './parse-static-remotes-config';
2
- export declare function startRemoteProxies(staticRemotesConfig: StaticRemotesConfig, mappedLocationsOfRemotes: Record<string, string>, sslOptions?: {
3
- pathToCert: string;
4
- pathToKey: string;
5
- }): void;
@@ -1,38 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.startRemoteProxies = startRemoteProxies;
4
- const devkit_1 = require("@nx/devkit");
5
- const fs_1 = require("fs");
6
- function startRemoteProxies(staticRemotesConfig, mappedLocationsOfRemotes, sslOptions) {
7
- const { createProxyMiddleware } = require('http-proxy-middleware');
8
- const express = require('express');
9
- let sslCert;
10
- let sslKey;
11
- if (sslOptions && sslOptions.pathToCert && sslOptions.pathToKey) {
12
- if ((0, fs_1.existsSync)(sslOptions.pathToCert) && (0, fs_1.existsSync)(sslOptions.pathToKey)) {
13
- sslCert = (0, fs_1.readFileSync)(sslOptions.pathToCert);
14
- sslKey = (0, fs_1.readFileSync)(sslOptions.pathToKey);
15
- }
16
- else {
17
- devkit_1.logger.warn(`Encountered SSL options in project.json, however, the certificate files do not exist in the filesystem. Using http.`);
18
- devkit_1.logger.warn(`Attempted to find '${sslOptions.pathToCert}' and '${sslOptions.pathToKey}'.`);
19
- }
20
- }
21
- const http = require('http');
22
- const https = require('https');
23
- devkit_1.logger.info(`NX Starting static remotes proxies...`);
24
- for (const app of staticRemotesConfig.remotes) {
25
- const expressProxy = express();
26
- expressProxy.use(createProxyMiddleware({
27
- target: mappedLocationsOfRemotes[app],
28
- changeOrigin: true,
29
- secure: sslCert ? false : undefined,
30
- }));
31
- const proxyServer = (sslCert ? https : http)
32
- .createServer({ cert: sslCert, key: sslKey }, expressProxy)
33
- .listen(staticRemotesConfig.config[app].port);
34
- process.on('SIGTERM', () => proxyServer.close());
35
- process.on('exit', () => proxyServer.close());
36
- }
37
- devkit_1.logger.info(`NX Static remotes proxies started successfully`);
38
- }
@@ -1,5 +0,0 @@
1
- import type { StaticRemotesConfig } from './parse-static-remotes-config';
2
- export declare function startSsrRemoteProxies(staticRemotesConfig: StaticRemotesConfig, mappedLocationsOfRemotes: Record<string, string>, sslOptions?: {
3
- pathToCert: string;
4
- pathToKey: string;
5
- }): void;
@@ -1,52 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.startSsrRemoteProxies = startSsrRemoteProxies;
4
- const devkit_1 = require("@nx/devkit");
5
- const fs_1 = require("fs");
6
- function startSsrRemoteProxies(staticRemotesConfig, mappedLocationsOfRemotes, sslOptions) {
7
- const { createProxyMiddleware } = require('http-proxy-middleware');
8
- const express = require('express');
9
- let sslCert;
10
- let sslKey;
11
- if (sslOptions && sslOptions.pathToCert && sslOptions.pathToKey) {
12
- if ((0, fs_1.existsSync)(sslOptions.pathToCert) && (0, fs_1.existsSync)(sslOptions.pathToKey)) {
13
- sslCert = (0, fs_1.readFileSync)(sslOptions.pathToCert);
14
- sslKey = (0, fs_1.readFileSync)(sslOptions.pathToKey);
15
- }
16
- else {
17
- devkit_1.logger.warn(`Encountered SSL options in project.json, however, the certificate files do not exist in the filesystem. Using http.`);
18
- devkit_1.logger.warn(`Attempted to find '${sslOptions.pathToCert}' and '${sslOptions.pathToKey}'.`);
19
- }
20
- }
21
- const http = require('http');
22
- const https = require('https');
23
- devkit_1.logger.info(`NX Starting static remotes proxies...`);
24
- for (const app of staticRemotesConfig.remotes) {
25
- const expressProxy = express();
26
- /**
27
- * SSR remotes have two output paths: one for the browser and one for the server.
28
- * We need to handle paths for both of them.
29
- * The browser output path is used to serve the client-side code.
30
- * The server output path is used to serve the server-side code.
31
- */
32
- expressProxy.use(createProxyMiddleware({
33
- target: `${mappedLocationsOfRemotes[app]}`,
34
- secure: sslCert ? false : undefined,
35
- changeOrigin: true,
36
- pathRewrite: (path) => {
37
- if (path.includes('/server')) {
38
- return path;
39
- }
40
- else {
41
- return `browser/${path}`;
42
- }
43
- },
44
- }));
45
- const proxyServer = (sslCert ? https : http)
46
- .createServer({ cert: sslCert, key: sslKey }, expressProxy)
47
- .listen(staticRemotesConfig.config[app].port);
48
- process.on('SIGTERM', () => proxyServer.close());
49
- process.on('exit', () => proxyServer.close());
50
- }
51
- devkit_1.logger.info(`Nx SSR Static remotes proxies started successfully`);
52
- }
@@ -1,4 +0,0 @@
1
- import { ParsedCommandLine } from 'typescript';
2
- export declare function readTsPathMappings(tsConfigPath?: string): ParsedCommandLine['options']['paths'];
3
- export declare function readTsConfig(tsConfigPath: string): ParsedCommandLine;
4
- export declare function getRootTsConfigPath(): string | null;
@@ -1,53 +0,0 @@
1
- "use strict";
2
- Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.readTsPathMappings = readTsPathMappings;
4
- exports.readTsConfig = readTsConfig;
5
- exports.getRootTsConfigPath = getRootTsConfigPath;
6
- const fs_1 = require("fs");
7
- const path_1 = require("path");
8
- const devkit_1 = require("@nx/devkit");
9
- let tsConfig = new Map();
10
- let tsPathMappings = new Map();
11
- function readTsPathMappings(tsConfigPath = process.env.NX_TSCONFIG_PATH ?? getRootTsConfigPath()) {
12
- if (tsPathMappings.has(tsConfigPath)) {
13
- return tsPathMappings.get(tsConfigPath);
14
- }
15
- if (!tsConfig.has(tsConfigPath)) {
16
- tsConfig.set(tsConfigPath, readTsConfiguration(tsConfigPath));
17
- }
18
- tsPathMappings.set(tsConfigPath, {});
19
- Object.entries(tsConfig.get(tsConfigPath).options?.paths ?? {}).forEach(([alias, paths]) => {
20
- tsPathMappings.set(tsConfigPath, {
21
- ...tsPathMappings.get(tsConfigPath),
22
- [alias]: paths.map((path) => path.replace(/^\.\//, '')),
23
- });
24
- });
25
- return tsPathMappings.get(tsConfigPath);
26
- }
27
- function readTsConfiguration(tsConfigPath) {
28
- if (!(0, fs_1.existsSync)(tsConfigPath)) {
29
- throw new Error(`NX MF: TsConfig Path for workspace libraries does not exist! (${tsConfigPath}).`);
30
- }
31
- return readTsConfig(tsConfigPath);
32
- }
33
- let tsModule;
34
- function readTsConfig(tsConfigPath) {
35
- if (!tsModule) {
36
- tsModule = require('typescript');
37
- }
38
- const readResult = tsModule.readConfigFile(tsConfigPath, tsModule.sys.readFile);
39
- return tsModule.parseJsonConfigFileContent(readResult.config, tsModule.sys, (0, path_1.dirname)(tsConfigPath));
40
- }
41
- function getRootTsConfigPath() {
42
- const tsConfigFileName = getRootTsConfigFileName();
43
- return tsConfigFileName ? (0, path_1.join)(devkit_1.workspaceRoot, tsConfigFileName) : null;
44
- }
45
- function getRootTsConfigFileName() {
46
- for (const tsConfigName of ['tsconfig.base.json', 'tsconfig.json']) {
47
- const tsConfigPath = (0, path_1.join)(devkit_1.workspaceRoot, tsConfigName);
48
- if ((0, fs_1.existsSync)(tsConfigPath)) {
49
- return tsConfigName;
50
- }
51
- }
52
- return null;
53
- }