@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.esm.js CHANGED
@@ -6,6 +6,9 @@ import path__default, { resolve, basename, parse, join, dirname } from 'pathe';
6
6
  import MagicString from 'magic-string';
7
7
  import { createFilter } from '@rollup/pluginutils';
8
8
  import { walk } from 'estree-walker';
9
+ import { normalizeOptions } from '@module-federation/sdk';
10
+ import { normalizeGenerateTypesOptions, generateTypesAPI, normalizeDtsOptions, normalizeConsumeTypesOptions, consumeTypesAPI, isTSProject } from '@module-federation/dts-plugin';
11
+ import { rpc } from '@module-federation/dts-plugin/core';
9
12
 
10
13
  var mapCodeToCodeWithSourcemap = function mapCodeToCodeWithSourcemap(code) {
11
14
  return Promise.resolve(code).then(function (resolvedCode) {
@@ -563,6 +566,96 @@ function createFile(filePath, content) {
563
566
  writeFileSync(filePath, content);
564
567
  }
565
568
 
569
+ /**
570
+ * Serializes a JavaScript object into a string of source code that can be evaluated.
571
+ * This function is used to create runtime plugin options without relying solely on JSON.stringify,
572
+ * allowing support for non-JSON types like RegExp, Date, Map, Set, and Functions.
573
+ * It also safely handles circular references.
574
+ *
575
+ * @param {Record<string, unknown>} options - The options object to serialize.
576
+ * @returns {string} The resulting JavaScript source code string.
577
+ */
578
+ function serializeRuntimeOptions(options) {
579
+ // Use a WeakSet to track objects already encountered, which helps in detecting circular references.
580
+ var seenObjects = new WeakSet();
581
+ /**
582
+ * Recursive inner function to serialize any value into a source code string.
583
+ */
584
+ function valueToCode(val) {
585
+ // 1. Handle primitive values
586
+ if (val === null) return 'null';
587
+ var type = typeof val;
588
+ if (type === 'string') return JSON.stringify(val);
589
+ if (type === 'number' || type === 'boolean') return String(val);
590
+ if (type === 'undefined') return 'undefined';
591
+ // Handle Symbol
592
+ if (type === 'symbol') {
593
+ var _val$description;
594
+ var desc = (_val$description = val.description) != null ? _val$description : '';
595
+ return "Symbol(" + JSON.stringify(desc) + ")";
596
+ }
597
+ // Handle Function (returns the function's source code)
598
+ if (type === 'function') return val.toString();
599
+ // 2. Handle special built-in objects
600
+ if (val instanceof Date) return "new Date(" + JSON.stringify(val.toISOString()) + ")";
601
+ if (val instanceof RegExp) {
602
+ return "new RegExp(" + JSON.stringify(val.source) + ", " + JSON.stringify(val.flags) + ")";
603
+ }
604
+ // 3. Check for circular references and mark object as seen
605
+ // This applies to objects, arrays, maps, and sets.
606
+ if (type === 'object') {
607
+ if (seenObjects.has(val)) {
608
+ // This object has been seen previously in the recursion path
609
+ return "\"__circular__\"";
610
+ }
611
+ seenObjects.add(val);
612
+ }
613
+ // 4. Handle Array, Map, Set
614
+ if (Array.isArray(val)) {
615
+ // Recursively serialize each element
616
+ return "[" + val.map(valueToCode).join(', ') + "]";
617
+ }
618
+ if (val instanceof Map) {
619
+ // Serialize Map entries into an array of [key, value] pairs
620
+ var entries = Array.from(val.entries()).map(function (_ref) {
621
+ var k = _ref[0],
622
+ v = _ref[1];
623
+ return "[" + valueToCode(k) + ", " + valueToCode(v) + "]";
624
+ });
625
+ return "new Map([" + entries.join(', ') + "])";
626
+ }
627
+ if (val instanceof Set) {
628
+ // Serialize Set values into an array
629
+ var items = Array.from(val.values()).map(valueToCode);
630
+ return "new Set([" + items.join(', ') + "])";
631
+ }
632
+ // 5. Handle plain objects (the default object type)
633
+ if (type === 'object') {
634
+ var properties = [];
635
+ // Iterate over the object's own enumerable properties
636
+ for (var key in val) {
637
+ if (Object.prototype.hasOwnProperty.call(val, key)) {
638
+ // Wrap the key in JSON.stringify to handle non-identifier keys
639
+ properties.push(JSON.stringify(key) + ": " + valueToCode(val[key]));
640
+ }
641
+ }
642
+ return "{" + properties.join(', ') + "}";
643
+ }
644
+ // 6. Fallback case (e.g., BigInt, other object types)
645
+ // Coerce to string and then JSON.stringify that string for safety
646
+ return JSON.stringify(String(val));
647
+ }
648
+ // Start serialization for the top-level object
649
+ var topLevelProps = [];
650
+ // Iterate over the properties of the root 'options' object
651
+ for (var key in options) {
652
+ if (Object.prototype.hasOwnProperty.call(options, key)) {
653
+ topLevelProps.push(JSON.stringify(key) + ": " + valueToCode(options[key]));
654
+ }
655
+ }
656
+ return "{" + topLevelProps.join(', ') + "}";
657
+ }
658
+
566
659
  // Cache root path
567
660
  var rootDir;
568
661
  function findNodeModulesDir(root) {
@@ -799,12 +892,16 @@ function generateLocalSharedImportMap() {
799
892
  var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
800
893
  function generateRemoteEntry(options) {
801
894
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
802
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
895
+ if (typeof p === 'string') {
896
+ return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";", "undefined"];
897
+ } else {
898
+ return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p[0] + "\";", serializeRuntimeOptions(p[1])];
899
+ }
803
900
  });
804
901
  return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
805
902
  return item[1];
806
903
  }).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) {
807
- return item[0] + "()";
904
+ return item[0] + "(" + item[2] + ")";
808
905
  }).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 ";
809
906
  }
810
907
  /**
@@ -1418,6 +1515,322 @@ function pluginProxyRemotes (options) {
1418
1515
  };
1419
1516
  }
1420
1517
 
1518
+ function _catch(body, recover) {
1519
+ try {
1520
+ var result = body();
1521
+ } catch (e) {
1522
+ return recover(e);
1523
+ }
1524
+ if (result && result.then) {
1525
+ return result.then(void 0, recover);
1526
+ }
1527
+ return result;
1528
+ }
1529
+ var DEFAULT_DEV_OPTIONS = {
1530
+ disableLiveReload: true,
1531
+ disableHotTypesReload: false,
1532
+ disableDynamicRemoteTypeHints: false
1533
+ };
1534
+ var DYNAMIC_HINTS_PLUGIN = '@module-federation/dts-plugin/dynamic-remote-type-hints-plugin';
1535
+ var getIPv4 = function getIPv4() {
1536
+ return process.env['FEDERATION_IPV4'] || '127.0.0.1';
1537
+ };
1538
+ var forkDevWorkerPath = function () {
1539
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
1540
+ return require.resolve('@module-federation/dts-plugin/dist/fork-dev-worker.js');
1541
+ }();
1542
+ var DevWorker = /*#__PURE__*/function () {
1543
+ function DevWorker(options) {
1544
+ this.worker = rpc.createRpcWorker(forkDevWorkerPath, {}, undefined, false);
1545
+ this.worker.connect(options);
1546
+ }
1547
+ var _proto = DevWorker.prototype;
1548
+ _proto.update = function update() {
1549
+ var _this$worker$process;
1550
+ (_this$worker$process = this.worker.process) == null || _this$worker$process.send == null || _this$worker$process.send({
1551
+ type: rpc.RpcGMCallTypes.CALL,
1552
+ id: this.worker.id,
1553
+ args: [undefined, 'update']
1554
+ });
1555
+ };
1556
+ _proto.exit = function exit() {
1557
+ this.worker.terminate();
1558
+ };
1559
+ return DevWorker;
1560
+ }();
1561
+ var normalizeDevOptions = function normalizeDevOptions(dev) {
1562
+ if (dev === false) {
1563
+ return false;
1564
+ }
1565
+ if (dev === true || typeof dev === 'undefined') {
1566
+ return _extends({}, DEFAULT_DEV_OPTIONS);
1567
+ }
1568
+ return _extends({}, DEFAULT_DEV_OPTIONS, dev);
1569
+ };
1570
+ var buildDtsModuleFederationConfig = function buildDtsModuleFederationConfig(options) {
1571
+ var exposes = {};
1572
+ Object.entries(options.exposes).forEach(function (_ref) {
1573
+ var key = _ref[0],
1574
+ value = _ref[1];
1575
+ if (typeof value === 'string') {
1576
+ exposes[key] = value;
1577
+ return;
1578
+ }
1579
+ var importValue = Array.isArray(value["import"]) ? value["import"][0] : value["import"];
1580
+ if (importValue) {
1581
+ exposes[key] = importValue;
1582
+ }
1583
+ });
1584
+ var remotes = {};
1585
+ Object.entries(options.remotes).forEach(function (_ref2) {
1586
+ var _remote$entryGlobalNa, _remote$entryGlobalNa2;
1587
+ var key = _ref2[0],
1588
+ remote = _ref2[1];
1589
+ if (typeof remote === 'string') {
1590
+ remotes[key] = remote;
1591
+ return;
1592
+ }
1593
+ if (!remote.entry) {
1594
+ return;
1595
+ }
1596
+ var entryLooksLikeUrl = ((_remote$entryGlobalNa = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa.startsWith('http')) || ((_remote$entryGlobalNa2 = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa2.includes('.json'));
1597
+ var entryGlobalName = entryLooksLikeUrl ? remote.name || key : remote.entryGlobalName || remote.name || key;
1598
+ remotes[key] = entryGlobalName + "@" + remote.entry;
1599
+ });
1600
+ return _extends({}, options, {
1601
+ exposes: exposes,
1602
+ remotes: remotes
1603
+ });
1604
+ };
1605
+ var resolveOutputDir = function resolveOutputDir(config) {
1606
+ var outDir = config.build.outDir;
1607
+ if (path.isAbsolute(outDir)) {
1608
+ return path.relative(config.root, outDir);
1609
+ }
1610
+ return outDir;
1611
+ };
1612
+ var ensureRuntimePlugin = function ensureRuntimePlugin(options, pluginId) {
1613
+ var hasPlugin = options.runtimePlugins.some(function (plugin) {
1614
+ if (typeof plugin === 'string') {
1615
+ return plugin === pluginId;
1616
+ }
1617
+ return plugin[0] === pluginId;
1618
+ });
1619
+ if (!hasPlugin) {
1620
+ options.runtimePlugins.push(pluginId);
1621
+ }
1622
+ };
1623
+ var normalizeDevDtsOptions = function normalizeDevDtsOptions(dts, context) {
1624
+ var defaultGenerateTypes = {
1625
+ compileInChildProcess: true
1626
+ };
1627
+ var defaultConsumeTypes = {
1628
+ consumeAPITypes: true
1629
+ };
1630
+ return normalizeOptions(isTSProject(dts, context), {
1631
+ generateTypes: defaultGenerateTypes,
1632
+ consumeTypes: defaultConsumeTypes,
1633
+ extraOptions: {},
1634
+ displayErrorInTerminal: typeof dts === 'object' && dts ? dts.displayErrorInTerminal : undefined
1635
+ }, 'mfOptions.dts')(dts);
1636
+ };
1637
+ var logDtsError = function logDtsError(error, dtsOptions) {
1638
+ if (dtsOptions && dtsOptions.displayErrorInTerminal !== false) {
1639
+ console.error(error);
1640
+ }
1641
+ };
1642
+ function pluginDts(options) {
1643
+ if (options.dts === false) {
1644
+ return [];
1645
+ }
1646
+ var dtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
1647
+ var resolvedConfig;
1648
+ var devWorker;
1649
+ var normalizedDevOptions;
1650
+ var hasGeneratedBundle = false;
1651
+ var devPlugin = {
1652
+ name: 'module-federation-dts-dev',
1653
+ apply: 'serve',
1654
+ config: function config(_config) {
1655
+ normalizedDevOptions = normalizeDevOptions(options.dev);
1656
+ if (!normalizedDevOptions) {
1657
+ return;
1658
+ }
1659
+ if (normalizedDevOptions.disableDynamicRemoteTypeHints) {
1660
+ return;
1661
+ }
1662
+ ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
1663
+ var define = _config.define ? _extends({}, _config.define) : {};
1664
+ if (!('FEDERATION_IPV4' in define)) {
1665
+ define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
1666
+ }
1667
+ _config.define = define;
1668
+ },
1669
+ configResolved: function configResolved(config) {
1670
+ resolvedConfig = config;
1671
+ },
1672
+ configureServer: function configureServer(server) {
1673
+ if (!normalizedDevOptions || !resolvedConfig) {
1674
+ return;
1675
+ }
1676
+ var devOptions = normalizedDevOptions;
1677
+ if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) {
1678
+ return;
1679
+ }
1680
+ if (!options.name) {
1681
+ throw new Error('name is required if you want to enable dev server!');
1682
+ }
1683
+ var outputDir = resolveOutputDir(resolvedConfig);
1684
+ var normalizedDtsOptions = normalizeDevDtsOptions(options.dts, resolvedConfig.root);
1685
+ if (typeof normalizedDtsOptions !== 'object') {
1686
+ return;
1687
+ }
1688
+ var normalizedGenerateTypes = normalizeOptions(Boolean(normalizedDtsOptions), {
1689
+ compileInChildProcess: true
1690
+ }, 'mfOptions.dts.generateTypes')(normalizedDtsOptions.generateTypes);
1691
+ var remote = normalizedGenerateTypes === false ? undefined : _extends({
1692
+ implementation: normalizedDtsOptions.implementation,
1693
+ context: resolvedConfig.root,
1694
+ outputDir: outputDir,
1695
+ moduleFederationConfig: _extends({}, dtsModuleFederationConfig),
1696
+ hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || '@mf-types'
1697
+ }, normalizedGenerateTypes, {
1698
+ typesFolder: '.dev-server'
1699
+ });
1700
+ if (remote && !remote.tsConfigPath && typeof normalizedDtsOptions === 'object' && normalizedDtsOptions.tsConfigPath) {
1701
+ remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
1702
+ }
1703
+ var normalizedConsumeTypes = normalizeOptions(Boolean(normalizedDtsOptions), {
1704
+ consumeAPITypes: true
1705
+ }, 'mfOptions.dts.consumeTypes')(normalizedDtsOptions.consumeTypes);
1706
+ var host = normalizedConsumeTypes === false ? undefined : _extends({
1707
+ implementation: normalizedDtsOptions.implementation,
1708
+ context: resolvedConfig.root,
1709
+ moduleFederationConfig: dtsModuleFederationConfig,
1710
+ typesFolder: normalizedConsumeTypes.typesFolder || '@mf-types',
1711
+ abortOnError: false
1712
+ }, normalizedConsumeTypes);
1713
+ var extraOptions = normalizedDtsOptions.extraOptions || {};
1714
+ if (!remote && !host && devOptions.disableLiveReload) {
1715
+ return;
1716
+ }
1717
+ var startDevWorker = function startDevWorker() {
1718
+ try {
1719
+ var _temp2 = function _temp2() {
1720
+ var _server$httpServer;
1721
+ devWorker = new DevWorker({
1722
+ name: options.name,
1723
+ remote: remote,
1724
+ host: host ? _extends({}, host, {
1725
+ remoteTypeUrls: remoteTypeUrls
1726
+ }) : undefined,
1727
+ extraOptions: extraOptions,
1728
+ disableLiveReload: devOptions.disableLiveReload,
1729
+ disableHotTypesReload: devOptions.disableHotTypesReload
1730
+ });
1731
+ var update = function update() {
1732
+ var _devWorker;
1733
+ return (_devWorker = devWorker) == null ? void 0 : _devWorker.update();
1734
+ };
1735
+ server.watcher.on('change', update);
1736
+ server.watcher.on('add', update);
1737
+ server.watcher.on('unlink', update);
1738
+ (_server$httpServer = server.httpServer) == null || _server$httpServer.once('close', function () {
1739
+ var _devWorker2;
1740
+ (_devWorker2 = devWorker) == null || _devWorker2.exit();
1741
+ server.watcher.off('change', update);
1742
+ server.watcher.off('add', update);
1743
+ server.watcher.off('unlink', update);
1744
+ });
1745
+ };
1746
+ var remoteTypeUrls;
1747
+ var _temp = function () {
1748
+ if (host) {
1749
+ return Promise.resolve(new Promise(function (resolve) {
1750
+ consumeTypesAPI({
1751
+ host: host,
1752
+ extraOptions: extraOptions,
1753
+ displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
1754
+ }, resolve);
1755
+ })).then(function (_Promise) {
1756
+ remoteTypeUrls = _Promise;
1757
+ });
1758
+ }
1759
+ }();
1760
+ return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp));
1761
+ } catch (e) {
1762
+ return Promise.reject(e);
1763
+ }
1764
+ };
1765
+ startDevWorker()["catch"](function (error) {
1766
+ logDtsError(error, normalizedDtsOptions);
1767
+ });
1768
+ }
1769
+ };
1770
+ var buildPlugin = {
1771
+ name: 'module-federation-dts-build',
1772
+ apply: 'build',
1773
+ configResolved: function configResolved(config) {
1774
+ resolvedConfig = config;
1775
+ },
1776
+ generateBundle: function generateBundle() {
1777
+ try {
1778
+ var _temp6 = function _temp6() {
1779
+ var generateOptions = normalizeGenerateTypesOptions({
1780
+ context: context,
1781
+ outputDir: outputDir,
1782
+ dtsOptions: normalizedDtsOptions,
1783
+ pluginOptions: dtsModuleFederationConfig
1784
+ });
1785
+ if (!generateOptions) {
1786
+ return;
1787
+ }
1788
+ var _temp4 = _catch(function () {
1789
+ return Promise.resolve(generateTypesAPI({
1790
+ dtsManagerOptions: generateOptions
1791
+ })).then(function () {});
1792
+ }, function (error) {
1793
+ logDtsError(error, normalizedDtsOptions);
1794
+ });
1795
+ if (_temp4 && _temp4.then) return _temp4.then(function () {});
1796
+ };
1797
+ if (hasGeneratedBundle) {
1798
+ return Promise.resolve();
1799
+ }
1800
+ hasGeneratedBundle = true;
1801
+ if (!resolvedConfig) {
1802
+ return Promise.resolve();
1803
+ }
1804
+ var normalizedDtsOptions = normalizeDtsOptions(dtsModuleFederationConfig, resolvedConfig.root);
1805
+ if (typeof normalizedDtsOptions !== 'object') {
1806
+ return Promise.resolve();
1807
+ }
1808
+ var context = resolvedConfig.root;
1809
+ var outputDir = resolveOutputDir(resolvedConfig);
1810
+ var consumeOptions = normalizeConsumeTypesOptions({
1811
+ context: context,
1812
+ dtsOptions: normalizedDtsOptions,
1813
+ pluginOptions: dtsModuleFederationConfig
1814
+ });
1815
+ var _temp5 = function (_consumeOptions$host) {
1816
+ if (consumeOptions != null && (_consumeOptions$host = consumeOptions.host) != null && _consumeOptions$host.typesOnBuild) {
1817
+ var _temp3 = _catch(function () {
1818
+ return Promise.resolve(consumeTypesAPI(consumeOptions)).then(function () {});
1819
+ }, function (error) {
1820
+ logDtsError(error, normalizedDtsOptions);
1821
+ });
1822
+ if (_temp3 && _temp3.then) return _temp3.then(function () {});
1823
+ }
1824
+ }();
1825
+ return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5));
1826
+ } catch (e) {
1827
+ return Promise.reject(e);
1828
+ }
1829
+ }
1830
+ };
1831
+ return [devPlugin, buildPlugin];
1832
+ }
1833
+
1421
1834
  /**
1422
1835
  * example:
1423
1836
  * const store = new PromiseStore<number>();
@@ -1595,7 +2008,7 @@ function federation(mfUserOptions) {
1595
2008
  }
1596
2009
  }, aliasToArrayPlugin, checkAliasConflicts({
1597
2010
  shared: shared
1598
- }), normalizeOptimizeDepsPlugin].concat(addEntry({
2011
+ }), normalizeOptimizeDepsPlugin].concat(pluginDts(options), addEntry({
1599
2012
  entryName: 'remoteEntry',
1600
2013
  entryPath: REMOTE_ENTRY_ID,
1601
2014
  fileName: filename