@module-federation/vite 1.9.4 → 1.9.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.cjs CHANGED
@@ -4,6 +4,9 @@ var path = require('pathe');
4
4
  var MagicString = require('magic-string');
5
5
  var pluginutils = require('@rollup/pluginutils');
6
6
  var estreeWalker = require('estree-walker');
7
+ var sdk = require('@module-federation/sdk');
8
+ var dtsPlugin = require('@module-federation/dts-plugin');
9
+ var core = require('@module-federation/dts-plugin/core');
7
10
 
8
11
  function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
9
12
 
@@ -587,6 +590,96 @@ function createFile(filePath, content) {
587
590
  fs.writeFileSync(filePath, content);
588
591
  }
589
592
 
593
+ /**
594
+ * Serializes a JavaScript object into a string of source code that can be evaluated.
595
+ * This function is used to create runtime plugin options without relying solely on JSON.stringify,
596
+ * allowing support for non-JSON types like RegExp, Date, Map, Set, and Functions.
597
+ * It also safely handles circular references.
598
+ *
599
+ * @param {Record<string, unknown>} options - The options object to serialize.
600
+ * @returns {string} The resulting JavaScript source code string.
601
+ */
602
+ function serializeRuntimeOptions(options) {
603
+ // Use a WeakSet to track objects already encountered, which helps in detecting circular references.
604
+ var seenObjects = new WeakSet();
605
+ /**
606
+ * Recursive inner function to serialize any value into a source code string.
607
+ */
608
+ function valueToCode(val) {
609
+ // 1. Handle primitive values
610
+ if (val === null) return 'null';
611
+ var type = typeof val;
612
+ if (type === 'string') return JSON.stringify(val);
613
+ if (type === 'number' || type === 'boolean') return String(val);
614
+ if (type === 'undefined') return 'undefined';
615
+ // Handle Symbol
616
+ if (type === 'symbol') {
617
+ var _val$description;
618
+ var desc = (_val$description = val.description) != null ? _val$description : '';
619
+ return "Symbol(" + JSON.stringify(desc) + ")";
620
+ }
621
+ // Handle Function (returns the function's source code)
622
+ if (type === 'function') return val.toString();
623
+ // 2. Handle special built-in objects
624
+ if (val instanceof Date) return "new Date(" + JSON.stringify(val.toISOString()) + ")";
625
+ if (val instanceof RegExp) {
626
+ return "new RegExp(" + JSON.stringify(val.source) + ", " + JSON.stringify(val.flags) + ")";
627
+ }
628
+ // 3. Check for circular references and mark object as seen
629
+ // This applies to objects, arrays, maps, and sets.
630
+ if (type === 'object') {
631
+ if (seenObjects.has(val)) {
632
+ // This object has been seen previously in the recursion path
633
+ return "\"__circular__\"";
634
+ }
635
+ seenObjects.add(val);
636
+ }
637
+ // 4. Handle Array, Map, Set
638
+ if (Array.isArray(val)) {
639
+ // Recursively serialize each element
640
+ return "[" + val.map(valueToCode).join(', ') + "]";
641
+ }
642
+ if (val instanceof Map) {
643
+ // Serialize Map entries into an array of [key, value] pairs
644
+ var entries = Array.from(val.entries()).map(function (_ref) {
645
+ var k = _ref[0],
646
+ v = _ref[1];
647
+ return "[" + valueToCode(k) + ", " + valueToCode(v) + "]";
648
+ });
649
+ return "new Map([" + entries.join(', ') + "])";
650
+ }
651
+ if (val instanceof Set) {
652
+ // Serialize Set values into an array
653
+ var items = Array.from(val.values()).map(valueToCode);
654
+ return "new Set([" + items.join(', ') + "])";
655
+ }
656
+ // 5. Handle plain objects (the default object type)
657
+ if (type === 'object') {
658
+ var properties = [];
659
+ // Iterate over the object's own enumerable properties
660
+ for (var key in val) {
661
+ if (Object.prototype.hasOwnProperty.call(val, key)) {
662
+ // Wrap the key in JSON.stringify to handle non-identifier keys
663
+ properties.push(JSON.stringify(key) + ": " + valueToCode(val[key]));
664
+ }
665
+ }
666
+ return "{" + properties.join(', ') + "}";
667
+ }
668
+ // 6. Fallback case (e.g., BigInt, other object types)
669
+ // Coerce to string and then JSON.stringify that string for safety
670
+ return JSON.stringify(String(val));
671
+ }
672
+ // Start serialization for the top-level object
673
+ var topLevelProps = [];
674
+ // Iterate over the properties of the root 'options' object
675
+ for (var key in options) {
676
+ if (Object.prototype.hasOwnProperty.call(options, key)) {
677
+ topLevelProps.push(JSON.stringify(key) + ": " + valueToCode(options[key]));
678
+ }
679
+ }
680
+ return "{" + topLevelProps.join(', ') + "}";
681
+ }
682
+
590
683
  // Cache root path
591
684
  var rootDir;
592
685
  function findNodeModulesDir(root) {
@@ -823,12 +916,16 @@ function generateLocalSharedImportMap() {
823
916
  var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
824
917
  function generateRemoteEntry(options) {
825
918
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
826
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
919
+ if (typeof p === 'string') {
920
+ return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";", "undefined"];
921
+ } else {
922
+ return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p[0] + "\";", serializeRuntimeOptions(p[1])];
923
+ }
827
924
  });
828
925
  return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
829
926
  return item[1];
830
927
  }).join('\n') + "\n import exposesMap from \"" + VIRTUAL_EXPOSES + "\"\n import {usedShared, usedRemotes} from \"" + getLocalSharedImportMapPath() + "\"\n import {\n initResolve\n } from \"" + virtualRuntimeInitStatus.getImportId() + "\"\n const initTokens = {}\n const shareScopeName = " + JSON.stringify(options.shareScope) + "\n const mfName = " + JSON.stringify(options.name) + "\n async function init(shared = {}, initScope = []) {\n const initRes = runtimeInit({\n name: mfName,\n remotes: usedRemotes,\n shared: usedShared,\n plugins: [" + pluginImportNames.map(function (item) {
831
- return item[0] + "()";
928
+ return item[0] + "(" + item[2] + ")";
832
929
  }).join(', ') + "],\n " + (options.shareStrategy ? "shareStrategy: '" + options.shareStrategy + "'" : '') + "\n });\n // handling circular init calls\n var initToken = initTokens[shareScopeName];\n if (!initToken)\n initToken = initTokens[shareScopeName] = { from: mfName };\n if (initScope.indexOf(initToken) >= 0) return;\n initScope.push(initToken);\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\n try {\n await Promise.all(await initRes.initializeSharing('" + options.shareScope + "', {\n strategy: '" + options.shareStrategy + "',\n from: \"build\",\n initScope\n }));\n } catch (e) {\n console.error(e)\n }\n initResolve(initRes)\n return initRes\n }\n\n function getExposes(moduleName) {\n if (!(moduleName in exposesMap)) throw new Error(`Module ${moduleName} does not exist in container.`)\n return (exposesMap[moduleName])().then(res => () => res)\n }\n export {\n init,\n getExposes as get\n }\n ";
833
930
  }
834
931
  /**
@@ -1442,6 +1539,322 @@ function pluginProxyRemotes (options) {
1442
1539
  };
1443
1540
  }
1444
1541
 
1542
+ function _catch(body, recover) {
1543
+ try {
1544
+ var result = body();
1545
+ } catch (e) {
1546
+ return recover(e);
1547
+ }
1548
+ if (result && result.then) {
1549
+ return result.then(void 0, recover);
1550
+ }
1551
+ return result;
1552
+ }
1553
+ var DEFAULT_DEV_OPTIONS = {
1554
+ disableLiveReload: true,
1555
+ disableHotTypesReload: false,
1556
+ disableDynamicRemoteTypeHints: false
1557
+ };
1558
+ var DYNAMIC_HINTS_PLUGIN = '@module-federation/dts-plugin/dynamic-remote-type-hints-plugin';
1559
+ var getIPv4 = function getIPv4() {
1560
+ return process.env['FEDERATION_IPV4'] || '127.0.0.1';
1561
+ };
1562
+ var forkDevWorkerPath = function () {
1563
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
1564
+ return require.resolve('@module-federation/dts-plugin/dist/fork-dev-worker.js');
1565
+ }();
1566
+ var DevWorker = /*#__PURE__*/function () {
1567
+ function DevWorker(options) {
1568
+ this.worker = core.rpc.createRpcWorker(forkDevWorkerPath, {}, undefined, false);
1569
+ this.worker.connect(options);
1570
+ }
1571
+ var _proto = DevWorker.prototype;
1572
+ _proto.update = function update() {
1573
+ var _this$worker$process;
1574
+ (_this$worker$process = this.worker.process) == null || _this$worker$process.send == null || _this$worker$process.send({
1575
+ type: core.rpc.RpcGMCallTypes.CALL,
1576
+ id: this.worker.id,
1577
+ args: [undefined, 'update']
1578
+ });
1579
+ };
1580
+ _proto.exit = function exit() {
1581
+ this.worker.terminate();
1582
+ };
1583
+ return DevWorker;
1584
+ }();
1585
+ var normalizeDevOptions = function normalizeDevOptions(dev) {
1586
+ if (dev === false) {
1587
+ return false;
1588
+ }
1589
+ if (dev === true || typeof dev === 'undefined') {
1590
+ return _extends({}, DEFAULT_DEV_OPTIONS);
1591
+ }
1592
+ return _extends({}, DEFAULT_DEV_OPTIONS, dev);
1593
+ };
1594
+ var buildDtsModuleFederationConfig = function buildDtsModuleFederationConfig(options) {
1595
+ var exposes = {};
1596
+ Object.entries(options.exposes).forEach(function (_ref) {
1597
+ var key = _ref[0],
1598
+ value = _ref[1];
1599
+ if (typeof value === 'string') {
1600
+ exposes[key] = value;
1601
+ return;
1602
+ }
1603
+ var importValue = Array.isArray(value["import"]) ? value["import"][0] : value["import"];
1604
+ if (importValue) {
1605
+ exposes[key] = importValue;
1606
+ }
1607
+ });
1608
+ var remotes = {};
1609
+ Object.entries(options.remotes).forEach(function (_ref2) {
1610
+ var _remote$entryGlobalNa, _remote$entryGlobalNa2;
1611
+ var key = _ref2[0],
1612
+ remote = _ref2[1];
1613
+ if (typeof remote === 'string') {
1614
+ remotes[key] = remote;
1615
+ return;
1616
+ }
1617
+ if (!remote.entry) {
1618
+ return;
1619
+ }
1620
+ var entryLooksLikeUrl = ((_remote$entryGlobalNa = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa.startsWith('http')) || ((_remote$entryGlobalNa2 = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa2.includes('.json'));
1621
+ var entryGlobalName = entryLooksLikeUrl ? remote.name || key : remote.entryGlobalName || remote.name || key;
1622
+ remotes[key] = entryGlobalName + "@" + remote.entry;
1623
+ });
1624
+ return _extends({}, options, {
1625
+ exposes: exposes,
1626
+ remotes: remotes
1627
+ });
1628
+ };
1629
+ var resolveOutputDir = function resolveOutputDir(config) {
1630
+ var outDir = config.build.outDir;
1631
+ if (path__namespace.isAbsolute(outDir)) {
1632
+ return path__namespace.relative(config.root, outDir);
1633
+ }
1634
+ return outDir;
1635
+ };
1636
+ var ensureRuntimePlugin = function ensureRuntimePlugin(options, pluginId) {
1637
+ var hasPlugin = options.runtimePlugins.some(function (plugin) {
1638
+ if (typeof plugin === 'string') {
1639
+ return plugin === pluginId;
1640
+ }
1641
+ return plugin[0] === pluginId;
1642
+ });
1643
+ if (!hasPlugin) {
1644
+ options.runtimePlugins.push(pluginId);
1645
+ }
1646
+ };
1647
+ var normalizeDevDtsOptions = function normalizeDevDtsOptions(dts, context) {
1648
+ var defaultGenerateTypes = {
1649
+ compileInChildProcess: true
1650
+ };
1651
+ var defaultConsumeTypes = {
1652
+ consumeAPITypes: true
1653
+ };
1654
+ return sdk.normalizeOptions(dtsPlugin.isTSProject(dts, context), {
1655
+ generateTypes: defaultGenerateTypes,
1656
+ consumeTypes: defaultConsumeTypes,
1657
+ extraOptions: {},
1658
+ displayErrorInTerminal: typeof dts === 'object' && dts ? dts.displayErrorInTerminal : undefined
1659
+ }, 'mfOptions.dts')(dts);
1660
+ };
1661
+ var logDtsError = function logDtsError(error, dtsOptions) {
1662
+ if (dtsOptions && dtsOptions.displayErrorInTerminal !== false) {
1663
+ console.error(error);
1664
+ }
1665
+ };
1666
+ function pluginDts(options) {
1667
+ if (options.dts === false) {
1668
+ return [];
1669
+ }
1670
+ var dtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
1671
+ var resolvedConfig;
1672
+ var devWorker;
1673
+ var normalizedDevOptions;
1674
+ var hasGeneratedBundle = false;
1675
+ var devPlugin = {
1676
+ name: 'module-federation-dts-dev',
1677
+ apply: 'serve',
1678
+ config: function config(_config) {
1679
+ normalizedDevOptions = normalizeDevOptions(options.dev);
1680
+ if (!normalizedDevOptions) {
1681
+ return;
1682
+ }
1683
+ if (normalizedDevOptions.disableDynamicRemoteTypeHints) {
1684
+ return;
1685
+ }
1686
+ ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
1687
+ var define = _config.define ? _extends({}, _config.define) : {};
1688
+ if (!('FEDERATION_IPV4' in define)) {
1689
+ define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
1690
+ }
1691
+ _config.define = define;
1692
+ },
1693
+ configResolved: function configResolved(config) {
1694
+ resolvedConfig = config;
1695
+ },
1696
+ configureServer: function configureServer(server) {
1697
+ if (!normalizedDevOptions || !resolvedConfig) {
1698
+ return;
1699
+ }
1700
+ var devOptions = normalizedDevOptions;
1701
+ if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) {
1702
+ return;
1703
+ }
1704
+ if (!options.name) {
1705
+ throw new Error('name is required if you want to enable dev server!');
1706
+ }
1707
+ var outputDir = resolveOutputDir(resolvedConfig);
1708
+ var normalizedDtsOptions = normalizeDevDtsOptions(options.dts, resolvedConfig.root);
1709
+ if (typeof normalizedDtsOptions !== 'object') {
1710
+ return;
1711
+ }
1712
+ var normalizedGenerateTypes = sdk.normalizeOptions(Boolean(normalizedDtsOptions), {
1713
+ compileInChildProcess: true
1714
+ }, 'mfOptions.dts.generateTypes')(normalizedDtsOptions.generateTypes);
1715
+ var remote = normalizedGenerateTypes === false ? undefined : _extends({
1716
+ implementation: normalizedDtsOptions.implementation,
1717
+ context: resolvedConfig.root,
1718
+ outputDir: outputDir,
1719
+ moduleFederationConfig: _extends({}, dtsModuleFederationConfig),
1720
+ hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || '@mf-types'
1721
+ }, normalizedGenerateTypes, {
1722
+ typesFolder: '.dev-server'
1723
+ });
1724
+ if (remote && !remote.tsConfigPath && typeof normalizedDtsOptions === 'object' && normalizedDtsOptions.tsConfigPath) {
1725
+ remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
1726
+ }
1727
+ var normalizedConsumeTypes = sdk.normalizeOptions(Boolean(normalizedDtsOptions), {
1728
+ consumeAPITypes: true
1729
+ }, 'mfOptions.dts.consumeTypes')(normalizedDtsOptions.consumeTypes);
1730
+ var host = normalizedConsumeTypes === false ? undefined : _extends({
1731
+ implementation: normalizedDtsOptions.implementation,
1732
+ context: resolvedConfig.root,
1733
+ moduleFederationConfig: dtsModuleFederationConfig,
1734
+ typesFolder: normalizedConsumeTypes.typesFolder || '@mf-types',
1735
+ abortOnError: false
1736
+ }, normalizedConsumeTypes);
1737
+ var extraOptions = normalizedDtsOptions.extraOptions || {};
1738
+ if (!remote && !host && devOptions.disableLiveReload) {
1739
+ return;
1740
+ }
1741
+ var startDevWorker = function startDevWorker() {
1742
+ try {
1743
+ var _temp2 = function _temp2() {
1744
+ var _server$httpServer;
1745
+ devWorker = new DevWorker({
1746
+ name: options.name,
1747
+ remote: remote,
1748
+ host: host ? _extends({}, host, {
1749
+ remoteTypeUrls: remoteTypeUrls
1750
+ }) : undefined,
1751
+ extraOptions: extraOptions,
1752
+ disableLiveReload: devOptions.disableLiveReload,
1753
+ disableHotTypesReload: devOptions.disableHotTypesReload
1754
+ });
1755
+ var update = function update() {
1756
+ var _devWorker;
1757
+ return (_devWorker = devWorker) == null ? void 0 : _devWorker.update();
1758
+ };
1759
+ server.watcher.on('change', update);
1760
+ server.watcher.on('add', update);
1761
+ server.watcher.on('unlink', update);
1762
+ (_server$httpServer = server.httpServer) == null || _server$httpServer.once('close', function () {
1763
+ var _devWorker2;
1764
+ (_devWorker2 = devWorker) == null || _devWorker2.exit();
1765
+ server.watcher.off('change', update);
1766
+ server.watcher.off('add', update);
1767
+ server.watcher.off('unlink', update);
1768
+ });
1769
+ };
1770
+ var remoteTypeUrls;
1771
+ var _temp = function () {
1772
+ if (host) {
1773
+ return Promise.resolve(new Promise(function (resolve) {
1774
+ dtsPlugin.consumeTypesAPI({
1775
+ host: host,
1776
+ extraOptions: extraOptions,
1777
+ displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
1778
+ }, resolve);
1779
+ })).then(function (_Promise) {
1780
+ remoteTypeUrls = _Promise;
1781
+ });
1782
+ }
1783
+ }();
1784
+ return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp));
1785
+ } catch (e) {
1786
+ return Promise.reject(e);
1787
+ }
1788
+ };
1789
+ startDevWorker()["catch"](function (error) {
1790
+ logDtsError(error, normalizedDtsOptions);
1791
+ });
1792
+ }
1793
+ };
1794
+ var buildPlugin = {
1795
+ name: 'module-federation-dts-build',
1796
+ apply: 'build',
1797
+ configResolved: function configResolved(config) {
1798
+ resolvedConfig = config;
1799
+ },
1800
+ generateBundle: function generateBundle() {
1801
+ try {
1802
+ var _temp6 = function _temp6() {
1803
+ var generateOptions = dtsPlugin.normalizeGenerateTypesOptions({
1804
+ context: context,
1805
+ outputDir: outputDir,
1806
+ dtsOptions: normalizedDtsOptions,
1807
+ pluginOptions: dtsModuleFederationConfig
1808
+ });
1809
+ if (!generateOptions) {
1810
+ return;
1811
+ }
1812
+ var _temp4 = _catch(function () {
1813
+ return Promise.resolve(dtsPlugin.generateTypesAPI({
1814
+ dtsManagerOptions: generateOptions
1815
+ })).then(function () {});
1816
+ }, function (error) {
1817
+ logDtsError(error, normalizedDtsOptions);
1818
+ });
1819
+ if (_temp4 && _temp4.then) return _temp4.then(function () {});
1820
+ };
1821
+ if (hasGeneratedBundle) {
1822
+ return Promise.resolve();
1823
+ }
1824
+ hasGeneratedBundle = true;
1825
+ if (!resolvedConfig) {
1826
+ return Promise.resolve();
1827
+ }
1828
+ var normalizedDtsOptions = dtsPlugin.normalizeDtsOptions(dtsModuleFederationConfig, resolvedConfig.root);
1829
+ if (typeof normalizedDtsOptions !== 'object') {
1830
+ return Promise.resolve();
1831
+ }
1832
+ var context = resolvedConfig.root;
1833
+ var outputDir = resolveOutputDir(resolvedConfig);
1834
+ var consumeOptions = dtsPlugin.normalizeConsumeTypesOptions({
1835
+ context: context,
1836
+ dtsOptions: normalizedDtsOptions,
1837
+ pluginOptions: dtsModuleFederationConfig
1838
+ });
1839
+ var _temp5 = function (_consumeOptions$host) {
1840
+ if (consumeOptions != null && (_consumeOptions$host = consumeOptions.host) != null && _consumeOptions$host.typesOnBuild) {
1841
+ var _temp3 = _catch(function () {
1842
+ return Promise.resolve(dtsPlugin.consumeTypesAPI(consumeOptions)).then(function () {});
1843
+ }, function (error) {
1844
+ logDtsError(error, normalizedDtsOptions);
1845
+ });
1846
+ if (_temp3 && _temp3.then) return _temp3.then(function () {});
1847
+ }
1848
+ }();
1849
+ return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5));
1850
+ } catch (e) {
1851
+ return Promise.reject(e);
1852
+ }
1853
+ }
1854
+ };
1855
+ return [devPlugin, buildPlugin];
1856
+ }
1857
+
1445
1858
  /**
1446
1859
  * example:
1447
1860
  * const store = new PromiseStore<number>();
@@ -1619,7 +2032,7 @@ function federation(mfUserOptions) {
1619
2032
  }
1620
2033
  }, aliasToArrayPlugin, checkAliasConflicts({
1621
2034
  shared: shared
1622
- }), normalizeOptimizeDepsPlugin].concat(addEntry({
2035
+ }), normalizeOptimizeDepsPlugin].concat(pluginDts(options), addEntry({
1623
2036
  entryName: 'remoteEntry',
1624
2037
  entryPath: REMOTE_ENTRY_ID,
1625
2038
  fileName: filename