@module-federation/vite 1.0.0-alpha-54ad191 → 1.0.0-alpha-4a73cd4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/lib/index.esm.js CHANGED
@@ -1,61 +1,81 @@
1
- import { createFilter } from '@rollup/pluginutils';
2
- import * as path from 'path';
3
- import path__default from 'path';
4
1
  import * as fs from 'fs';
2
+ import { writeFileSync } from 'fs';
3
+ import * as path from 'pathe';
4
+ import { resolve } from 'pathe';
5
+ import { createFilter } from '@rollup/pluginutils';
5
6
  import { walk } from 'estree-walker';
6
7
  import MagicString from 'magic-string';
7
8
 
8
- var aliasToArrayPlugin = {
9
- name: 'alias-transform-plugin',
10
- config: function config(_config, _ref) {
11
- if (!_config.resolve) _config.resolve = {};
12
- if (!_config.resolve.alias) _config.resolve.alias = [];
13
- var alias = _config.resolve.alias;
14
- if (typeof alias === 'object' && !Array.isArray(alias)) {
15
- _config.resolve.alias = Object.entries(alias).map(function (_ref2) {
16
- var find = _ref2[0],
17
- replacement = _ref2[1];
18
- return {
19
- find: find,
20
- replacement: replacement
21
- };
9
+ var addEntry = function addEntry(_ref) {
10
+ var entryPath = _ref.entryPath,
11
+ fileName = _ref.fileName;
12
+ var entryFiles = [];
13
+ var htmlFilePath;
14
+ return [{
15
+ name: 'add-entry',
16
+ apply: "serve",
17
+ configureServer: function configureServer(server) {
18
+ var _server$httpServer;
19
+ (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', function () {
20
+ var port = server.config.server.port;
21
+ fetch(path.join("http://localhost:" + port, "" + entryPath))["catch"](function (e) {});
22
22
  });
23
+ server.middlewares.use(function (req, res, next) {
24
+ if (!fileName) {
25
+ next();
26
+ return;
27
+ }
28
+ if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
29
+ req.url = entryPath;
30
+ }
31
+ next();
32
+ });
33
+ },
34
+ transformIndexHtml: function transformIndexHtml(c) {
35
+ return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
23
36
  }
24
- }
25
- };
26
-
27
- var normalizeBuildPlugin = (function (singleChunkModules) {
28
- return {
29
- name: 'normalizeBuild',
30
- config: function config(_config, _ref) {
31
- if (!_config.build) _config.build = {};
32
- if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
33
- var rollupOptions = _config.build.rollupOptions;
34
- if (!rollupOptions.output) rollupOptions.output = {};
35
- normalizeManualChunks(rollupOptions.output, singleChunkModules);
36
- }
37
- };
38
- });
39
- function normalizeManualChunks(output, singleChunkModules) {
40
- var pattern = new RegExp("node_modules/(" + singleChunkModules.join('|') + ")/");
41
- if (!output.manualChunks) output.manualChunks = {};
42
- var wrapManualChunks = function wrapManualChunks(original) {
43
- return function (id) {
44
- var _ref2 = id.match(pattern) || [],
45
- moduleName = _ref2[1];
46
- if (moduleName) {
47
- return moduleName;
37
+ }, {
38
+ name: "add-entry",
39
+ enforce: "post",
40
+ apply: "build",
41
+ configResolved: function configResolved(config) {
42
+ var inputOptions = config.build.rollupOptions.input;
43
+ if (!inputOptions) {
44
+ htmlFilePath = path.resolve(config.root, 'index.html');
45
+ } else if (typeof inputOptions === 'string') {
46
+ entryFiles = [inputOptions];
47
+ htmlFilePath = path.resolve(config.root, inputOptions);
48
+ } else if (Array.isArray(inputOptions)) {
49
+ entryFiles = inputOptions;
50
+ htmlFilePath = path.resolve(config.root, inputOptions[0]);
51
+ } else if (typeof inputOptions === 'object') {
52
+ entryFiles = Object.values(inputOptions);
53
+ htmlFilePath = path.resolve(config.root, Object.values(inputOptions)[0]);
48
54
  }
49
- if (typeof original === 'function') {
50
- return original.apply(void 0, [id].concat([].slice.call(arguments, 1)));
55
+ },
56
+ buildStart: function buildStart() {
57
+ var _this$emitFile;
58
+ var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
59
+ this.emitFile((_this$emitFile = {}, _this$emitFile[hasHash ? "name" : "fileName"] = fileName, _this$emitFile.type = 'chunk', _this$emitFile.id = entryPath, _this$emitFile.preserveSignature = 'strict', _this$emitFile));
60
+ if (htmlFilePath) {
61
+ var htmlContent = fs.readFileSync(htmlFilePath, 'utf-8');
62
+ var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
63
+ var match;
64
+ while ((match = scriptRegex.exec(htmlContent)) !== null) {
65
+ entryFiles.push(match[1]);
66
+ }
51
67
  }
52
- if (typeof original === 'object' && original) {
53
- return original[id];
68
+ },
69
+ transform: function transform(code, id) {
70
+ if (entryFiles.some(function (file) {
71
+ return id.endsWith(file);
72
+ })) {
73
+ var injection = "\n import " + JSON.stringify(entryPath) + ";\n ";
74
+ return injection + code;
54
75
  }
55
- };
56
- };
57
- output.manualChunks = wrapManualChunks(output.manualChunks);
58
- }
76
+ }
77
+ }];
78
+ };
59
79
 
60
80
  function normalizeExposesItem(key, item) {
61
81
  var importPath = '';
@@ -73,7 +93,7 @@ function normalizeExposes(exposes) {
73
93
  if (!exposes) return {};
74
94
  var res = {};
75
95
  Object.keys(exposes).forEach(function (key) {
76
- res[key.replace(/^\.?\/?/, './')] = normalizeExposesItem(key, exposes[key]);
96
+ res[key] = normalizeExposesItem(key, exposes[key]);
77
97
  });
78
98
  return res;
79
99
  }
@@ -110,7 +130,7 @@ function normalizeRemoteItem(key, remote) {
110
130
  function normalizeShareItem(key, shareItem) {
111
131
  var version;
112
132
  try {
113
- version = require(path__default.join(key, 'package.json')).version;
133
+ version = require(path.join(key, 'package.json')).version;
114
134
  } catch (e) {
115
135
  console.log(e);
116
136
  }
@@ -158,8 +178,12 @@ function normalizeLibrary(library) {
158
178
  if (!library) return undefined;
159
179
  return library;
160
180
  }
181
+ var config;
182
+ function getNormalizeModuleFederationOptions() {
183
+ return config;
184
+ }
161
185
  function normalizeModuleFederationOptions(options) {
162
- return {
186
+ return config = {
163
187
  exposes: normalizeExposes(options.exposes),
164
188
  filename: options.filename || 'remoteEntry-[hash]',
165
189
  library: normalizeLibrary(options.library),
@@ -178,216 +202,63 @@ function normalizeModuleFederationOptions(options) {
178
202
  };
179
203
  }
180
204
 
181
- var normalizeOptimizeDepsPlugin = {
182
- name: 'normalizeOptimizeDeps',
183
- config: function config(_config, _ref) {
184
- var optimizeDeps = _config.optimizeDeps;
185
- if (!optimizeDeps) {
186
- _config.optimizeDeps = {};
187
- optimizeDeps = _config.optimizeDeps;
188
- }
189
- if (!optimizeDeps.include) optimizeDeps.include = [];
190
- if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
191
- }
192
- };
193
-
194
- var addEntry = function addEntry(_ref) {
195
- var entryPath = _ref.entryPath,
196
- fileName = _ref.fileName;
197
- var entryFiles = [];
198
- var htmlFilePath;
199
- return [{
200
- name: 'add-entry',
201
- apply: "serve",
202
- configureServer: function configureServer(server) {
203
- var _server$httpServer;
204
- (_server$httpServer = server.httpServer) == null || _server$httpServer.once == null || _server$httpServer.once('listening', function () {
205
- var port = server.config.server.port;
206
- fetch("http://localhost:" + port + entryPath);
207
- });
208
- server.middlewares.use(function (req, res, next) {
209
- if (!fileName) {
210
- next();
211
- return;
212
- }
213
- if (req.url && req.url.startsWith(fileName.replace(/^\/?/, '/'))) {
214
- req.url = entryPath;
215
- }
216
- next();
217
- });
218
- },
219
- transformIndexHtml: function transformIndexHtml(c) {
220
- return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(entryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\/g, '/')) + "></script>");
221
- }
222
- }, {
223
- name: "add-entry",
224
- enforce: "post",
225
- apply: "build",
226
- configResolved: function configResolved(config) {
227
- var inputOptions = config.build.rollupOptions.input;
228
- if (!inputOptions) {
229
- htmlFilePath = path.resolve(config.root, 'index.html');
230
- } else if (typeof inputOptions === 'string') {
231
- entryFiles = [inputOptions];
232
- htmlFilePath = path.resolve(config.root, inputOptions);
233
- } else if (Array.isArray(inputOptions)) {
234
- entryFiles = inputOptions;
235
- htmlFilePath = path.resolve(config.root, inputOptions[0]);
236
- } else if (typeof inputOptions === 'object') {
237
- entryFiles = Object.values(inputOptions);
238
- htmlFilePath = path.resolve(config.root, Object.values(inputOptions)[0]);
239
- }
240
- },
241
- buildStart: function buildStart() {
242
- var _this$emitFile;
243
- var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes("[hash");
244
- this.emitFile((_this$emitFile = {}, _this$emitFile[hasHash ? "name" : "fileName"] = fileName, _this$emitFile.type = 'chunk', _this$emitFile.id = entryPath, _this$emitFile.preserveSignature = 'strict', _this$emitFile));
245
- if (htmlFilePath) {
246
- var htmlContent = fs.readFileSync(htmlFilePath, 'utf-8');
247
- var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
248
- var match;
249
- while ((match = scriptRegex.exec(htmlContent)) !== null) {
250
- entryFiles.push(match[1]);
251
- }
252
- }
253
- },
254
- transform: function transform(code, id) {
255
- if (entryFiles.some(function (file) {
256
- return id.endsWith(file);
257
- })) {
258
- var injection = "\n import " + JSON.stringify(entryPath) + ";\n ";
259
- return injection + code;
260
- }
261
- }
262
- }];
263
- };
264
-
265
- function _arrayLikeToArray(r, a) {
266
- (null == a || a > r.length) && (a = r.length);
267
- for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
268
- return n;
205
+ /**
206
+ * Even the resolveId hook cannot interfere with vite pre-build,
207
+ * and adding query parameter virtual modules will also fail.
208
+ * You can only proxy to the real file through alias
209
+ */
210
+ var emptyNpmDir = resolve(require.resolve("an-empty-js-file"), "../");
211
+ /**
212
+ * The original shared module is proxied by getLoadShareModulePath, and the new shared module is prebuilt here
213
+ */
214
+ var cacheMap2 = {};
215
+ function getPreBuildLibPath(pkg) {
216
+ if (!cacheMap2[pkg]) cacheMap2[pkg] = "__mf__prebuildwrap_" + npmPackageNameToFileName(pkg) + ".js";
217
+ var filename = cacheMap2[pkg];
218
+ return filename;
269
219
  }
270
- function _createForOfIteratorHelperLoose(r, e) {
271
- var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
272
- if (t) return (t = t.call(r)).next.bind(t);
273
- if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
274
- t && (r = t);
275
- var o = 0;
276
- return function () {
277
- return o >= r.length ? {
278
- done: !0
279
- } : {
280
- done: !1,
281
- value: r[o++]
282
- };
283
- };
284
- }
285
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
220
+ function getLocalSharedImportMapFileName() {
221
+ var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
222
+ name = _getNormalizeModuleFe.name;
223
+ return npmPackageNameToFileName(name) + "_" + "__mf__localSharedImportMap.js";
286
224
  }
287
- function _unsupportedIterableToArray(r, a) {
288
- if (r) {
289
- if ("string" == typeof r) return _arrayLikeToArray(r, a);
290
- var t = {}.toString.call(r).slice(8, -1);
291
- return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0;
292
- }
225
+ // Only npm package name import can trigger pre-build, absolute path cannot
226
+ function getLocalSharedImportMapId() {
227
+ return "an-empty-js-file/" + getLocalSharedImportMapFileName();
293
228
  }
294
-
295
- function overrideModule(options) {
296
- if (options === void 0) {
297
- options = {};
298
- }
299
- var _options = options,
300
- _options$override = _options.override,
301
- _override = _options$override === void 0 ? [] : _options$override,
302
- include = _options.include,
303
- exclude = _options.exclude;
304
- var override = new Set(_override);
305
- var filterFunction = createFilter(include, exclude);
306
- var alias = {};
307
- var keys = override.keys();
308
- for (var _iterator = _createForOfIteratorHelperLoose(keys), _step; !(_step = _iterator()).done;) {
309
- var key = _step.value;
310
- alias['__overrideModule__' + key] = require.resolve("an-empty-js-file") + ("?__overrideModule__=" + encodeURIComponent(key));
311
- }
312
- return {
313
- name: 'overrideModule',
314
- enforce: 'post',
315
- config: function config(_config) {
316
- var _config$resolve$alias;
317
- if (!_config.optimizeDeps) _config.optimizeDeps = {};
318
- if (!_config.optimizeDeps.needsInterop) _config.optimizeDeps.needsInterop = [];
319
- Object.keys(alias).forEach(function (key) {
320
- var _config$optimizeDeps;
321
- (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.needsInterop) == null || _config$optimizeDeps.push(key);
322
- });
323
- _config.optimizeDeps.needsInterop.push('an-empty-js-file');
324
- (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(alias).map(function (key) {
325
- return {
326
- find: key,
327
- replacement: alias[key]
328
- };
329
- }));
330
- },
331
- resolveId: function resolveId(id) {
332
- return alias[id];
333
- },
334
- transform: {
335
- handler: function handler(code, id) {
336
- if (!filterFunction(id)) return null;
337
- var ast;
338
- try {
339
- ast = this.parse(code, {
340
- allowReturnOutsideFunction: true
341
- });
342
- } catch (e) {
343
- throw new Error(id + ": " + e);
344
- }
345
- var s = new MagicString(code);
346
- walk(ast, {
347
- enter: function enter(node) {
348
- var replaceIfMatch = function replaceIfMatch(sourceNode) {
349
- if (sourceNode && sourceNode.value) {
350
- if (override.has(sourceNode.value)) {
351
- var start = sourceNode.start + 1; // Skip the opening quote
352
- var end = sourceNode.end - 1; // Skip the closing quote
353
- s.overwrite(start, end, '__overrideModule__' + sourceNode.value);
354
- }
355
- }
356
- };
357
- if (node.type === 'ImportDeclaration') {
358
- replaceIfMatch(node.source);
359
- }
360
- if (node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration') {
361
- replaceIfMatch(node.source);
362
- }
363
- if (node.type === 'CallExpression' && node.callee.type === 'Import' && node.arguments.length && node.arguments[0].type === 'Literal') {
364
- replaceIfMatch(node.arguments[0]);
365
- }
366
- if (node.type === 'CallExpression' && node.callee.name === 'require' && node.arguments.length && node.arguments[0].type === 'Literal') {
367
- replaceIfMatch(node.arguments[0]);
368
- }
369
- }
370
- });
371
- return {
372
- code: s.toString(),
373
- map: s.generateMap({
374
- hires: true
375
- })
376
- };
377
- }
378
- }
379
- };
229
+ function getLocalSharedImportMapPath() {
230
+ return resolve(emptyNpmDir, getLocalSharedImportMapFileName());
380
231
  }
381
-
382
- var emptyPath = require.resolve('an-empty-js-file');
383
- var filter = createFilter();
384
- var command = '';
385
- function wrapRemoteEntry() {
386
- return "\n import {init, get} from \"__mf__cwdRemoteEntry\"\n export {init, get}\n ";
232
+ function writeLocalSharedImportMap(pkgList) {
233
+ writeFileSync(getLocalSharedImportMapPath(), "\n export default {\n " + pkgList.map(function (pkg) {
234
+ return "\n " + JSON.stringify(pkg) + ": async () => {\n let pkg = await import(\"" + getPreBuildLibPath(pkg) + "\")\n return pkg\n }\n ";
235
+ }).join(",") + "\n }\n ");
387
236
  }
388
- function wrapHostInit() {
389
- return "\n import {init} from \"__mf__cwdRemoteEntry\"\n init()\n ";
237
+ /**
238
+ * generate loadShare virtual module
239
+ */
240
+ var cacheMap1 = {};
241
+ function getLoadShareModulePath(pkg) {
242
+ var _getNormalizeModuleFe2 = getNormalizeModuleFederationOptions(),
243
+ name = _getNormalizeModuleFe2.name;
244
+ if (!cacheMap1[pkg]) cacheMap1[pkg] = npmPackageNameToFileName(name) + "_" + ("__mf__loadShare_" + npmPackageNameToFileName(pkg) + ".js");
245
+ var filename = cacheMap1[pkg];
246
+ return resolve(emptyNpmDir, filename);
390
247
  }
248
+ function writeLoadShareModule(pkg, shareItem, command) {
249
+ writeFileSync(getLoadShareModulePath(pkg), "\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 ");
250
+ }
251
+ function npmPackageNameToFileName(packageName) {
252
+ // 1. 去掉包名前的 "@"
253
+ // 2. 将包名中的 "/" 替换为 "__" 以避免文件路径问题
254
+ // 3. 去掉不合法的文件名字符
255
+ return packageName.replace(/^@/, '') // 移除作用域前缀 "@"
256
+ .replace(/\//g, '__') // 将 "/" 替换为 "__"
257
+ .replace(/[^a-zA-Z0-9_.-]/g, '_'); // 替换其他非法字符为 "_"
258
+ }
259
+
260
+ var emptyPath = require.resolve('an-empty-js-file');
261
+ var REMOTE_ENTRY_ID = "REMOTE_ENTRY_ID";
391
262
  function generateRemoteEntry(options) {
392
263
  var pluginImportNames = options.runtimePlugins.map(function (p, i) {
393
264
  return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";"];
@@ -396,9 +267,9 @@ function generateRemoteEntry(options) {
396
267
  return item[1];
397
268
  }).join('\n') + "\n\n const exposesMap = {\n " + Object.keys(options.exposes).map(function (key) {
398
269
  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 ";
399
- }).join(',') + "\n }\n async function init(shared = {}) {\n const localShared = {\n " + Object.keys(options.shared).map(function (key) {
270
+ }).join(',') + "\n }\n import localSharedImportMap from \"" + getLocalSharedImportMapId() + "\"\n async function init(shared = {}) {\n const localShared = {\n " + Object.keys(options.shared).map(function (key) {
400
271
  var shareItem = options.shared[key];
401
- 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 pkg = await import(" + JSON.stringify(key) + ")\n return function () {\n return pkg\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
272
+ 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 return function () {\n return res\n }\n },\n shareConfig: {\n singleton: " + shareItem.shareConfig.singleton + ",\n requiredVersion: " + JSON.stringify(shareItem.shareConfig.requiredVersion) + "\n }\n }\n ";
402
273
  }).join(',') + "\n }\n const initRes = runtimeInit({\n name: " + JSON.stringify(options.name) + ",\n remotes: [" + Object.keys(options.remotes).map(function (key) {
403
274
  var remote = options.remotes[key];
404
275
  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 ";
@@ -406,124 +277,315 @@ function generateRemoteEntry(options) {
406
277
  return item[0] + "()";
407
278
  }).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 ";
408
279
  }
409
- function wrapShare(id, shared) {
410
- var shareConfig = shared[id].shareConfig;
280
+ var WRAP_REMOTE_ENTRY_PATH = emptyPath + '?__mf__wrapRemoteEntry__';
281
+ function generateWrapRemoteEntry() {
282
+ return "\n import {init, get} from \"" + REMOTE_ENTRY_ID + "\"\n export {init, get}\n ";
283
+ }
284
+ /**
285
+ * Inject entry file, automatically init when used as host,
286
+ * and will not inject remoteEntry
287
+ */
288
+ var HOST_AUTO_INIT = emptyPath + '?__mf__isHostInit';
289
+ function generateWrapHostInit() {
290
+ return "\n import {init} from \"" + REMOTE_ENTRY_ID + "\"\n init()\n ";
291
+ }
292
+
293
+ var filter$1 = createFilter();
294
+ function pluginProxyRemoteEntry () {
411
295
  return {
412
- code: "\n import {loadShare} from \"@module-federation/runtime\"\n const res = await loadShare(" + JSON.stringify(id) + ", {\n customShareInfo: {shareConfig:{\n singleton: " + shareConfig.singleton + ",\n strictVersion: " + JSON.stringify(shareConfig.strictVersion) + ",\n requiredVersion: " + JSON.stringify(shareConfig.requiredVersion) + "\n }}})\n export default res()\n ",
413
- map: null,
414
- syntheticNamedExports: 'default'
296
+ name: 'proxyRemoteEntry',
297
+ enforce: 'post',
298
+ resolveId: function resolveId(id) {
299
+ if (id === REMOTE_ENTRY_ID) {
300
+ return REMOTE_ENTRY_ID;
301
+ }
302
+ },
303
+ load: function load(id) {
304
+ if (id === REMOTE_ENTRY_ID) {
305
+ return generateRemoteEntry(getNormalizeModuleFederationOptions());
306
+ }
307
+ },
308
+ transform: function transform(code, id) {
309
+ try {
310
+ if (!filter$1(id)) return Promise.resolve();
311
+ if (id === REMOTE_ENTRY_ID) {
312
+ return Promise.resolve(generateRemoteEntry(getNormalizeModuleFederationOptions()));
313
+ }
314
+ if (id.includes(WRAP_REMOTE_ENTRY_PATH)) {
315
+ return Promise.resolve(generateWrapRemoteEntry());
316
+ }
317
+ if (id.includes(HOST_AUTO_INIT)) {
318
+ return Promise.resolve(generateWrapHostInit());
319
+ }
320
+ return Promise.resolve();
321
+ } catch (e) {
322
+ return Promise.reject(e);
323
+ }
324
+ }
415
325
  };
416
326
  }
417
- var con;
418
- function wrapRemote(id) {
327
+
328
+ function generateRemotes(id, command) {
419
329
  return {
420
- code: "\n import {loadRemote} from \"@module-federation/runtime\"\n export " + (command !== 'build' ? 'default' : 'const dynamicExport = ') + " await loadRemote(" + JSON.stringify(id) + ")\n ",
330
+ 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 ",
421
331
  map: null,
422
- syntheticNamedExports: 'dynamicExport'
332
+ // TODO: vite dev mode invalid, use optimizeDeps.needsInterop
333
+ syntheticNamedExports: '__mf__dynamicExports'
423
334
  };
424
335
  }
425
- function federation(mfUserOptions) {
426
- var options = normalizeModuleFederationOptions(mfUserOptions);
427
- var remotes = options.remotes,
428
- shared = options.shared,
429
- filename = options.filename;
430
- var alias = [{
431
- find: '@module-federation/runtime',
432
- replacement: require.resolve('@module-federation/runtime')
433
- }];
434
- Object.keys(remotes).forEach(function (key) {
435
- var remote = remotes[key];
436
- alias.push({
437
- find: new RegExp("(" + remote.name + "(/.*|$)?)"),
438
- replacement: '$1',
439
- customResolver: function customResolver(source) {
440
- if (!con.optimizeDeps) con.optimizeDeps = {};
441
- if (!con.optimizeDeps.needsInterop) con.optimizeDeps.needsInterop = [];
442
- if (con.optimizeDeps.needsInterop.indexOf(source) === -1) con.optimizeDeps.needsInterop.push(source);
443
- return this.resolve(require.resolve('an-empty-js-file') + '?__moduleRemote__=' + encodeURIComponent(source));
444
- }
445
- });
446
- });
447
- var remotePrefixList = Object.keys(remotes);
448
- // pkgname will be escaped, and matching path also needs to be processed in the same way:
449
- // @json2csv/plainjs --> .vite/deps/@json2csv_plainjs
450
- var sharedKeyMatchList = Object.keys(shared).map(function (item) {
451
- return "__overrideModule__" + item.replace('/', '_');
336
+
337
+ var filter = createFilter();
338
+ function pluginProxyRemotes (options) {
339
+ var command;
340
+ var remotes = options.remotes;
341
+ var matchRemotesList = Object.keys(remotes).map(function (item) {
342
+ return item.replace(/\//g, "_");
452
343
  });
453
- return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin, normalizeBuildPlugin([].concat(Object.keys(shared), ["@module-federation/runtime"]))].concat(addEntry({
454
- entryName: 'remoteEntry',
455
- entryPath: emptyPath + '?__mf__wrapRemoteEntry__',
456
- fileName: filename
457
- }), addEntry({
458
- entryName: 'hostInit',
459
- entryPath: emptyPath + '?__mf__isHostInit'
460
- }), [overrideModule({
461
- override: Object.keys(shared)
462
- }), {
463
- name: 'module-federation-vite',
464
- enforce: 'post',
344
+ return {
345
+ name: "proxyRemotes",
465
346
  config: function config(_config, _ref) {
466
- var _config$resolve$alias, _config$optimizeDeps;
467
347
  var _command = _ref.command;
468
- con = _config;
469
348
  command = _command;
470
- (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, alias);
471
- (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
472
- Object.keys(shared).forEach(function (key) {
473
- var _config$optimizeDeps2;
474
- (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.include) == null || _config$optimizeDeps2.push(key);
349
+ Object.keys(remotes).forEach(function (key) {
350
+ var remote = remotes[key];
351
+ _config.resolve.alias.push({
352
+ find: new RegExp("(" + remote.name + "(/.*|$)?)"),
353
+ replacement: '$1',
354
+ customResolver: function customResolver(source) {
355
+ if (!_config.optimizeDeps) _config.optimizeDeps = {};
356
+ if (!_config.optimizeDeps.needsInterop) _config.optimizeDeps.needsInterop = [];
357
+ if (_config.optimizeDeps.needsInterop.indexOf(source) === -1) _config.optimizeDeps.needsInterop.push(source);
358
+ return this.resolve(require.resolve('an-empty-js-file') + '?__moduleRemote__=' + encodeURIComponent(source));
359
+ }
360
+ });
475
361
  });
476
362
  },
477
- resolveId: function resolveId(id) {
478
- if (id === '__mf__cwdRemoteEntry') {
479
- return '__mf__cwdRemoteEntry';
480
- }
481
- },
482
- load: function load(id) {
483
- if (id === '__mf__cwdRemoteEntry') {
484
- return generateRemoteEntry(options);
485
- }
486
- },
487
363
  transform: function transform(code, id) {
488
364
  try {
489
365
  if (!filter(id)) return Promise.resolve();
490
- if (id === '__mf__cwdRemoteEntry') {
491
- return Promise.resolve(generateRemoteEntry(options));
492
- }
493
- if (id.indexOf('__mf__wrapRemoteEntry__') > -1) {
494
- return Promise.resolve(wrapRemoteEntry());
495
- }
496
- if (id.indexOf('__mf__isHostInit') > -1) {
497
- return Promise.resolve(wrapHostInit());
498
- }
499
- if (id.indexOf('__mf__cwdRemoteEntry') > -1) {
500
- return Promise.resolve(generateRemoteEntry(options));
501
- }
502
- var _ref2 = sharedKeyMatchList.length && id.match(new RegExp("/(" + sharedKeyMatchList.join('|') + ")(_.*.js|.js)")) || [],
503
- devSharedModuleName = _ref2[0];
504
- if (devSharedModuleName) {
505
- return Promise.resolve(wrapShare(devSharedModuleName.replace('/__overrideModule__', '').replace(/_/g, '/').replace('.js', ''), shared));
506
- }
507
- var _ref3 = id.match(/\_\_overrideModule\_\_=[^&]+/) || [],
508
- prodSharedName = _ref3[0];
509
- if (prodSharedName) {
510
- return Promise.resolve(wrapShare(decodeURIComponent(prodSharedName.replace('__overrideModule__=', '')), shared));
511
- }
512
- var _ref4 = remotePrefixList.length && id.match(new RegExp("/(" + remotePrefixList.join('|') + ")(_.*.js|.js)")) || [],
513
- devRemoteModuleName = _ref4[0];
366
+ var _ref2 = matchRemotesList.length && id.match(new RegExp("/(" + matchRemotesList.join('|') + ")(_.*.js|.js)")) || [],
367
+ devRemoteModuleName = _ref2[0];
514
368
  if (devRemoteModuleName) {
515
- return Promise.resolve(wrapRemote(devRemoteModuleName.replace('/', '').replace(/_/g, '/').replace('.js', '')));
369
+ return Promise.resolve(generateRemotes(devRemoteModuleName.replace('/', '').replace(/_/g, '/').replace('.js', ''), command));
516
370
  }
517
- var _ref5 = id.match(/\_\_moduleRemote\_\_=[^&]+/) || [],
518
- prodRemoteName = _ref5[0];
371
+ var _ref3 = id.match(/\_\_moduleRemote\_\_=[^&]+/) || [],
372
+ prodRemoteName = _ref3[0];
519
373
  if (prodRemoteName) {
520
- return Promise.resolve(wrapRemote(decodeURIComponent(prodRemoteName.replace('__moduleRemote__=', ''))));
374
+ return Promise.resolve(generateRemotes(decodeURIComponent(prodRemoteName.replace('__moduleRemote__=', '')), command));
521
375
  }
522
376
  return Promise.resolve();
523
377
  } catch (e) {
524
378
  return Promise.reject(e);
525
379
  }
526
380
  }
381
+ };
382
+ }
383
+
384
+ function proxySharedModule(options) {
385
+ var _options$shared = options.shared,
386
+ shared = _options$shared === void 0 ? {} : _options$shared,
387
+ include = options.include,
388
+ exclude = options.exclude;
389
+ var filterFunction = createFilter(include, exclude);
390
+ writeLocalSharedImportMap(Object.keys(shared));
391
+ return [{
392
+ name: 'preBuildShared',
393
+ enforce: 'post',
394
+ config: function config(_config, _ref) {
395
+ var _config$resolve$alias, _config$resolve$alias2;
396
+ var command = _ref.command;
397
+ // config?.optimizeDeps?.include?.push?.("an-empty-js-file");
398
+ // config.optimizeDeps.needsInterop.push('an-empty-js-file');
399
+ (_config$resolve$alias = _config.resolve.alias).push.apply(_config$resolve$alias, Object.keys(shared).map(function (key) {
400
+ var _config$optimizeDeps;
401
+ _config == null || (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push == null || _config$optimizeDeps.push(getPreBuildLibPath(key));
402
+ // write proxyFile
403
+ writeLoadShareModule(key, shared[key], command);
404
+ var preBuildLibPath = getLoadShareModulePath(key);
405
+ return {
406
+ // Intercept all dependency requests to the proxy module
407
+ // Dependency requests issued by localSharedImportMap are allowed without proxying.
408
+ find: new RegExp("^" + key + "$"),
409
+ replacement: preBuildLibPath,
410
+ customResolver: function customResolver(source, importer) {
411
+ if (importer.includes("node_modules/" + key + "/")) {
412
+ return this.resolve(key);
413
+ }
414
+ return this.resolve(preBuildLibPath);
415
+ }
416
+ };
417
+ }));
418
+ (_config$resolve$alias2 = _config.resolve.alias).push.apply(_config$resolve$alias2, Object.keys(shared).map(function (key) {
419
+ return {
420
+ find: new RegExp("^" + getPreBuildLibPath(key) + "$"),
421
+ customResolver: function customResolver(source, importer) {
422
+ return this.resolve(key);
423
+ }
424
+ };
425
+ }));
426
+ }
427
+ }, {
428
+ name: "prebuild-top-level-await",
429
+ apply: "serve",
430
+ transform: function transform(code, id) {
431
+ if (!code.includes("/*mf top-level-await placeholder replacement mf*/")) {
432
+ return null;
433
+ }
434
+ if (!filterFunction(id)) return null;
435
+ var ast;
436
+ try {
437
+ ast = this.parse(code, {
438
+ allowReturnOutsideFunction: true
439
+ });
440
+ } catch (e) {
441
+ throw new Error(id + ": " + e);
442
+ }
443
+ var magicString = new MagicString(code);
444
+ walk(ast, {
445
+ enter: function enter(node) {
446
+ // 处理命名导出
447
+ if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
448
+ var exportSpecifiers = node.specifiers.map(function (specifier) {
449
+ return specifier.exported.name;
450
+ });
451
+ var proxyStatements = exportSpecifiers.map(function (name) {
452
+ return "\n const __mfproxy__await" + name + " = await " + name + "();\n const __mfproxy__" + name + " = () => __mfproxy__await" + name + ";\n ";
453
+ }).join('\n');
454
+ var exportStatements = exportSpecifiers.map(function (name) {
455
+ return "__mfproxy__" + name + " as " + name;
456
+ }).join(', ');
457
+ var start = node.start;
458
+ var end = node.end;
459
+ var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
460
+ magicString.overwrite(start, end, replacement);
461
+ }
462
+ // 处理默认导出
463
+ if (node.type === 'ExportDefaultDeclaration') {
464
+ var declaration = node.declaration;
465
+ var _start = node.start;
466
+ var _end = node.end;
467
+ var proxyStatement;
468
+ var exportStatement = 'default';
469
+ if (declaration.type === 'Identifier') {
470
+ // 处理标识符 (如: export default foo;)
471
+ proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
472
+ } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
473
+ // 处理调用表达式或函数声明 (如: export default someFunction();)
474
+ var declarationCode = code.slice(declaration.start, declaration.end);
475
+ proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
476
+ } else {
477
+ // 其他类型 (可以根据需要添加更多处理逻辑)
478
+ proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
479
+ }
480
+ var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
481
+ magicString.overwrite(_start, _end, _replacement);
482
+ }
483
+ }
484
+ });
485
+ return {
486
+ code: magicString.toString(),
487
+ map: magicString.generateMap({
488
+ hires: true
489
+ })
490
+ };
491
+ }
492
+ }];
493
+ }
494
+
495
+ var aliasToArrayPlugin = {
496
+ name: 'alias-transform-plugin',
497
+ config: function config(_config, _ref) {
498
+ if (!_config.resolve) _config.resolve = {};
499
+ if (!_config.resolve.alias) _config.resolve.alias = [];
500
+ var alias = _config.resolve.alias;
501
+ if (typeof alias === 'object' && !Array.isArray(alias)) {
502
+ _config.resolve.alias = Object.entries(alias).map(function (_ref2) {
503
+ var find = _ref2[0],
504
+ replacement = _ref2[1];
505
+ return {
506
+ find: find,
507
+ replacement: replacement
508
+ };
509
+ });
510
+ }
511
+ }
512
+ };
513
+
514
+ var normalizeBuildPlugin = (function (singleChunkModules) {
515
+ return {
516
+ name: 'normalizeBuild',
517
+ config: function config(_config, _ref) {
518
+ if (!_config.build) _config.build = {};
519
+ if (!_config.build.rollupOptions) _config.build.rollupOptions = {};
520
+ var rollupOptions = _config.build.rollupOptions;
521
+ if (!rollupOptions.output) rollupOptions.output = {};
522
+ normalizeManualChunks(rollupOptions.output, singleChunkModules);
523
+ }
524
+ };
525
+ });
526
+ function normalizeManualChunks(output, singleChunkModules) {
527
+ var pattern = new RegExp("node_modules/(" + singleChunkModules.join('|') + ")/");
528
+ if (!output.manualChunks) output.manualChunks = {};
529
+ var wrapManualChunks = function wrapManualChunks(original) {
530
+ return function (id) {
531
+ var _ref2 = id.match(pattern) || [],
532
+ moduleName = _ref2[1];
533
+ if (moduleName) {
534
+ return moduleName;
535
+ }
536
+ if (typeof original === 'function') {
537
+ return original.apply(void 0, [id].concat([].slice.call(arguments, 1)));
538
+ }
539
+ if (typeof original === 'object' && original) {
540
+ return original[id];
541
+ }
542
+ };
543
+ };
544
+ output.manualChunks = wrapManualChunks(output.manualChunks);
545
+ }
546
+
547
+ var normalizeOptimizeDepsPlugin = {
548
+ name: 'normalizeOptimizeDeps',
549
+ config: function config(_config, _ref) {
550
+ var optimizeDeps = _config.optimizeDeps;
551
+ if (!optimizeDeps) {
552
+ _config.optimizeDeps = {};
553
+ optimizeDeps = _config.optimizeDeps;
554
+ }
555
+ if (!optimizeDeps.include) optimizeDeps.include = [];
556
+ if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
557
+ }
558
+ };
559
+
560
+ function federation(mfUserOptions) {
561
+ var options = normalizeModuleFederationOptions(mfUserOptions);
562
+ var name = options.name,
563
+ shared = options.shared,
564
+ filename = options.filename;
565
+ if (!name) throw new Error("name is required");
566
+ return [aliasToArrayPlugin, normalizeOptimizeDepsPlugin, normalizeBuildPlugin([].concat(Object.keys(shared), ["@module-federation/runtime"]))].concat(addEntry({
567
+ entryName: 'remoteEntry',
568
+ entryPath: WRAP_REMOTE_ENTRY_PATH,
569
+ fileName: filename
570
+ }), addEntry({
571
+ entryName: 'hostInit',
572
+ entryPath: HOST_AUTO_INIT
573
+ }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], proxySharedModule({
574
+ shared: shared
575
+ }), [{
576
+ name: 'module-federation-vite',
577
+ enforce: 'post',
578
+ config: function config(_config, _ref) {
579
+ var _config$optimizeDeps;
580
+ _config.resolve.alias.push({
581
+ find: '@module-federation/runtime',
582
+ replacement: require.resolve('@module-federation/runtime')
583
+ });
584
+ (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
585
+ // Object.keys(shared).forEach((key) => {
586
+ // config.optimizeDeps?.include?.push(key);
587
+ // });
588
+ }
527
589
  }]);
528
590
  }
529
591