@module-federation/vite 1.9.8 → 1.11.0

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.umd.js CHANGED
@@ -145,15 +145,44 @@
145
145
  }
146
146
  },
147
147
  generateBundle: function generateBundle(options, bundle) {
148
- var _viteConfig$experimen, _viteConfig$experimen2;
149
148
  if (!injectHtml()) return;
150
149
  var file = this.getFileName(emitFileId);
151
- var path = (_viteConfig$experimen = viteConfig.experimental) != null && _viteConfig$experimen.renderBuiltUrl ? (_viteConfig$experimen2 = viteConfig.experimental) == null ? void 0 : _viteConfig$experimen2.renderBuiltUrl(file) : viteConfig.base + file;
152
- var scriptContent = "\n <script type=\"module\" src=\"" + path + "\"></script>\n ";
150
+ // Helper to resolve path with proper renderBuiltUrl handling
151
+ var resolvePath = function resolvePath(htmlFileName) {
152
+ var _viteConfig$experimen;
153
+ if (!((_viteConfig$experimen = viteConfig.experimental) != null && _viteConfig$experimen.renderBuiltUrl)) {
154
+ return viteConfig.base + file;
155
+ }
156
+ var result = viteConfig.experimental.renderBuiltUrl(file, {
157
+ hostId: htmlFileName,
158
+ hostType: 'html',
159
+ type: 'asset',
160
+ ssr: false
161
+ });
162
+ // Handle return types
163
+ if (typeof result === 'string') {
164
+ return result;
165
+ }
166
+ if (result && typeof result === 'object') {
167
+ if ('runtime' in result) {
168
+ // Runtime code cannot be used in <script src="">
169
+ console.warn('[vite-plugin-federation] renderBuiltUrl returned runtime code for HTML injection. ' + 'Runtime code cannot be used in <script src="">. Falling back to base path.');
170
+ return viteConfig.base + file;
171
+ }
172
+ if (result.relative) {
173
+ return file;
174
+ }
175
+ }
176
+ // Fallback for undefined or unexpected values
177
+ return viteConfig.base + file;
178
+ };
179
+ // Process each HTML file
153
180
  for (var _fileName in bundle) {
154
181
  if (_fileName.endsWith('.html')) {
155
182
  var htmlAsset = bundle[_fileName];
156
183
  if (htmlAsset.type === 'chunk') return;
184
+ var _path = resolvePath(_fileName);
185
+ var scriptContent = "\n <script type=\"module\" src=\"" + _path + "\"></script>\n ";
157
186
  var htmlContent = htmlAsset.source.toString() || '';
158
187
  htmlContent = htmlContent.replace('<head>', "<head>" + scriptContent);
159
188
  htmlAsset.source = htmlContent;
@@ -342,181 +371,519 @@
342
371
  };
343
372
  }
344
373
 
345
- function normalizeExposesItem(key, item) {
346
- var importPath = '';
347
- if (typeof item === 'string') {
348
- importPath = item;
374
+ function _catch(body, recover) {
375
+ try {
376
+ var result = body();
377
+ } catch (e) {
378
+ return recover(e);
349
379
  }
350
- if (typeof item === 'object') {
351
- importPath = item["import"];
380
+ if (result && result.then) {
381
+ return result.then(void 0, recover);
352
382
  }
353
- return {
354
- "import": importPath
355
- };
356
- }
357
- function normalizeExposes(exposes) {
358
- if (!exposes) return {};
359
- var res = {};
360
- Object.keys(exposes).forEach(function (key) {
361
- res[key] = normalizeExposesItem(key, exposes[key]);
362
- });
363
- return res;
383
+ return result;
364
384
  }
365
- function normalizeRemotes(remotes) {
366
- if (!remotes) return {};
367
- var result = {};
368
- if (typeof remotes === 'object') {
369
- Object.keys(remotes).forEach(function (key) {
370
- result[key] = normalizeRemoteItem(key, remotes[key]);
385
+ var DEFAULT_DEV_OPTIONS = {
386
+ disableLiveReload: true,
387
+ disableHotTypesReload: false,
388
+ disableDynamicRemoteTypeHints: false
389
+ };
390
+ var DYNAMIC_HINTS_PLUGIN = '@module-federation/dts-plugin/dynamic-remote-type-hints-plugin';
391
+ var getIPv4 = function getIPv4() {
392
+ return process.env['FEDERATION_IPV4'] || '127.0.0.1';
393
+ };
394
+ var forkDevWorkerPath = function () {
395
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
396
+ return require.resolve('@module-federation/dts-plugin/dist/fork-dev-worker.js');
397
+ }();
398
+ var DevWorker = /*#__PURE__*/function () {
399
+ function DevWorker(options) {
400
+ this.worker = core.rpc.createRpcWorker(forkDevWorkerPath, {}, undefined, false);
401
+ this.worker.connect(options);
402
+ }
403
+ var _proto = DevWorker.prototype;
404
+ _proto.update = function update() {
405
+ var _this$worker$process;
406
+ (_this$worker$process = this.worker.process) == null || _this$worker$process.send == null || _this$worker$process.send({
407
+ type: core.rpc.RpcGMCallTypes.CALL,
408
+ id: this.worker.id,
409
+ args: [undefined, 'update']
371
410
  });
411
+ };
412
+ _proto.exit = function exit() {
413
+ this.worker.terminate();
414
+ };
415
+ return DevWorker;
416
+ }();
417
+ var normalizeDevOptions = function normalizeDevOptions(dev) {
418
+ if (dev === false) {
419
+ return false;
372
420
  }
373
- return result;
374
- }
375
- function normalizeRemoteItem(key, remote) {
376
- if (typeof remote === 'string') {
377
- var _remote$split = remote.split('@'),
378
- entryGlobalName = _remote$split[0];
379
- var entry = remote.replace(entryGlobalName + '@', '');
380
- return {
381
- type: 'var',
382
- name: key,
383
- entry: entry,
384
- entryGlobalName: entryGlobalName,
385
- shareScope: 'default'
386
- };
421
+ if (dev === true || typeof dev === 'undefined') {
422
+ return _extends({}, DEFAULT_DEV_OPTIONS);
387
423
  }
388
- return Object.assign({
389
- type: 'var',
390
- name: key,
391
- shareScope: 'default',
392
- entryGlobalName: key
393
- }, remote);
394
- }
395
- function removePathFromNpmPackage(packageString) {
396
- // 匹配npm包名的正则表达式,忽略路径部分
397
- var regex = /^(?:@[^/]+\/)?[^/]+/;
398
- // 使用正则表达式匹配并提取包名
399
- var match = packageString.match(regex);
400
- // 返回匹配到的包名,如果没有匹配到则返回原字符串
401
- return match ? match[0] : packageString;
402
- }
403
- /**
404
- * Tries to find the package.json's version of a shared package
405
- * if `package.json` is not declared in `exports`
406
- * @param {string} sharedName
407
- * @returns {string | undefined}
408
- */
409
- function searchPackageVersion(sharedName) {
410
- try {
411
- var sharedPath = require.resolve(sharedName);
412
- var potentialPackageJsonDir = path__namespace.dirname(sharedPath);
413
- var rootDir = path__namespace.parse(potentialPackageJsonDir).root;
414
- while (path__namespace.parse(potentialPackageJsonDir).base !== 'node_modules' && potentialPackageJsonDir !== rootDir) {
415
- var potentialPackageJsonPath = path__namespace.join(potentialPackageJsonDir, 'package.json');
416
- if (fs__namespace.existsSync(potentialPackageJsonPath)) {
417
- var potentialPackageJson = require(potentialPackageJsonPath);
418
- if (typeof potentialPackageJson == 'object' && potentialPackageJson !== null && typeof potentialPackageJson.version === 'string' && potentialPackageJson.name === sharedName) {
419
- return potentialPackageJson.version;
420
- }
421
- }
422
- potentialPackageJsonDir = path__namespace.dirname(potentialPackageJsonDir);
424
+ return _extends({}, DEFAULT_DEV_OPTIONS, dev);
425
+ };
426
+ var buildDtsModuleFederationConfig = function buildDtsModuleFederationConfig(options) {
427
+ var exposes = {};
428
+ Object.entries(options.exposes).forEach(function (_ref) {
429
+ var key = _ref[0],
430
+ value = _ref[1];
431
+ if (typeof value === 'string') {
432
+ exposes[key] = value;
433
+ return;
423
434
  }
424
- } catch (_) {}
425
- return undefined;
426
- }
427
- function normalizeShareItem(key, shareItem) {
428
- var version;
429
- try {
430
- try {
431
- version = require(path__namespace.join(removePathFromNpmPackage(key), 'package.json')).version;
432
- } catch (e1) {
433
- try {
434
- var localPath = path__namespace.join(process.cwd(), 'node_modules', removePathFromNpmPackage(key), 'package.json');
435
- version = require(localPath).version;
436
- } catch (e2) {
437
- version = searchPackageVersion(key);
438
- if (!version) console.error(e1);
439
- }
435
+ var importValue = Array.isArray(value["import"]) ? value["import"][0] : value["import"];
436
+ if (importValue) {
437
+ exposes[key] = importValue;
440
438
  }
441
- } catch (e) {
442
- console.error("Unexpected error resolving version for " + key + ":", e);
443
- }
444
- if (typeof shareItem === 'string') {
445
- return {
446
- name: shareItem,
447
- version: version,
448
- scope: 'default',
449
- from: '',
450
- shareConfig: {
451
- "import": undefined,
452
- singleton: false,
453
- requiredVersion: version ? "^" + version : '*'
454
- }
455
- };
439
+ });
440
+ var remotes = {};
441
+ Object.entries(options.remotes).forEach(function (_ref2) {
442
+ var _remote$entryGlobalNa, _remote$entryGlobalNa2;
443
+ var key = _ref2[0],
444
+ remote = _ref2[1];
445
+ if (typeof remote === 'string') {
446
+ remotes[key] = remote;
447
+ return;
448
+ }
449
+ if (!remote.entry) {
450
+ return;
451
+ }
452
+ var entryLooksLikeUrl = ((_remote$entryGlobalNa = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa.startsWith('http')) || ((_remote$entryGlobalNa2 = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa2.includes('.json'));
453
+ var entryGlobalName = entryLooksLikeUrl ? remote.name || key : remote.entryGlobalName || remote.name || key;
454
+ remotes[key] = entryGlobalName + "@" + remote.entry;
455
+ });
456
+ return _extends({}, options, {
457
+ exposes: exposes,
458
+ remotes: remotes
459
+ });
460
+ };
461
+ var resolveOutputDir = function resolveOutputDir(config) {
462
+ var outDir = config.build.outDir;
463
+ if (path__namespace.isAbsolute(outDir)) {
464
+ return path__namespace.relative(config.root, outDir);
456
465
  }
457
- return {
458
- name: key,
459
- from: '',
460
- version: shareItem.version || version,
461
- scope: shareItem.shareScope || 'default',
462
- shareConfig: {
463
- "import": typeof shareItem === 'object' ? shareItem["import"] : undefined,
464
- singleton: shareItem.singleton || false,
465
- requiredVersion: shareItem.requiredVersion || (version ? "^" + version : '*'),
466
- strictVersion: !!shareItem.strictVersion
466
+ return outDir;
467
+ };
468
+ var ensureRuntimePlugin = function ensureRuntimePlugin(options, pluginId) {
469
+ var hasPlugin = options.runtimePlugins.some(function (plugin) {
470
+ if (typeof plugin === 'string') {
471
+ return plugin === pluginId;
467
472
  }
468
- };
469
- }
470
- function normalizeShared(shared) {
471
- if (!shared) return {};
472
- var result = {};
473
- if (Array.isArray(shared)) {
474
- shared.forEach(function (key) {
475
- result[key] = normalizeShareItem(key, key);
476
- });
477
- return result;
473
+ return plugin[0] === pluginId;
474
+ });
475
+ if (!hasPlugin) {
476
+ options.runtimePlugins.push(pluginId);
478
477
  }
479
- if (typeof shared === 'object') {
480
- Object.keys(shared).forEach(function (key) {
481
- result[key] = normalizeShareItem(key, shared[key]);
482
- });
478
+ };
479
+ var normalizeDevDtsOptions = function normalizeDevDtsOptions(dts, context) {
480
+ var defaultGenerateTypes = {
481
+ compileInChildProcess: true
482
+ };
483
+ var defaultConsumeTypes = {
484
+ consumeAPITypes: true
485
+ };
486
+ return sdk.normalizeOptions(dtsPlugin.isTSProject(dts, context), {
487
+ generateTypes: defaultGenerateTypes,
488
+ consumeTypes: defaultConsumeTypes,
489
+ extraOptions: {},
490
+ displayErrorInTerminal: typeof dts === 'object' && dts ? dts.displayErrorInTerminal : undefined
491
+ }, 'mfOptions.dts')(dts);
492
+ };
493
+ var logDtsError = function logDtsError(error, dtsOptions) {
494
+ if (dtsOptions === false) {
495
+ return;
483
496
  }
484
- return result;
485
- }
486
- function normalizeLibrary(library) {
487
- if (!library) return undefined;
488
- return library;
489
- }
490
- function normalizeManifest(manifest) {
491
- if (manifest === void 0) {
492
- manifest = false;
497
+ if (typeof dtsOptions === 'object' && dtsOptions && dtsOptions.displayErrorInTerminal === false) {
498
+ return;
493
499
  }
494
- if (typeof manifest === 'boolean') {
495
- return manifest;
500
+ console.error(error);
501
+ };
502
+ function pluginDts(options) {
503
+ if (options.dts === false) {
504
+ return [];
496
505
  }
497
- return Object.assign({
498
- filePath: '',
499
- disableAssetsAnalyze: false,
500
- fileName: 'mf-manifest.json'
501
- }, manifest);
506
+ var dtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
507
+ var resolvedConfig;
508
+ var devWorker;
509
+ var normalizedDevOptions;
510
+ var hasGeneratedBundle = false;
511
+ var devPlugin = {
512
+ name: 'module-federation-dts-dev',
513
+ apply: 'serve',
514
+ config: function config(_config) {
515
+ normalizedDevOptions = normalizeDevOptions(options.dev);
516
+ if (!normalizedDevOptions) {
517
+ return;
518
+ }
519
+ if (normalizedDevOptions.disableDynamicRemoteTypeHints) {
520
+ return;
521
+ }
522
+ ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
523
+ var define = _config.define ? _extends({}, _config.define) : {};
524
+ if (!('FEDERATION_IPV4' in define)) {
525
+ define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
526
+ }
527
+ _config.define = define;
528
+ },
529
+ configResolved: function configResolved(config) {
530
+ resolvedConfig = config;
531
+ },
532
+ configureServer: function configureServer(server) {
533
+ if (!normalizedDevOptions || !resolvedConfig) {
534
+ return;
535
+ }
536
+ var devOptions = normalizedDevOptions;
537
+ if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) {
538
+ return;
539
+ }
540
+ if (!options.name) {
541
+ throw new Error('name is required if you want to enable dev server!');
542
+ }
543
+ var outputDir = resolveOutputDir(resolvedConfig);
544
+ var normalizedDtsOptions = normalizeDevDtsOptions(options.dts, resolvedConfig.root);
545
+ if (typeof normalizedDtsOptions !== 'object') {
546
+ return;
547
+ }
548
+ var normalizedGenerateTypes = sdk.normalizeOptions(Boolean(normalizedDtsOptions), {
549
+ compileInChildProcess: true
550
+ }, 'mfOptions.dts.generateTypes')(normalizedDtsOptions.generateTypes);
551
+ var remote = normalizedGenerateTypes === false ? undefined : _extends({
552
+ implementation: normalizedDtsOptions.implementation,
553
+ context: resolvedConfig.root,
554
+ outputDir: outputDir,
555
+ moduleFederationConfig: _extends({}, dtsModuleFederationConfig),
556
+ hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || '@mf-types'
557
+ }, normalizedGenerateTypes, {
558
+ typesFolder: '.dev-server'
559
+ });
560
+ if (remote && !remote.tsConfigPath && typeof normalizedDtsOptions === 'object' && normalizedDtsOptions.tsConfigPath) {
561
+ remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
562
+ }
563
+ var normalizedConsumeTypes = sdk.normalizeOptions(Boolean(normalizedDtsOptions), {
564
+ consumeAPITypes: true
565
+ }, 'mfOptions.dts.consumeTypes')(normalizedDtsOptions.consumeTypes);
566
+ var host = normalizedConsumeTypes === false ? undefined : _extends({
567
+ implementation: normalizedDtsOptions.implementation,
568
+ context: resolvedConfig.root,
569
+ moduleFederationConfig: dtsModuleFederationConfig,
570
+ typesFolder: normalizedConsumeTypes.typesFolder || '@mf-types',
571
+ abortOnError: false
572
+ }, normalizedConsumeTypes);
573
+ var extraOptions = normalizedDtsOptions.extraOptions || {};
574
+ if (!remote && !host && devOptions.disableLiveReload) {
575
+ return;
576
+ }
577
+ var startDevWorker = function startDevWorker() {
578
+ try {
579
+ var _temp2 = function _temp2() {
580
+ var _server$httpServer;
581
+ devWorker = new DevWorker({
582
+ name: options.name,
583
+ remote: remote,
584
+ host: host ? _extends({}, host, {
585
+ remoteTypeUrls: remoteTypeUrls
586
+ }) : undefined,
587
+ extraOptions: extraOptions,
588
+ disableLiveReload: devOptions.disableLiveReload,
589
+ disableHotTypesReload: devOptions.disableHotTypesReload
590
+ });
591
+ var update = function update() {
592
+ var _devWorker;
593
+ return (_devWorker = devWorker) == null ? void 0 : _devWorker.update();
594
+ };
595
+ server.watcher.on('change', update);
596
+ server.watcher.on('add', update);
597
+ server.watcher.on('unlink', update);
598
+ (_server$httpServer = server.httpServer) == null || _server$httpServer.once('close', function () {
599
+ var _devWorker2;
600
+ (_devWorker2 = devWorker) == null || _devWorker2.exit();
601
+ server.watcher.off('change', update);
602
+ server.watcher.off('add', update);
603
+ server.watcher.off('unlink', update);
604
+ });
605
+ };
606
+ var remoteTypeUrls;
607
+ var _temp = function () {
608
+ if (host) {
609
+ return Promise.resolve(new Promise(function (resolve) {
610
+ dtsPlugin.consumeTypesAPI({
611
+ host: host,
612
+ extraOptions: extraOptions,
613
+ displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
614
+ }, resolve);
615
+ })).then(function (_Promise) {
616
+ remoteTypeUrls = _Promise;
617
+ });
618
+ }
619
+ }();
620
+ return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp));
621
+ } catch (e) {
622
+ return Promise.reject(e);
623
+ }
624
+ };
625
+ startDevWorker()["catch"](function (error) {
626
+ logDtsError(error, normalizedDtsOptions);
627
+ });
628
+ }
629
+ };
630
+ var buildPlugin = {
631
+ name: 'module-federation-dts-build',
632
+ apply: 'build',
633
+ configResolved: function configResolved(config) {
634
+ resolvedConfig = config;
635
+ },
636
+ generateBundle: function generateBundle() {
637
+ try {
638
+ var _temp6 = function _temp6() {
639
+ var generateOptions;
640
+ try {
641
+ generateOptions = dtsPlugin.normalizeGenerateTypesOptions({
642
+ context: context,
643
+ outputDir: outputDir,
644
+ dtsOptions: normalizedDtsOptions,
645
+ pluginOptions: dtsModuleFederationConfig
646
+ });
647
+ } catch (error) {
648
+ logDtsError(error, normalizedDtsOptions);
649
+ return;
650
+ }
651
+ if (!generateOptions) {
652
+ return;
653
+ }
654
+ var _temp4 = _catch(function () {
655
+ return Promise.resolve(dtsPlugin.generateTypesAPI({
656
+ dtsManagerOptions: generateOptions
657
+ })).then(function () {});
658
+ }, function (error) {
659
+ logDtsError(error, normalizedDtsOptions);
660
+ });
661
+ if (_temp4 && _temp4.then) return _temp4.then(function () {});
662
+ };
663
+ if (hasGeneratedBundle) {
664
+ return Promise.resolve();
665
+ }
666
+ hasGeneratedBundle = true;
667
+ if (!resolvedConfig) {
668
+ return Promise.resolve();
669
+ }
670
+ var normalizedDtsOptions;
671
+ try {
672
+ normalizedDtsOptions = dtsPlugin.normalizeDtsOptions(dtsModuleFederationConfig, resolvedConfig.root);
673
+ } catch (error) {
674
+ logDtsError(error, options.dts);
675
+ return Promise.resolve();
676
+ }
677
+ if (typeof normalizedDtsOptions !== 'object') {
678
+ return Promise.resolve();
679
+ }
680
+ var context = resolvedConfig.root;
681
+ var outputDir = resolveOutputDir(resolvedConfig);
682
+ var consumeOptions;
683
+ try {
684
+ consumeOptions = dtsPlugin.normalizeConsumeTypesOptions({
685
+ context: context,
686
+ dtsOptions: normalizedDtsOptions,
687
+ pluginOptions: dtsModuleFederationConfig
688
+ });
689
+ } catch (error) {
690
+ logDtsError(error, normalizedDtsOptions);
691
+ return Promise.resolve();
692
+ }
693
+ var _temp5 = function (_consumeOptions) {
694
+ if ((_consumeOptions = consumeOptions) != null && (_consumeOptions = _consumeOptions.host) != null && _consumeOptions.typesOnBuild) {
695
+ var _temp3 = _catch(function () {
696
+ return Promise.resolve(dtsPlugin.consumeTypesAPI(consumeOptions)).then(function () {});
697
+ }, function (error) {
698
+ logDtsError(error, normalizedDtsOptions);
699
+ });
700
+ if (_temp3 && _temp3.then) return _temp3.then(function () {});
701
+ }
702
+ }();
703
+ return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5));
704
+ } catch (e) {
705
+ return Promise.reject(e);
706
+ }
707
+ }
708
+ };
709
+ return [devPlugin, buildPlugin];
502
710
  }
503
- var config;
504
- function getNormalizeModuleFederationOptions() {
505
- return config;
711
+
712
+ function normalizeExposesItem(key, item) {
713
+ var importPath = '';
714
+ if (typeof item === 'string') {
715
+ importPath = item;
716
+ }
717
+ if (typeof item === 'object') {
718
+ importPath = item["import"];
719
+ }
720
+ return {
721
+ "import": importPath
722
+ };
506
723
  }
507
- function getNormalizeShareItem(key) {
508
- var options = getNormalizeModuleFederationOptions();
509
- var shareItem = options.shared[key] || options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + '/'];
510
- return shareItem;
724
+ function normalizeExposes(exposes) {
725
+ if (!exposes) return {};
726
+ var res = {};
727
+ Object.keys(exposes).forEach(function (key) {
728
+ res[key] = normalizeExposesItem(key, exposes[key]);
729
+ });
730
+ return res;
511
731
  }
512
- function normalizeModuleFederationOptions(options) {
513
- if (options.virtualModuleDir && options.virtualModuleDir.includes('/')) {
514
- throw new Error("Invalid virtualModuleDir: \"" + options.virtualModuleDir + "\". " + "The virtualModuleDir option cannot contain slashes (/). " + "Please use a single directory name like '__mf__virtual__your_app_name'.");
732
+ function normalizeRemotes(remotes) {
733
+ if (!remotes) return {};
734
+ var result = {};
735
+ if (typeof remotes === 'object') {
736
+ Object.keys(remotes).forEach(function (key) {
737
+ result[key] = normalizeRemoteItem(key, remotes[key]);
738
+ });
515
739
  }
516
- return config = {
517
- exposes: normalizeExposes(options.exposes),
518
- filename: options.filename || 'remoteEntry-[hash]',
519
- library: normalizeLibrary(options.library),
740
+ return result;
741
+ }
742
+ function normalizeRemoteItem(key, remote) {
743
+ if (typeof remote === 'string') {
744
+ var _remote$split = remote.split('@'),
745
+ entryGlobalName = _remote$split[0];
746
+ var entry = remote.replace(entryGlobalName + '@', '');
747
+ return {
748
+ type: 'var',
749
+ name: key,
750
+ entry: entry,
751
+ entryGlobalName: entryGlobalName,
752
+ shareScope: 'default'
753
+ };
754
+ }
755
+ return Object.assign({
756
+ type: 'var',
757
+ name: key,
758
+ shareScope: 'default',
759
+ entryGlobalName: key
760
+ }, remote);
761
+ }
762
+ function removePathFromNpmPackage(packageString) {
763
+ // 匹配npm包名的正则表达式,忽略路径部分
764
+ var regex = /^(?:@[^/]+\/)?[^/]+/;
765
+ // 使用正则表达式匹配并提取包名
766
+ var match = packageString.match(regex);
767
+ // 返回匹配到的包名,如果没有匹配到则返回原字符串
768
+ return match ? match[0] : packageString;
769
+ }
770
+ /**
771
+ * Tries to find the package.json's version of a shared package
772
+ * if `package.json` is not declared in `exports`
773
+ * @param {string} sharedName
774
+ * @returns {string | undefined}
775
+ */
776
+ function searchPackageVersion(sharedName) {
777
+ try {
778
+ var sharedPath = require.resolve(sharedName);
779
+ var potentialPackageJsonDir = path__namespace.dirname(sharedPath);
780
+ var rootDir = path__namespace.parse(potentialPackageJsonDir).root;
781
+ while (path__namespace.parse(potentialPackageJsonDir).base !== 'node_modules' && potentialPackageJsonDir !== rootDir) {
782
+ var potentialPackageJsonPath = path__namespace.join(potentialPackageJsonDir, 'package.json');
783
+ if (fs__namespace.existsSync(potentialPackageJsonPath)) {
784
+ var potentialPackageJson = require(potentialPackageJsonPath);
785
+ if (typeof potentialPackageJson == 'object' && potentialPackageJson !== null && typeof potentialPackageJson.version === 'string' && potentialPackageJson.name === sharedName) {
786
+ return potentialPackageJson.version;
787
+ }
788
+ }
789
+ potentialPackageJsonDir = path__namespace.dirname(potentialPackageJsonDir);
790
+ }
791
+ } catch (_) {}
792
+ return undefined;
793
+ }
794
+ function normalizeShareItem(key, shareItem) {
795
+ var version;
796
+ try {
797
+ try {
798
+ version = require(path__namespace.join(removePathFromNpmPackage(key), 'package.json')).version;
799
+ } catch (e1) {
800
+ try {
801
+ var localPath = path__namespace.join(process.cwd(), 'node_modules', removePathFromNpmPackage(key), 'package.json');
802
+ version = require(localPath).version;
803
+ } catch (e2) {
804
+ version = searchPackageVersion(key);
805
+ if (!version) console.error(e1);
806
+ }
807
+ }
808
+ } catch (e) {
809
+ console.error("Unexpected error resolving version for " + key + ":", e);
810
+ }
811
+ if (typeof shareItem === 'string') {
812
+ return {
813
+ name: shareItem,
814
+ version: version,
815
+ scope: 'default',
816
+ from: '',
817
+ shareConfig: {
818
+ "import": undefined,
819
+ singleton: false,
820
+ requiredVersion: version ? "^" + version : '*'
821
+ }
822
+ };
823
+ }
824
+ return {
825
+ name: key,
826
+ from: '',
827
+ version: shareItem.version || version,
828
+ scope: shareItem.shareScope || 'default',
829
+ shareConfig: {
830
+ "import": typeof shareItem === 'object' ? shareItem["import"] : undefined,
831
+ singleton: shareItem.singleton || false,
832
+ requiredVersion: shareItem.requiredVersion || (version ? "^" + version : '*'),
833
+ strictVersion: !!shareItem.strictVersion
834
+ }
835
+ };
836
+ }
837
+ function normalizeShared(shared) {
838
+ if (!shared) return {};
839
+ var result = {};
840
+ if (Array.isArray(shared)) {
841
+ shared.forEach(function (key) {
842
+ result[key] = normalizeShareItem(key, key);
843
+ });
844
+ return result;
845
+ }
846
+ if (typeof shared === 'object') {
847
+ Object.keys(shared).forEach(function (key) {
848
+ result[key] = normalizeShareItem(key, shared[key]);
849
+ });
850
+ }
851
+ return result;
852
+ }
853
+ function normalizeLibrary(library) {
854
+ if (!library) return undefined;
855
+ return library;
856
+ }
857
+ function normalizeManifest(manifest) {
858
+ if (manifest === void 0) {
859
+ manifest = false;
860
+ }
861
+ if (typeof manifest === 'boolean') {
862
+ return manifest;
863
+ }
864
+ return Object.assign({
865
+ filePath: '',
866
+ disableAssetsAnalyze: false,
867
+ fileName: 'mf-manifest.json'
868
+ }, manifest);
869
+ }
870
+ var config;
871
+ function getNormalizeModuleFederationOptions() {
872
+ return config;
873
+ }
874
+ function getNormalizeShareItem(key) {
875
+ var options = getNormalizeModuleFederationOptions();
876
+ var shareItem = options.shared[key] || options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + '/'];
877
+ return shareItem;
878
+ }
879
+ function normalizeModuleFederationOptions(options) {
880
+ if (options.virtualModuleDir && options.virtualModuleDir.includes('/')) {
881
+ throw new Error("Invalid virtualModuleDir: \"" + options.virtualModuleDir + "\". " + "The virtualModuleDir option cannot contain slashes (/). " + "Please use a single directory name like '__mf__virtual__your_app_name'.");
882
+ }
883
+ return config = {
884
+ exposes: normalizeExposes(options.exposes),
885
+ filename: options.filename || 'remoteEntry-[hash]',
886
+ library: normalizeLibrary(options.library),
520
887
  name: options.name,
521
888
  // remoteType: options.remoteType,
522
889
  remotes: normalizeRemotes(options.remotes),
@@ -534,7 +901,9 @@
534
901
  ignoreOrigin: options.ignoreOrigin || false,
535
902
  virtualModuleDir: options.virtualModuleDir || '__mf__virtual',
536
903
  hostInitInjectLocation: options.hostInitInjectLocation || 'html',
537
- bundleAllCSS: options.bundleAllCSS || false
904
+ bundleAllCSS: options.bundleAllCSS || false,
905
+ moduleParseTimeout: options.moduleParseTimeout || 10,
906
+ varFilename: options.varFilename
538
907
  };
539
908
  }
540
909
 
@@ -907,969 +1276,662 @@
907
1276
  }).filter(function (x) {
908
1277
  return x !== null;
909
1278
  }).join(',') + "\n ]\n export {\n usedShared,\n usedRemotes\n }\n ";
910
- }
911
- var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
912
- function generateRemoteEntry(options) {
913
- var pluginImportNames = options.runtimePlugins.map(function (p, i) {
914
- if (typeof p === 'string') {
915
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";", "undefined"];
916
- } else {
917
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p[0] + "\";", serializeRuntimeOptions(p[1])];
918
- }
919
- });
920
- return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
921
- return item[1];
922
- }).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) {
923
- return item[0] + "(" + item[2] + ")";
924
- }).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 ";
925
- }
926
- /**
927
- * Inject entry file, automatically init when used as host,
928
- * and will not inject remoteEntry
929
- */
930
- var HOST_AUTO_INIT_TAG = '__H_A_I__';
931
- var hostAutoInitModule = new VirtualModule('hostAutoInit', HOST_AUTO_INIT_TAG);
932
- function writeHostAutoInit() {
933
- hostAutoInitModule.writeSync("\n const remoteEntryPromise = import(\"" + REMOTE_ENTRY_ID + "\")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ");
934
- }
935
- function getHostAutoInitImportId() {
936
- return hostAutoInitModule.getImportId();
937
- }
938
- function getHostAutoInitPath() {
939
- return hostAutoInitModule.getPath();
940
- }
941
-
942
- function initVirtualModules() {
943
- writeLocalSharedImportMap();
944
- writeHostAutoInit();
945
- writeRuntimeInitStatus();
946
- }
947
-
948
- var ASSET_TYPES = ['js', 'css'];
949
- var LOAD_TIMINGS = ['sync', 'async'];
950
- var JS_EXTENSIONS = ['.ts', '.tsx', '.jsx', '.mjs', '.cjs'];
951
- /**
952
- * Creates an empty asset map structure for tracking JS and CSS assets
953
- * @returns Initialized asset map with sync/async arrays for JS and CSS
954
- */
955
- var createEmptyAssetMap = function createEmptyAssetMap() {
956
- return {
957
- js: {
958
- sync: [],
959
- async: []
960
- },
961
- css: {
962
- sync: [],
963
- async: []
964
- }
965
- };
966
- };
967
- /**
968
- * Tracks an asset in the preload map with deduplication
969
- * @param map - The preload map to update
970
- * @param key - The module key to track under
971
- * @param fileName - The asset filename to track
972
- * @param isAsync - Whether the asset is loaded async
973
- * @param type - The asset type ('js' or 'css')
974
- */
975
- var trackAsset = function trackAsset(map, key, fileName, isAsync, type) {
976
- if (!map[key]) {
977
- map[key] = createEmptyAssetMap();
978
- }
979
- var target = isAsync ? map[key][type].async : map[key][type].sync;
980
- if (!target.includes(fileName)) {
981
- target.push(fileName);
982
- }
983
- };
984
- /**
985
- * Checks if a file is a CSS file by extension
986
- * @param fileName - The filename to check
987
- * @returns True if file has a CSS extension (.css, .scss, .less)
988
- */
989
- var isCSSFile = function isCSSFile(fileName) {
990
- return fileName.endsWith('.css') || fileName.endsWith('.scss') || fileName.endsWith('.less');
991
- };
992
- /**
993
- * Collects all CSS assets from the bundle
994
- * @param bundle - The Rollup output bundle
995
- * @returns Set of CSS asset filenames
996
- */
997
- var collectCssAssets = function collectCssAssets(bundle) {
998
- var cssAssets = new Set();
999
- for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1000
- var _Object$entries$_i = _Object$entries[_i],
1001
- fileName = _Object$entries$_i[0],
1002
- fileData = _Object$entries$_i[1];
1003
- if (fileData.type === 'asset' && isCSSFile(fileName)) {
1004
- cssAssets.add(fileName);
1005
- }
1006
- }
1007
- return cssAssets;
1008
- };
1009
- /**
1010
- * Processes module assets and tracks them in the files map
1011
- * @param bundle - The Rollup output bundle
1012
- * @param filesMap - The preload map to populate
1013
- * @param moduleMatcher - Function that matches module paths to keys
1014
- */
1015
- var processModuleAssets = function processModuleAssets(bundle, filesMap, moduleMatcher) {
1016
- for (var _i2 = 0, _Object$entries2 = Object.entries(bundle); _i2 < _Object$entries2.length; _i2++) {
1017
- var _Object$entries2$_i = _Object$entries2[_i2],
1018
- fileName = _Object$entries2$_i[0],
1019
- fileData = _Object$entries2$_i[1];
1020
- if (fileData.type !== 'chunk') continue;
1021
- if (!fileData.modules) continue;
1022
- for (var _i3 = 0, _Object$keys = Object.keys(fileData.modules); _i3 < _Object$keys.length; _i3++) {
1023
- var modulePath = _Object$keys[_i3];
1024
- var matchKey = moduleMatcher(modulePath);
1025
- if (!matchKey) continue;
1026
- // Track main JS chunk
1027
- trackAsset(filesMap, matchKey, fileName, false, 'js');
1028
- // Handle dynamic imports
1029
- if (fileData.dynamicImports) {
1030
- for (var _iterator = _createForOfIteratorHelperLoose(fileData.dynamicImports), _step; !(_step = _iterator()).done;) {
1031
- var dynamicImport = _step.value;
1032
- var importData = bundle[dynamicImport];
1033
- if (!importData) continue;
1034
- var isCss = isCSSFile(dynamicImport);
1035
- trackAsset(filesMap, matchKey, dynamicImport, true, isCss ? 'css' : 'js');
1036
- }
1037
- }
1038
- }
1039
- }
1040
- };
1041
- /**
1042
- * Deduplicates assets in the files map
1043
- * @param filesMap - The preload map to deduplicate
1044
- * @returns New deduplicated preload map
1045
- */
1046
- var deduplicateAssets = function deduplicateAssets(filesMap) {
1047
- var result = {};
1048
- for (var _i4 = 0, _Object$entries3 = Object.entries(filesMap); _i4 < _Object$entries3.length; _i4++) {
1049
- var _Object$entries3$_i = _Object$entries3[_i4],
1050
- key = _Object$entries3$_i[0],
1051
- assetMaps = _Object$entries3$_i[1];
1052
- result[key] = createEmptyAssetMap();
1053
- for (var _i5 = 0, _ASSET_TYPES = ASSET_TYPES; _i5 < _ASSET_TYPES.length; _i5++) {
1054
- var type = _ASSET_TYPES[_i5];
1055
- for (var _i6 = 0, _LOAD_TIMINGS = LOAD_TIMINGS; _i6 < _LOAD_TIMINGS.length; _i6++) {
1056
- var timing = _LOAD_TIMINGS[_i6];
1057
- result[key][type][timing] = Array.from(new Set(assetMaps[type][timing]));
1058
- }
1059
- }
1060
- }
1061
- return result;
1062
- };
1063
- /**
1064
- * Builds a mapping between module files and their share keys
1065
- * @param shareKeys - Set of share keys to map
1066
- * @param resolveFn - Function to resolve module paths
1067
- * @returns Map of file paths to their corresponding share keys
1068
- */
1069
- var buildFileToShareKeyMap = function buildFileToShareKeyMap(shareKeys, resolveFn) {
1070
- try {
1071
- var fileToShareKey = new Map();
1072
- return Promise.resolve(Promise.all(Array.from(shareKeys).map(function (shareKey) {
1073
- return resolveFn(getPreBuildLibImportId(shareKey)).then(function (resolution) {
1074
- var _resolution$id;
1075
- return {
1076
- shareKey: shareKey,
1077
- file: resolution == null || (_resolution$id = resolution.id) == null ? void 0 : _resolution$id.split('?')[0]
1078
- };
1079
- })["catch"](function () {
1080
- return null;
1081
- });
1082
- }))).then(function (resolutions) {
1083
- for (var _iterator2 = _createForOfIteratorHelperLoose(resolutions), _step2; !(_step2 = _iterator2()).done;) {
1084
- var resolution = _step2.value;
1085
- if (resolution != null && resolution.file) {
1086
- fileToShareKey.set(resolution.file, resolution.shareKey);
1087
- }
1088
- }
1089
- return fileToShareKey;
1090
- });
1091
- } catch (e) {
1092
- return Promise.reject(e);
1093
- }
1094
- };
1095
-
1096
- /**
1097
- * Resolves the public path for remote entries
1098
- * @param options - Module Federation options
1099
- * @param viteBase - Vite's base config value
1100
- * @param originalBase - Original base config before any transformations
1101
- * @returns The resolved public path
1102
- */
1103
- function resolvePublicPath(options, viteBase, originalBase) {
1104
- // Use explicitly set publicPath if provided
1105
- if (options.publicPath) {
1106
- return options.publicPath;
1107
- }
1108
- // Handle empty original base case
1109
- if (originalBase === '') {
1110
- return 'auto';
1111
- }
1112
- // Use viteBase if available, ensuring it ends with a slash
1113
- if (viteBase) {
1114
- return viteBase.replace(/\/?$/, '/');
1115
- }
1116
- // Fallback to auto if no base is specified
1117
- return 'auto';
1118
- }
1119
-
1120
- var Manifest = function Manifest() {
1121
- var mfOptions = getNormalizeModuleFederationOptions();
1122
- var name = mfOptions.name,
1123
- filename = mfOptions.filename,
1124
- getPublicPath = mfOptions.getPublicPath,
1125
- manifestOptions = mfOptions.manifest;
1126
- var mfManifestName = '';
1127
- if (manifestOptions === true) {
1128
- mfManifestName = 'mf-manifest.json';
1129
- }
1130
- if (typeof manifestOptions !== 'boolean') {
1131
- mfManifestName = path__namespace.join((manifestOptions == null ? void 0 : manifestOptions.filePath) || '', (manifestOptions == null ? void 0 : manifestOptions.fileName) || '');
1132
- }
1133
- var root;
1134
- var remoteEntryFile;
1135
- var publicPath;
1136
- var _command;
1137
- var _originalConfigBase;
1138
- var viteConfig;
1139
- /**
1140
- * Adds global CSS assets to all module exports
1141
- * @param filesMap - The preload map to update
1142
- * @param cssAssets - Set of CSS asset filenames to add
1143
- */
1144
- var addCssAssetsToAllExports = function addCssAssetsToAllExports(filesMap, cssAssets) {
1145
- Object.keys(filesMap).forEach(function (key) {
1146
- cssAssets.forEach(function (cssAsset) {
1147
- trackAsset(filesMap, key, cssAsset, false, 'css');
1148
- });
1149
- });
1150
- };
1151
- return [{
1152
- name: 'module-federation-manifest',
1153
- apply: 'serve',
1154
- /**
1155
- * Stores resolved Vite config for later use
1156
- */
1157
- /**
1158
- * Finalizes configuration after all plugins are resolved
1159
- * @param config - Fully resolved Vite config
1160
- */
1161
- configResolved: function configResolved(config) {
1162
- viteConfig = config;
1163
- },
1164
- /**
1165
- * Configures dev server middleware to handle manifest requests
1166
- * @param server - Vite dev server instance
1167
- */
1168
- configureServer: function configureServer(server) {
1169
- server.middlewares.use(function (req, res, next) {
1170
- var _req$url;
1171
- if (!mfManifestName) {
1172
- next();
1173
- return;
1174
- }
1175
- if (((_req$url = req.url) == null ? void 0 : _req$url.replace(/\?.*/, '')) === (viteConfig.base + mfManifestName).replace(/^\/?/, '/')) {
1176
- res.setHeader('Content-Type', 'application/json');
1177
- res.setHeader('Access-Control-Allow-Origin', '*');
1178
- res.end(JSON.stringify(_extends({}, generateMFManifest({}), {
1179
- id: name,
1180
- name: name,
1181
- metaData: {
1182
- name: name,
1183
- type: 'app',
1184
- buildInfo: {
1185
- buildVersion: '1.0.0',
1186
- buildName: name
1187
- },
1188
- remoteEntry: {
1189
- name: filename,
1190
- path: '',
1191
- type: 'module'
1192
- },
1193
- ssrRemoteEntry: {
1194
- name: filename,
1195
- path: '',
1196
- type: 'module'
1197
- },
1198
- types: {
1199
- path: '',
1200
- name: ''
1201
- },
1202
- globalName: name,
1203
- pluginVersion: '0.2.5',
1204
- publicPath: publicPath
1205
- }
1206
- })));
1207
- } else {
1208
- next();
1209
- }
1210
- });
1211
- }
1212
- }, {
1213
- name: 'module-federation-manifest',
1214
- enforce: 'post',
1215
- /**
1216
- * Initial plugin configuration
1217
- * @param config - Vite config object
1218
- * @param command - Current Vite command (serve/build)
1219
- */
1220
- config: function config(_config, _ref) {
1221
- var command = _ref.command;
1222
- if (!_config.build) _config.build = {};
1223
- if (!_config.build.manifest) {
1224
- _config.build.manifest = _config.build.manifest || !!manifestOptions;
1225
- }
1226
- _command = command;
1227
- _originalConfigBase = _config.base;
1228
- },
1229
- configResolved: function configResolved(config) {
1230
- root = config.root;
1231
- var base = config.base;
1232
- if (_command === 'serve') {
1233
- base = (config.server.origin || '') + config.base;
1234
- }
1235
- publicPath = resolvePublicPath(mfOptions, base, _originalConfigBase);
1236
- },
1237
- /**
1238
- * Generates the module federation manifest file
1239
- * @param options - Rollup output options
1240
- * @param bundle - Generated bundle assets
1241
- */
1242
- generateBundle: function generateBundle(options, bundle) {
1243
- try {
1244
- var _this = this;
1245
- if (!mfManifestName) return Promise.resolve();
1246
- var filesMap = {};
1247
- // First pass: Find remoteEntry file
1248
- for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1249
- var _Object$entries$_i = _Object$entries[_i],
1250
- _ = _Object$entries$_i[0],
1251
- fileData = _Object$entries$_i[1];
1252
- if (mfOptions.filename.replace(/[\[\]]/g, '_').replace(/\.[^/.]+$/, '') === fileData.name || fileData.name === 'remoteEntry') {
1253
- remoteEntryFile = fileData.fileName;
1254
- break; // We can break early since we only need to find remoteEntry once
1255
- }
1256
- }
1257
- // Second pass: Collect all CSS assets
1258
- var allCssAssets = mfOptions.bundleAllCSS ? collectCssAssets(bundle) : new Set();
1259
- var exposesModules = Object.keys(mfOptions.exposes).map(function (item) {
1260
- return mfOptions.exposes[item]["import"];
1261
- });
1262
- // Process exposed modules
1263
- processModuleAssets(bundle, filesMap, function (modulePath) {
1264
- var absoluteModulePath = path__namespace.resolve(root, modulePath);
1265
- return exposesModules.find(function (exposeModule) {
1266
- var exposePath = path__namespace.resolve(root, exposeModule);
1267
- // First try exact path match
1268
- if (absoluteModulePath === exposePath) {
1269
- return true;
1270
- }
1271
- // Then try path match without known extensions
1272
- var getPathWithoutKnownExt = function getPathWithoutKnownExt(filePath) {
1273
- var ext = path__namespace.extname(filePath);
1274
- return JS_EXTENSIONS.includes(ext) ? path__namespace.join(path__namespace.dirname(filePath), path__namespace.basename(filePath, ext)) : filePath;
1275
- };
1276
- var modulePathNoExt = getPathWithoutKnownExt(absoluteModulePath);
1277
- var exposePathNoExt = getPathWithoutKnownExt(exposePath);
1278
- return modulePathNoExt === exposePathNoExt;
1279
- });
1280
- });
1281
- // Process shared modules
1282
- return Promise.resolve(buildFileToShareKeyMap(getUsedShares(), _this.resolve.bind(_this))).then(function (fileToShareKey) {
1283
- processModuleAssets(bundle, filesMap, function (modulePath) {
1284
- return fileToShareKey.get(modulePath);
1285
- });
1286
- // Add all CSS assets to every export if bundleAllCSS is enabled
1287
- if (mfOptions.bundleAllCSS) {
1288
- addCssAssetsToAllExports(filesMap, allCssAssets);
1289
- }
1290
- // Final deduplication of all assets
1291
- filesMap = deduplicateAssets(filesMap);
1292
- _this.emitFile({
1293
- type: 'asset',
1294
- fileName: mfManifestName,
1295
- source: JSON.stringify(generateMFManifest(filesMap))
1296
- });
1297
- });
1298
- } catch (e) {
1299
- return Promise.reject(e);
1300
- }
1301
- }
1302
- }];
1303
- /**
1304
- * Generates the final manifest JSON structure
1305
- * @param preloadMap - Map of module assets to include
1306
- * @returns Complete manifest object
1307
- */
1308
- function generateMFManifest(preloadMap) {
1309
- var options = getNormalizeModuleFederationOptions();
1310
- var name = options.name;
1311
- var remoteEntry = {
1312
- name: remoteEntryFile,
1313
- path: '',
1314
- type: 'module'
1315
- };
1316
- // Process remotes
1317
- var remotes = Array.from(Object.entries(getUsedRemotesMap())).flatMap(function (_ref2) {
1318
- var remoteKey = _ref2[0],
1319
- modules = _ref2[1];
1320
- return Array.from(modules).map(function (moduleKey) {
1321
- return {
1322
- federationContainerName: options.remotes[remoteKey].entry,
1323
- moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
1324
- alias: remoteKey,
1325
- entry: '*'
1326
- };
1327
- });
1328
- });
1329
- // Process shared dependencies
1330
- var shared = Array.from(getUsedShares()).map(function (shareKey) {
1331
- var shareItem = getNormalizeShareItem(shareKey);
1332
- var assets = preloadMap[shareKey] || createEmptyAssetMap();
1333
- return {
1334
- id: name + ":" + shareKey,
1335
- name: shareKey,
1336
- version: shareItem.version,
1337
- requiredVersion: shareItem.shareConfig.requiredVersion,
1338
- assets: {
1339
- js: {
1340
- async: assets.js.async,
1341
- sync: assets.js.sync
1342
- },
1343
- css: {
1344
- async: assets.css.async,
1345
- sync: assets.css.sync
1346
- }
1347
- }
1348
- };
1349
- }).filter(Boolean);
1350
- // Process exposed modules
1351
- var exposes = Object.entries(options.exposes).map(function (_ref3) {
1352
- var key = _ref3[0],
1353
- value = _ref3[1];
1354
- var formatKey = key.replace('./', '');
1355
- var sourceFile = value["import"];
1356
- var assets = preloadMap[sourceFile] || createEmptyAssetMap();
1357
- return {
1358
- id: name + ":" + formatKey,
1359
- name: formatKey,
1360
- assets: {
1361
- js: {
1362
- async: assets.js.async,
1363
- sync: assets.js.sync
1364
- },
1365
- css: {
1366
- async: assets.css.async,
1367
- sync: assets.css.sync
1368
- }
1369
- },
1370
- path: key
1371
- };
1372
- }).filter(Boolean);
1373
- return {
1374
- id: name,
1375
- name: name,
1376
- metaData: _extends({
1377
- name: name,
1378
- type: 'app',
1379
- buildInfo: {
1380
- buildVersion: '1.0.0',
1381
- buildName: name
1382
- },
1383
- remoteEntry: remoteEntry,
1384
- ssrRemoteEntry: remoteEntry,
1385
- types: {
1386
- path: '',
1387
- name: ''
1388
- },
1389
- globalName: name,
1390
- pluginVersion: '0.2.5'
1391
- }, !!getPublicPath ? {
1392
- getPublicPath: getPublicPath
1393
- } : {
1394
- publicPath: publicPath
1395
- }),
1396
- shared: shared,
1397
- remotes: remotes,
1398
- exposes: exposes
1399
- };
1400
- }
1401
- };
1402
-
1403
- var _resolve,
1404
- promise = new Promise(function (resolve, reject) {
1405
- _resolve = resolve;
1406
- });
1407
- var parsePromise = promise;
1408
- var exposesParseEnd = false;
1409
- var parseStartSet = new Set();
1410
- var parseEndSet = new Set();
1411
- function pluginModuleParseEnd (excludeFn) {
1412
- return [{
1413
- name: '_',
1414
- apply: 'serve',
1415
- config: function config() {
1416
- // No waiting in development mode
1417
- _resolve(1);
1418
- }
1419
- }, {
1420
- enforce: 'pre',
1421
- name: 'parseStart',
1422
- apply: 'build',
1423
- load: function load(id) {
1424
- if (excludeFn(id)) {
1425
- return;
1426
- }
1427
- parseStartSet.add(id);
1428
- }
1429
- }, {
1430
- enforce: 'post',
1431
- name: 'parseEnd',
1432
- apply: 'build',
1433
- moduleParsed: function moduleParsed(module) {
1434
- var id = module.id;
1435
- if (id === VIRTUAL_EXPOSES) {
1436
- // When the entry JS file is empty and only contains exposes export code, it’s necessary to wait for the exposes modules to be resolved in order to collect the dependencies being used.
1437
- exposesParseEnd = true;
1438
- }
1439
- if (excludeFn(id)) {
1440
- return;
1441
- }
1442
- parseEndSet.add(id);
1443
- if (exposesParseEnd && parseStartSet.size === parseEndSet.size) {
1444
- _resolve(1);
1445
- }
1279
+ }
1280
+ var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
1281
+ function generateRemoteEntry(options) {
1282
+ var pluginImportNames = options.runtimePlugins.map(function (p, i) {
1283
+ if (typeof p === 'string') {
1284
+ return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";", "undefined"];
1285
+ } else {
1286
+ return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p[0] + "\";", serializeRuntimeOptions(p[1])];
1446
1287
  }
1447
- }];
1288
+ });
1289
+ return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
1290
+ return item[1];
1291
+ }).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) {
1292
+ return item[0] + "(" + item[2] + ")";
1293
+ }).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 ";
1294
+ }
1295
+ /**
1296
+ * Inject entry file, automatically init when used as host,
1297
+ * and will not inject remoteEntry
1298
+ */
1299
+ var HOST_AUTO_INIT_TAG = '__H_A_I__';
1300
+ var hostAutoInitModule = new VirtualModule('hostAutoInit', HOST_AUTO_INIT_TAG);
1301
+ function writeHostAutoInit() {
1302
+ hostAutoInitModule.writeSync("\n const remoteEntryPromise = import(\"" + REMOTE_ENTRY_ID + "\")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ");
1303
+ }
1304
+ function getHostAutoInitImportId() {
1305
+ return hostAutoInitModule.getImportId();
1306
+ }
1307
+ function getHostAutoInitPath() {
1308
+ return hostAutoInitModule.getPath();
1448
1309
  }
1449
1310
 
1450
- var filter = pluginutils.createFilter();
1451
- function pluginProxyRemoteEntry () {
1452
- var viteConfig, _command;
1453
- return {
1454
- name: 'proxyRemoteEntry',
1455
- enforce: 'post',
1456
- configResolved: function configResolved(config) {
1457
- viteConfig = config;
1458
- },
1459
- config: function config(_config, _ref) {
1460
- var command = _ref.command;
1461
- _command = command;
1462
- },
1463
- resolveId: function resolveId(id) {
1464
- if (id === REMOTE_ENTRY_ID) {
1465
- return REMOTE_ENTRY_ID;
1466
- }
1467
- if (id === VIRTUAL_EXPOSES) {
1468
- return VIRTUAL_EXPOSES;
1469
- }
1470
- if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1471
- return id;
1472
- }
1473
- },
1474
- load: function load(id) {
1475
- if (id === REMOTE_ENTRY_ID) {
1476
- return parsePromise.then(function (_) {
1477
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1478
- });
1479
- }
1480
- if (id === VIRTUAL_EXPOSES) {
1481
- return generateExposes();
1482
- }
1483
- if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1484
- return id;
1485
- }
1486
- },
1487
- transform: function transform(code, id) {
1488
- var transformedCode = function () {
1489
- if (!filter(id)) return;
1490
- if (id.includes(REMOTE_ENTRY_ID)) {
1491
- return parsePromise.then(function (_) {
1492
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1493
- });
1494
- }
1495
- if (id === VIRTUAL_EXPOSES) {
1496
- return generateExposes();
1497
- }
1498
- if (id.includes(getHostAutoInitPath())) {
1499
- var options = getNormalizeModuleFederationOptions();
1500
- if (_command === 'serve') {
1501
- var _viteConfig$server, _viteConfig$server2;
1502
- var host = typeof ((_viteConfig$server = viteConfig.server) == null ? void 0 : _viteConfig$server.host) === 'string' && viteConfig.server.host !== '0.0.0.0' ? viteConfig.server.host : 'localhost';
1503
- var publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
1504
- return "\n const origin = (window && " + !options.ignoreOrigin + ") ? window.origin : \"//" + host + ":" + ((_viteConfig$server2 = viteConfig.server) == null ? void 0 : _viteConfig$server2.port) + "\"\n const remoteEntryPromise = await import(origin + " + publicPath + ")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ";
1505
- }
1506
- return code;
1507
- }
1508
- }();
1509
- return mapCodeToCodeWithSourcemap(transformedCode);
1311
+ function initVirtualModules() {
1312
+ writeLocalSharedImportMap();
1313
+ writeHostAutoInit();
1314
+ writeRuntimeInitStatus();
1315
+ }
1316
+
1317
+ function findRemoteEntryFile(filename, bundle) {
1318
+ for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1319
+ var _Object$entries$_i = _Object$entries[_i],
1320
+ fileData = _Object$entries$_i[1];
1321
+ if (filename.replace(/[\[\]]/g, '_').replace(/\.[^/.]+$/, '') === fileData.name || fileData.name === 'remoteEntry') {
1322
+ return fileData.fileName; // We can return early since we only need to find remoteEntry once
1510
1323
  }
1511
- };
1324
+ }
1512
1325
  }
1513
1326
 
1514
- pluginutils.createFilter();
1515
- function pluginProxyRemotes (options) {
1516
- var remotes = options.remotes;
1327
+ var ASSET_TYPES = ['js', 'css'];
1328
+ var LOAD_TIMINGS = ['sync', 'async'];
1329
+ var JS_EXTENSIONS = ['.ts', '.tsx', '.jsx', '.mjs', '.cjs'];
1330
+ /**
1331
+ * Creates an empty asset map structure for tracking JS and CSS assets
1332
+ * @returns Initialized asset map with sync/async arrays for JS and CSS
1333
+ */
1334
+ var createEmptyAssetMap = function createEmptyAssetMap() {
1517
1335
  return {
1518
- name: 'proxyRemotes',
1519
- config: function config(_config, _ref) {
1520
- var _command = _ref.command;
1521
- Object.keys(remotes).forEach(function (key) {
1522
- var remote = remotes[key];
1523
- _config.resolve.alias.push({
1524
- find: new RegExp("^(" + remote.name + "(/.*|$))"),
1525
- replacement: '$1',
1526
- customResolver: function customResolver(source) {
1527
- var remoteModule = getRemoteVirtualModule(source, _command);
1528
- addUsedRemote(remote.name, source);
1529
- return remoteModule.getPath();
1530
- }
1531
- });
1532
- });
1336
+ js: {
1337
+ sync: [],
1338
+ async: []
1339
+ },
1340
+ css: {
1341
+ sync: [],
1342
+ async: []
1533
1343
  }
1534
1344
  };
1535
- }
1536
-
1537
- function _catch(body, recover) {
1538
- try {
1539
- var result = body();
1540
- } catch (e) {
1541
- return recover(e);
1345
+ };
1346
+ /**
1347
+ * Tracks an asset in the preload map with deduplication
1348
+ * @param map - The preload map to update
1349
+ * @param key - The module key to track under
1350
+ * @param fileName - The asset filename to track
1351
+ * @param isAsync - Whether the asset is loaded async
1352
+ * @param type - The asset type ('js' or 'css')
1353
+ */
1354
+ var trackAsset = function trackAsset(map, key, fileName, isAsync, type) {
1355
+ if (!map[key]) {
1356
+ map[key] = createEmptyAssetMap();
1542
1357
  }
1543
- if (result && result.then) {
1544
- return result.then(void 0, recover);
1358
+ var target = isAsync ? map[key][type].async : map[key][type].sync;
1359
+ if (!target.includes(fileName)) {
1360
+ target.push(fileName);
1545
1361
  }
1546
- return result;
1547
- }
1548
- var DEFAULT_DEV_OPTIONS = {
1549
- disableLiveReload: true,
1550
- disableHotTypesReload: false,
1551
- disableDynamicRemoteTypeHints: false
1552
1362
  };
1553
- var DYNAMIC_HINTS_PLUGIN = '@module-federation/dts-plugin/dynamic-remote-type-hints-plugin';
1554
- var getIPv4 = function getIPv4() {
1555
- return process.env['FEDERATION_IPV4'] || '127.0.0.1';
1363
+ /**
1364
+ * Checks if a file is a CSS file by extension
1365
+ * @param fileName - The filename to check
1366
+ * @returns True if file has a CSS extension (.css, .scss, .less)
1367
+ */
1368
+ var isCSSFile = function isCSSFile(fileName) {
1369
+ return fileName.endsWith('.css') || fileName.endsWith('.scss') || fileName.endsWith('.less');
1556
1370
  };
1557
- var forkDevWorkerPath = function () {
1558
- // eslint-disable-next-line @typescript-eslint/no-var-requires
1559
- return require.resolve('@module-federation/dts-plugin/dist/fork-dev-worker.js');
1560
- }();
1561
- var DevWorker = /*#__PURE__*/function () {
1562
- function DevWorker(options) {
1563
- this.worker = core.rpc.createRpcWorker(forkDevWorkerPath, {}, undefined, false);
1564
- this.worker.connect(options);
1565
- }
1566
- var _proto = DevWorker.prototype;
1567
- _proto.update = function update() {
1568
- var _this$worker$process;
1569
- (_this$worker$process = this.worker.process) == null || _this$worker$process.send == null || _this$worker$process.send({
1570
- type: core.rpc.RpcGMCallTypes.CALL,
1571
- id: this.worker.id,
1572
- args: [undefined, 'update']
1573
- });
1574
- };
1575
- _proto.exit = function exit() {
1576
- this.worker.terminate();
1577
- };
1578
- return DevWorker;
1579
- }();
1580
- var normalizeDevOptions = function normalizeDevOptions(dev) {
1581
- if (dev === false) {
1582
- return false;
1583
- }
1584
- if (dev === true || typeof dev === 'undefined') {
1585
- return _extends({}, DEFAULT_DEV_OPTIONS);
1371
+ /**
1372
+ * Collects all CSS assets from the bundle
1373
+ * @param bundle - The Rollup output bundle
1374
+ * @returns Set of CSS asset filenames
1375
+ */
1376
+ var collectCssAssets = function collectCssAssets(bundle) {
1377
+ var cssAssets = new Set();
1378
+ for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1379
+ var _Object$entries$_i = _Object$entries[_i],
1380
+ fileName = _Object$entries$_i[0],
1381
+ fileData = _Object$entries$_i[1];
1382
+ if (fileData.type === 'asset' && isCSSFile(fileName)) {
1383
+ cssAssets.add(fileName);
1384
+ }
1586
1385
  }
1587
- return _extends({}, DEFAULT_DEV_OPTIONS, dev);
1386
+ return cssAssets;
1588
1387
  };
1589
- var buildDtsModuleFederationConfig = function buildDtsModuleFederationConfig(options) {
1590
- var exposes = {};
1591
- Object.entries(options.exposes).forEach(function (_ref) {
1592
- var key = _ref[0],
1593
- value = _ref[1];
1594
- if (typeof value === 'string') {
1595
- exposes[key] = value;
1596
- return;
1597
- }
1598
- var importValue = Array.isArray(value["import"]) ? value["import"][0] : value["import"];
1599
- if (importValue) {
1600
- exposes[key] = importValue;
1601
- }
1602
- });
1603
- var remotes = {};
1604
- Object.entries(options.remotes).forEach(function (_ref2) {
1605
- var _remote$entryGlobalNa, _remote$entryGlobalNa2;
1606
- var key = _ref2[0],
1607
- remote = _ref2[1];
1608
- if (typeof remote === 'string') {
1609
- remotes[key] = remote;
1610
- return;
1611
- }
1612
- if (!remote.entry) {
1613
- return;
1388
+ /**
1389
+ * Processes module assets and tracks them in the files map
1390
+ * @param bundle - The Rollup output bundle
1391
+ * @param filesMap - The preload map to populate
1392
+ * @param moduleMatcher - Function that matches module paths to keys
1393
+ */
1394
+ var processModuleAssets = function processModuleAssets(bundle, filesMap, moduleMatcher) {
1395
+ for (var _i2 = 0, _Object$entries2 = Object.entries(bundle); _i2 < _Object$entries2.length; _i2++) {
1396
+ var _Object$entries2$_i = _Object$entries2[_i2],
1397
+ fileName = _Object$entries2$_i[0],
1398
+ fileData = _Object$entries2$_i[1];
1399
+ if (fileData.type !== 'chunk') continue;
1400
+ if (!fileData.modules) continue;
1401
+ for (var _i3 = 0, _Object$keys = Object.keys(fileData.modules); _i3 < _Object$keys.length; _i3++) {
1402
+ var modulePath = _Object$keys[_i3];
1403
+ var matchKey = moduleMatcher(modulePath);
1404
+ if (!matchKey) continue;
1405
+ // Track main JS chunk
1406
+ trackAsset(filesMap, matchKey, fileName, false, 'js');
1407
+ // Handle dynamic imports
1408
+ if (fileData.dynamicImports) {
1409
+ for (var _iterator = _createForOfIteratorHelperLoose(fileData.dynamicImports), _step; !(_step = _iterator()).done;) {
1410
+ var dynamicImport = _step.value;
1411
+ var importData = bundle[dynamicImport];
1412
+ if (!importData) continue;
1413
+ var isCss = isCSSFile(dynamicImport);
1414
+ trackAsset(filesMap, matchKey, dynamicImport, true, isCss ? 'css' : 'js');
1415
+ }
1416
+ }
1614
1417
  }
1615
- var entryLooksLikeUrl = ((_remote$entryGlobalNa = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa.startsWith('http')) || ((_remote$entryGlobalNa2 = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa2.includes('.json'));
1616
- var entryGlobalName = entryLooksLikeUrl ? remote.name || key : remote.entryGlobalName || remote.name || key;
1617
- remotes[key] = entryGlobalName + "@" + remote.entry;
1618
- });
1619
- return _extends({}, options, {
1620
- exposes: exposes,
1621
- remotes: remotes
1622
- });
1623
- };
1624
- var resolveOutputDir = function resolveOutputDir(config) {
1625
- var outDir = config.build.outDir;
1626
- if (path__namespace.isAbsolute(outDir)) {
1627
- return path__namespace.relative(config.root, outDir);
1628
1418
  }
1629
- return outDir;
1630
1419
  };
1631
- var ensureRuntimePlugin = function ensureRuntimePlugin(options, pluginId) {
1632
- var hasPlugin = options.runtimePlugins.some(function (plugin) {
1633
- if (typeof plugin === 'string') {
1634
- return plugin === pluginId;
1420
+ /**
1421
+ * Deduplicates assets in the files map
1422
+ * @param filesMap - The preload map to deduplicate
1423
+ * @returns New deduplicated preload map
1424
+ */
1425
+ var deduplicateAssets = function deduplicateAssets(filesMap) {
1426
+ var result = {};
1427
+ for (var _i4 = 0, _Object$entries3 = Object.entries(filesMap); _i4 < _Object$entries3.length; _i4++) {
1428
+ var _Object$entries3$_i = _Object$entries3[_i4],
1429
+ key = _Object$entries3$_i[0],
1430
+ assetMaps = _Object$entries3$_i[1];
1431
+ result[key] = createEmptyAssetMap();
1432
+ for (var _i5 = 0, _ASSET_TYPES = ASSET_TYPES; _i5 < _ASSET_TYPES.length; _i5++) {
1433
+ var type = _ASSET_TYPES[_i5];
1434
+ for (var _i6 = 0, _LOAD_TIMINGS = LOAD_TIMINGS; _i6 < _LOAD_TIMINGS.length; _i6++) {
1435
+ var timing = _LOAD_TIMINGS[_i6];
1436
+ result[key][type][timing] = Array.from(new Set(assetMaps[type][timing]));
1437
+ }
1635
1438
  }
1636
- return plugin[0] === pluginId;
1637
- });
1638
- if (!hasPlugin) {
1639
- options.runtimePlugins.push(pluginId);
1640
1439
  }
1440
+ return result;
1641
1441
  };
1642
- var normalizeDevDtsOptions = function normalizeDevDtsOptions(dts, context) {
1643
- var defaultGenerateTypes = {
1644
- compileInChildProcess: true
1645
- };
1646
- var defaultConsumeTypes = {
1647
- consumeAPITypes: true
1648
- };
1649
- return sdk.normalizeOptions(dtsPlugin.isTSProject(dts, context), {
1650
- generateTypes: defaultGenerateTypes,
1651
- consumeTypes: defaultConsumeTypes,
1652
- extraOptions: {},
1653
- displayErrorInTerminal: typeof dts === 'object' && dts ? dts.displayErrorInTerminal : undefined
1654
- }, 'mfOptions.dts')(dts);
1442
+ /**
1443
+ * Builds a mapping between module files and their share keys
1444
+ * @param shareKeys - Set of share keys to map
1445
+ * @param resolveFn - Function to resolve module paths
1446
+ * @returns Map of file paths to their corresponding share keys
1447
+ */
1448
+ var buildFileToShareKeyMap = function buildFileToShareKeyMap(shareKeys, resolveFn) {
1449
+ try {
1450
+ var fileToShareKey = new Map();
1451
+ return Promise.resolve(Promise.all(Array.from(shareKeys).map(function (shareKey) {
1452
+ return resolveFn(getPreBuildLibImportId(shareKey)).then(function (resolution) {
1453
+ var _resolution$id;
1454
+ return {
1455
+ shareKey: shareKey,
1456
+ file: resolution == null || (_resolution$id = resolution.id) == null ? void 0 : _resolution$id.split('?')[0]
1457
+ };
1458
+ })["catch"](function () {
1459
+ return null;
1460
+ });
1461
+ }))).then(function (resolutions) {
1462
+ for (var _iterator2 = _createForOfIteratorHelperLoose(resolutions), _step2; !(_step2 = _iterator2()).done;) {
1463
+ var resolution = _step2.value;
1464
+ if (resolution != null && resolution.file) {
1465
+ fileToShareKey.set(resolution.file, resolution.shareKey);
1466
+ }
1467
+ }
1468
+ return fileToShareKey;
1469
+ });
1470
+ } catch (e) {
1471
+ return Promise.reject(e);
1472
+ }
1655
1473
  };
1656
- var logDtsError = function logDtsError(error, dtsOptions) {
1657
- if (dtsOptions === false) {
1658
- return;
1474
+
1475
+ /**
1476
+ * Resolves the public path for remote entries
1477
+ * @param options - Module Federation options
1478
+ * @param viteBase - Vite's base config value
1479
+ * @param originalBase - Original base config before any transformations
1480
+ * @returns The resolved public path
1481
+ */
1482
+ function resolvePublicPath(options, viteBase, originalBase) {
1483
+ // Use explicitly set publicPath if provided
1484
+ if (options.publicPath) {
1485
+ return options.publicPath;
1659
1486
  }
1660
- if (typeof dtsOptions === 'object' && dtsOptions && dtsOptions.displayErrorInTerminal === false) {
1661
- return;
1487
+ // Handle empty original base case
1488
+ if (originalBase === '') {
1489
+ return 'auto';
1662
1490
  }
1663
- console.error(error);
1664
- };
1665
- function pluginDts(options) {
1666
- if (options.dts === false) {
1667
- return [];
1491
+ // Use viteBase if available, ensuring it ends with a slash
1492
+ if (viteBase) {
1493
+ return viteBase.replace(/\/?$/, '/');
1668
1494
  }
1669
- var dtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
1670
- var resolvedConfig;
1671
- var devWorker;
1672
- var normalizedDevOptions;
1673
- var hasGeneratedBundle = false;
1674
- var devPlugin = {
1675
- name: 'module-federation-dts-dev',
1495
+ // Fallback to auto if no base is specified
1496
+ return 'auto';
1497
+ }
1498
+
1499
+ var Manifest = function Manifest() {
1500
+ var mfOptions = getNormalizeModuleFederationOptions();
1501
+ var name = mfOptions.name,
1502
+ filename = mfOptions.filename,
1503
+ getPublicPath = mfOptions.getPublicPath,
1504
+ manifestOptions = mfOptions.manifest,
1505
+ varFilename = mfOptions.varFilename;
1506
+ var mfManifestName = '';
1507
+ if (manifestOptions === true) {
1508
+ mfManifestName = 'mf-manifest.json';
1509
+ }
1510
+ if (typeof manifestOptions !== 'boolean') {
1511
+ mfManifestName = path__namespace.join((manifestOptions == null ? void 0 : manifestOptions.filePath) || '', (manifestOptions == null ? void 0 : manifestOptions.fileName) || '');
1512
+ }
1513
+ var root;
1514
+ var remoteEntryFile;
1515
+ var publicPath;
1516
+ var _command;
1517
+ var _originalConfigBase;
1518
+ var viteConfig;
1519
+ /**
1520
+ * Adds global CSS assets to all module exports
1521
+ * @param filesMap - The preload map to update
1522
+ * @param cssAssets - Set of CSS asset filenames to add
1523
+ */
1524
+ var addCssAssetsToAllExports = function addCssAssetsToAllExports(filesMap, cssAssets) {
1525
+ Object.keys(filesMap).forEach(function (key) {
1526
+ cssAssets.forEach(function (cssAsset) {
1527
+ trackAsset(filesMap, key, cssAsset, false, 'css');
1528
+ });
1529
+ });
1530
+ };
1531
+ return [{
1532
+ name: 'module-federation-manifest',
1676
1533
  apply: 'serve',
1677
- config: function config(_config) {
1678
- normalizedDevOptions = normalizeDevOptions(options.dev);
1679
- if (!normalizedDevOptions) {
1680
- return;
1681
- }
1682
- if (normalizedDevOptions.disableDynamicRemoteTypeHints) {
1683
- return;
1684
- }
1685
- ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
1686
- var define = _config.define ? _extends({}, _config.define) : {};
1687
- if (!('FEDERATION_IPV4' in define)) {
1688
- define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
1534
+ /**
1535
+ * Stores resolved Vite config for later use
1536
+ */
1537
+ /**
1538
+ * Finalizes configuration after all plugins are resolved
1539
+ * @param config - Fully resolved Vite config
1540
+ */
1541
+ configResolved: function configResolved(config) {
1542
+ viteConfig = config;
1543
+ },
1544
+ /**
1545
+ * Configures dev server middleware to handle manifest requests
1546
+ * @param server - Vite dev server instance
1547
+ */
1548
+ configureServer: function configureServer(server) {
1549
+ server.middlewares.use(function (req, res, next) {
1550
+ var _req$url;
1551
+ if (!mfManifestName) {
1552
+ next();
1553
+ return;
1554
+ }
1555
+ if (((_req$url = req.url) == null ? void 0 : _req$url.replace(/\?.*/, '')) === (viteConfig.base + mfManifestName).replace(/^\/?/, '/')) {
1556
+ res.setHeader('Content-Type', 'application/json');
1557
+ res.setHeader('Access-Control-Allow-Origin', '*');
1558
+ res.end(JSON.stringify(_extends({}, generateMFManifest({}), {
1559
+ id: name,
1560
+ name: name,
1561
+ metaData: {
1562
+ name: name,
1563
+ type: 'app',
1564
+ buildInfo: {
1565
+ buildVersion: '1.0.0',
1566
+ buildName: name
1567
+ },
1568
+ remoteEntry: {
1569
+ name: filename,
1570
+ path: '',
1571
+ type: 'module'
1572
+ },
1573
+ ssrRemoteEntry: {
1574
+ name: filename,
1575
+ path: '',
1576
+ type: 'module'
1577
+ },
1578
+ varRemoteEntry: varFilename ? {
1579
+ name: varFilename,
1580
+ path: '',
1581
+ type: 'var'
1582
+ } : undefined,
1583
+ types: {
1584
+ path: '',
1585
+ name: ''
1586
+ },
1587
+ globalName: name,
1588
+ pluginVersion: '0.2.5',
1589
+ publicPath: publicPath
1590
+ }
1591
+ })));
1592
+ } else {
1593
+ next();
1594
+ }
1595
+ });
1596
+ }
1597
+ }, {
1598
+ name: 'module-federation-manifest',
1599
+ enforce: 'post',
1600
+ /**
1601
+ * Initial plugin configuration
1602
+ * @param config - Vite config object
1603
+ * @param command - Current Vite command (serve/build)
1604
+ */
1605
+ config: function config(_config, _ref) {
1606
+ var command = _ref.command;
1607
+ if (!_config.build) _config.build = {};
1608
+ if (!_config.build.manifest) {
1609
+ _config.build.manifest = _config.build.manifest || !!manifestOptions;
1689
1610
  }
1690
- _config.define = define;
1611
+ _command = command;
1612
+ _originalConfigBase = _config.base;
1691
1613
  },
1692
1614
  configResolved: function configResolved(config) {
1693
- resolvedConfig = config;
1694
- },
1695
- configureServer: function configureServer(server) {
1696
- if (!normalizedDevOptions || !resolvedConfig) {
1697
- return;
1698
- }
1699
- var devOptions = normalizedDevOptions;
1700
- if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) {
1701
- return;
1702
- }
1703
- if (!options.name) {
1704
- throw new Error('name is required if you want to enable dev server!');
1615
+ root = config.root;
1616
+ var base = config.base;
1617
+ if (_command === 'serve') {
1618
+ base = (config.server.origin || '') + config.base;
1705
1619
  }
1706
- var outputDir = resolveOutputDir(resolvedConfig);
1707
- var normalizedDtsOptions = normalizeDevDtsOptions(options.dts, resolvedConfig.root);
1708
- if (typeof normalizedDtsOptions !== 'object') {
1709
- return;
1620
+ publicPath = resolvePublicPath(mfOptions, base, _originalConfigBase);
1621
+ },
1622
+ /**
1623
+ * Generates the module federation manifest file
1624
+ * @param options - Rollup output options
1625
+ * @param bundle - Generated bundle assets
1626
+ */
1627
+ generateBundle: function generateBundle(options, bundle) {
1628
+ try {
1629
+ var _this = this;
1630
+ if (!mfManifestName) return Promise.resolve();
1631
+ var filesMap = {};
1632
+ var foundRemoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
1633
+ // First pass: Find remoteEntry file
1634
+ if (foundRemoteEntryFile) {
1635
+ remoteEntryFile = foundRemoteEntryFile;
1636
+ }
1637
+ // Second pass: Collect all CSS assets
1638
+ var allCssAssets = mfOptions.bundleAllCSS ? collectCssAssets(bundle) : new Set();
1639
+ var exposesModules = Object.keys(mfOptions.exposes).map(function (item) {
1640
+ return mfOptions.exposes[item]["import"];
1641
+ });
1642
+ // Process exposed modules
1643
+ processModuleAssets(bundle, filesMap, function (modulePath) {
1644
+ var absoluteModulePath = path__namespace.resolve(root, modulePath);
1645
+ return exposesModules.find(function (exposeModule) {
1646
+ var exposePath = path__namespace.resolve(root, exposeModule);
1647
+ // First try exact path match
1648
+ if (absoluteModulePath === exposePath) {
1649
+ return true;
1650
+ }
1651
+ // Then try path match without known extensions
1652
+ var getPathWithoutKnownExt = function getPathWithoutKnownExt(filePath) {
1653
+ var ext = path__namespace.extname(filePath);
1654
+ return JS_EXTENSIONS.includes(ext) ? path__namespace.join(path__namespace.dirname(filePath), path__namespace.basename(filePath, ext)) : filePath;
1655
+ };
1656
+ var modulePathNoExt = getPathWithoutKnownExt(absoluteModulePath);
1657
+ var exposePathNoExt = getPathWithoutKnownExt(exposePath);
1658
+ return modulePathNoExt === exposePathNoExt;
1659
+ });
1660
+ });
1661
+ // Process shared modules
1662
+ return Promise.resolve(buildFileToShareKeyMap(getUsedShares(), _this.resolve.bind(_this))).then(function (fileToShareKey) {
1663
+ processModuleAssets(bundle, filesMap, function (modulePath) {
1664
+ return fileToShareKey.get(modulePath);
1665
+ });
1666
+ // Add all CSS assets to every export if bundleAllCSS is enabled
1667
+ if (mfOptions.bundleAllCSS) {
1668
+ addCssAssetsToAllExports(filesMap, allCssAssets);
1669
+ }
1670
+ // Final deduplication of all assets
1671
+ filesMap = deduplicateAssets(filesMap);
1672
+ _this.emitFile({
1673
+ type: 'asset',
1674
+ fileName: mfManifestName,
1675
+ source: JSON.stringify(generateMFManifest(filesMap))
1676
+ });
1677
+ });
1678
+ } catch (e) {
1679
+ return Promise.reject(e);
1710
1680
  }
1711
- var normalizedGenerateTypes = sdk.normalizeOptions(Boolean(normalizedDtsOptions), {
1712
- compileInChildProcess: true
1713
- }, 'mfOptions.dts.generateTypes')(normalizedDtsOptions.generateTypes);
1714
- var remote = normalizedGenerateTypes === false ? undefined : _extends({
1715
- implementation: normalizedDtsOptions.implementation,
1716
- context: resolvedConfig.root,
1717
- outputDir: outputDir,
1718
- moduleFederationConfig: _extends({}, dtsModuleFederationConfig),
1719
- hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || '@mf-types'
1720
- }, normalizedGenerateTypes, {
1721
- typesFolder: '.dev-server'
1681
+ }
1682
+ }];
1683
+ /**
1684
+ * Generates the final manifest JSON structure
1685
+ * @param preloadMap - Map of module assets to include
1686
+ * @returns Complete manifest object
1687
+ */
1688
+ function generateMFManifest(preloadMap) {
1689
+ var options = getNormalizeModuleFederationOptions();
1690
+ var name = options.name,
1691
+ varFilename = options.varFilename;
1692
+ var remoteEntry = {
1693
+ name: remoteEntryFile,
1694
+ path: '',
1695
+ type: 'module'
1696
+ };
1697
+ var varRemoteEntry = varFilename ? {
1698
+ name: varFilename,
1699
+ path: '',
1700
+ type: 'module'
1701
+ } : undefined;
1702
+ // Process remotes
1703
+ var remotes = Array.from(Object.entries(getUsedRemotesMap())).flatMap(function (_ref2) {
1704
+ var remoteKey = _ref2[0],
1705
+ modules = _ref2[1];
1706
+ return Array.from(modules).map(function (moduleKey) {
1707
+ return {
1708
+ federationContainerName: options.remotes[remoteKey].entry,
1709
+ moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
1710
+ alias: remoteKey,
1711
+ entry: '*'
1712
+ };
1722
1713
  });
1723
- if (remote && !remote.tsConfigPath && typeof normalizedDtsOptions === 'object' && normalizedDtsOptions.tsConfigPath) {
1724
- remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
1725
- }
1726
- var normalizedConsumeTypes = sdk.normalizeOptions(Boolean(normalizedDtsOptions), {
1727
- consumeAPITypes: true
1728
- }, 'mfOptions.dts.consumeTypes')(normalizedDtsOptions.consumeTypes);
1729
- var host = normalizedConsumeTypes === false ? undefined : _extends({
1730
- implementation: normalizedDtsOptions.implementation,
1731
- context: resolvedConfig.root,
1732
- moduleFederationConfig: dtsModuleFederationConfig,
1733
- typesFolder: normalizedConsumeTypes.typesFolder || '@mf-types',
1734
- abortOnError: false
1735
- }, normalizedConsumeTypes);
1736
- var extraOptions = normalizedDtsOptions.extraOptions || {};
1737
- if (!remote && !host && devOptions.disableLiveReload) {
1738
- return;
1739
- }
1740
- var startDevWorker = function startDevWorker() {
1741
- try {
1742
- var _temp2 = function _temp2() {
1743
- var _server$httpServer;
1744
- devWorker = new DevWorker({
1745
- name: options.name,
1746
- remote: remote,
1747
- host: host ? _extends({}, host, {
1748
- remoteTypeUrls: remoteTypeUrls
1749
- }) : undefined,
1750
- extraOptions: extraOptions,
1751
- disableLiveReload: devOptions.disableLiveReload,
1752
- disableHotTypesReload: devOptions.disableHotTypesReload
1753
- });
1754
- var update = function update() {
1755
- var _devWorker;
1756
- return (_devWorker = devWorker) == null ? void 0 : _devWorker.update();
1757
- };
1758
- server.watcher.on('change', update);
1759
- server.watcher.on('add', update);
1760
- server.watcher.on('unlink', update);
1761
- (_server$httpServer = server.httpServer) == null || _server$httpServer.once('close', function () {
1762
- var _devWorker2;
1763
- (_devWorker2 = devWorker) == null || _devWorker2.exit();
1764
- server.watcher.off('change', update);
1765
- server.watcher.off('add', update);
1766
- server.watcher.off('unlink', update);
1767
- });
1768
- };
1769
- var remoteTypeUrls;
1770
- var _temp = function () {
1771
- if (host) {
1772
- return Promise.resolve(new Promise(function (resolve) {
1773
- dtsPlugin.consumeTypesAPI({
1774
- host: host,
1775
- extraOptions: extraOptions,
1776
- displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
1777
- }, resolve);
1778
- })).then(function (_Promise) {
1779
- remoteTypeUrls = _Promise;
1780
- });
1781
- }
1782
- }();
1783
- return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp));
1784
- } catch (e) {
1785
- return Promise.reject(e);
1714
+ });
1715
+ // Process shared dependencies
1716
+ var shared = Array.from(getUsedShares()).map(function (shareKey) {
1717
+ var shareItem = getNormalizeShareItem(shareKey);
1718
+ var assets = preloadMap[shareKey] || createEmptyAssetMap();
1719
+ return {
1720
+ id: name + ":" + shareKey,
1721
+ name: shareKey,
1722
+ version: shareItem.version,
1723
+ requiredVersion: shareItem.shareConfig.requiredVersion,
1724
+ assets: {
1725
+ js: {
1726
+ async: assets.js.async,
1727
+ sync: assets.js.sync
1728
+ },
1729
+ css: {
1730
+ async: assets.css.async,
1731
+ sync: assets.css.sync
1732
+ }
1786
1733
  }
1787
1734
  };
1788
- startDevWorker()["catch"](function (error) {
1789
- logDtsError(error, normalizedDtsOptions);
1790
- });
1791
- }
1735
+ }).filter(Boolean);
1736
+ // Process exposed modules
1737
+ var exposes = Object.entries(options.exposes).map(function (_ref3) {
1738
+ var key = _ref3[0],
1739
+ value = _ref3[1];
1740
+ var formatKey = key.replace('./', '');
1741
+ var sourceFile = value["import"];
1742
+ var assets = preloadMap[sourceFile] || createEmptyAssetMap();
1743
+ return {
1744
+ id: name + ":" + formatKey,
1745
+ name: formatKey,
1746
+ assets: {
1747
+ js: {
1748
+ async: assets.js.async,
1749
+ sync: assets.js.sync
1750
+ },
1751
+ css: {
1752
+ async: assets.css.async,
1753
+ sync: assets.css.sync
1754
+ }
1755
+ },
1756
+ path: key
1757
+ };
1758
+ }).filter(Boolean);
1759
+ return {
1760
+ id: name,
1761
+ name: name,
1762
+ metaData: _extends({
1763
+ name: name,
1764
+ type: 'app',
1765
+ buildInfo: {
1766
+ buildVersion: '1.0.0',
1767
+ buildName: name
1768
+ },
1769
+ remoteEntry: remoteEntry,
1770
+ ssrRemoteEntry: remoteEntry,
1771
+ varRemoteEntry: varRemoteEntry,
1772
+ types: {
1773
+ path: '',
1774
+ name: ''
1775
+ },
1776
+ globalName: name,
1777
+ pluginVersion: '0.2.5'
1778
+ }, !!getPublicPath ? {
1779
+ getPublicPath: getPublicPath
1780
+ } : {
1781
+ publicPath: publicPath
1782
+ }),
1783
+ shared: shared,
1784
+ remotes: remotes,
1785
+ exposes: exposes
1786
+ };
1787
+ }
1788
+ };
1789
+
1790
+ var _resolve, _parseTimeout;
1791
+ var promise = new Promise(function (resolve, reject) {
1792
+ _resolve = function _resolve(v) {
1793
+ clearTimeout(_parseTimeout);
1794
+ _parseTimeout = null;
1795
+ resolve(v);
1792
1796
  };
1793
- var buildPlugin = {
1794
- name: 'module-federation-dts-build',
1797
+ });
1798
+ function setParseTimeout(timeout) {
1799
+ if (!_parseTimeout) {
1800
+ _parseTimeout = setTimeout(function () {
1801
+ console.warn("Parse timeout (" + timeout + "s) - forcing resolve");
1802
+ _resolve(1);
1803
+ }, timeout * 1000);
1804
+ }
1805
+ }
1806
+ var parsePromise = promise;
1807
+ var exposesParseEnd = false;
1808
+ var parseStartSet = new Set();
1809
+ var parseEndSet = new Set();
1810
+ function pluginModuleParseEnd (excludeFn, options) {
1811
+ setParseTimeout(options.moduleParseTimeout);
1812
+ return [{
1813
+ name: '_',
1814
+ apply: 'serve',
1815
+ config: function config() {
1816
+ // No waiting in development mode
1817
+ _resolve(1);
1818
+ }
1819
+ }, {
1820
+ enforce: 'pre',
1821
+ name: 'parseStart',
1822
+ apply: 'build',
1823
+ load: function load(id) {
1824
+ if (excludeFn(id)) {
1825
+ return;
1826
+ }
1827
+ parseStartSet.add(id);
1828
+ }
1829
+ }, {
1830
+ enforce: 'post',
1831
+ name: 'parseEnd',
1795
1832
  apply: 'build',
1833
+ moduleParsed: function moduleParsed(module) {
1834
+ var id = module.id;
1835
+ if (id === VIRTUAL_EXPOSES) {
1836
+ // When the entry JS file is empty and only contains exposes export code, it’s necessary to wait for the exposes modules to be resolved in order to collect the dependencies being used.
1837
+ exposesParseEnd = true;
1838
+ }
1839
+ if (excludeFn(id)) {
1840
+ return;
1841
+ }
1842
+ parseEndSet.add(id);
1843
+ if (exposesParseEnd && parseStartSet.size === parseEndSet.size) {
1844
+ _resolve(1);
1845
+ }
1846
+ }
1847
+ }];
1848
+ }
1849
+
1850
+ var filter = pluginutils.createFilter();
1851
+ function pluginProxyRemoteEntry () {
1852
+ var viteConfig, _command;
1853
+ return {
1854
+ name: 'proxyRemoteEntry',
1855
+ enforce: 'post',
1796
1856
  configResolved: function configResolved(config) {
1797
- resolvedConfig = config;
1857
+ viteConfig = config;
1798
1858
  },
1799
- generateBundle: function generateBundle() {
1800
- try {
1801
- var _temp6 = function _temp6() {
1802
- var generateOptions;
1803
- try {
1804
- generateOptions = dtsPlugin.normalizeGenerateTypesOptions({
1805
- context: context,
1806
- outputDir: outputDir,
1807
- dtsOptions: normalizedDtsOptions,
1808
- pluginOptions: dtsModuleFederationConfig
1809
- });
1810
- } catch (error) {
1811
- logDtsError(error, normalizedDtsOptions);
1812
- return;
1813
- }
1814
- if (!generateOptions) {
1815
- return;
1816
- }
1817
- var _temp4 = _catch(function () {
1818
- return Promise.resolve(dtsPlugin.generateTypesAPI({
1819
- dtsManagerOptions: generateOptions
1820
- })).then(function () {});
1821
- }, function (error) {
1822
- logDtsError(error, normalizedDtsOptions);
1859
+ config: function config(_config, _ref) {
1860
+ var command = _ref.command;
1861
+ _command = command;
1862
+ },
1863
+ resolveId: function resolveId(id) {
1864
+ if (id === REMOTE_ENTRY_ID) {
1865
+ return REMOTE_ENTRY_ID;
1866
+ }
1867
+ if (id === VIRTUAL_EXPOSES) {
1868
+ return VIRTUAL_EXPOSES;
1869
+ }
1870
+ if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1871
+ return id;
1872
+ }
1873
+ },
1874
+ load: function load(id) {
1875
+ if (id === REMOTE_ENTRY_ID) {
1876
+ return parsePromise.then(function (_) {
1877
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
1878
+ });
1879
+ }
1880
+ if (id === VIRTUAL_EXPOSES) {
1881
+ return generateExposes();
1882
+ }
1883
+ if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1884
+ return id;
1885
+ }
1886
+ },
1887
+ transform: function transform(code, id) {
1888
+ var transformedCode = function () {
1889
+ if (!filter(id)) return;
1890
+ if (id.includes(REMOTE_ENTRY_ID)) {
1891
+ return parsePromise.then(function (_) {
1892
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
1823
1893
  });
1824
- if (_temp4 && _temp4.then) return _temp4.then(function () {});
1825
- };
1826
- if (hasGeneratedBundle) {
1827
- return Promise.resolve();
1828
- }
1829
- hasGeneratedBundle = true;
1830
- if (!resolvedConfig) {
1831
- return Promise.resolve();
1832
- }
1833
- var normalizedDtsOptions;
1834
- try {
1835
- normalizedDtsOptions = dtsPlugin.normalizeDtsOptions(dtsModuleFederationConfig, resolvedConfig.root);
1836
- } catch (error) {
1837
- logDtsError(error, options.dts);
1838
- return Promise.resolve();
1839
1894
  }
1840
- if (typeof normalizedDtsOptions !== 'object') {
1841
- return Promise.resolve();
1895
+ if (id === VIRTUAL_EXPOSES) {
1896
+ return generateExposes();
1842
1897
  }
1843
- var context = resolvedConfig.root;
1844
- var outputDir = resolveOutputDir(resolvedConfig);
1845
- var consumeOptions;
1846
- try {
1847
- consumeOptions = dtsPlugin.normalizeConsumeTypesOptions({
1848
- context: context,
1849
- dtsOptions: normalizedDtsOptions,
1850
- pluginOptions: dtsModuleFederationConfig
1851
- });
1852
- } catch (error) {
1853
- logDtsError(error, normalizedDtsOptions);
1854
- return Promise.resolve();
1898
+ if (id.includes(getHostAutoInitPath())) {
1899
+ var options = getNormalizeModuleFederationOptions();
1900
+ if (_command === 'serve') {
1901
+ var _viteConfig$server, _viteConfig$server2;
1902
+ var host = typeof ((_viteConfig$server = viteConfig.server) == null ? void 0 : _viteConfig$server.host) === 'string' && viteConfig.server.host !== '0.0.0.0' ? viteConfig.server.host : 'localhost';
1903
+ var publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
1904
+ return "\n const origin = (window && " + !options.ignoreOrigin + ") ? window.origin : \"//" + host + ":" + ((_viteConfig$server2 = viteConfig.server) == null ? void 0 : _viteConfig$server2.port) + "\"\n const remoteEntryPromise = await import(origin + " + publicPath + ")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ";
1905
+ }
1906
+ return code;
1855
1907
  }
1856
- var _temp5 = function (_consumeOptions) {
1857
- if ((_consumeOptions = consumeOptions) != null && (_consumeOptions = _consumeOptions.host) != null && _consumeOptions.typesOnBuild) {
1858
- var _temp3 = _catch(function () {
1859
- return Promise.resolve(dtsPlugin.consumeTypesAPI(consumeOptions)).then(function () {});
1860
- }, function (error) {
1861
- logDtsError(error, normalizedDtsOptions);
1862
- });
1863
- if (_temp3 && _temp3.then) return _temp3.then(function () {});
1908
+ }();
1909
+ return mapCodeToCodeWithSourcemap(transformedCode);
1910
+ }
1911
+ };
1912
+ }
1913
+
1914
+ pluginutils.createFilter();
1915
+ function pluginProxyRemotes (options) {
1916
+ var remotes = options.remotes;
1917
+ return {
1918
+ name: 'proxyRemotes',
1919
+ config: function config(_config, _ref) {
1920
+ var _command = _ref.command;
1921
+ Object.keys(remotes).forEach(function (key) {
1922
+ var remote = remotes[key];
1923
+ _config.resolve.alias.push({
1924
+ find: new RegExp("^(" + remote.name + "(/.*|$))"),
1925
+ replacement: '$1',
1926
+ customResolver: function customResolver(source) {
1927
+ var remoteModule = getRemoteVirtualModule(source, _command);
1928
+ addUsedRemote(remote.name, source);
1929
+ return remoteModule.getPath();
1864
1930
  }
1865
- }();
1866
- return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5));
1867
- } catch (e) {
1868
- return Promise.reject(e);
1869
- }
1931
+ });
1932
+ });
1870
1933
  }
1871
1934
  };
1872
- return [devPlugin, buildPlugin];
1873
1935
  }
1874
1936
 
1875
1937
  /**
@@ -1996,6 +2058,103 @@
1996
2058
  }];
1997
2059
  }
1998
2060
 
2061
+ var VarRemoteEntry = function VarRemoteEntry() {
2062
+ var mfOptions = getNormalizeModuleFederationOptions();
2063
+ var name = mfOptions.name,
2064
+ varFilename = mfOptions.varFilename,
2065
+ filename = mfOptions.filename;
2066
+ var viteConfig;
2067
+ return [{
2068
+ name: 'module-federation-var-remote-entry',
2069
+ apply: 'serve',
2070
+ /**
2071
+ * Stores resolved Vite config for later use
2072
+ */
2073
+ /**
2074
+ * Finalizes configuration after all plugins are resolved
2075
+ * @param config - Fully resolved Vite config
2076
+ */
2077
+ configResolved: function configResolved(config) {
2078
+ viteConfig = config;
2079
+ },
2080
+ /**
2081
+ * Configures dev server middleware to handle varRemoteEntry requests
2082
+ * @param server - Vite dev server instance
2083
+ */
2084
+ configureServer: function configureServer(server) {
2085
+ server.middlewares.use(function (req, res, next) {
2086
+ var _req$url;
2087
+ if (!varFilename) {
2088
+ next();
2089
+ return;
2090
+ }
2091
+ if (((_req$url = req.url) == null ? void 0 : _req$url.replace(/\?.*/, '')) === (viteConfig.base + varFilename).replace(/^\/?/, '/')) {
2092
+ res.setHeader('Content-Type', 'text/javascript');
2093
+ res.setHeader('Access-Control-Allow-Origin', '*');
2094
+ console.log({
2095
+ filename: filename
2096
+ });
2097
+ res.end(generateVarRemoteEntry(filename));
2098
+ } else {
2099
+ next();
2100
+ }
2101
+ });
2102
+ }
2103
+ }, {
2104
+ name: 'module-federation-var-remote-entry',
2105
+ enforce: 'post',
2106
+ /**
2107
+ * Initial plugin configuration
2108
+ * @param config - Vite config object
2109
+ * @param command - Current Vite command (serve/build)
2110
+ */
2111
+ config: function config(_config, _ref) {
2112
+ if (!_config.build) _config.build = {};
2113
+ },
2114
+ /**
2115
+ * Generates the module federation "var" remote entry file
2116
+ * @param options - Rollup output options
2117
+ * @param bundle - Generated bundle assets
2118
+ */
2119
+ generateBundle: function generateBundle(options, bundle) {
2120
+ try {
2121
+ var _this = this;
2122
+ if (!varFilename) return Promise.resolve();
2123
+ var isValidName = isValidVarName(name);
2124
+ if (!isValidName) {
2125
+ viteConfig.logger.warn("Provided remote name \"" + name + "\" is not valid for \"var\" remoteEntry type, thus it's placed in globalThis['" + name + "'].\nIt may cause problems, so you would better want to use valid var name (see https://www.w3schools.com/js/js_variables.asp).");
2126
+ }
2127
+ var remoteEntryFile = findRemoteEntryFile(mfOptions.filename, bundle);
2128
+ if (!remoteEntryFile) throw new Error("Couldn't find a remoteEntry chunk file for " + mfOptions.filename + ", can't generate varRemoteEntry file");
2129
+ _this.emitFile({
2130
+ type: 'asset',
2131
+ fileName: varFilename,
2132
+ source: generateVarRemoteEntry(remoteEntryFile)
2133
+ });
2134
+ return Promise.resolve();
2135
+ } catch (e) {
2136
+ return Promise.reject(e);
2137
+ }
2138
+ }
2139
+ }];
2140
+ function isValidVarName(name) {
2141
+ return /^[A-Za-z_$][A-Za-z0-9_$]*$/.test(name);
2142
+ }
2143
+ /**
2144
+ * Generates the final "var" remote entry file
2145
+ * @param remoteEntryFile - Path to esm remote entry file
2146
+ * @returns Complete "var" remoteEntry.js file source
2147
+ */
2148
+ function generateVarRemoteEntry(remoteEntryFile) {
2149
+ var options = getNormalizeModuleFederationOptions();
2150
+ var name = options.name,
2151
+ varFilename = options.varFilename;
2152
+ var isValidName = isValidVarName(name);
2153
+ // todo: implement publicPath/getPublicPath support
2154
+ return "\n " + (isValidName ? "var " + name + ";" : '') + "\n " + (isValidName ? name : "globalThis['" + name + "']") + " = (function () {\n function getScriptUrl() {\n const currentScript = document.currentScript;\n if (!currentScript) {\n console.error(\"[VarRemoteEntry] " + varFilename + " script should be called from sync <script> tag (document.currentScript is undefined)\")\n return '/';\n }\n return document.currentScript.src.replace(/\\/[^/]*$/, '/');\n }\n\n const entry = getScriptUrl() + '" + remoteEntryFile + "';\n\n return {\n get: (...args) => import(entry).then(m => m.get(...args)),\n init: (...args) => import(entry).then(m => m.init(...args)),\n };\n })();\n ";
2155
+ }
2156
+ };
2157
+
1999
2158
  var aliasToArrayPlugin = {
2000
2159
  name: 'alias-transform-plugin',
2001
2160
  config: function config(_config, _ref) {
@@ -2062,6 +2221,8 @@
2062
2221
  entryPath: VIRTUAL_EXPOSES
2063
2222
  }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
2064
2223
  return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(VIRTUAL_EXPOSES) || id.includes(getLocalSharedImportMapPath());
2224
+ }, {
2225
+ moduleParseTimeout: options.moduleParseTimeout
2065
2226
  }), proxySharedModule({
2066
2227
  shared: shared
2067
2228
  }), [PluginDevProxyModuleTopLevelAwait(), {
@@ -2088,7 +2249,7 @@
2088
2249
  (_config$optimizeDeps3 = _config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push(virtualDir);
2089
2250
  (_config$optimizeDeps4 = _config.optimizeDeps) == null || (_config$optimizeDeps4 = _config$optimizeDeps4.needsInterop) == null || _config$optimizeDeps4.push(getLocalSharedImportMapPath());
2090
2251
  }
2091
- }], Manifest());
2252
+ }], Manifest(), VarRemoteEntry());
2092
2253
  }
2093
2254
 
2094
2255
  exports.federation = federation;