@module-federation/vite 1.0.0-alpha-51eeeb6 → 1.0.0-alpha-661e052

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/README.md CHANGED
@@ -23,7 +23,7 @@ https://module-federation.io/guide/basic/webpack.html
23
23
  // vite.config.js
24
24
  import { defineConfig } from 'vite';
25
25
  import vue from '@vitejs/plugin-vue';
26
- import { federation } from 'module-federation-vite';
26
+ import { federation } from '@module-federation/vite';
27
27
  import topLevelAwait from 'vite-plugin-top-level-await';
28
28
 
29
29
  // https://vitejs.dev/config/
@@ -43,7 +43,7 @@ export default defineConfig({
43
43
  // }
44
44
  },
45
45
  exposes: {
46
- App: './src/App.vue',
46
+ './App': './src/App.vue',
47
47
  },
48
48
  filename: 'dd/remoteEntry.js',
49
49
  shared: {
@@ -59,7 +59,7 @@ export default defineConfig({
59
59
  server: {
60
60
  port: 5173,
61
61
  // dev mode please set origin
62
- origin: "http://localhost:5173"
62
+ origin: 'http://localhost:5173',
63
63
  },
64
64
  build: {
65
65
  target: 'chrome89',
package/lib/index.cjs CHANGED
@@ -1,6 +1,7 @@
1
1
  var fs = require('fs');
2
2
  var path = require('pathe');
3
3
  var pluginutils = require('@rollup/pluginutils');
4
+ var defu = require('defu');
4
5
  var estreeWalker = require('estree-walker');
5
6
  var MagicString = require('magic-string');
6
7
 
@@ -102,6 +103,48 @@ var addEntry = function addEntry(_ref) {
102
103
  }];
103
104
  };
104
105
 
106
+ var _resolve,
107
+ promise = new Promise(function (resolve, reject) {
108
+ _resolve = resolve;
109
+ });
110
+ var parsePromise = promise;
111
+ var parseStartSet = new Set();
112
+ var parseEndSet = new Set();
113
+ function pluginModuleParseEnd (excludeFn) {
114
+ return [{
115
+ name: "_",
116
+ apply: "serve",
117
+ config: function config() {
118
+ // No waiting in development mode
119
+ _resolve(1);
120
+ }
121
+ }, {
122
+ enforce: "pre",
123
+ name: "parseStart",
124
+ apply: "build",
125
+ load: function load(id) {
126
+ if (excludeFn(id)) {
127
+ return;
128
+ }
129
+ parseStartSet.add(id);
130
+ }
131
+ }, {
132
+ enforce: "post",
133
+ name: "parseEnd",
134
+ apply: "build",
135
+ moduleParsed: function moduleParsed(module) {
136
+ var id = module.id;
137
+ if (excludeFn(id)) {
138
+ return;
139
+ }
140
+ parseEndSet.add(id);
141
+ if (parseStartSet.size === parseEndSet.size) {
142
+ _resolve(1);
143
+ }
144
+ }
145
+ }];
146
+ }
147
+
105
148
  function normalizeExposesItem(key, item) {
106
149
  var importPath = '';
107
150
  if (typeof item === 'string') {
@@ -152,7 +195,7 @@ function normalizeRemoteItem(key, remote) {
152
195
  entryGlobalName: key
153
196
  }, remote);
154
197
  }
155
- function removePathFromNpmPackage(packageString) {
198
+ function removePathFromNpmPackage$1(packageString) {
156
199
  // 匹配npm包名的正则表达式,忽略路径部分
157
200
  var regex = /^(?:@[^/]+\/)?[^/]+/;
158
201
  // 使用正则表达式匹配并提取包名
@@ -163,7 +206,7 @@ function removePathFromNpmPackage(packageString) {
163
206
  function normalizeShareItem(key, shareItem) {
164
207
  var version;
165
208
  try {
166
- version = require(path__namespace.join(removePathFromNpmPackage(key), 'package.json')).version;
209
+ version = require(path__namespace.join(removePathFromNpmPackage$1(key), 'package.json')).version;
167
210
  } catch (e) {
168
211
  console.log(e);
169
212
  }
@@ -236,62 +279,151 @@ function normalizeModuleFederationOptions(options) {
236
279
  }
237
280
 
238
281
  /**
239
- * Even the resolveId hook cannot interfere with vite pre-build,
240
- * and adding query parameter virtual modules will also fail.
241
- * You can only proxy to the real file through alias
282
+ * Escaping rules:
283
+ * Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
284
+ * @ => 1
285
+ * / => 2
286
+ * - => 3
287
+ * . => 4
242
288
  */
243
- var emptyNpmDir = path.resolve(require.resolve("an-empty-js-file"), "../");
244
289
  /**
245
- * The original shared module is proxied by getLoadShareModulePath, and the new shared module is prebuilt here
290
+ * @param {*} name "@scope/xx-xx.xx" => "__$1__scope__$2__xx__$3__xx$__4__xx"
246
291
  */
247
- var cacheMap2 = {};
248
- function getPreBuildLibPath(pkg) {
249
- if (!cacheMap2[pkg]) cacheMap2[pkg] = "__mf__prebuildwrap_" + npmPackageNameToFileName(pkg) + ".js";
250
- var filename = cacheMap2[pkg];
251
- return filename;
252
- }
253
- function getLocalSharedImportMapFileName() {
254
- var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
255
- name = _getNormalizeModuleFe.name;
256
- return npmPackageNameToFileName(name) + "_" + "__mf__localSharedImportMap.js";
292
+ function packageNameEncode(name) {
293
+ if (typeof name !== "string") throw new Error("A string package name is required");
294
+ return name.replace(/\@/g, "__$1__").replace(/\//g, "__$2__").replace(/\-/g, "__$3__").replace(/\./g, "__$4__");
257
295
  }
258
- // Only npm package name import can trigger pre-build, absolute path cannot
259
- function getLocalSharedImportMapId() {
260
- return "an-empty-js-file/" + getLocalSharedImportMapFileName();
296
+ /**
297
+ * @param {*} global "__$1__scope__$2__xx__$3__xx$__4__xx" => "@scope/xx-xx.xx"
298
+ */
299
+ function packageNameDecode(global) {
300
+ if (typeof global !== "string") throw new Error("A string global variable name is required");
301
+ return global.replace(/\_\_\$1\_\_/g, "@").replace(/\_\_\$2\_\_/g, "/").replace(/\_\_\$3\_\_/g, "-").replace(/\_\_\$4\_\_/g, ".");
261
302
  }
262
- function getLocalSharedImportMapPath() {
263
- return path.resolve(emptyNpmDir, getLocalSharedImportMapFileName());
303
+ function removePathFromNpmPackage(packageString) {
304
+ // Regular expression to match npm package name, ignoring path parts
305
+ var regex = /^(?:@[^/]+\/)?[^/]+/;
306
+ // Use regular expression to match and extract the package name
307
+ var match = packageString.match(regex);
308
+ // Return the matched package name or the original string if no match is found
309
+ return match ? match[0] : packageString;
264
310
  }
265
- function writeLocalSharedImportMap(pkgList) {
266
- fs.writeFileSync(getLocalSharedImportMapPath(), "\n export default {\n " + pkgList.map(function (pkg) {
267
- return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibPath(pkg) + "\")\n return pkg\n }\n ";
268
- }).join(",") + "\n }\n ");
311
+
312
+ var nodeModulesDir = function findNodeModulesDir(startDir) {
313
+ if (startDir === void 0) {
314
+ startDir = process.cwd();
315
+ }
316
+ var currentDir = startDir;
317
+ while (currentDir !== path.parse(currentDir).root) {
318
+ var nodeModulesPath = path.join(currentDir, 'node_modules');
319
+ if (fs.existsSync(nodeModulesPath)) {
320
+ return nodeModulesPath;
321
+ }
322
+ currentDir = path.dirname(currentDir);
323
+ }
324
+ return "";
325
+ }();
326
+ var virtualPackageName = "__mf__virtual";
327
+ if (!fs.existsSync(path.resolve(nodeModulesDir, virtualPackageName))) {
328
+ fs.mkdirSync(path.resolve(nodeModulesDir, virtualPackageName));
269
329
  }
270
- var LOAD_SHARE_TAG = "__mf__loadShare_";
330
+ fs.writeFileSync(path.resolve(nodeModulesDir, virtualPackageName, "empty.js"), "");
331
+ fs.writeFileSync(path.resolve(nodeModulesDir, virtualPackageName, "package.json"), JSON.stringify({
332
+ name: virtualPackageName,
333
+ main: "empty.js"
334
+ }));
271
335
  /**
272
- * generate loadShare virtual module
336
+ * Physically generate files as virtual modules under node_modules/__mf__virtual/*
273
337
  */
274
- var cacheMap1 = {};
338
+ var VirtualModule = /*#__PURE__*/function () {
339
+ function VirtualModule(name) {
340
+ this.originName = void 0;
341
+ this.originName = name;
342
+ }
343
+ var _proto = VirtualModule.prototype;
344
+ _proto.getPath = function getPath() {
345
+ return path.resolve(nodeModulesDir, this.getImportId());
346
+ };
347
+ _proto.getImportId = function getImportId() {
348
+ return virtualPackageName + "/" + packageNameEncode(this.originName);
349
+ };
350
+ _proto.writeSync = function writeSync(code) {
351
+ fs.writeFileSync(this.getPath() + ".js", code);
352
+ };
353
+ _proto.write = function write(code) {
354
+ fs.writeFile(this.getPath() + ".js", code, function () {});
355
+ };
356
+ return VirtualModule;
357
+ }();
358
+
359
+ /**
360
+ * Even the resolveId hook cannot interfere with vite pre-build,
361
+ * and adding query parameter virtual modules will also fail.
362
+ * You can only proxy to the real file through alias
363
+ */
364
+ // *** __prebuild__
365
+
366
+ var generateLocalSharedImportMap = function generateLocalSharedImportMap() {
367
+ return Promise.resolve(parsePromise).then(function () {
368
+ var options = getNormalizeModuleFederationOptions();
369
+ return "\n const localSharedImportMap = {\n " + Array.from(shareds).map(function (pkg) {
370
+ return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\")\n return pkg\n }\n ";
371
+ }).join(",") + "\n }\n const localShared = {\n " + Array.from(shareds).map(function (key) {
372
+ var shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
373
+ return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(key) + ",\n version: " + JSON.stringify(shareItem.version) + ",\n scope: [" + JSON.stringify(shareItem.scope) + "],\n loaded: false,\n from: " + JSON.stringify(options.name) + ",\n async get () {\n localShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = localSharedImportMap \n const res = await pkgDynamicImport()\n const exportModule = {...res}\n // All npm packages pre-built by vite will be converted to esm\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return function () {\n return exportModule\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
374
+ }).join(',') + "\n }\n export default localShared\n ";
375
+ });
376
+ };
377
+ // *** __loadShare__
378
+ var writeLocalSharedImportMap = function writeLocalSharedImportMap() {
379
+ try {
380
+ var sharedCount = shareds.size;
381
+ return Promise.resolve(function () {
382
+ if (prevSharedCount !== sharedCount) {
383
+ prevSharedCount = sharedCount;
384
+ var _writeSync = localSharedImportMapModule.writeSync;
385
+ return Promise.resolve(generateLocalSharedImportMap()).then(function (_generateLocalSharedI) {
386
+ return _writeSync.call(localSharedImportMapModule, _generateLocalSharedI);
387
+ });
388
+ }
389
+ }());
390
+ } catch (e) {
391
+ return Promise.reject(e);
392
+ }
393
+ };
394
+ var preBuildCacheMap = {};
395
+ var PREBUILD_TAG = "__prebuild__";
396
+ function writePreBuildLibPath(pkg) {
397
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg);
398
+ preBuildCacheMap[pkg].writeSync("");
399
+ }
400
+ function getPreBuildLibImportId(pkg) {
401
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg);
402
+ var importId = preBuildCacheMap[pkg].getImportId();
403
+ return importId;
404
+ }
405
+ var shareds = new Set();
406
+ function addShare(pkg) {
407
+ shareds.add(pkg);
408
+ }
409
+ // *** Expose locally provided shared modules here
410
+ var localSharedImportMapModule = new VirtualModule("localSharedImportMap");
411
+ localSharedImportMapModule.writeSync("");
412
+ function getLocalSharedImportMapId() {
413
+ return localSharedImportMapModule.getPath();
414
+ }
415
+ var prevSharedCount = 0;
416
+ var LOAD_SHARE_TAG = "__loadShare__";
417
+ var loadShareCacheMap = {};
275
418
  function getLoadShareModulePath(pkg) {
276
- var _getNormalizeModuleFe2 = getNormalizeModuleFederationOptions(),
277
- name = _getNormalizeModuleFe2.name;
278
- if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + ("" + LOAD_SHARE_TAG + npmPackageNameToFileName(pkg) + ".js");
279
- var filename = cacheMap1[pkg];
280
- return path.resolve(emptyNpmDir, filename);
419
+ if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(LOAD_SHARE_TAG + pkg);
420
+ var filepath = loadShareCacheMap[pkg].getPath();
421
+ return filepath;
281
422
  }
282
423
  function writeLoadShareModule(pkg, shareItem, command) {
283
- fs.writeFileSync(getLoadShareModulePath(pkg), "\n // dev uses dynamic import to separate chunks\n " + (command !== "build" ? ";() => import(" + JSON.stringify(pkg) + ").catch(() => {});" : '') + "\n const {loadShare} = require(\"@module-federation/runtime\")\n const res = loadShare(" + JSON.stringify(pkg) + ", {\n customShareInfo: {shareConfig:{\n singleton: " + shareItem.shareConfig.singleton + ",\n strictVersion: " + shareItem.shareConfig.strictVersion + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }}})\n const exportModule = " + (command !== "build" ? "/*mf top-level-await placeholder replacement mf*/" : "await ") + "res.then(factory => factory())\n module.exports = exportModule\n ");
284
- }
285
- function npmPackageNameToFileName(packageName) {
286
- // 1. 去掉包名前的 "@"
287
- // 2. 将包名中的 "/" 替换为 "__" 以避免文件路径问题
288
- // 3. 去掉不合法的文件名字符
289
- return packageName.replace(/^@/, '') // 移除作用域前缀 "@"
290
- .replace(/\//g, '__') // 将 "/" 替换为 "__"
291
- .replace(/[^a-zA-Z0-9_.-]/g, '_'); // 替换其他非法字符为 "_"
424
+ loadShareCacheMap[pkg].writeSync("\n () => import(" + JSON.stringify(getPreBuildLibImportId(pkg)) + ").catch(() => {});\n // dev uses dynamic import to separate chunks\n " + (command !== "build" ? ";() => import(" + JSON.stringify(pkg) + ").catch(() => {});" : '') + "\n const {loadShare} = require(\"@module-federation/runtime\")\n const res = loadShare(" + JSON.stringify(pkg) + ", {\n customShareInfo: {shareConfig:{\n singleton: " + shareItem.shareConfig.singleton + ",\n strictVersion: " + shareItem.shareConfig.strictVersion + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }}})\n const exportModule = " + (command !== "build" ? "/*mf top-level-await placeholder replacement mf*/" : "await ") + "res.then(factory => factory())\n module.exports = exportModule\n ");
292
425
  }
293
426
 
294
- var emptyPath = require.resolve('an-empty-js-file');
295
427
  var REMOTE_ENTRY_ID = 'REMOTE_ENTRY_ID';
296
428
  function generateRemoteEntry(options) {
297
429
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
@@ -301,30 +433,25 @@ function generateRemoteEntry(options) {
301
433
  return item[1];
302
434
  }).join('\n') + "\n\n const exposesMap = {\n " + Object.keys(options.exposes).map(function (key) {
303
435
  return "\n " + JSON.stringify(key) + ": async () => {\n const importModule = await import(" + JSON.stringify(options.exposes[key]["import"]) + ")\n const exportModule = {}\n Object.assign(exportModule, importModule)\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return exportModule\n }\n ";
304
- }).join(',') + "\n }\n import localSharedImportMap from \"" + getLocalSharedImportMapId() + "\"\n async function init(shared = {}) {\n const localShared = {\n " + Object.keys(options.shared).map(function (key) {
305
- var shareItem = options.shared[key];
306
- return "\n " + JSON.stringify(key) + ": {\n name: " + JSON.stringify(shareItem.name) + ",\n version: " + JSON.stringify(shareItem.version) + ",\n scope: [" + JSON.stringify(shareItem.scope) + "],\n loaded: false,\n from: " + JSON.stringify(options.name) + ",\n async get () {\n localShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = localSharedImportMap \n const res = await pkgDynamicImport()\n const exportModule = {...res}\n // All npm packages pre-built by vite will be converted to esm\n Object.defineProperty(exportModule, \"__esModule\", {\n value: true,\n enumerable: false\n })\n return function () {\n return exportModule\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
307
- }).join(',') + "\n }\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: [" + Object.keys(options.remotes).map(function (key) {
436
+ }).join(',') + "\n }\n import localSharedImportMap from \"" + getLocalSharedImportMapId() + "\"\n async function init(shared = {}) {\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: [" + Object.keys(options.remotes).map(function (key) {
308
437
  var remote = options.remotes[key];
309
438
  return "\n {\n entryGlobalName: " + JSON.stringify(remote.entryGlobalName) + ",\n name: " + JSON.stringify(remote.name) + ",\n type: " + JSON.stringify(remote.type) + ",\n entry: " + JSON.stringify(remote.entry) + ",\n }\n ";
310
- }).join(',') + "\n ],\n shared: localShared,\n plugins: [" + pluginImportNames.map(function (item) {
439
+ }).join(',') + "\n ],\n shared: localSharedImportMap,\n plugins: [" + pluginImportNames.map(function (item) {
311
440
  return item[0] + "()";
312
441
  }).join(', ') + "]\n });\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\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 ";
313
442
  }
314
- var WRAP_REMOTE_ENTRY_QUERY_STR = '__mf__wrapRemoteEntry__';
315
- var WRAP_REMOTE_ENTRY_PATH = emptyPath + '?' + WRAP_REMOTE_ENTRY_QUERY_STR;
316
- function generateWrapRemoteEntry() {
317
- return "\n import {init, get} from \"" + REMOTE_ENTRY_ID + "\"\n export {init, get}\n ";
318
- }
443
+ var wrapRemoteEntryModule = new VirtualModule("wrapRemoteEntry");
444
+ wrapRemoteEntryModule.writeSync("\nimport {init, get} from \"" + REMOTE_ENTRY_ID + "\"\nexport {init, get}\n");
445
+ var WRAP_REMOTE_ENTRY_QUERY_STR = wrapRemoteEntryModule.getImportId();
446
+ var WRAP_REMOTE_ENTRY_PATH = wrapRemoteEntryModule.getPath();
319
447
  /**
320
448
  * Inject entry file, automatically init when used as host,
321
449
  * and will not inject remoteEntry
322
450
  */
323
- var HOST_AUTO_INIT_QUERY_STR = '__mf__isHostInit';
324
- var HOST_AUTO_INIT_PATH = emptyPath + '?' + HOST_AUTO_INIT_QUERY_STR;
325
- function generateWrapHostInit() {
326
- return "\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ";
327
- }
451
+ var hostAutoInitModule = new VirtualModule("hostAutoInit");
452
+ hostAutoInitModule.writeSync("\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ");
453
+ var HOST_AUTO_INIT_QUERY_STR = hostAutoInitModule.getImportId();
454
+ var HOST_AUTO_INIT_PATH = hostAutoInitModule.getPath();
328
455
 
329
456
  var filter$1 = pluginutils.createFilter();
330
457
  function pluginProxyRemoteEntry () {
@@ -347,12 +474,6 @@ function pluginProxyRemoteEntry () {
347
474
  if (id.includes(REMOTE_ENTRY_ID)) {
348
475
  return Promise.resolve(generateRemoteEntry(getNormalizeModuleFederationOptions()));
349
476
  }
350
- if (id.includes(WRAP_REMOTE_ENTRY_QUERY_STR)) {
351
- return Promise.resolve(generateWrapRemoteEntry());
352
- }
353
- if (id.includes(HOST_AUTO_INIT_QUERY_STR)) {
354
- return Promise.resolve(generateWrapHostInit());
355
- }
356
477
  return Promise.resolve();
357
478
  } catch (e) {
358
479
  return Promise.reject(e);
@@ -361,6 +482,8 @@ function pluginProxyRemoteEntry () {
361
482
  };
362
483
  }
363
484
 
485
+ var remoteVirtualModule = new VirtualModule("remoteModule");
486
+ remoteVirtualModule.writeSync("");
364
487
  function generateRemotes(id, command) {
365
488
  return {
366
489
  code: "\n import {loadRemote} from \"@module-federation/runtime\"\n const exportModule = await loadRemote(" + JSON.stringify(id) + ")\n " + (command === "build" && "\n export default 'default' in (exportModule || {}) ? exportModule.default : undefined\n export const __mf__dynamicExports = exportModule\n " || "") + "\n " + (command !== "build" && "\n export default exportModule\n " || "") + "\n ",
@@ -388,10 +511,11 @@ function pluginProxyRemotes (options) {
388
511
  find: new RegExp("(" + remote.name + "(/.*|$)?)"),
389
512
  replacement: '$1',
390
513
  customResolver: function customResolver(source) {
514
+ var requestPath = remoteVirtualModule.getImportId() + '?__moduleRemote__=' + encodeURIComponent(source);
391
515
  if (!_config.optimizeDeps) _config.optimizeDeps = {};
392
516
  if (!_config.optimizeDeps.needsInterop) _config.optimizeDeps.needsInterop = [];
393
- if (_config.optimizeDeps.needsInterop.indexOf(source) === -1) _config.optimizeDeps.needsInterop.push(source);
394
- return this.resolve(require.resolve('an-empty-js-file') + '?__moduleRemote__=' + encodeURIComponent(source));
517
+ if (_config.optimizeDeps.needsInterop.indexOf(requestPath) === -1) _config.optimizeDeps.needsInterop.push(requestPath);
518
+ return this.resolve(requestPath);
395
519
  }
396
520
  });
397
521
  });
@@ -417,6 +541,43 @@ function pluginProxyRemotes (options) {
417
541
  };
418
542
  }
419
543
 
544
+ /**
545
+ * example:
546
+ * const store = new PromiseStore<number>();
547
+ * store.get("example").then((result) => {
548
+ * console.log("Result from example:", result); // 42
549
+ * });
550
+ * setTimeout(() => {
551
+ * store.set("example", Promise.resolve(42));
552
+ * }, 2000);
553
+ */
554
+ var PromiseStore = /*#__PURE__*/function () {
555
+ function PromiseStore() {
556
+ this.promiseMap = new Map();
557
+ this.resolveMap = new Map();
558
+ }
559
+ var _proto = PromiseStore.prototype;
560
+ _proto.set = function set(id, promise) {
561
+ if (this.resolveMap.has(id)) {
562
+ promise.then(this.resolveMap.get(id));
563
+ this.resolveMap["delete"](id);
564
+ }
565
+ this.promiseMap.set(id, promise);
566
+ };
567
+ _proto.get = function get(id) {
568
+ var _this = this;
569
+ if (this.promiseMap.has(id)) {
570
+ return this.promiseMap.get(id);
571
+ }
572
+ var pendingPromise = new Promise(function (resolve) {
573
+ _this.resolveMap.set(id, resolve);
574
+ });
575
+ this.promiseMap.set(id, pendingPromise);
576
+ return pendingPromise;
577
+ };
578
+ return PromiseStore;
579
+ }();
580
+
420
581
  function wrapManualChunks(output, manualChunksCb) {
421
582
  if (!output.manualChunks) output.manualChunks = {};
422
583
  var wrapManualChunks = function wrapManualChunks(original) {
@@ -441,9 +602,24 @@ function proxySharedModule(options) {
441
602
  include = options.include,
442
603
  exclude = options.exclude;
443
604
  var filterFunction = pluginutils.createFilter(include, exclude);
444
- writeLocalSharedImportMap(Object.keys(shared));
445
605
  return [{
446
- name: 'preBuildShared',
606
+ name: "generateLocalSharedImportMap",
607
+ enforce: "post",
608
+ resolveId: function resolveId(id) {
609
+ if (id.includes(getLocalSharedImportMapId())) return id;
610
+ },
611
+ load: function load(id) {
612
+ if (id.includes(getLocalSharedImportMapId())) {
613
+ return generateLocalSharedImportMap();
614
+ }
615
+ },
616
+ transform: function transform(code, id) {
617
+ if (id.includes(getLocalSharedImportMapId())) {
618
+ return generateLocalSharedImportMap();
619
+ }
620
+ }
621
+ }, {
622
+ name: 'proxyPreBuildShared',
447
623
  enforce: 'post',
448
624
  config: function config(_config, _ref) {
449
625
  var _config$resolve$alias, _config$resolve$alias2;
@@ -452,50 +628,77 @@ function proxySharedModule(options) {
452
628
  if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
453
629
  var rollupOptions = _config.build.rollupOptions;
454
630
  if (!rollupOptions.output) rollupOptions.output = {};
455
- // config?.optimizeDeps?.include?.push?.("an-empty-js-file");
456
- // config.optimizeDeps.needsInterop.push('an-empty-js-file');
457
631
  wrapManualChunks(_config.build.rollupOptions.output, function (id) {
632
+ // https://github.com/module-federation/vite/issues/40#issuecomment-2311434503
633
+ if (id.includes('/preload-helper.js')) {
634
+ return "preload-helper";
635
+ }
458
636
  if (id.includes("node_modules/@module-federation/runtime")) {
459
637
  return "@module-federation/runtime";
460
638
  }
461
- if (id.includes(LOAD_SHARE_TAG) || id.includes("__mf__prebuildwrap_")) {
462
- return id.split("/").pop();
463
- }
464
639
  });
465
640
  (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(shared).map(function (key) {
466
- var _config$optimizeDeps, _config$optimizeDeps2;
467
- _config == null || (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push == null || _config$optimizeDeps.push(getPreBuildLibPath(key));
468
- // write proxyFile
469
- writeLoadShareModule(key, shared[key], command);
470
- var preBuildLibPath = getLoadShareModulePath(key);
471
- _config == null || (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.needsInterop) == null || _config$optimizeDeps2.push(key);
641
+ var pattern = key.endsWith("/") ? "(^" + key.replace(/\/$/, "") + "(/.+)?$)" : "(^" + key + "$)";
472
642
  return {
473
- // Intercept all dependency requests to the proxy module
474
- // Dependency requests issued by localSharedImportMap are allowed without proxying.
475
- find: new RegExp("^" + key + "$"),
476
- replacement: preBuildLibPath,
643
+ // Intercept all shared requests and proxy them to loadShare
644
+ find: new RegExp(pattern),
645
+ replacement: "$1",
477
646
  customResolver: function customResolver(source, importer) {
478
- var _config$optimizeDeps3;
479
- if (importer.includes("node_modules/" + key + "/")) {
480
- return this.resolve(key);
481
- }
482
- _config == null || (_config$optimizeDeps3 = _config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push(preBuildLibPath);
483
- return this.resolve(preBuildLibPath);
647
+ var _config$optimizeDeps;
648
+ var loadSharePath = getLoadShareModulePath(source);
649
+ _config == null || (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.needsInterop) == null || _config$optimizeDeps.push(loadSharePath);
650
+ writeLoadShareModule(source, shared[key], command);
651
+ writePreBuildLibPath(source);
652
+ addShare(source);
653
+ writeLocalSharedImportMap();
654
+ return this.resolve(loadSharePath);
484
655
  }
485
656
  };
486
657
  }));
658
+ var savePrebuild = new PromiseStore();
487
659
  (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
488
660
  return command === "build" ? {
489
- find: new RegExp("^" + getPreBuildLibPath(key) + "$"),
490
- replacement: key
661
+ find: new RegExp(virtualPackageName + "/" + PREBUILD_TAG + "(.+)"),
662
+ replacement: function replacement(_, $1) {
663
+ return packageNameDecode($1);
664
+ }
491
665
  } : {
492
- find: new RegExp("^" + getPreBuildLibPath(key) + "$"),
666
+ find: new RegExp(virtualPackageName + "/" + PREBUILD_TAG + "(.+)"),
667
+ replacement: "$1",
493
668
  customResolver: function customResolver(source, importer) {
494
- return this.resolve(key);
669
+ try {
670
+ var _this = this;
671
+ if (importer.includes(LOAD_SHARE_TAG)) {
672
+ // save pre-bunding module id
673
+ savePrebuild.set(source, _this.resolve(packageNameDecode(source)).then(function (item) {
674
+ return item.id;
675
+ }));
676
+ }
677
+ // Fix localSharedImportMap import id
678
+ var _resolve = _this.resolve;
679
+ return Promise.resolve(savePrebuild.get(source)).then(function (_savePrebuild$get) {
680
+ return Promise.resolve(_resolve.call(_this, _savePrebuild$get));
681
+ });
682
+ } catch (e) {
683
+ return Promise.reject(e);
684
+ }
495
685
  }
496
686
  };
497
687
  }));
498
688
  }
689
+ }, {
690
+ name: "watchLocalSharedImportMap",
691
+ apply: "serve",
692
+ config: function config(_config2) {
693
+ _config2.server = defu.defu(_config2.server, {
694
+ watch: {
695
+ ignored: []
696
+ }
697
+ });
698
+ var watch = _config2.server.watch;
699
+ watch.ignored = [].concat(watch.ignored);
700
+ watch.ignored.push("!**/node_modules/" + localSharedImportMapModule.getImportId() + ".js");
701
+ }
499
702
  }, {
500
703
  name: "prebuild-top-level-await",
501
704
  apply: "serve",
@@ -515,7 +718,6 @@ function proxySharedModule(options) {
515
718
  var magicString = new MagicString__default["default"](code);
516
719
  estreeWalker.walk(ast, {
517
720
  enter: function enter(node) {
518
- // 处理命名导出
519
721
  if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
520
722
  var exportSpecifiers = node.specifiers.map(function (specifier) {
521
723
  return specifier.exported.name;
@@ -531,7 +733,6 @@ function proxySharedModule(options) {
531
733
  var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
532
734
  magicString.overwrite(start, end, replacement);
533
735
  }
534
- // 处理默认导出
535
736
  if (node.type === 'ExportDefaultDeclaration') {
536
737
  var declaration = node.declaration;
537
738
  var _start = node.start;
@@ -539,14 +740,14 @@ function proxySharedModule(options) {
539
740
  var proxyStatement;
540
741
  var exportStatement = 'default';
541
742
  if (declaration.type === 'Identifier') {
542
- // 处理标识符 (如: export default foo;)
743
+ // example: export default foo;
543
744
  proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
544
745
  } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
545
- // 处理调用表达式或函数声明 (如: export default someFunction();)
746
+ // example: export default someFunction();
546
747
  var declarationCode = code.slice(declaration.start, declaration.end);
547
748
  proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
548
749
  } else {
549
- // 其他类型 (可以根据需要添加更多处理逻辑)
750
+ // other
550
751
  proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
551
752
  }
552
753
  var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
@@ -609,7 +810,9 @@ function federation(mfUserOptions) {
609
810
  }), addEntry({
610
811
  entryName: 'hostInit',
611
812
  entryPath: HOST_AUTO_INIT_PATH
612
- }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], proxySharedModule({
813
+ }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
814
+ return id.includes(HOST_AUTO_INIT_QUERY_STR) || id.includes(WRAP_REMOTE_ENTRY_QUERY_STR) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapId());
815
+ }), proxySharedModule({
613
816
  shared: shared
614
817
  }), [{
615
818
  name: 'module-federation-vite',