@module-federation/vite 1.0.0-alpha-c13dc95 → 1.0.0-alpha-b1bba84

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.
@@ -1,11 +1,11 @@
1
1
  import * as fs from 'fs';
2
- import { existsSync, mkdirSync, writeFileSync, writeFile } from 'fs';
2
+ import { mkdirSync, writeFileSync, existsSync, writeFile } from 'fs';
3
3
  import * as path from 'pathe';
4
- import path__default, { parse, join, dirname, resolve } from 'pathe';
4
+ import path__default, { parse, join, dirname, resolve, relative } from 'pathe';
5
5
  import { createFilter } from '@rollup/pluginutils';
6
- import { defu } from 'defu';
7
6
  import { walk } from 'estree-walker';
8
7
  import MagicString from 'magic-string';
8
+ import { defu } from 'defu';
9
9
 
10
10
  const addEntry = ({
11
11
  entryName,
@@ -15,9 +15,15 @@ const addEntry = ({
15
15
  const devEntryPath = entryPath.startsWith("virtual:mf") ? "/@id/" + entryPath : entryPath;
16
16
  let entryFiles = [];
17
17
  let htmlFilePath;
18
+ let _command;
18
19
  return [{
19
20
  name: 'add-entry',
20
21
  apply: "serve",
22
+ config(config, {
23
+ command
24
+ }) {
25
+ _command = command;
26
+ },
21
27
  configureServer(server) {
22
28
  var _server$httpServer;
23
29
  (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', () => {
@@ -43,7 +49,6 @@ const addEntry = ({
43
49
  }, {
44
50
  name: "add-entry",
45
51
  enforce: "post",
46
- apply: "build",
47
52
  configResolved(config) {
48
53
  const inputOptions = config.build.rollupOptions.input;
49
54
  if (!inputOptions) {
@@ -60,6 +65,7 @@ const addEntry = ({
60
65
  }
61
66
  },
62
67
  buildStart() {
68
+ if (_command === "serve") return;
63
69
  const hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
64
70
  this.emitFile({
65
71
  name: entryName,
@@ -88,46 +94,81 @@ const addEntry = ({
88
94
  }];
89
95
  };
90
96
 
91
- let _resolve,
92
- promise = new Promise((resolve, reject) => {
93
- _resolve = resolve;
94
- });
95
- let parsePromise = promise;
96
- const parseStartSet = new Set();
97
- const parseEndSet = new Set();
98
- function pluginModuleParseEnd (excludeFn) {
99
- return [{
100
- name: "_",
97
+ /**
98
+ * Solve the problem that dev mode dependency prebunding does not support top-level await syntax
99
+ */
100
+ function PluginDevProxyModuleTopLevelAwait() {
101
+ const filterFunction = createFilter();
102
+ return {
103
+ name: "dev-proxy-module-top-level-await",
101
104
  apply: "serve",
102
- config() {
103
- // No waiting in development mode
104
- _resolve(1);
105
- }
106
- }, {
107
- enforce: "pre",
108
- name: "parseStart",
109
- apply: "build",
110
- load(id) {
111
- if (excludeFn(id)) {
112
- return;
113
- }
114
- parseStartSet.add(id);
115
- }
116
- }, {
117
- enforce: "post",
118
- name: "parseEnd",
119
- apply: "build",
120
- moduleParsed(module) {
121
- const id = module.id;
122
- if (excludeFn(id)) {
123
- return;
105
+ transform(code, id) {
106
+ if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
107
+ return null;
124
108
  }
125
- parseEndSet.add(id);
126
- if (parseStartSet.size === parseEndSet.size) {
127
- _resolve(1);
109
+ if (!filterFunction(id)) return null;
110
+ let ast;
111
+ try {
112
+ ast = this.parse(code, {
113
+ allowReturnOutsideFunction: true
114
+ });
115
+ } catch (e) {
116
+ throw new Error(`${id}: ${e}`);
128
117
  }
118
+ const magicString = new MagicString(code);
119
+ walk(ast, {
120
+ enter(node) {
121
+ if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
122
+ const exportSpecifiers = node.specifiers.map(specifier => specifier.exported.name);
123
+ const proxyStatements = exportSpecifiers.map(name => `
124
+ const __mfproxy__await${name} = await ${name}();
125
+ const __mfproxy__${name} = () => __mfproxy__await${name};
126
+ `).join('\n');
127
+ const exportStatements = exportSpecifiers.map(name => `__mfproxy__${name} as ${name}`).join(', ');
128
+ const start = node.start;
129
+ const end = node.end;
130
+ const replacement = `${proxyStatements}\nexport { ${exportStatements} };`;
131
+ magicString.overwrite(start, end, replacement);
132
+ }
133
+ if (node.type === 'ExportDefaultDeclaration') {
134
+ const declaration = node.declaration;
135
+ const start = node.start;
136
+ const end = node.end;
137
+ let proxyStatement;
138
+ let exportStatement = 'default';
139
+ if (declaration.type === 'Identifier') {
140
+ // example: export default foo;
141
+ proxyStatement = `
142
+ const __mfproxy__awaitdefault = await ${declaration.name}();
143
+ const __mfproxy__default = __mfproxy__awaitdefault;
144
+ `;
145
+ } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
146
+ // example: export default someFunction();
147
+ const declarationCode = code.slice(declaration.start, declaration.end);
148
+ proxyStatement = `
149
+ const __mfproxy__awaitdefault = await (${declarationCode});
150
+ const __mfproxy__default = __mfproxy__awaitdefault;
151
+ `;
152
+ } else {
153
+ // other
154
+ proxyStatement = `
155
+ const __mfproxy__awaitdefault = await (${code.slice(declaration.start, declaration.end)});
156
+ const __mfproxy__default = __mfproxy__awaitdefault;
157
+ `;
158
+ }
159
+ const replacement = `${proxyStatement}\nexport { __mfproxy__default as ${exportStatement} };`;
160
+ magicString.overwrite(start, end, replacement);
161
+ }
162
+ }
163
+ });
164
+ return {
165
+ code: magicString.toString(),
166
+ map: magicString.generateMap({
167
+ hires: true
168
+ })
169
+ };
129
170
  }
130
- }];
171
+ };
131
172
  }
132
173
 
133
174
  function normalizeExposesItem(key, item) {
@@ -179,7 +220,7 @@ function normalizeRemoteItem(key, remote) {
179
220
  entryGlobalName: key
180
221
  }, remote);
181
222
  }
182
- function removePathFromNpmPackage$1(packageString) {
223
+ function removePathFromNpmPackage(packageString) {
183
224
  // 匹配npm包名的正则表达式,忽略路径部分
184
225
  const regex = /^(?:@[^/]+\/)?[^/]+/;
185
226
  // 使用正则表达式匹配并提取包名
@@ -190,7 +231,7 @@ function removePathFromNpmPackage$1(packageString) {
190
231
  function normalizeShareItem(key, shareItem) {
191
232
  let version;
192
233
  try {
193
- version = require(path.join(removePathFromNpmPackage$1(key), 'package.json')).version;
234
+ version = require(path.join(removePathFromNpmPackage(key), 'package.json')).version;
194
235
  } catch (e) {
195
236
  console.log(e);
196
237
  }
@@ -238,10 +279,25 @@ function normalizeLibrary(library) {
238
279
  if (!library) return undefined;
239
280
  return library;
240
281
  }
282
+ function normalizeManifest(manifest = false) {
283
+ if (typeof manifest === "boolean") {
284
+ return manifest;
285
+ }
286
+ return Object.assign({
287
+ filePath: "",
288
+ disableAssetsAnalyze: false,
289
+ fileName: "mf-manifest.json"
290
+ }, manifest);
291
+ }
241
292
  let config;
242
293
  function getNormalizeModuleFederationOptions() {
243
294
  return config;
244
295
  }
296
+ function getNormalizeShareItem(key) {
297
+ const options = getNormalizeModuleFederationOptions();
298
+ const shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
299
+ return shareItem;
300
+ }
245
301
  function normalizeModuleFederationOptions(options) {
246
302
  return config = {
247
303
  exposes: normalizeExposes(options.exposes),
@@ -256,7 +312,7 @@ function normalizeModuleFederationOptions(options) {
256
312
  runtimePlugins: options.runtimePlugins || [],
257
313
  getPublicPath: options.getPublicPath,
258
314
  implementation: options.implementation,
259
- manifest: options.manifest,
315
+ manifest: normalizeManifest(options.manifest),
260
316
  dev: options.dev,
261
317
  dts: options.dts
262
318
  };
@@ -271,33 +327,43 @@ function normalizeModuleFederationOptions(options) {
271
327
  * . => 4
272
328
  */
273
329
  /**
274
- * @param {*} name "@scope/xx-xx.xx" => "__$1__scope__$2__xx__$3__xx$__4__xx"
330
+ * Encodes a package name into a valid file name.
331
+ * @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
332
+ * @returns {string} - The encoded file name.
275
333
  */
276
334
  function packageNameEncode(name) {
277
335
  if (typeof name !== "string") throw new Error("A string package name is required");
278
- return name.replace(/\@/g, "__$1__").replace(/\//g, "__$2__").replace(/\-/g, "__$3__").replace(/\./g, "__$4__");
336
+ return name.replace(/@/g, "_mf_0_").replace(/\//g, "_mf_1_").replace(/-/g, "_mf_2_").replace(/\./g, "_mf_3_");
279
337
  }
280
338
  /**
281
- * @param {*} global "__$1__scope__$2__xx__$3__xx$__4__xx" => "@scope/xx-xx.xx"
339
+ * Decodes an encoded file name back to the original package name.
340
+ * @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
341
+ * @returns {string} - The decoded package name.
282
342
  */
283
- function packageNameDecode(global) {
284
- if (typeof global !== "string") throw new Error("A string global variable name is required");
285
- return global.replace(/\_\_\$1\_\_/g, "@").replace(/\_\_\$2\_\_/g, "/").replace(/\_\_\$3\_\_/g, "-").replace(/\_\_\$4\_\_/g, ".");
343
+ function packageNameDecode(encoded) {
344
+ if (typeof encoded !== "string") throw new Error("A string encoded file name is required");
345
+ return encoded.replace(/_mf_0_/g, "@").replace(/_mf_1_/g, "/").replace(/_mf_2_/g, "-").replace(/_mf_3_/g, ".");
286
346
  }
287
- function removePathFromNpmPackage(packageString) {
288
- // Regular expression to match npm package name, ignoring path parts
289
- const regex = /^(?:@[^/]+\/)?[^/]+/;
290
- // Use regular expression to match and extract the package name
291
- const match = packageString.match(regex);
292
- // Return the matched package name or the original string if no match is found
293
- return match ? match[0] : packageString;
347
+
348
+ /**
349
+ * https://github.com/module-federation/vite/issues/68
350
+ */
351
+ function getLocalSharedImportMapPath_windows() {
352
+ const {
353
+ name
354
+ } = getNormalizeModuleFederationOptions();
355
+ return path__default.resolve(".__mf__win", packageNameEncode(name), "localSharedImportMap");
294
356
  }
295
- function getExtFromNpmPackage(packageString) {
296
- const pkgName = removePathFromNpmPackage(packageString);
297
- const subpath = packageString.replace(pkgName, "");
298
- const parts = subpath.split('.');
299
- const ext = parts.length > 1 ? "." + parts.pop() : undefined;
300
- return ext;
357
+ function writeLocalSharedImportMap_windows(content) {
358
+ const localSharedImportMapId = getLocalSharedImportMapPath_windows();
359
+ createFile(localSharedImportMapId + ".js", "\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n" + content);
360
+ }
361
+ function createFile(filePath, content) {
362
+ const dir = path__default.dirname(filePath);
363
+ mkdirSync(dir, {
364
+ recursive: true
365
+ });
366
+ writeFileSync(filePath, content);
301
367
  }
302
368
 
303
369
  const nodeModulesDir = function findNodeModulesDir(startDir = process.cwd()) {
@@ -320,25 +386,38 @@ writeFileSync(resolve(nodeModulesDir, virtualPackageName, "package.json"), JSON.
320
386
  name: virtualPackageName,
321
387
  main: "empty.js"
322
388
  }));
389
+ const patternMap = {};
390
+ const cacheMap = {};
323
391
  /**
324
392
  * Physically generate files as virtual modules under node_modules/__mf__virtual/*
325
393
  */
326
394
  class VirtualModule {
327
- constructor(name, ext = ".js") {
328
- this.originName = void 0;
395
+ static findModule(tag, str = "") {
396
+ if (!patternMap[tag]) patternMap[tag] = new RegExp(`(.*${packageNameEncode(tag)}(.+?)${packageNameEncode(tag)}.*)`);
397
+ const moduleName = (str.match(patternMap[tag]) || [])[2];
398
+ if (moduleName) return cacheMap[tag][packageNameDecode(moduleName)];
399
+ return undefined;
400
+ }
401
+ constructor(name, tag = '__mf_v__', suffix = "") {
402
+ var _name$split$slice$pop;
403
+ this.name = void 0;
404
+ this.tag = void 0;
405
+ this.suffix = void 0;
329
406
  this.inited = false;
330
- this.ext = void 0;
331
- this.originName = name;
332
- this.ext = ext;
407
+ this.name = name;
408
+ this.tag = tag;
409
+ this.suffix = suffix || ((_name$split$slice$pop = name.split(".").slice(1).pop()) == null ? void 0 : _name$split$slice$pop.replace(/(.)/, ".$1")) || ".js";
410
+ if (!cacheMap[this.tag]) cacheMap[this.tag] = {};
411
+ cacheMap[this.tag][this.name] = this;
333
412
  }
334
413
  getPath() {
335
414
  return resolve(nodeModulesDir, this.getImportId());
336
415
  }
337
416
  getImportId() {
338
417
  const {
339
- name
418
+ name: mfName
340
419
  } = getNormalizeModuleFederationOptions();
341
- return `${virtualPackageName}/${packageNameEncode(name)}-${packageNameEncode(this.originName)}${this.ext}`;
420
+ return `${virtualPackageName}/${packageNameEncode(`${mfName}${this.tag}${this.name}${this.tag}`)}${this.suffix}`;
342
421
  }
343
422
  writeSync(code, force) {
344
423
  if (!force && this.inited) return;
@@ -352,25 +431,50 @@ class VirtualModule {
352
431
  }
353
432
  }
354
433
 
355
- /**
356
- * https://github.com/module-federation/vite/issues/68
357
- */
358
- function getLocalSharedImportMapPath_windows() {
359
- const {
360
- name
361
- } = getNormalizeModuleFederationOptions();
362
- return path__default.resolve(".__mf__win", packageNameEncode(name), "localSharedImportMap");
434
+ const virtualRuntimeInitStatus = new VirtualModule("runtimeInit");
435
+ function writeRuntimeInitStatus() {
436
+ virtualRuntimeInitStatus.writeSync(`
437
+ let initResolve, initReject
438
+ const initPromise = new Promise((re, rj) => {
439
+ initResolve = re
440
+ initReject = rj
441
+ })
442
+ export {
443
+ initPromise,
444
+ initResolve,
445
+ initReject
446
+ }
447
+ `);
363
448
  }
364
- function writeLocalSharedImportMap_windows(content) {
365
- const localSharedImportMapId = getLocalSharedImportMapPath_windows();
366
- createFile(localSharedImportMapId + ".js", "\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n" + content);
449
+
450
+ const cacheRemoteMap = {};
451
+ const LOAD_REMOTE_TAG = '__loadRemote__';
452
+ function getRemoteVirtualModule(remote, command) {
453
+ if (!cacheRemoteMap[remote]) {
454
+ cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, ".js");
455
+ cacheRemoteMap[remote].writeSync(generateRemotes(remote, command));
456
+ }
457
+ const virtual = cacheRemoteMap[remote];
458
+ return virtual;
367
459
  }
368
- function createFile(filePath, content) {
369
- const dir = path__default.dirname(filePath);
370
- mkdirSync(dir, {
371
- recursive: true
372
- });
373
- writeFileSync(filePath, content);
460
+ const usedRemotesMap = {
461
+ // remote1: {remote1/App, remote1, remote1/Button}
462
+ };
463
+ function addUsedRemote(remoteKey, remoteModule) {
464
+ if (!usedRemotesMap[remoteKey]) usedRemotesMap[remoteKey] = new Set();
465
+ usedRemotesMap[remoteKey].add(remoteModule);
466
+ }
467
+ function getUsedRemotesMap() {
468
+ return usedRemotesMap;
469
+ }
470
+ function generateRemotes(id, command) {
471
+ return `
472
+ const {loadRemote} = require("@module-federation/runtime")
473
+ const {initPromise} = require("${virtualRuntimeInitStatus.getImportId()}")
474
+ const res = initPromise.then(_ => loadRemote(${JSON.stringify(id)}))
475
+ const exportModule = ${command !== "build" ? "/*mf top-level-await placeholder replacement mf*/" : "await "}initPromise.then(_ => res)
476
+ module.exports = exportModule
477
+ `;
374
478
  }
375
479
 
376
480
  /**
@@ -382,17 +486,47 @@ function createFile(filePath, content) {
382
486
  const preBuildCacheMap = {};
383
487
  const PREBUILD_TAG = "__prebuild__";
384
488
  function writePreBuildLibPath(pkg) {
385
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
489
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
386
490
  preBuildCacheMap[pkg].writeSync("");
387
491
  }
388
492
  function getPreBuildLibImportId(pkg) {
389
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(PREBUILD_TAG + pkg, getExtFromNpmPackage(pkg));
493
+ if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
390
494
  const importId = preBuildCacheMap[pkg].getImportId();
391
495
  return importId;
392
496
  }
393
- let shareds = new Set();
394
- function addShare(pkg) {
395
- shareds.add(pkg);
497
+ // *** __loadShare__
498
+ const LOAD_SHARE_TAG = "__loadShare__";
499
+ const loadShareCacheMap = {};
500
+ function getLoadShareModulePath(pkg) {
501
+ if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, ".js");
502
+ const filepath = loadShareCacheMap[pkg].getPath();
503
+ return filepath;
504
+ }
505
+ function writeLoadShareModule(pkg, shareItem, command) {
506
+ loadShareCacheMap[pkg].writeSync(`
507
+
508
+ ;() => import(${JSON.stringify(getPreBuildLibImportId(pkg))}).catch(() => {});
509
+ // dev uses dynamic import to separate chunks
510
+ ${command !== "build" ? `;() => import(${JSON.stringify(pkg)}).catch(() => {});` : ''}
511
+ const {loadShare} = require("@module-federation/runtime")
512
+ const {initPromise} = require("${virtualRuntimeInitStatus.getImportId()}")
513
+ const res = initPromise.then(_ => loadShare(${JSON.stringify(pkg)}, {
514
+ customShareInfo: {shareConfig:{
515
+ singleton: ${shareItem.shareConfig.singleton},
516
+ strictVersion: ${shareItem.shareConfig.strictVersion},
517
+ requiredVersion: ${JSON.stringify(shareItem.shareConfig.requiredVersion)}
518
+ }}}))
519
+ const exportModule = ${command !== "build" ? "/*mf top-level-await placeholder replacement mf*/" : "await "}res.then(factory => factory())
520
+ module.exports = exportModule
521
+ `);
522
+ }
523
+
524
+ let usedShares = new Set();
525
+ function getUsedShares() {
526
+ return usedShares;
527
+ }
528
+ function addUsedShares(pkg) {
529
+ usedShares.add(pkg);
396
530
  }
397
531
  // *** Expose locally provided shared modules here
398
532
  const localSharedImportMapModule = new VirtualModule("localSharedImportMap");
@@ -402,32 +536,32 @@ function getLocalSharedImportMapPath() {
402
536
  }
403
537
  return localSharedImportMapModule.getPath();
404
538
  }
405
- let prevSharedCount = 0;
406
- async function writeLocalSharedImportMap() {
407
- const sharedCount = shareds.size;
539
+ let prevSharedCount;
540
+ function writeLocalSharedImportMap() {
541
+ const sharedCount = getUsedShares().size;
408
542
  if (prevSharedCount !== sharedCount) {
409
543
  prevSharedCount = sharedCount;
410
544
  if (process.platform === "win32") {
411
- return writeLocalSharedImportMap_windows(await generateLocalSharedImportMap());
545
+ writeLocalSharedImportMap_windows(generateLocalSharedImportMap());
546
+ } else {
547
+ localSharedImportMapModule.writeSync(generateLocalSharedImportMap(), true);
412
548
  }
413
- return localSharedImportMapModule.writeSync(await generateLocalSharedImportMap(), true);
414
549
  }
415
550
  }
416
- async function generateLocalSharedImportMap() {
417
- await parsePromise;
551
+ function generateLocalSharedImportMap() {
418
552
  const options = getNormalizeModuleFederationOptions();
419
553
  return `
420
- const localSharedImportMap = {
421
- ${Array.from(shareds).map(pkg => `
554
+ const importMap = {
555
+ ${Array.from(getUsedShares()).map(pkg => `
422
556
  ${JSON.stringify(pkg)}: async () => {
423
557
  let pkg = await import("${getPreBuildLibImportId(pkg)}")
424
558
  return pkg
425
559
  }
426
560
  `).join(",")}
427
561
  }
428
- const localShared = {
429
- ${Array.from(shareds).map(key => {
430
- const shareItem = options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + "/"];
562
+ const usedShared = {
563
+ ${Array.from(getUsedShares()).map(key => {
564
+ const shareItem = getNormalizeShareItem(key);
431
565
  return `
432
566
  ${JSON.stringify(key)}: {
433
567
  name: ${JSON.stringify(key)},
@@ -436,8 +570,8 @@ async function generateLocalSharedImportMap() {
436
570
  loaded: false,
437
571
  from: ${JSON.stringify(options.name)},
438
572
  async get () {
439
- localShared[${JSON.stringify(key)}].loaded = true
440
- const {${JSON.stringify(key)}: pkgDynamicImport} = localSharedImportMap
573
+ usedShared[${JSON.stringify(key)}].loaded = true
574
+ const {${JSON.stringify(key)}: pkgDynamicImport} = importMap
441
575
  const res = await pkgDynamicImport()
442
576
  const exportModule = {...res}
443
577
  // All npm packages pre-built by vite will be converted to esm
@@ -457,40 +591,29 @@ async function generateLocalSharedImportMap() {
457
591
  `;
458
592
  }).join(',')}
459
593
  }
460
- export default localShared
594
+ const usedRemotes = [${Object.keys(getUsedRemotesMap()).map(key => {
595
+ const remote = options.remotes[key];
596
+ return `
597
+ {
598
+ entryGlobalName: ${JSON.stringify(remote.entryGlobalName)},
599
+ name: ${JSON.stringify(remote.name)},
600
+ type: ${JSON.stringify(remote.type)},
601
+ entry: ${JSON.stringify(remote.entry)},
602
+ }
603
+ `;
604
+ }).join(',')}
605
+ ]
606
+ export {
607
+ usedShared,
608
+ usedRemotes
609
+ }
461
610
  `;
462
611
  }
463
- // *** __loadShare__
464
- const LOAD_SHARE_TAG = "__loadShare__";
465
- const loadShareCacheMap = {};
466
- function getLoadShareModulePath(pkg) {
467
- if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(LOAD_SHARE_TAG + pkg);
468
- const filepath = loadShareCacheMap[pkg].getPath();
469
- return filepath;
470
- }
471
- function writeLoadShareModule(pkg, shareItem, command) {
472
- loadShareCacheMap[pkg].writeSync(`
473
- () => import(${JSON.stringify(getPreBuildLibImportId(pkg))}).catch(() => {});
474
- // dev uses dynamic import to separate chunks
475
- ${command !== "build" ? `;() => import(${JSON.stringify(pkg)}).catch(() => {});` : ''}
476
- const {loadShare} = require("@module-federation/runtime")
477
- const res = loadShare(${JSON.stringify(pkg)}, {
478
- customShareInfo: {shareConfig:{
479
- singleton: ${shareItem.shareConfig.singleton},
480
- strictVersion: ${shareItem.shareConfig.strictVersion},
481
- requiredVersion: ${JSON.stringify(shareItem.shareConfig.requiredVersion)}
482
- }}})
483
- const exportModule = ${command !== "build" ? "/*mf top-level-await placeholder replacement mf*/" : "await "}res.then(factory => factory())
484
- module.exports = exportModule
485
- `);
486
- }
487
-
488
612
  const REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
489
613
  function generateRemoteEntry(options) {
490
614
  const pluginImportNames = options.runtimePlugins.map((p, i) => [`$runtimePlugin_${i}`, `import $runtimePlugin_${i} from "${p}";`]);
491
615
  return `
492
616
  import {init as runtimeInit, loadRemote} from "@module-federation/runtime";
493
-
494
617
  ${pluginImportNames.map(item => item[1]).join('\n')}
495
618
 
496
619
  const exposesMap = {
@@ -509,26 +632,19 @@ function generateRemoteEntry(options) {
509
632
  `;
510
633
  }).join(',')}
511
634
  }
512
- import localSharedImportMap from "${getLocalSharedImportMapPath()}"
635
+ import {usedShared, usedRemotes} from "${getLocalSharedImportMapPath()}"
636
+ import {
637
+ initResolve
638
+ } from "${virtualRuntimeInitStatus.getImportId()}"
513
639
  async function init(shared = {}) {
514
640
  const initRes = runtimeInit({
515
641
  name: ${JSON.stringify(options.name)},
516
- remotes: [${Object.keys(options.remotes).map(key => {
517
- const remote = options.remotes[key];
518
- return `
519
- {
520
- entryGlobalName: ${JSON.stringify(remote.entryGlobalName)},
521
- name: ${JSON.stringify(remote.name)},
522
- type: ${JSON.stringify(remote.type)},
523
- entry: ${JSON.stringify(remote.entry)},
524
- }
525
- `;
526
- }).join(',')}
527
- ],
528
- shared: localSharedImportMap,
642
+ remotes: usedRemotes,
643
+ shared: usedShared,
529
644
  plugins: [${pluginImportNames.map(item => `${item[0]}()`).join(', ')}]
530
645
  });
531
646
  initRes.initShareScopeMap('${options.shareScope}', shared);
647
+ initResolve(initRes)
532
648
  return initRes
533
649
  }
534
650
 
@@ -560,36 +676,374 @@ function getHostAutoInitPath() {
560
676
  return hostAutoInitModule.getPath();
561
677
  }
562
678
 
563
- const remoteVirtualModule = new VirtualModule("remoteModule");
564
- function writeRemote() {
565
- remoteVirtualModule.writeSync("");
566
- }
567
- function generateRemotes(id, command) {
568
- return {
569
- code: `
570
- import {loadRemote} from "@module-federation/runtime"
571
- const exportModule = await loadRemote(${JSON.stringify(id)})
572
- ${command === "build" && `
573
- export default 'default' in (exportModule || {}) ? exportModule.default : undefined
574
- export const __mf__dynamicExports = exportModule
575
- ` || ""}
576
- ${command !== "build" && `
577
- export default exportModule
578
- ` || ""}
579
- `,
580
- map: null,
581
- // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
582
- syntheticNamedExports: '__mf__dynamicExports'
583
- };
584
- }
585
-
586
679
  function initVirtualModules() {
587
680
  writeLocalSharedImportMap();
588
681
  writeHostAutoInit();
589
- writeRemote();
682
+ writeRuntimeInitStatus();
590
683
  }
591
684
 
592
- const filter$1 = createFilter();
685
+ const Manifest = () => {
686
+ const mfOptions = getNormalizeModuleFederationOptions();
687
+ const {
688
+ name,
689
+ filename,
690
+ manifest: manifestOptions
691
+ } = mfOptions;
692
+ let mfManifestName = "";
693
+ if (manifestOptions === true) {
694
+ mfManifestName = "mf-manifest.json";
695
+ }
696
+ if (typeof manifestOptions !== "boolean") {
697
+ mfManifestName = join((manifestOptions == null ? void 0 : manifestOptions.filePath) || "", (manifestOptions == null ? void 0 : manifestOptions.fileName) || "");
698
+ }
699
+ let extensions;
700
+ let root;
701
+ let remoteEntryFile;
702
+ return [{
703
+ name: 'moddule-federation-manifest',
704
+ apply: 'serve',
705
+ configureServer(server) {
706
+ server.middlewares.use((req, res, next) => {
707
+ if (!mfManifestName) {
708
+ next();
709
+ return;
710
+ }
711
+ if (req.url === mfManifestName.replace(/^\/?/, "/")) {
712
+ res.setHeader('Content-Type', 'application/json');
713
+ res.setHeader('Access-Control-Allow-Origin', '*');
714
+ res.end(JSON.stringify({
715
+ id: name,
716
+ name: name,
717
+ metaData: {
718
+ name: name,
719
+ type: 'app',
720
+ buildInfo: {
721
+ buildVersion: '1.0.0',
722
+ buildName: name
723
+ },
724
+ remoteEntry: {
725
+ name: filename,
726
+ path: '',
727
+ type: 'module'
728
+ },
729
+ ssrRemoteEntry: {
730
+ name: filename,
731
+ path: '',
732
+ type: 'module'
733
+ },
734
+ types: {
735
+ path: '',
736
+ name: ''
737
+ },
738
+ globalName: name,
739
+ pluginVersion: '0.2.5',
740
+ publicPath: 'auto'
741
+ },
742
+ shared: Array.from(getUsedShares()).map(shareKey => {
743
+ const shareItem = getNormalizeShareItem(shareKey);
744
+ return {
745
+ id: `${name}:${shareKey}`,
746
+ name: shareKey,
747
+ version: shareItem.version,
748
+ requiredVersion: shareItem.shareConfig.requiredVersion,
749
+ assets: {
750
+ js: {
751
+ async: [],
752
+ sync: []
753
+ },
754
+ css: {
755
+ async: [],
756
+ sync: []
757
+ }
758
+ }
759
+ };
760
+ }),
761
+ remotes: function () {
762
+ const remotes = [];
763
+ const usedRemotesMap = getUsedRemotesMap();
764
+ Object.keys(usedRemotesMap).forEach(remoteKey => {
765
+ const usedModules = Array.from(usedRemotesMap[remoteKey]);
766
+ usedModules.forEach(moduleKey => {
767
+ remotes.push({
768
+ federationContainerName: mfOptions.remotes[remoteKey].entry,
769
+ moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
770
+ alias: remoteKey,
771
+ entry: '*'
772
+ });
773
+ });
774
+ });
775
+ return remotes;
776
+ }(),
777
+ exposes: Object.keys(mfOptions.exposes).map(key => {
778
+ const formatKey = key.replace('./', '');
779
+ return {
780
+ id: name + ':' + formatKey,
781
+ name: formatKey,
782
+ assets: {
783
+ js: {
784
+ async: [],
785
+ sync: []
786
+ },
787
+ css: {
788
+ sync: [],
789
+ async: []
790
+ }
791
+ },
792
+ path: key
793
+ };
794
+ })
795
+ }));
796
+ } else {
797
+ next();
798
+ }
799
+ });
800
+ }
801
+ }, {
802
+ name: 'moddule-federation-manifest',
803
+ enforce: 'post',
804
+ config(config) {
805
+ if (!config.build) config.build = {};
806
+ if (!config.build.manifest) config.build.manifest = config.build.manifest || !!manifestOptions;
807
+ },
808
+ configResolved(config) {
809
+ root = config.root;
810
+ extensions = config.resolve.extensions || ['.mjs', '.js', '.mts', '.ts', '.jsx', '.tsx', '.json'];
811
+ },
812
+ async generateBundle(options, bundle) {
813
+ if (!mfManifestName) return;
814
+ const exposesModules = Object.keys(mfOptions.exposes).map(item => mfOptions.exposes[item].import); // 获取你提供的 moduleIds
815
+ const filesContainingModules = {};
816
+ // 帮助函数:检查模块路径是否匹配
817
+ const isModuleMatched = (relativeModulePath, preloadModule) => {
818
+ // 先尝试直接匹配
819
+ if (relativeModulePath === preloadModule) return true;
820
+ // 如果 preloadModule 没有后缀,尝试添加可能的后缀进行匹配
821
+ for (const ext of extensions) {
822
+ if (relativeModulePath === `${preloadModule}${ext}`) {
823
+ return true;
824
+ }
825
+ }
826
+ return false;
827
+ };
828
+ // 遍历打包生成的每个文件
829
+ for (const [fileName, fileData] of Object.entries(bundle)) {
830
+ if (mfOptions.filename.replace(/[\[\]]/g, "_") === fileData.name) {
831
+ remoteEntryFile = fileData.fileName;
832
+ }
833
+ if (fileData.type === 'chunk') {
834
+ // 遍历该文件的所有模块
835
+ for (const modulePath of Object.keys(fileData.modules)) {
836
+ // 将绝对路径转换为相对于 Vite root 的相对路径
837
+ const relativeModulePath = relative(root, modulePath);
838
+ // 检查模块是否在 preloadModules 列表中
839
+ for (const preloadModule of exposesModules) {
840
+ const formatPreloadModule = preloadModule.replace("./", "");
841
+ if (isModuleMatched(relativeModulePath, formatPreloadModule)) {
842
+ if (!filesContainingModules[preloadModule]) {
843
+ filesContainingModules[preloadModule] = {
844
+ sync: [],
845
+ async: []
846
+ };
847
+ }
848
+ console.log(Object.keys(fileData.modules));
849
+ filesContainingModules[preloadModule].sync.push(fileName);
850
+ filesContainingModules[preloadModule].async.push(...(fileData.dynamicImports || []));
851
+ findSynchronousImports(fileName, filesContainingModules[preloadModule].sync);
852
+ break; // 如果找到匹配,跳出循环
853
+ }
854
+ }
855
+ }
856
+ }
857
+ }
858
+ // 递归查找模块的同步导入文件
859
+ function findSynchronousImports(fileName, array) {
860
+ const fileData = bundle[fileName];
861
+ if (fileData && fileData.type === 'chunk') {
862
+ array.push(fileName); // 将当前文件加入预加载列表
863
+ // 遍历该文件的同步导入文件
864
+ fileData.imports.forEach(importedFile => {
865
+ if (array.indexOf(importedFile) === -1) {
866
+ findSynchronousImports(importedFile, array); // 递归查找同步导入的文件
867
+ }
868
+ });
869
+ }
870
+ }
871
+ const fileToShareKey = {};
872
+ await Promise.all(Array.from(getUsedShares()).map(async shareKey => {
873
+ const file = (await this.resolve(getPreBuildLibImportId(shareKey))).id.split("?")[0];
874
+ fileToShareKey[file] = shareKey;
875
+ }));
876
+ // 遍历打包生成的每个文件
877
+ for (const [fileName, fileData] of Object.entries(bundle)) {
878
+ if (fileData.type === 'chunk') {
879
+ // 遍历该文件的所有模块
880
+ for (const modulePath of Object.keys(fileData.modules)) {
881
+ const sharedKey = fileToShareKey[modulePath];
882
+ if (sharedKey) {
883
+ if (!filesContainingModules[sharedKey]) {
884
+ filesContainingModules[sharedKey] = {
885
+ sync: [],
886
+ async: []
887
+ };
888
+ }
889
+ filesContainingModules[sharedKey].sync.push(fileName);
890
+ filesContainingModules[sharedKey].async.push(...(fileData.dynamicImports || []));
891
+ findSynchronousImports(fileName, filesContainingModules[sharedKey].sync);
892
+ break; // 如果找到匹配,跳出循环
893
+ }
894
+ }
895
+ }
896
+ }
897
+ Object.keys(filesContainingModules).forEach(key => {
898
+ filesContainingModules[key].sync = Array.from(new Set(filesContainingModules[key].sync));
899
+ filesContainingModules[key].async = Array.from(new Set(filesContainingModules[key].async));
900
+ });
901
+ this.emitFile({
902
+ type: 'asset',
903
+ fileName: mfManifestName,
904
+ source: generateMFManifest(filesContainingModules)
905
+ });
906
+ }
907
+ }];
908
+ function generateMFManifest(preloadMap) {
909
+ const options = getNormalizeModuleFederationOptions();
910
+ const {
911
+ name
912
+ } = options;
913
+ const remoteEntry = {
914
+ name: remoteEntryFile,
915
+ path: '',
916
+ type: 'module'
917
+ };
918
+ const remotes = [];
919
+ const usedRemotesMap = getUsedRemotesMap();
920
+ Object.keys(usedRemotesMap).forEach(remoteKey => {
921
+ const usedModules = Array.from(usedRemotesMap[remoteKey]);
922
+ usedModules.forEach(moduleKey => {
923
+ remotes.push({
924
+ federationContainerName: options.remotes[remoteKey].entry,
925
+ moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
926
+ alias: remoteKey,
927
+ entry: '*'
928
+ });
929
+ });
930
+ });
931
+ // @ts-ignore
932
+ const shared = Array.from(getUsedShares()).map(shareKey => {
933
+ // assets(.css, .jpg, .svg等)其他资源, 不重要, 暂未处理
934
+ if (!preloadMap[shareKey]) return;
935
+ const shareItem = getNormalizeShareItem(shareKey);
936
+ return {
937
+ id: `${name}:${shareKey}`,
938
+ name: shareKey,
939
+ version: shareItem.version,
940
+ requiredVersion: shareItem.shareConfig.requiredVersion,
941
+ assets: {
942
+ js: {
943
+ async: preloadMap[shareKey].async,
944
+ sync: preloadMap[shareKey].sync
945
+ },
946
+ css: {
947
+ async: [],
948
+ sync: []
949
+ }
950
+ }
951
+ };
952
+ }).filter(item => item);
953
+ const exposes = Object.keys(options.exposes).map(key => {
954
+ // assets(.css, .jpg, .svg等)其他资源, 不重要, 暂未处理
955
+ const formatKey = key.replace('./', '');
956
+ const sourceFile = options.exposes[key].import;
957
+ if (!preloadMap[sourceFile]) return;
958
+ return {
959
+ id: name + ':' + formatKey,
960
+ name: formatKey,
961
+ assets: {
962
+ js: {
963
+ async: preloadMap[sourceFile].async,
964
+ sync: preloadMap[sourceFile].sync
965
+ },
966
+ css: {
967
+ sync: [],
968
+ async: []
969
+ }
970
+ },
971
+ path: key
972
+ };
973
+ }).filter(item => item); // Filter out any null values
974
+ const result = {
975
+ id: name,
976
+ name: name,
977
+ metaData: {
978
+ name: name,
979
+ type: 'app',
980
+ buildInfo: {
981
+ buildVersion: '1.0.0',
982
+ buildName: name
983
+ },
984
+ remoteEntry,
985
+ ssrRemoteEntry: remoteEntry,
986
+ types: {
987
+ path: '',
988
+ name: ''
989
+ // "zip": "@mf-types.zip",
990
+ // "api": "@mf-types.d.ts"
991
+ },
992
+ globalName: name,
993
+ pluginVersion: '0.2.5',
994
+ publicPath: 'auto'
995
+ },
996
+ shared,
997
+ remotes,
998
+ exposes
999
+ };
1000
+ return JSON.stringify(result);
1001
+ }
1002
+ };
1003
+
1004
+ let _resolve,
1005
+ promise = new Promise((resolve, reject) => {
1006
+ _resolve = resolve;
1007
+ });
1008
+ let parsePromise = promise;
1009
+ const parseStartSet = new Set();
1010
+ const parseEndSet = new Set();
1011
+ function pluginModuleParseEnd (excludeFn) {
1012
+ return [{
1013
+ name: "_",
1014
+ apply: "serve",
1015
+ config() {
1016
+ // No waiting in development mode
1017
+ _resolve(1);
1018
+ }
1019
+ }, {
1020
+ enforce: "pre",
1021
+ name: "parseStart",
1022
+ apply: "build",
1023
+ load(id) {
1024
+ if (excludeFn(id)) {
1025
+ return;
1026
+ }
1027
+ parseStartSet.add(id);
1028
+ }
1029
+ }, {
1030
+ enforce: "post",
1031
+ name: "parseEnd",
1032
+ apply: "build",
1033
+ moduleParsed(module) {
1034
+ const id = module.id;
1035
+ if (excludeFn(id)) {
1036
+ return;
1037
+ }
1038
+ parseEndSet.add(id);
1039
+ if (parseStartSet.size === parseEndSet.size) {
1040
+ _resolve(1);
1041
+ }
1042
+ }
1043
+ }];
1044
+ }
1045
+
1046
+ const filter = createFilter();
593
1047
  function pluginProxyRemoteEntry () {
594
1048
  return {
595
1049
  name: 'proxyRemoteEntry',
@@ -601,56 +1055,40 @@ function pluginProxyRemoteEntry () {
601
1055
  },
602
1056
  load(id) {
603
1057
  if (id === REMOTE_ENTRY_ID) {
604
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1058
+ return parsePromise.then(_ => generateRemoteEntry(getNormalizeModuleFederationOptions()));
605
1059
  }
606
1060
  },
607
1061
  async transform(code, id) {
608
- if (!filter$1(id)) return;
1062
+ if (!filter(id)) return;
609
1063
  if (id.includes(REMOTE_ENTRY_ID)) {
610
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1064
+ return parsePromise.then(_ => generateRemoteEntry(getNormalizeModuleFederationOptions()));
611
1065
  }
612
1066
  }
613
1067
  };
614
1068
  }
615
1069
 
616
- const filter = createFilter();
1070
+ createFilter();
617
1071
  function pluginProxyRemotes (options) {
618
- let command;
619
1072
  const {
620
1073
  remotes
621
1074
  } = options;
622
- const matchRemotesList = Object.keys(remotes).map(item => item.replace(/\//g, "_"));
623
1075
  return {
624
1076
  name: "proxyRemotes",
625
1077
  config(config, {
626
1078
  command: _command
627
1079
  }) {
628
- command = _command;
629
1080
  Object.keys(remotes).forEach(key => {
630
1081
  const remote = remotes[key];
631
1082
  config.resolve.alias.push({
632
- find: new RegExp(`(${remote.name}(\/.*|$)?)`),
633
- replacement: '$1',
1083
+ find: new RegExp(`^(${remote.name}(\/.*|$))`),
1084
+ replacement: "$1",
634
1085
  customResolver(source) {
635
- const requestPath = remoteVirtualModule.getImportId() + '?__moduleRemote__=' + encodeURIComponent(source);
636
- if (!config.optimizeDeps) config.optimizeDeps = {};
637
- if (!config.optimizeDeps.needsInterop) config.optimizeDeps.needsInterop = [];
638
- if (config.optimizeDeps.needsInterop.indexOf(requestPath) === -1) config.optimizeDeps.needsInterop.push(requestPath);
639
- return this.resolve(requestPath);
1086
+ const remoteModule = getRemoteVirtualModule(source, _command);
1087
+ addUsedRemote(remote.name, source);
1088
+ return remoteModule.getPath();
640
1089
  }
641
1090
  });
642
1091
  });
643
- },
644
- async transform(code, id) {
645
- if (!filter(id)) return;
646
- let [devRemoteModuleName] = matchRemotesList.length && id.match(new RegExp(`\/(${matchRemotesList.join('|')})(\_.*\.js|\.js)`)) || [];
647
- if (devRemoteModuleName) {
648
- return generateRemotes(devRemoteModuleName.replace('/', '').replace(/_/g, '/').replace('.js', ''), command);
649
- }
650
- let [prodRemoteName] = id.match(/\_\_moduleRemote\_\_=[^&]+/) || [];
651
- if (prodRemoteName) {
652
- return generateRemotes(decodeURIComponent(prodRemoteName.replace('__moduleRemote__=', '')), command);
653
- }
654
1092
  }
655
1093
  };
656
1094
  }
@@ -689,42 +1127,23 @@ class PromiseStore {
689
1127
  }
690
1128
  }
691
1129
 
692
- function wrapManualChunks(output, manualChunksCb) {
693
- if (!output.manualChunks) output.manualChunks = {};
694
- const wrapManualChunks = original => (id, ...args) => {
695
- const customRes = manualChunksCb == null ? void 0 : manualChunksCb(id, ...args);
696
- if (customRes) return customRes;
697
- if (typeof original === 'function') {
698
- return original(id, ...args);
699
- }
700
- if (typeof original === 'object' && original) {
701
- return original[id];
702
- }
703
- };
704
- output.manualChunks = wrapManualChunks(output.manualChunks);
705
- }
706
-
707
1130
  function proxySharedModule(options) {
708
1131
  let {
709
1132
  shared = {},
710
1133
  include,
711
1134
  exclude
712
1135
  } = options;
713
- const filterFunction = createFilter(include, exclude);
714
1136
  return [{
715
1137
  name: "generateLocalSharedImportMap",
716
1138
  enforce: "post",
717
- resolveId(id) {
718
- if (id.includes(getLocalSharedImportMapPath())) return id;
719
- },
720
1139
  load(id) {
721
1140
  if (id.includes(getLocalSharedImportMapPath())) {
722
- return generateLocalSharedImportMap();
1141
+ return parsePromise.then(_ => generateLocalSharedImportMap());
723
1142
  }
724
1143
  },
725
1144
  transform(code, id) {
726
1145
  if (id.includes(getLocalSharedImportMapPath())) {
727
- return generateLocalSharedImportMap();
1146
+ return parsePromise.then(_ => generateLocalSharedImportMap());
728
1147
  }
729
1148
  }
730
1149
  }, {
@@ -733,21 +1152,6 @@ function proxySharedModule(options) {
733
1152
  config(config, {
734
1153
  command
735
1154
  }) {
736
- if (!config.build) config.build = {};
737
- if (!config.build.rollupOptions) config.build.rollupOptions = {};
738
- let {
739
- rollupOptions
740
- } = config.build;
741
- if (!rollupOptions.output) rollupOptions.output = {};
742
- wrapManualChunks(config.build.rollupOptions.output, id => {
743
- // https://github.com/module-federation/vite/issues/40#issuecomment-2311434503
744
- if (id.includes('/preload-helper.js')) {
745
- return "preload-helper";
746
- }
747
- if (id.includes("node_modules/@module-federation/runtime")) {
748
- return "@module-federation/runtime";
749
- }
750
- });
751
1155
  config.resolve.alias.push(...Object.keys(shared).map(key => {
752
1156
  const pattern = key.endsWith("/") ? `(^${key.replace(/\/$/, "")}(\/.+)?$)` : `(^${key}$)`;
753
1157
  return {
@@ -755,12 +1159,10 @@ function proxySharedModule(options) {
755
1159
  find: new RegExp(pattern),
756
1160
  replacement: "$1",
757
1161
  customResolver(source, importer) {
758
- var _config$optimizeDeps;
759
1162
  const loadSharePath = getLoadShareModulePath(source);
760
- config == null || (_config$optimizeDeps = config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.needsInterop) == null || _config$optimizeDeps.push(loadSharePath);
761
1163
  writeLoadShareModule(source, shared[key], command);
762
1164
  writePreBuildLibPath(source);
763
- addShare(source);
1165
+ addUsedShares(source);
764
1166
  writeLocalSharedImportMap();
765
1167
  return this.resolve(loadSharePath);
766
1168
  }
@@ -769,18 +1171,16 @@ function proxySharedModule(options) {
769
1171
  const savePrebuild = new PromiseStore();
770
1172
  config.resolve.alias.push(...Object.keys(shared).map(key => {
771
1173
  return command === "build" ? {
772
- find: new RegExp(`(.*${PREBUILD_TAG}(.+))`),
1174
+ find: new RegExp(`(.*${PREBUILD_TAG}.*)`),
773
1175
  replacement: function ($1) {
774
- $1 = $1.replace(/\.[^.]+$/, "");
775
- const pkgName = packageNameDecode($1.split(PREBUILD_TAG)[1]);
776
- return packageNameDecode(pkgName);
1176
+ const pkgName = VirtualModule.findModule(PREBUILD_TAG, $1).name;
1177
+ return pkgName;
777
1178
  }
778
1179
  } : {
779
- find: new RegExp(`(.*${PREBUILD_TAG}(.+))`),
1180
+ find: new RegExp(`(.*${PREBUILD_TAG}.*)`),
780
1181
  replacement: "$1",
781
1182
  async customResolver(source, importer) {
782
- source = source.replace(/\.[^.]+$/, "");
783
- const pkgName = packageNameDecode(source.split(PREBUILD_TAG)[1]);
1183
+ const pkgName = VirtualModule.findModule(PREBUILD_TAG, source).name;
784
1184
  if (importer.includes(LOAD_SHARE_TAG)) {
785
1185
  // save pre-bunding module id
786
1186
  savePrebuild.set(pkgName, this.resolve(pkgName).then(item => item.id));
@@ -807,75 +1207,6 @@ function proxySharedModule(options) {
807
1207
  watch.ignored = [].concat(watch.ignored);
808
1208
  watch.ignored.push(`!**${getLocalSharedImportMapPath()}**`);
809
1209
  }
810
- }, {
811
- name: "prebuild-top-level-await",
812
- apply: "serve",
813
- transform(code, id) {
814
- if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
815
- return null;
816
- }
817
- if (!filterFunction(id)) return null;
818
- let ast;
819
- try {
820
- ast = this.parse(code, {
821
- allowReturnOutsideFunction: true
822
- });
823
- } catch (e) {
824
- throw new Error(`${id}: ${e}`);
825
- }
826
- const magicString = new MagicString(code);
827
- walk(ast, {
828
- enter(node) {
829
- if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
830
- const exportSpecifiers = node.specifiers.map(specifier => specifier.exported.name);
831
- const proxyStatements = exportSpecifiers.map(name => `
832
- const __mfproxy__await${name} = await ${name}();
833
- const __mfproxy__${name} = () => __mfproxy__await${name};
834
- `).join('\n');
835
- const exportStatements = exportSpecifiers.map(name => `__mfproxy__${name} as ${name}`).join(', ');
836
- const start = node.start;
837
- const end = node.end;
838
- const replacement = `${proxyStatements}\nexport { ${exportStatements} };`;
839
- magicString.overwrite(start, end, replacement);
840
- }
841
- if (node.type === 'ExportDefaultDeclaration') {
842
- const declaration = node.declaration;
843
- const start = node.start;
844
- const end = node.end;
845
- let proxyStatement;
846
- let exportStatement = 'default';
847
- if (declaration.type === 'Identifier') {
848
- // example: export default foo;
849
- proxyStatement = `
850
- const __mfproxy__awaitdefault = await ${declaration.name}();
851
- const __mfproxy__default = __mfproxy__awaitdefault;
852
- `;
853
- } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
854
- // example: export default someFunction();
855
- const declarationCode = code.slice(declaration.start, declaration.end);
856
- proxyStatement = `
857
- const __mfproxy__awaitdefault = await (${declarationCode});
858
- const __mfproxy__default = __mfproxy__awaitdefault;
859
- `;
860
- } else {
861
- // other
862
- proxyStatement = `
863
- const __mfproxy__awaitdefault = await (${code.slice(declaration.start, declaration.end)});
864
- const __mfproxy__default = __mfproxy__awaitdefault;
865
- `;
866
- }
867
- const replacement = `${proxyStatement}\nexport { __mfproxy__default as ${exportStatement} };`;
868
- magicString.overwrite(start, end, replacement);
869
- }
870
- }
871
- });
872
- return {
873
- code: magicString.toString(),
874
- map: magicString.generateMap({
875
- hires: true
876
- })
877
- };
878
- }
879
1210
  }];
880
1211
  }
881
1212
 
@@ -938,7 +1269,7 @@ function federation(mfUserOptions) {
938
1269
  return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(getLocalSharedImportMapPath());
939
1270
  }), ...proxySharedModule({
940
1271
  shared
941
- }), {
1272
+ }), PluginDevProxyModuleTopLevelAwait(), {
942
1273
  name: 'module-federation-vite',
943
1274
  enforce: 'post',
944
1275
  config(config, {
@@ -950,11 +1281,8 @@ function federation(mfUserOptions) {
950
1281
  replacement: require.resolve('@module-federation/runtime')
951
1282
  });
952
1283
  (_config$optimizeDeps = config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
953
- // Object.keys(shared).forEach((key) => {
954
- // config.optimizeDeps?.include?.push(key);
955
- // });
956
1284
  }
957
- }];
1285
+ }, ...Manifest()];
958
1286
  }
959
1287
 
960
1288
  export { federation };