@module-federation/vite 1.10.0 → 1.11.1

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.
Files changed (45) hide show
  1. package/README.md +4 -1
  2. package/lib/index.cjs +1819 -1963
  3. package/lib/index.d.cts +131 -0
  4. package/lib/index.d.mts +131 -0
  5. package/lib/index.mjs +1946 -0
  6. package/package.json +29 -18
  7. package/lib/index.d.ts +0 -4
  8. package/lib/index.esm.js +0 -2091
  9. package/lib/index.modern.js +0 -2123
  10. package/lib/index.umd.js +0 -2112
  11. package/lib/plugins/__tests__/pluginCheckAliasConflicts.test.d.ts +0 -1
  12. package/lib/plugins/__tests__/pluginDts.test.d.ts +0 -1
  13. package/lib/plugins/pluginAddEntry.d.ts +0 -10
  14. package/lib/plugins/pluginCheckAliasConflicts.d.ts +0 -9
  15. package/lib/plugins/pluginDevProxyModuleTopLevelAwait.d.ts +0 -2
  16. package/lib/plugins/pluginDts.d.ts +0 -3
  17. package/lib/plugins/pluginMFManifest.d.ts +0 -3
  18. package/lib/plugins/pluginModuleParseEnd.d.ts +0 -10
  19. package/lib/plugins/pluginProxyRemoteEntry.d.ts +0 -2
  20. package/lib/plugins/pluginProxyRemotes.d.ts +0 -3
  21. package/lib/plugins/pluginProxySharedModule_preBuild.d.ts +0 -7
  22. package/lib/utils/PromiseStore.d.ts +0 -16
  23. package/lib/utils/VirtualModule.d.ts +0 -26
  24. package/lib/utils/__tests__/VirtualModule.test.d.ts +0 -1
  25. package/lib/utils/__tests__/cssModuleHelpers.test.d.ts +0 -1
  26. package/lib/utils/__tests__/helpers.d.ts +0 -2
  27. package/lib/utils/__tests__/normalizeModuleFederationOption.test.d.ts +0 -1
  28. package/lib/utils/__tests__/publicPath.test.d.ts +0 -1
  29. package/lib/utils/__tests__/serializeRuntimeOptions.test.d.ts +0 -1
  30. package/lib/utils/aliasToArrayPlugin.d.ts +0 -10
  31. package/lib/utils/cssModuleHelpers.d.ts +0 -75
  32. package/lib/utils/localSharedImportMap_temp.d.ts +0 -2
  33. package/lib/utils/mapCodeToCodeWithSourcemap.d.ts +0 -4
  34. package/lib/utils/normalizeModuleFederationOptions.d.ts +0 -159
  35. package/lib/utils/normalizeOptimizeDeps.d.ts +0 -9
  36. package/lib/utils/packageNameUtils.d.ts +0 -22
  37. package/lib/utils/publicPath.d.ts +0 -9
  38. package/lib/utils/serializeRuntimeOptions.d.ts +0 -10
  39. package/lib/utils/wrapManualChunks.d.ts +0 -1
  40. package/lib/virtualModules/index.d.ts +0 -6
  41. package/lib/virtualModules/virtualExposes.d.ts +0 -2
  42. package/lib/virtualModules/virtualRemoteEntry.d.ts +0 -16
  43. package/lib/virtualModules/virtualRemotes.d.ts +0 -6
  44. package/lib/virtualModules/virtualRuntimeInitStatus.d.ts +0 -3
  45. package/lib/virtualModules/virtualShared_preBuild.d.ts +0 -17
package/lib/index.esm.js DELETED
@@ -1,2091 +0,0 @@
1
- import defu from 'defu';
2
- import * as fs from 'fs';
3
- import { mkdirSync, writeFileSync, existsSync, writeFile } from 'fs';
4
- import * as path from 'pathe';
5
- import path__default, { resolve, basename, parse, join, dirname } from 'pathe';
6
- import MagicString from 'magic-string';
7
- import { createFilter } from '@rollup/pluginutils';
8
- import { walk } from 'estree-walker';
9
- import { normalizeOptions } from '@module-federation/sdk';
10
- import { normalizeGenerateTypesOptions, generateTypesAPI, normalizeDtsOptions, normalizeConsumeTypesOptions, consumeTypesAPI, isTSProject } from '@module-federation/dts-plugin';
11
- import { rpc } from '@module-federation/dts-plugin/core';
12
-
13
- var mapCodeToCodeWithSourcemap = function mapCodeToCodeWithSourcemap(code) {
14
- return Promise.resolve(code).then(function (resolvedCode) {
15
- if (resolvedCode === undefined) {
16
- return;
17
- }
18
- var s = new MagicString(resolvedCode);
19
- return {
20
- code: s.toString(),
21
- map: s.generateMap({
22
- hires: true
23
- })
24
- };
25
- });
26
- };
27
-
28
- function getFirstHtmlEntryFile(entryFiles) {
29
- return entryFiles.find(function (file) {
30
- return file.endsWith('.html');
31
- });
32
- }
33
- var addEntry = function addEntry(_ref) {
34
- var entryName = _ref.entryName,
35
- entryPath = _ref.entryPath,
36
- fileName = _ref.fileName,
37
- _ref$inject = _ref.inject,
38
- inject = _ref$inject === void 0 ? 'entry' : _ref$inject;
39
- var devEntryPath = entryPath.startsWith('virtual:mf') ? '@id/' + entryPath : entryPath;
40
- var entryFiles = [];
41
- var htmlFilePath;
42
- var _command;
43
- var emitFileId;
44
- var viteConfig;
45
- function injectHtml() {
46
- return inject === 'html' && htmlFilePath;
47
- }
48
- function injectEntry() {
49
- return inject === 'entry' || !htmlFilePath;
50
- }
51
- return [{
52
- name: 'add-entry',
53
- apply: 'serve',
54
- config: function config(_config, _ref2) {
55
- var command = _ref2.command;
56
- _command = command;
57
- },
58
- configResolved: function configResolved(config) {
59
- viteConfig = config;
60
- devEntryPath = config.base + devEntryPath.replace(/\\\\?/g, '/').replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/^\//, '');
61
- },
62
- configureServer: function configureServer(server) {
63
- server.middlewares.use(function (req, res, next) {
64
- if (!fileName) {
65
- next();
66
- return;
67
- }
68
- if (req.url && req.url.startsWith((viteConfig.base + fileName).replace(/^\/?/, '/'))) {
69
- req.url = devEntryPath;
70
- }
71
- next();
72
- });
73
- },
74
- transformIndexHtml: function transformIndexHtml(c) {
75
- if (!injectHtml()) return;
76
- return c.replace('<head>', "<head><script type=\"module\" src=" + JSON.stringify(devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/')) + "></script>");
77
- },
78
- transform: function transform(code, id) {
79
- if (id.includes('node_modules') || inject !== 'html' || htmlFilePath) {
80
- return;
81
- }
82
- if (id.includes('.svelte-kit') && id.includes('internal.js')) {
83
- var src = devEntryPath.replace(/.+?\:([/\\])[/\\]?/, '$1').replace(/\\\\?/g, '/');
84
- return code.replace(/<head>/g, '<head><script type=\\"module\\" src=\\"' + src + '\\"></script>');
85
- }
86
- }
87
- }, {
88
- name: 'add-entry',
89
- enforce: 'post',
90
- configResolved: function configResolved(config) {
91
- viteConfig = config;
92
- var inputOptions = config.build.rollupOptions.input;
93
- if (!inputOptions) {
94
- htmlFilePath = path.resolve(config.root, 'index.html');
95
- } else if (typeof inputOptions === 'string') {
96
- entryFiles = [inputOptions];
97
- } else if (Array.isArray(inputOptions)) {
98
- entryFiles = inputOptions;
99
- } else if (typeof inputOptions === 'object') {
100
- entryFiles = Object.values(inputOptions);
101
- }
102
- if (entryFiles && entryFiles.length > 0) {
103
- htmlFilePath = getFirstHtmlEntryFile(entryFiles);
104
- }
105
- },
106
- buildStart: function buildStart() {
107
- if (_command === 'serve') return;
108
- var hasHash = fileName == null || fileName.includes == null ? void 0 : fileName.includes('[hash');
109
- var emitFileOptions = {
110
- name: entryName,
111
- type: 'chunk',
112
- id: entryPath,
113
- preserveSignature: 'strict'
114
- };
115
- if (!hasHash) {
116
- emitFileOptions.fileName = fileName;
117
- }
118
- emitFileId = this.emitFile(emitFileOptions);
119
- if (htmlFilePath && fs.existsSync(htmlFilePath)) {
120
- var htmlContent = fs.readFileSync(htmlFilePath, 'utf-8');
121
- var scriptRegex = /<script\s+[^>]*src=["']([^"']+)["'][^>]*>/gi;
122
- var match;
123
- while ((match = scriptRegex.exec(htmlContent)) !== null) {
124
- entryFiles.push(match[1]);
125
- }
126
- }
127
- },
128
- generateBundle: function generateBundle(options, bundle) {
129
- var _viteConfig$experimen, _viteConfig$experimen2;
130
- if (!injectHtml()) return;
131
- var file = this.getFileName(emitFileId);
132
- var path = (_viteConfig$experimen = viteConfig.experimental) != null && _viteConfig$experimen.renderBuiltUrl ? (_viteConfig$experimen2 = viteConfig.experimental) == null ? void 0 : _viteConfig$experimen2.renderBuiltUrl(file) : viteConfig.base + file;
133
- var scriptContent = "\n <script type=\"module\" src=\"" + path + "\"></script>\n ";
134
- for (var _fileName in bundle) {
135
- if (_fileName.endsWith('.html')) {
136
- var htmlAsset = bundle[_fileName];
137
- if (htmlAsset.type === 'chunk') return;
138
- var htmlContent = htmlAsset.source.toString() || '';
139
- htmlContent = htmlContent.replace('<head>', "<head>" + scriptContent);
140
- htmlAsset.source = htmlContent;
141
- }
142
- }
143
- },
144
- transform: function transform(code, id) {
145
- if (injectEntry() && entryFiles.some(function (file) {
146
- return id.endsWith(file);
147
- })) {
148
- var injection = "\n import " + JSON.stringify(entryPath) + ";\n ";
149
- return mapCodeToCodeWithSourcemap(injection + code);
150
- }
151
- }
152
- }];
153
- };
154
-
155
- function _arrayLikeToArray(r, a) {
156
- (null == a || a > r.length) && (a = r.length);
157
- for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e];
158
- return n;
159
- }
160
- function _createForOfIteratorHelperLoose(r, e) {
161
- var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"];
162
- if (t) return (t = t.call(r)).next.bind(t);
163
- if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e && r && "number" == typeof r.length) {
164
- t && (r = t);
165
- var o = 0;
166
- return function () {
167
- return o >= r.length ? {
168
- done: !0
169
- } : {
170
- done: !1,
171
- value: r[o++]
172
- };
173
- };
174
- }
175
- throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");
176
- }
177
- function _extends() {
178
- return _extends = Object.assign ? Object.assign.bind() : function (n) {
179
- for (var e = 1; e < arguments.length; e++) {
180
- var t = arguments[e];
181
- for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]);
182
- }
183
- return n;
184
- }, _extends.apply(null, arguments);
185
- }
186
- function _unsupportedIterableToArray(r, a) {
187
- if (r) {
188
- if ("string" == typeof r) return _arrayLikeToArray(r, a);
189
- var t = {}.toString.call(r).slice(8, -1);
190
- 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;
191
- }
192
- }
193
-
194
- /**
195
- * Check if user-defined alias conflicts with shared modules
196
- * This should run after aliasToArrayPlugin to ensure alias is an array
197
- */
198
- function checkAliasConflicts(options) {
199
- var _options$shared = options.shared,
200
- shared = _options$shared === void 0 ? {} : _options$shared;
201
- var sharedKeys = Object.keys(shared);
202
- return {
203
- name: 'check-alias-conflicts',
204
- configResolved: function configResolved(config) {
205
- var _config$resolve;
206
- if (sharedKeys.length === 0) return;
207
- var userAliases = ((_config$resolve = config.resolve) == null ? void 0 : _config$resolve.alias) || [];
208
- var conflicts = [];
209
- for (var _i = 0, _sharedKeys = sharedKeys; _i < _sharedKeys.length; _i++) {
210
- var sharedKey = _sharedKeys[_i];
211
- for (var _iterator = _createForOfIteratorHelperLoose(userAliases), _step; !(_step = _iterator()).done;) {
212
- var aliasEntry = _step.value;
213
- var findPattern = aliasEntry.find;
214
- var replacement = aliasEntry.replacement;
215
- // Skip if replacement is not a string (e.g., customResolver)
216
- if (typeof replacement !== 'string') continue;
217
- // Skip Module Federation internal aliases (used for proxying shared modules)
218
- // These are generated with replacement '$1' and should not trigger warnings
219
- if (replacement === '$1') continue;
220
- // Check if alias pattern matches the shared module
221
- var isMatch = false;
222
- if (typeof findPattern === 'string') {
223
- isMatch = findPattern === sharedKey || sharedKey.startsWith(findPattern + '/');
224
- } else if (findPattern instanceof RegExp) {
225
- isMatch = findPattern.test(sharedKey);
226
- }
227
- if (isMatch) {
228
- conflicts.push({
229
- sharedModule: sharedKey,
230
- alias: String(findPattern),
231
- target: replacement
232
- });
233
- }
234
- }
235
- }
236
- if (conflicts.length > 0) {
237
- config.logger.warn('\n[Module Federation] Detected alias conflicts with shared modules:');
238
- conflicts.forEach(function (_ref) {
239
- var sharedModule = _ref.sharedModule,
240
- alias = _ref.alias,
241
- target = _ref.target;
242
- config.logger.warn(" - Shared module \"" + sharedModule + "\" is aliased by \"" + alias + "\" to \"" + target + "\"");
243
- });
244
- config.logger.warn(" This may cause runtime errors as the shared module will bypass Module Federation's sharing mechanism.");
245
- }
246
- }
247
- };
248
- }
249
-
250
- /**
251
- * Solve the problem that dev mode dependency prebunding does not support top-level await syntax
252
- */
253
- function PluginDevProxyModuleTopLevelAwait() {
254
- var filterFunction = createFilter();
255
- var processedFlag = '/* already-processed-by-dev-proxy-module-top-level-await */';
256
- return {
257
- name: 'dev-proxy-module-top-level-await',
258
- apply: 'serve',
259
- transform: function transform(code, id) {
260
- if (code.includes(processedFlag)) {
261
- return null;
262
- }
263
- if (!code.includes('/*mf top-level-await placeholder replacement mf*/')) {
264
- return null;
265
- }
266
- if (!filterFunction(id)) return null;
267
- var ast;
268
- try {
269
- ast = this.parse(code, {
270
- allowReturnOutsideFunction: true
271
- });
272
- } catch (e) {
273
- throw new Error(id + ": " + e);
274
- }
275
- var magicString = new MagicString(code);
276
- walk(ast, {
277
- enter: function enter(node) {
278
- if (node.type === 'ExportNamedDeclaration' && node.specifiers) {
279
- var exportSpecifiers = node.specifiers.map(function (specifier) {
280
- return specifier.exported.name;
281
- });
282
- var proxyStatements = exportSpecifiers.map(function (name) {
283
- return "\n const __mfproxy__await" + name + " = await " + name + "();\n const __mfproxy__" + name + " = () => __mfproxy__await" + name + ";\n ";
284
- }).join('\n');
285
- var exportStatements = exportSpecifiers.map(function (name) {
286
- return "__mfproxy__" + name + " as " + name;
287
- }).join(', ');
288
- var start = node.start;
289
- var end = node.end;
290
- var replacement = proxyStatements + "\nexport { " + exportStatements + " };";
291
- magicString.overwrite(start, end, replacement);
292
- }
293
- if (node.type === 'ExportDefaultDeclaration') {
294
- var declaration = node.declaration;
295
- var _start = node.start;
296
- var _end = node.end;
297
- var proxyStatement;
298
- var exportStatement = 'default';
299
- if (declaration.type === 'Identifier') {
300
- // example: export default foo;
301
- proxyStatement = "\n const __mfproxy__awaitdefault = await " + declaration.name + "();\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
302
- } else if (declaration.type === 'CallExpression' || declaration.type === 'FunctionDeclaration') {
303
- // example: export default someFunction();
304
- var declarationCode = code.slice(declaration.start, declaration.end);
305
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + declarationCode + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
306
- } else {
307
- // other
308
- proxyStatement = "\n const __mfproxy__awaitdefault = await (" + code.slice(declaration.start, declaration.end) + ");\n const __mfproxy__default = __mfproxy__awaitdefault;\n ";
309
- }
310
- var _replacement = proxyStatement + "\nexport { __mfproxy__default as " + exportStatement + " };";
311
- magicString.overwrite(_start, _end, _replacement);
312
- }
313
- }
314
- });
315
- var transformedCode = magicString.toString();
316
- return {
317
- code: processedFlag + "\n" + transformedCode,
318
- map: magicString.generateMap({
319
- hires: true
320
- })
321
- };
322
- }
323
- };
324
- }
325
-
326
- function _catch(body, recover) {
327
- try {
328
- var result = body();
329
- } catch (e) {
330
- return recover(e);
331
- }
332
- if (result && result.then) {
333
- return result.then(void 0, recover);
334
- }
335
- return result;
336
- }
337
- var DEFAULT_DEV_OPTIONS = {
338
- disableLiveReload: true,
339
- disableHotTypesReload: false,
340
- disableDynamicRemoteTypeHints: false
341
- };
342
- var DYNAMIC_HINTS_PLUGIN = '@module-federation/dts-plugin/dynamic-remote-type-hints-plugin';
343
- var getIPv4 = function getIPv4() {
344
- return process.env['FEDERATION_IPV4'] || '127.0.0.1';
345
- };
346
- var forkDevWorkerPath = function () {
347
- // eslint-disable-next-line @typescript-eslint/no-var-requires
348
- return require.resolve('@module-federation/dts-plugin/dist/fork-dev-worker.js');
349
- }();
350
- var DevWorker = /*#__PURE__*/function () {
351
- function DevWorker(options) {
352
- this.worker = rpc.createRpcWorker(forkDevWorkerPath, {}, undefined, false);
353
- this.worker.connect(options);
354
- }
355
- var _proto = DevWorker.prototype;
356
- _proto.update = function update() {
357
- var _this$worker$process;
358
- (_this$worker$process = this.worker.process) == null || _this$worker$process.send == null || _this$worker$process.send({
359
- type: rpc.RpcGMCallTypes.CALL,
360
- id: this.worker.id,
361
- args: [undefined, 'update']
362
- });
363
- };
364
- _proto.exit = function exit() {
365
- this.worker.terminate();
366
- };
367
- return DevWorker;
368
- }();
369
- var normalizeDevOptions = function normalizeDevOptions(dev) {
370
- if (dev === false) {
371
- return false;
372
- }
373
- if (dev === true || typeof dev === 'undefined') {
374
- return _extends({}, DEFAULT_DEV_OPTIONS);
375
- }
376
- return _extends({}, DEFAULT_DEV_OPTIONS, dev);
377
- };
378
- var buildDtsModuleFederationConfig = function buildDtsModuleFederationConfig(options) {
379
- var exposes = {};
380
- Object.entries(options.exposes).forEach(function (_ref) {
381
- var key = _ref[0],
382
- value = _ref[1];
383
- if (typeof value === 'string') {
384
- exposes[key] = value;
385
- return;
386
- }
387
- var importValue = Array.isArray(value["import"]) ? value["import"][0] : value["import"];
388
- if (importValue) {
389
- exposes[key] = importValue;
390
- }
391
- });
392
- var remotes = {};
393
- Object.entries(options.remotes).forEach(function (_ref2) {
394
- var _remote$entryGlobalNa, _remote$entryGlobalNa2;
395
- var key = _ref2[0],
396
- remote = _ref2[1];
397
- if (typeof remote === 'string') {
398
- remotes[key] = remote;
399
- return;
400
- }
401
- if (!remote.entry) {
402
- return;
403
- }
404
- var entryLooksLikeUrl = ((_remote$entryGlobalNa = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa.startsWith('http')) || ((_remote$entryGlobalNa2 = remote.entryGlobalName) == null ? void 0 : _remote$entryGlobalNa2.includes('.json'));
405
- var entryGlobalName = entryLooksLikeUrl ? remote.name || key : remote.entryGlobalName || remote.name || key;
406
- remotes[key] = entryGlobalName + "@" + remote.entry;
407
- });
408
- return _extends({}, options, {
409
- exposes: exposes,
410
- remotes: remotes
411
- });
412
- };
413
- var resolveOutputDir = function resolveOutputDir(config) {
414
- var outDir = config.build.outDir;
415
- if (path.isAbsolute(outDir)) {
416
- return path.relative(config.root, outDir);
417
- }
418
- return outDir;
419
- };
420
- var ensureRuntimePlugin = function ensureRuntimePlugin(options, pluginId) {
421
- var hasPlugin = options.runtimePlugins.some(function (plugin) {
422
- if (typeof plugin === 'string') {
423
- return plugin === pluginId;
424
- }
425
- return plugin[0] === pluginId;
426
- });
427
- if (!hasPlugin) {
428
- options.runtimePlugins.push(pluginId);
429
- }
430
- };
431
- var normalizeDevDtsOptions = function normalizeDevDtsOptions(dts, context) {
432
- var defaultGenerateTypes = {
433
- compileInChildProcess: true
434
- };
435
- var defaultConsumeTypes = {
436
- consumeAPITypes: true
437
- };
438
- return normalizeOptions(isTSProject(dts, context), {
439
- generateTypes: defaultGenerateTypes,
440
- consumeTypes: defaultConsumeTypes,
441
- extraOptions: {},
442
- displayErrorInTerminal: typeof dts === 'object' && dts ? dts.displayErrorInTerminal : undefined
443
- }, 'mfOptions.dts')(dts);
444
- };
445
- var logDtsError = function logDtsError(error, dtsOptions) {
446
- if (dtsOptions === false) {
447
- return;
448
- }
449
- if (typeof dtsOptions === 'object' && dtsOptions && dtsOptions.displayErrorInTerminal === false) {
450
- return;
451
- }
452
- console.error(error);
453
- };
454
- function pluginDts(options) {
455
- if (options.dts === false) {
456
- return [];
457
- }
458
- var dtsModuleFederationConfig = buildDtsModuleFederationConfig(options);
459
- var resolvedConfig;
460
- var devWorker;
461
- var normalizedDevOptions;
462
- var hasGeneratedBundle = false;
463
- var devPlugin = {
464
- name: 'module-federation-dts-dev',
465
- apply: 'serve',
466
- config: function config(_config) {
467
- normalizedDevOptions = normalizeDevOptions(options.dev);
468
- if (!normalizedDevOptions) {
469
- return;
470
- }
471
- if (normalizedDevOptions.disableDynamicRemoteTypeHints) {
472
- return;
473
- }
474
- ensureRuntimePlugin(options, DYNAMIC_HINTS_PLUGIN);
475
- var define = _config.define ? _extends({}, _config.define) : {};
476
- if (!('FEDERATION_IPV4' in define)) {
477
- define.FEDERATION_IPV4 = JSON.stringify(getIPv4());
478
- }
479
- _config.define = define;
480
- },
481
- configResolved: function configResolved(config) {
482
- resolvedConfig = config;
483
- },
484
- configureServer: function configureServer(server) {
485
- if (!normalizedDevOptions || !resolvedConfig) {
486
- return;
487
- }
488
- var devOptions = normalizedDevOptions;
489
- if (devOptions.disableDynamicRemoteTypeHints && devOptions.disableHotTypesReload && devOptions.disableLiveReload) {
490
- return;
491
- }
492
- if (!options.name) {
493
- throw new Error('name is required if you want to enable dev server!');
494
- }
495
- var outputDir = resolveOutputDir(resolvedConfig);
496
- var normalizedDtsOptions = normalizeDevDtsOptions(options.dts, resolvedConfig.root);
497
- if (typeof normalizedDtsOptions !== 'object') {
498
- return;
499
- }
500
- var normalizedGenerateTypes = normalizeOptions(Boolean(normalizedDtsOptions), {
501
- compileInChildProcess: true
502
- }, 'mfOptions.dts.generateTypes')(normalizedDtsOptions.generateTypes);
503
- var remote = normalizedGenerateTypes === false ? undefined : _extends({
504
- implementation: normalizedDtsOptions.implementation,
505
- context: resolvedConfig.root,
506
- outputDir: outputDir,
507
- moduleFederationConfig: _extends({}, dtsModuleFederationConfig),
508
- hostRemoteTypesFolder: normalizedGenerateTypes.typesFolder || '@mf-types'
509
- }, normalizedGenerateTypes, {
510
- typesFolder: '.dev-server'
511
- });
512
- if (remote && !remote.tsConfigPath && typeof normalizedDtsOptions === 'object' && normalizedDtsOptions.tsConfigPath) {
513
- remote.tsConfigPath = normalizedDtsOptions.tsConfigPath;
514
- }
515
- var normalizedConsumeTypes = normalizeOptions(Boolean(normalizedDtsOptions), {
516
- consumeAPITypes: true
517
- }, 'mfOptions.dts.consumeTypes')(normalizedDtsOptions.consumeTypes);
518
- var host = normalizedConsumeTypes === false ? undefined : _extends({
519
- implementation: normalizedDtsOptions.implementation,
520
- context: resolvedConfig.root,
521
- moduleFederationConfig: dtsModuleFederationConfig,
522
- typesFolder: normalizedConsumeTypes.typesFolder || '@mf-types',
523
- abortOnError: false
524
- }, normalizedConsumeTypes);
525
- var extraOptions = normalizedDtsOptions.extraOptions || {};
526
- if (!remote && !host && devOptions.disableLiveReload) {
527
- return;
528
- }
529
- var startDevWorker = function startDevWorker() {
530
- try {
531
- var _temp2 = function _temp2() {
532
- var _server$httpServer;
533
- devWorker = new DevWorker({
534
- name: options.name,
535
- remote: remote,
536
- host: host ? _extends({}, host, {
537
- remoteTypeUrls: remoteTypeUrls
538
- }) : undefined,
539
- extraOptions: extraOptions,
540
- disableLiveReload: devOptions.disableLiveReload,
541
- disableHotTypesReload: devOptions.disableHotTypesReload
542
- });
543
- var update = function update() {
544
- var _devWorker;
545
- return (_devWorker = devWorker) == null ? void 0 : _devWorker.update();
546
- };
547
- server.watcher.on('change', update);
548
- server.watcher.on('add', update);
549
- server.watcher.on('unlink', update);
550
- (_server$httpServer = server.httpServer) == null || _server$httpServer.once('close', function () {
551
- var _devWorker2;
552
- (_devWorker2 = devWorker) == null || _devWorker2.exit();
553
- server.watcher.off('change', update);
554
- server.watcher.off('add', update);
555
- server.watcher.off('unlink', update);
556
- });
557
- };
558
- var remoteTypeUrls;
559
- var _temp = function () {
560
- if (host) {
561
- return Promise.resolve(new Promise(function (resolve) {
562
- consumeTypesAPI({
563
- host: host,
564
- extraOptions: extraOptions,
565
- displayErrorInTerminal: normalizedDtsOptions.displayErrorInTerminal
566
- }, resolve);
567
- })).then(function (_Promise) {
568
- remoteTypeUrls = _Promise;
569
- });
570
- }
571
- }();
572
- return Promise.resolve(_temp && _temp.then ? _temp.then(_temp2) : _temp2(_temp));
573
- } catch (e) {
574
- return Promise.reject(e);
575
- }
576
- };
577
- startDevWorker()["catch"](function (error) {
578
- logDtsError(error, normalizedDtsOptions);
579
- });
580
- }
581
- };
582
- var buildPlugin = {
583
- name: 'module-federation-dts-build',
584
- apply: 'build',
585
- configResolved: function configResolved(config) {
586
- resolvedConfig = config;
587
- },
588
- generateBundle: function generateBundle() {
589
- try {
590
- var _temp6 = function _temp6() {
591
- var generateOptions;
592
- try {
593
- generateOptions = normalizeGenerateTypesOptions({
594
- context: context,
595
- outputDir: outputDir,
596
- dtsOptions: normalizedDtsOptions,
597
- pluginOptions: dtsModuleFederationConfig
598
- });
599
- } catch (error) {
600
- logDtsError(error, normalizedDtsOptions);
601
- return;
602
- }
603
- if (!generateOptions) {
604
- return;
605
- }
606
- var _temp4 = _catch(function () {
607
- return Promise.resolve(generateTypesAPI({
608
- dtsManagerOptions: generateOptions
609
- })).then(function () {});
610
- }, function (error) {
611
- logDtsError(error, normalizedDtsOptions);
612
- });
613
- if (_temp4 && _temp4.then) return _temp4.then(function () {});
614
- };
615
- if (hasGeneratedBundle) {
616
- return Promise.resolve();
617
- }
618
- hasGeneratedBundle = true;
619
- if (!resolvedConfig) {
620
- return Promise.resolve();
621
- }
622
- var normalizedDtsOptions;
623
- try {
624
- normalizedDtsOptions = normalizeDtsOptions(dtsModuleFederationConfig, resolvedConfig.root);
625
- } catch (error) {
626
- logDtsError(error, options.dts);
627
- return Promise.resolve();
628
- }
629
- if (typeof normalizedDtsOptions !== 'object') {
630
- return Promise.resolve();
631
- }
632
- var context = resolvedConfig.root;
633
- var outputDir = resolveOutputDir(resolvedConfig);
634
- var consumeOptions;
635
- try {
636
- consumeOptions = normalizeConsumeTypesOptions({
637
- context: context,
638
- dtsOptions: normalizedDtsOptions,
639
- pluginOptions: dtsModuleFederationConfig
640
- });
641
- } catch (error) {
642
- logDtsError(error, normalizedDtsOptions);
643
- return Promise.resolve();
644
- }
645
- var _temp5 = function (_consumeOptions) {
646
- if ((_consumeOptions = consumeOptions) != null && (_consumeOptions = _consumeOptions.host) != null && _consumeOptions.typesOnBuild) {
647
- var _temp3 = _catch(function () {
648
- return Promise.resolve(consumeTypesAPI(consumeOptions)).then(function () {});
649
- }, function (error) {
650
- logDtsError(error, normalizedDtsOptions);
651
- });
652
- if (_temp3 && _temp3.then) return _temp3.then(function () {});
653
- }
654
- }();
655
- return Promise.resolve(_temp5 && _temp5.then ? _temp5.then(_temp6) : _temp6(_temp5));
656
- } catch (e) {
657
- return Promise.reject(e);
658
- }
659
- }
660
- };
661
- return [devPlugin, buildPlugin];
662
- }
663
-
664
- function normalizeExposesItem(key, item) {
665
- var importPath = '';
666
- if (typeof item === 'string') {
667
- importPath = item;
668
- }
669
- if (typeof item === 'object') {
670
- importPath = item["import"];
671
- }
672
- return {
673
- "import": importPath
674
- };
675
- }
676
- function normalizeExposes(exposes) {
677
- if (!exposes) return {};
678
- var res = {};
679
- Object.keys(exposes).forEach(function (key) {
680
- res[key] = normalizeExposesItem(key, exposes[key]);
681
- });
682
- return res;
683
- }
684
- function normalizeRemotes(remotes) {
685
- if (!remotes) return {};
686
- var result = {};
687
- if (typeof remotes === 'object') {
688
- Object.keys(remotes).forEach(function (key) {
689
- result[key] = normalizeRemoteItem(key, remotes[key]);
690
- });
691
- }
692
- return result;
693
- }
694
- function normalizeRemoteItem(key, remote) {
695
- if (typeof remote === 'string') {
696
- var _remote$split = remote.split('@'),
697
- entryGlobalName = _remote$split[0];
698
- var entry = remote.replace(entryGlobalName + '@', '');
699
- return {
700
- type: 'var',
701
- name: key,
702
- entry: entry,
703
- entryGlobalName: entryGlobalName,
704
- shareScope: 'default'
705
- };
706
- }
707
- return Object.assign({
708
- type: 'var',
709
- name: key,
710
- shareScope: 'default',
711
- entryGlobalName: key
712
- }, remote);
713
- }
714
- function removePathFromNpmPackage(packageString) {
715
- // 匹配npm包名的正则表达式,忽略路径部分
716
- var regex = /^(?:@[^/]+\/)?[^/]+/;
717
- // 使用正则表达式匹配并提取包名
718
- var match = packageString.match(regex);
719
- // 返回匹配到的包名,如果没有匹配到则返回原字符串
720
- return match ? match[0] : packageString;
721
- }
722
- /**
723
- * Tries to find the package.json's version of a shared package
724
- * if `package.json` is not declared in `exports`
725
- * @param {string} sharedName
726
- * @returns {string | undefined}
727
- */
728
- function searchPackageVersion(sharedName) {
729
- try {
730
- var sharedPath = require.resolve(sharedName);
731
- var potentialPackageJsonDir = path.dirname(sharedPath);
732
- var rootDir = path.parse(potentialPackageJsonDir).root;
733
- while (path.parse(potentialPackageJsonDir).base !== 'node_modules' && potentialPackageJsonDir !== rootDir) {
734
- var potentialPackageJsonPath = path.join(potentialPackageJsonDir, 'package.json');
735
- if (fs.existsSync(potentialPackageJsonPath)) {
736
- var potentialPackageJson = require(potentialPackageJsonPath);
737
- if (typeof potentialPackageJson == 'object' && potentialPackageJson !== null && typeof potentialPackageJson.version === 'string' && potentialPackageJson.name === sharedName) {
738
- return potentialPackageJson.version;
739
- }
740
- }
741
- potentialPackageJsonDir = path.dirname(potentialPackageJsonDir);
742
- }
743
- } catch (_) {}
744
- return undefined;
745
- }
746
- function normalizeShareItem(key, shareItem) {
747
- var version;
748
- try {
749
- try {
750
- version = require(path.join(removePathFromNpmPackage(key), 'package.json')).version;
751
- } catch (e1) {
752
- try {
753
- var localPath = path.join(process.cwd(), 'node_modules', removePathFromNpmPackage(key), 'package.json');
754
- version = require(localPath).version;
755
- } catch (e2) {
756
- version = searchPackageVersion(key);
757
- if (!version) console.error(e1);
758
- }
759
- }
760
- } catch (e) {
761
- console.error("Unexpected error resolving version for " + key + ":", e);
762
- }
763
- if (typeof shareItem === 'string') {
764
- return {
765
- name: shareItem,
766
- version: version,
767
- scope: 'default',
768
- from: '',
769
- shareConfig: {
770
- "import": undefined,
771
- singleton: false,
772
- requiredVersion: version ? "^" + version : '*'
773
- }
774
- };
775
- }
776
- return {
777
- name: key,
778
- from: '',
779
- version: shareItem.version || version,
780
- scope: shareItem.shareScope || 'default',
781
- shareConfig: {
782
- "import": typeof shareItem === 'object' ? shareItem["import"] : undefined,
783
- singleton: shareItem.singleton || false,
784
- requiredVersion: shareItem.requiredVersion || (version ? "^" + version : '*'),
785
- strictVersion: !!shareItem.strictVersion
786
- }
787
- };
788
- }
789
- function normalizeShared(shared) {
790
- if (!shared) return {};
791
- var result = {};
792
- if (Array.isArray(shared)) {
793
- shared.forEach(function (key) {
794
- result[key] = normalizeShareItem(key, key);
795
- });
796
- return result;
797
- }
798
- if (typeof shared === 'object') {
799
- Object.keys(shared).forEach(function (key) {
800
- result[key] = normalizeShareItem(key, shared[key]);
801
- });
802
- }
803
- return result;
804
- }
805
- function normalizeLibrary(library) {
806
- if (!library) return undefined;
807
- return library;
808
- }
809
- function normalizeManifest(manifest) {
810
- if (manifest === void 0) {
811
- manifest = false;
812
- }
813
- if (typeof manifest === 'boolean') {
814
- return manifest;
815
- }
816
- return Object.assign({
817
- filePath: '',
818
- disableAssetsAnalyze: false,
819
- fileName: 'mf-manifest.json'
820
- }, manifest);
821
- }
822
- var config;
823
- function getNormalizeModuleFederationOptions() {
824
- return config;
825
- }
826
- function getNormalizeShareItem(key) {
827
- var options = getNormalizeModuleFederationOptions();
828
- var shareItem = options.shared[key] || options.shared[removePathFromNpmPackage(key)] || options.shared[removePathFromNpmPackage(key) + '/'];
829
- return shareItem;
830
- }
831
- function normalizeModuleFederationOptions(options) {
832
- if (options.virtualModuleDir && options.virtualModuleDir.includes('/')) {
833
- throw new Error("Invalid virtualModuleDir: \"" + options.virtualModuleDir + "\". " + "The virtualModuleDir option cannot contain slashes (/). " + "Please use a single directory name like '__mf__virtual__your_app_name'.");
834
- }
835
- return config = {
836
- exposes: normalizeExposes(options.exposes),
837
- filename: options.filename || 'remoteEntry-[hash]',
838
- library: normalizeLibrary(options.library),
839
- name: options.name,
840
- // remoteType: options.remoteType,
841
- remotes: normalizeRemotes(options.remotes),
842
- runtime: options.runtime,
843
- shareScope: options.shareScope || 'default',
844
- shared: normalizeShared(options.shared),
845
- runtimePlugins: options.runtimePlugins || [],
846
- implementation: options.implementation || require.resolve('@module-federation/runtime'),
847
- manifest: normalizeManifest(options.manifest),
848
- dev: options.dev,
849
- dts: options.dts,
850
- getPublicPath: options.getPublicPath,
851
- publicPath: options.publicPath,
852
- shareStrategy: options.shareStrategy || 'version-first',
853
- ignoreOrigin: options.ignoreOrigin || false,
854
- virtualModuleDir: options.virtualModuleDir || '__mf__virtual',
855
- hostInitInjectLocation: options.hostInitInjectLocation || 'html',
856
- bundleAllCSS: options.bundleAllCSS || false,
857
- moduleParseTimeout: options.moduleParseTimeout || 10
858
- };
859
- }
860
-
861
- /**
862
- * Escaping rules:
863
- * Convert using the format __${mapping}__, where _ and $ are not allowed in npm package names but can be used in variable names.
864
- * @ => 1
865
- * / => 2
866
- * - => 3
867
- * . => 4
868
- */
869
- /**
870
- * Encodes a package name into a valid file name.
871
- * @param {string} name - The package name, e.g., "@scope/xx-xx.xx".
872
- * @returns {string} - The encoded file name.
873
- */
874
- function packageNameEncode(name) {
875
- if (typeof name !== 'string') throw new Error('A string package name is required');
876
- return name.replace(/@/g, '_mf_0_').replace(/\//g, '_mf_1_').replace(/-/g, '_mf_2_').replace(/\./g, '_mf_3_');
877
- }
878
- /**
879
- * Decodes an encoded file name back to the original package name.
880
- * @param {string} encoded - The encoded file name, e.g., "_mf_0_scope_mf_1_xx_mf_2_xx_mf_3_xx".
881
- * @returns {string} - The decoded package name.
882
- */
883
- function packageNameDecode(encoded) {
884
- if (typeof encoded !== 'string') throw new Error('A string encoded file name is required');
885
- return encoded.replace(/_mf_0_/g, '@').replace(/_mf_1_/g, '/').replace(/_mf_2_/g, '-').replace(/_mf_3_/g, '.');
886
- }
887
-
888
- /**
889
- * https://github.com/module-federation/vite/issues/68
890
- */
891
- function getLocalSharedImportMapPath_temp() {
892
- var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
893
- name = _getNormalizeModuleFe.name;
894
- return path__default.resolve('.__mf__temp', packageNameEncode(name), 'localSharedImportMap');
895
- }
896
- function writeLocalSharedImportMap_temp(content) {
897
- var localSharedImportMapId = getLocalSharedImportMapPath_temp();
898
- createFile(localSharedImportMapId + '.js', '\n// Windows temporarily needs this file, https://github.com/module-federation/vite/issues/68\n' + content);
899
- }
900
- function createFile(filePath, content) {
901
- var dir = path__default.dirname(filePath);
902
- mkdirSync(dir, {
903
- recursive: true
904
- });
905
- writeFileSync(filePath, content);
906
- }
907
-
908
- /**
909
- * Serializes a JavaScript object into a string of source code that can be evaluated.
910
- * This function is used to create runtime plugin options without relying solely on JSON.stringify,
911
- * allowing support for non-JSON types like RegExp, Date, Map, Set, and Functions.
912
- * It also safely handles circular references.
913
- *
914
- * @param {Record<string, unknown>} options - The options object to serialize.
915
- * @returns {string} The resulting JavaScript source code string.
916
- */
917
- function serializeRuntimeOptions(options) {
918
- // Use a WeakSet to track objects already encountered, which helps in detecting circular references.
919
- var seenObjects = new WeakSet();
920
- /**
921
- * Recursive inner function to serialize any value into a source code string.
922
- */
923
- function valueToCode(val) {
924
- // 1. Handle primitive values
925
- if (val === null) return 'null';
926
- var type = typeof val;
927
- if (type === 'string') return JSON.stringify(val);
928
- if (type === 'number' || type === 'boolean') return String(val);
929
- if (type === 'undefined') return 'undefined';
930
- // Handle Symbol
931
- if (type === 'symbol') {
932
- var _val$description;
933
- var desc = (_val$description = val.description) != null ? _val$description : '';
934
- return "Symbol(" + JSON.stringify(desc) + ")";
935
- }
936
- // Handle Function (returns the function's source code)
937
- if (type === 'function') return val.toString();
938
- // 2. Handle special built-in objects
939
- if (val instanceof Date) return "new Date(" + JSON.stringify(val.toISOString()) + ")";
940
- if (val instanceof RegExp) {
941
- return "new RegExp(" + JSON.stringify(val.source) + ", " + JSON.stringify(val.flags) + ")";
942
- }
943
- // 3. Check for circular references and mark object as seen
944
- // This applies to objects, arrays, maps, and sets.
945
- if (type === 'object') {
946
- if (seenObjects.has(val)) {
947
- // This object has been seen previously in the recursion path
948
- return "\"__circular__\"";
949
- }
950
- seenObjects.add(val);
951
- }
952
- // 4. Handle Array, Map, Set
953
- if (Array.isArray(val)) {
954
- // Recursively serialize each element
955
- return "[" + val.map(valueToCode).join(', ') + "]";
956
- }
957
- if (val instanceof Map) {
958
- // Serialize Map entries into an array of [key, value] pairs
959
- var entries = Array.from(val.entries()).map(function (_ref) {
960
- var k = _ref[0],
961
- v = _ref[1];
962
- return "[" + valueToCode(k) + ", " + valueToCode(v) + "]";
963
- });
964
- return "new Map([" + entries.join(', ') + "])";
965
- }
966
- if (val instanceof Set) {
967
- // Serialize Set values into an array
968
- var items = Array.from(val.values()).map(valueToCode);
969
- return "new Set([" + items.join(', ') + "])";
970
- }
971
- // 5. Handle plain objects (the default object type)
972
- if (type === 'object') {
973
- var properties = [];
974
- // Iterate over the object's own enumerable properties
975
- for (var key in val) {
976
- if (Object.prototype.hasOwnProperty.call(val, key)) {
977
- // Wrap the key in JSON.stringify to handle non-identifier keys
978
- properties.push(JSON.stringify(key) + ": " + valueToCode(val[key]));
979
- }
980
- }
981
- return "{" + properties.join(', ') + "}";
982
- }
983
- // 6. Fallback case (e.g., BigInt, other object types)
984
- // Coerce to string and then JSON.stringify that string for safety
985
- return JSON.stringify(String(val));
986
- }
987
- // Start serialization for the top-level object
988
- var topLevelProps = [];
989
- // Iterate over the properties of the root 'options' object
990
- for (var key in options) {
991
- if (Object.prototype.hasOwnProperty.call(options, key)) {
992
- topLevelProps.push(JSON.stringify(key) + ": " + valueToCode(options[key]));
993
- }
994
- }
995
- return "{" + topLevelProps.join(', ') + "}";
996
- }
997
-
998
- // Cache root path
999
- var rootDir;
1000
- function findNodeModulesDir(root) {
1001
- if (root === void 0) {
1002
- root = process.cwd();
1003
- }
1004
- var currentDir = root;
1005
- while (currentDir !== parse(currentDir).root) {
1006
- var nodeModulesPath = join(currentDir, 'node_modules');
1007
- if (existsSync(nodeModulesPath)) {
1008
- return nodeModulesPath;
1009
- }
1010
- currentDir = dirname(currentDir);
1011
- }
1012
- return '';
1013
- }
1014
- // Cache nodeModulesDir result to avoid repeated calculations
1015
- var cachedNodeModulesDir;
1016
- function getNodeModulesDir() {
1017
- if (!cachedNodeModulesDir) {
1018
- cachedNodeModulesDir = findNodeModulesDir(rootDir);
1019
- }
1020
- return cachedNodeModulesDir;
1021
- }
1022
- function getSuffix(name) {
1023
- var base = basename(name);
1024
- var dotIndex = base.lastIndexOf('.');
1025
- if (dotIndex > 0 && dotIndex < base.length - 1) {
1026
- return base.slice(dotIndex);
1027
- }
1028
- return '.js';
1029
- }
1030
- var patternMap = {};
1031
- var cacheMap = {};
1032
- /**
1033
- * Physically generate files as virtual modules under node_modules/__mf__virtual/*
1034
- */
1035
- function assertModuleFound(tag, str) {
1036
- if (str === void 0) {
1037
- str = '';
1038
- }
1039
- var module = VirtualModule.findModule(tag, str);
1040
- if (!module) {
1041
- throw new Error("Module Federation shared module '" + str + "' not found. Please ensure it's installed as a dependency in your package.json.");
1042
- }
1043
- return module;
1044
- }
1045
- var VirtualModule = /*#__PURE__*/function () {
1046
- function VirtualModule(name, tag, suffix) {
1047
- if (tag === void 0) {
1048
- tag = '__mf_v__';
1049
- }
1050
- if (suffix === void 0) {
1051
- suffix = '';
1052
- }
1053
- this.name = void 0;
1054
- this.tag = void 0;
1055
- this.suffix = void 0;
1056
- this.inited = false;
1057
- this.name = name;
1058
- this.tag = tag;
1059
- this.suffix = suffix || getSuffix(name);
1060
- if (!cacheMap[this.tag]) cacheMap[this.tag] = {};
1061
- cacheMap[this.tag][this.name] = this;
1062
- }
1063
- /**
1064
- * Set the root path for finding node_modules
1065
- * @param root - Root path
1066
- */
1067
- VirtualModule.setRoot = function setRoot(root) {
1068
- rootDir = root;
1069
- // Reset cache to ensure using the new root path
1070
- cachedNodeModulesDir = undefined;
1071
- }
1072
- /**
1073
- * Ensure virtual package directory exists
1074
- */;
1075
- VirtualModule.ensureVirtualPackageExists = function ensureVirtualPackageExists() {
1076
- var nodeModulesDir = getNodeModulesDir();
1077
- var _getNormalizeModuleFe = getNormalizeModuleFederationOptions(),
1078
- virtualModuleDir = _getNormalizeModuleFe.virtualModuleDir;
1079
- var virtualPackagePath = resolve(nodeModulesDir, virtualModuleDir);
1080
- if (!existsSync(virtualPackagePath)) {
1081
- mkdirSync(virtualPackagePath);
1082
- writeFileSync(resolve(virtualPackagePath, 'empty.js'), '');
1083
- writeFileSync(resolve(virtualPackagePath, 'package.json'), JSON.stringify({
1084
- name: virtualModuleDir,
1085
- main: 'empty.js'
1086
- }));
1087
- }
1088
- };
1089
- VirtualModule.findModule = function findModule(tag, str) {
1090
- if (str === void 0) {
1091
- str = '';
1092
- }
1093
- if (!patternMap[tag]) patternMap[tag] = new RegExp("(.*" + packageNameEncode(tag) + "(.+?)" + packageNameEncode(tag) + ".*)");
1094
- var moduleName = (str.match(patternMap[tag]) || [])[2];
1095
- if (moduleName) return cacheMap[tag][packageNameDecode(moduleName)];
1096
- return undefined;
1097
- };
1098
- var _proto = VirtualModule.prototype;
1099
- _proto.getPath = function getPath() {
1100
- return resolve(getNodeModulesDir(), this.getImportId());
1101
- };
1102
- _proto.getImportId = function getImportId() {
1103
- var _getNormalizeModuleFe2 = getNormalizeModuleFederationOptions(),
1104
- mfName = _getNormalizeModuleFe2.name,
1105
- virtualModuleDir = _getNormalizeModuleFe2.virtualModuleDir;
1106
- return virtualModuleDir + "/" + packageNameEncode("" + mfName + this.tag + this.name + this.tag) + this.suffix;
1107
- };
1108
- _proto.writeSync = function writeSync(code, force) {
1109
- if (!force && this.inited) return;
1110
- if (!this.inited) {
1111
- this.inited = true;
1112
- }
1113
- writeFileSync(this.getPath(), code);
1114
- };
1115
- _proto.write = function write(code) {
1116
- writeFile(this.getPath(), code, function () {});
1117
- };
1118
- return VirtualModule;
1119
- }();
1120
-
1121
- var VIRTUAL_EXPOSES = 'virtual:mf-exposes';
1122
- function generateExposes() {
1123
- var options = getNormalizeModuleFederationOptions();
1124
- return "\n export default {\n " + Object.keys(options.exposes).map(function (key) {
1125
- 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 ";
1126
- }).join(',') + "\n }\n ";
1127
- }
1128
-
1129
- var virtualRuntimeInitStatus = new VirtualModule('runtimeInit');
1130
- function writeRuntimeInitStatus() {
1131
- // Use globalThis singleton to ensure only one initPromise exists
1132
- var globalKey = "__mf_init__" + virtualRuntimeInitStatus.getImportId() + "__";
1133
- virtualRuntimeInitStatus.writeSync("\n const globalKey = " + JSON.stringify(globalKey) + "\n if (!globalThis[globalKey]) {\n let initResolve, initReject\n const initPromise = new Promise((re, rj) => {\n initResolve = re\n initReject = rj\n })\n globalThis[globalKey] = {\n initPromise,\n initResolve,\n initReject\n }\n }\n module.exports = globalThis[globalKey]\n ");
1134
- }
1135
-
1136
- var cacheRemoteMap = {};
1137
- var LOAD_REMOTE_TAG = '__loadRemote__';
1138
- function getRemoteVirtualModule(remote, command) {
1139
- if (!cacheRemoteMap[remote]) {
1140
- cacheRemoteMap[remote] = new VirtualModule(remote, LOAD_REMOTE_TAG, '.js');
1141
- cacheRemoteMap[remote].writeSync(generateRemotes(remote, command));
1142
- }
1143
- var virtual = cacheRemoteMap[remote];
1144
- return virtual;
1145
- }
1146
- var usedRemotesMap = {
1147
- // remote1: {remote1/App, remote1, remote1/Button}
1148
- };
1149
- function addUsedRemote(remoteKey, remoteModule) {
1150
- if (!usedRemotesMap[remoteKey]) usedRemotesMap[remoteKey] = new Set();
1151
- usedRemotesMap[remoteKey].add(remoteModule);
1152
- }
1153
- function getUsedRemotesMap() {
1154
- return usedRemotesMap;
1155
- }
1156
- function generateRemotes(id, command) {
1157
- return "\n const {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(runtime => runtime.loadRemote(" + JSON.stringify(id) + "))\n const exportModule = " + (command !== 'build' ? '/*mf top-level-await placeholder replacement mf*/' : 'await ') + "initPromise.then(_ => res)\n module.exports = exportModule\n ";
1158
- }
1159
-
1160
- /**
1161
- * Even the resolveId hook cannot interfere with vite pre-build,
1162
- * and adding query parameter virtual modules will also fail.
1163
- * You can only proxy to the real file through alias
1164
- */
1165
- // *** __prebuild__
1166
- var preBuildCacheMap = {};
1167
- var PREBUILD_TAG = '__prebuild__';
1168
- function writePreBuildLibPath(pkg) {
1169
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
1170
- preBuildCacheMap[pkg].writeSync('');
1171
- }
1172
- function getPreBuildLibImportId(pkg) {
1173
- if (!preBuildCacheMap[pkg]) preBuildCacheMap[pkg] = new VirtualModule(pkg, PREBUILD_TAG);
1174
- var importId = preBuildCacheMap[pkg].getImportId();
1175
- return importId;
1176
- }
1177
- // *** __loadShare__
1178
- var LOAD_SHARE_TAG = '__loadShare__';
1179
- var loadShareCacheMap = {};
1180
- function getLoadShareModulePath(pkg) {
1181
- if (!loadShareCacheMap[pkg]) loadShareCacheMap[pkg] = new VirtualModule(pkg, LOAD_SHARE_TAG, '.js');
1182
- var filepath = loadShareCacheMap[pkg].getPath();
1183
- return filepath;
1184
- }
1185
- function writeLoadShareModule(pkg, shareItem, command) {
1186
- 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 {initPromise} = require(\"" + virtualRuntimeInitStatus.getImportId() + "\")\n const res = initPromise.then(runtime => runtime.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 }))\n const exportModule = " + (command !== 'build' ? '/*mf top-level-await placeholder replacement mf*/' : 'await ') + "res.then(factory => factory())\n module.exports = exportModule\n ");
1187
- }
1188
-
1189
- var usedShares = new Set();
1190
- function getUsedShares() {
1191
- return usedShares;
1192
- }
1193
- function addUsedShares(pkg) {
1194
- usedShares.add(pkg);
1195
- }
1196
- // *** Expose locally provided shared modules here
1197
- new VirtualModule('localSharedImportMap');
1198
- function getLocalSharedImportMapPath() {
1199
- return getLocalSharedImportMapPath_temp();
1200
- // return localSharedImportMapModule.getPath()
1201
- }
1202
- var prevSharedCount;
1203
- function writeLocalSharedImportMap() {
1204
- var sharedCount = getUsedShares().size;
1205
- if (prevSharedCount !== sharedCount) {
1206
- prevSharedCount = sharedCount;
1207
- writeLocalSharedImportMap_temp(generateLocalSharedImportMap());
1208
- // localSharedImportMapModule.writeSync(generateLocalSharedImportMap(), true)
1209
- }
1210
- }
1211
- function generateLocalSharedImportMap() {
1212
- var options = getNormalizeModuleFederationOptions();
1213
- return "\n import {loadShare} from \"@module-federation/runtime\";\n const importMap = {\n " + Array.from(getUsedShares()).sort().map(function (pkg) {
1214
- var shareItem = getNormalizeShareItem(pkg);
1215
- return "\n " + JSON.stringify(pkg) + ": async () => {\n " + ((shareItem == null ? void 0 : shareItem.shareConfig["import"]) === false ? "throw new Error(`Shared module '${" + JSON.stringify(pkg) + "}' must be provided by host`);" : "let pkg = await import(\"" + getPreBuildLibImportId(pkg) + "\");\n return pkg;") + "\n }\n ";
1216
- }).join(',') + "\n }\n const usedShared = {\n " + Array.from(getUsedShares()).sort().map(function (key) {
1217
- var shareItem = getNormalizeShareItem(key);
1218
- if (!shareItem) return null;
1219
- 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 if (" + (shareItem.shareConfig["import"] === false) + ") {\n throw new Error(`Shared module '${" + JSON.stringify(key) + "}' must be provided by host`);\n }\n usedShared[" + JSON.stringify(key) + "].loaded = true\n const {" + JSON.stringify(key) + ": pkgDynamicImport} = importMap\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 " + (shareItem.shareConfig["import"] === false ? 'import: false,' : '') + "\n }\n }\n ";
1220
- }).filter(function (x) {
1221
- return x !== null;
1222
- }).join(',') + "\n }\n const usedRemotes = [" + Object.keys(getUsedRemotesMap()).map(function (key) {
1223
- var _JSON$stringify;
1224
- var remote = options.remotes[key];
1225
- if (!remote) return null;
1226
- 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 shareScope: " + ((_JSON$stringify = JSON.stringify(remote.shareScope)) != null ? _JSON$stringify : 'default') + ",\n }\n ";
1227
- }).filter(function (x) {
1228
- return x !== null;
1229
- }).join(',') + "\n ]\n export {\n usedShared,\n usedRemotes\n }\n ";
1230
- }
1231
- var REMOTE_ENTRY_ID = 'virtual:mf-REMOTE_ENTRY_ID';
1232
- function generateRemoteEntry(options) {
1233
- var pluginImportNames = options.runtimePlugins.map(function (p, i) {
1234
- if (typeof p === 'string') {
1235
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p + "\";", "undefined"];
1236
- } else {
1237
- return ["$runtimePlugin_" + i, "import $runtimePlugin_" + i + " from \"" + p[0] + "\";", serializeRuntimeOptions(p[1])];
1238
- }
1239
- });
1240
- return "\n import {init as runtimeInit, loadRemote} from \"@module-federation/runtime\";\n " + pluginImportNames.map(function (item) {
1241
- return item[1];
1242
- }).join('\n') + "\n import exposesMap from \"" + VIRTUAL_EXPOSES + "\"\n import {usedShared, usedRemotes} from \"" + getLocalSharedImportMapPath() + "\"\n import {\n initResolve\n } from \"" + virtualRuntimeInitStatus.getImportId() + "\"\n const initTokens = {}\n const shareScopeName = " + JSON.stringify(options.shareScope) + "\n const mfName = " + JSON.stringify(options.name) + "\n async function init(shared = {}, initScope = []) {\n const initRes = runtimeInit({\n name: mfName,\n remotes: usedRemotes,\n shared: usedShared,\n plugins: [" + pluginImportNames.map(function (item) {
1243
- return item[0] + "(" + item[2] + ")";
1244
- }).join(', ') + "],\n " + (options.shareStrategy ? "shareStrategy: '" + options.shareStrategy + "'" : '') + "\n });\n // handling circular init calls\n var initToken = initTokens[shareScopeName];\n if (!initToken)\n initToken = initTokens[shareScopeName] = { from: mfName };\n if (initScope.indexOf(initToken) >= 0) return;\n initScope.push(initToken);\n initRes.initShareScopeMap('" + options.shareScope + "', shared);\n try {\n await Promise.all(await initRes.initializeSharing('" + options.shareScope + "', {\n strategy: '" + options.shareStrategy + "',\n from: \"build\",\n initScope\n }));\n } catch (e) {\n console.error(e)\n }\n initResolve(initRes)\n return initRes\n }\n\n function getExposes(moduleName) {\n if (!(moduleName in exposesMap)) throw new Error(`Module ${moduleName} does not exist in container.`)\n return (exposesMap[moduleName])().then(res => () => res)\n }\n export {\n init,\n getExposes as get\n }\n ";
1245
- }
1246
- /**
1247
- * Inject entry file, automatically init when used as host,
1248
- * and will not inject remoteEntry
1249
- */
1250
- var HOST_AUTO_INIT_TAG = '__H_A_I__';
1251
- var hostAutoInitModule = new VirtualModule('hostAutoInit', HOST_AUTO_INIT_TAG);
1252
- function writeHostAutoInit() {
1253
- hostAutoInitModule.writeSync("\n const remoteEntryPromise = import(\"" + REMOTE_ENTRY_ID + "\")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ");
1254
- }
1255
- function getHostAutoInitImportId() {
1256
- return hostAutoInitModule.getImportId();
1257
- }
1258
- function getHostAutoInitPath() {
1259
- return hostAutoInitModule.getPath();
1260
- }
1261
-
1262
- function initVirtualModules() {
1263
- writeLocalSharedImportMap();
1264
- writeHostAutoInit();
1265
- writeRuntimeInitStatus();
1266
- }
1267
-
1268
- var ASSET_TYPES = ['js', 'css'];
1269
- var LOAD_TIMINGS = ['sync', 'async'];
1270
- var JS_EXTENSIONS = ['.ts', '.tsx', '.jsx', '.mjs', '.cjs'];
1271
- /**
1272
- * Creates an empty asset map structure for tracking JS and CSS assets
1273
- * @returns Initialized asset map with sync/async arrays for JS and CSS
1274
- */
1275
- var createEmptyAssetMap = function createEmptyAssetMap() {
1276
- return {
1277
- js: {
1278
- sync: [],
1279
- async: []
1280
- },
1281
- css: {
1282
- sync: [],
1283
- async: []
1284
- }
1285
- };
1286
- };
1287
- /**
1288
- * Tracks an asset in the preload map with deduplication
1289
- * @param map - The preload map to update
1290
- * @param key - The module key to track under
1291
- * @param fileName - The asset filename to track
1292
- * @param isAsync - Whether the asset is loaded async
1293
- * @param type - The asset type ('js' or 'css')
1294
- */
1295
- var trackAsset = function trackAsset(map, key, fileName, isAsync, type) {
1296
- if (!map[key]) {
1297
- map[key] = createEmptyAssetMap();
1298
- }
1299
- var target = isAsync ? map[key][type].async : map[key][type].sync;
1300
- if (!target.includes(fileName)) {
1301
- target.push(fileName);
1302
- }
1303
- };
1304
- /**
1305
- * Checks if a file is a CSS file by extension
1306
- * @param fileName - The filename to check
1307
- * @returns True if file has a CSS extension (.css, .scss, .less)
1308
- */
1309
- var isCSSFile = function isCSSFile(fileName) {
1310
- return fileName.endsWith('.css') || fileName.endsWith('.scss') || fileName.endsWith('.less');
1311
- };
1312
- /**
1313
- * Collects all CSS assets from the bundle
1314
- * @param bundle - The Rollup output bundle
1315
- * @returns Set of CSS asset filenames
1316
- */
1317
- var collectCssAssets = function collectCssAssets(bundle) {
1318
- var cssAssets = new Set();
1319
- for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1320
- var _Object$entries$_i = _Object$entries[_i],
1321
- fileName = _Object$entries$_i[0],
1322
- fileData = _Object$entries$_i[1];
1323
- if (fileData.type === 'asset' && isCSSFile(fileName)) {
1324
- cssAssets.add(fileName);
1325
- }
1326
- }
1327
- return cssAssets;
1328
- };
1329
- /**
1330
- * Processes module assets and tracks them in the files map
1331
- * @param bundle - The Rollup output bundle
1332
- * @param filesMap - The preload map to populate
1333
- * @param moduleMatcher - Function that matches module paths to keys
1334
- */
1335
- var processModuleAssets = function processModuleAssets(bundle, filesMap, moduleMatcher) {
1336
- for (var _i2 = 0, _Object$entries2 = Object.entries(bundle); _i2 < _Object$entries2.length; _i2++) {
1337
- var _Object$entries2$_i = _Object$entries2[_i2],
1338
- fileName = _Object$entries2$_i[0],
1339
- fileData = _Object$entries2$_i[1];
1340
- if (fileData.type !== 'chunk') continue;
1341
- if (!fileData.modules) continue;
1342
- for (var _i3 = 0, _Object$keys = Object.keys(fileData.modules); _i3 < _Object$keys.length; _i3++) {
1343
- var modulePath = _Object$keys[_i3];
1344
- var matchKey = moduleMatcher(modulePath);
1345
- if (!matchKey) continue;
1346
- // Track main JS chunk
1347
- trackAsset(filesMap, matchKey, fileName, false, 'js');
1348
- // Handle dynamic imports
1349
- if (fileData.dynamicImports) {
1350
- for (var _iterator = _createForOfIteratorHelperLoose(fileData.dynamicImports), _step; !(_step = _iterator()).done;) {
1351
- var dynamicImport = _step.value;
1352
- var importData = bundle[dynamicImport];
1353
- if (!importData) continue;
1354
- var isCss = isCSSFile(dynamicImport);
1355
- trackAsset(filesMap, matchKey, dynamicImport, true, isCss ? 'css' : 'js');
1356
- }
1357
- }
1358
- }
1359
- }
1360
- };
1361
- /**
1362
- * Deduplicates assets in the files map
1363
- * @param filesMap - The preload map to deduplicate
1364
- * @returns New deduplicated preload map
1365
- */
1366
- var deduplicateAssets = function deduplicateAssets(filesMap) {
1367
- var result = {};
1368
- for (var _i4 = 0, _Object$entries3 = Object.entries(filesMap); _i4 < _Object$entries3.length; _i4++) {
1369
- var _Object$entries3$_i = _Object$entries3[_i4],
1370
- key = _Object$entries3$_i[0],
1371
- assetMaps = _Object$entries3$_i[1];
1372
- result[key] = createEmptyAssetMap();
1373
- for (var _i5 = 0, _ASSET_TYPES = ASSET_TYPES; _i5 < _ASSET_TYPES.length; _i5++) {
1374
- var type = _ASSET_TYPES[_i5];
1375
- for (var _i6 = 0, _LOAD_TIMINGS = LOAD_TIMINGS; _i6 < _LOAD_TIMINGS.length; _i6++) {
1376
- var timing = _LOAD_TIMINGS[_i6];
1377
- result[key][type][timing] = Array.from(new Set(assetMaps[type][timing]));
1378
- }
1379
- }
1380
- }
1381
- return result;
1382
- };
1383
- /**
1384
- * Builds a mapping between module files and their share keys
1385
- * @param shareKeys - Set of share keys to map
1386
- * @param resolveFn - Function to resolve module paths
1387
- * @returns Map of file paths to their corresponding share keys
1388
- */
1389
- var buildFileToShareKeyMap = function buildFileToShareKeyMap(shareKeys, resolveFn) {
1390
- try {
1391
- var fileToShareKey = new Map();
1392
- return Promise.resolve(Promise.all(Array.from(shareKeys).map(function (shareKey) {
1393
- return resolveFn(getPreBuildLibImportId(shareKey)).then(function (resolution) {
1394
- var _resolution$id;
1395
- return {
1396
- shareKey: shareKey,
1397
- file: resolution == null || (_resolution$id = resolution.id) == null ? void 0 : _resolution$id.split('?')[0]
1398
- };
1399
- })["catch"](function () {
1400
- return null;
1401
- });
1402
- }))).then(function (resolutions) {
1403
- for (var _iterator2 = _createForOfIteratorHelperLoose(resolutions), _step2; !(_step2 = _iterator2()).done;) {
1404
- var resolution = _step2.value;
1405
- if (resolution != null && resolution.file) {
1406
- fileToShareKey.set(resolution.file, resolution.shareKey);
1407
- }
1408
- }
1409
- return fileToShareKey;
1410
- });
1411
- } catch (e) {
1412
- return Promise.reject(e);
1413
- }
1414
- };
1415
-
1416
- /**
1417
- * Resolves the public path for remote entries
1418
- * @param options - Module Federation options
1419
- * @param viteBase - Vite's base config value
1420
- * @param originalBase - Original base config before any transformations
1421
- * @returns The resolved public path
1422
- */
1423
- function resolvePublicPath(options, viteBase, originalBase) {
1424
- // Use explicitly set publicPath if provided
1425
- if (options.publicPath) {
1426
- return options.publicPath;
1427
- }
1428
- // Handle empty original base case
1429
- if (originalBase === '') {
1430
- return 'auto';
1431
- }
1432
- // Use viteBase if available, ensuring it ends with a slash
1433
- if (viteBase) {
1434
- return viteBase.replace(/\/?$/, '/');
1435
- }
1436
- // Fallback to auto if no base is specified
1437
- return 'auto';
1438
- }
1439
-
1440
- var Manifest = function Manifest() {
1441
- var mfOptions = getNormalizeModuleFederationOptions();
1442
- var name = mfOptions.name,
1443
- filename = mfOptions.filename,
1444
- getPublicPath = mfOptions.getPublicPath,
1445
- manifestOptions = mfOptions.manifest;
1446
- var mfManifestName = '';
1447
- if (manifestOptions === true) {
1448
- mfManifestName = 'mf-manifest.json';
1449
- }
1450
- if (typeof manifestOptions !== 'boolean') {
1451
- mfManifestName = path.join((manifestOptions == null ? void 0 : manifestOptions.filePath) || '', (manifestOptions == null ? void 0 : manifestOptions.fileName) || '');
1452
- }
1453
- var root;
1454
- var remoteEntryFile;
1455
- var publicPath;
1456
- var _command;
1457
- var _originalConfigBase;
1458
- var viteConfig;
1459
- /**
1460
- * Adds global CSS assets to all module exports
1461
- * @param filesMap - The preload map to update
1462
- * @param cssAssets - Set of CSS asset filenames to add
1463
- */
1464
- var addCssAssetsToAllExports = function addCssAssetsToAllExports(filesMap, cssAssets) {
1465
- Object.keys(filesMap).forEach(function (key) {
1466
- cssAssets.forEach(function (cssAsset) {
1467
- trackAsset(filesMap, key, cssAsset, false, 'css');
1468
- });
1469
- });
1470
- };
1471
- return [{
1472
- name: 'module-federation-manifest',
1473
- apply: 'serve',
1474
- /**
1475
- * Stores resolved Vite config for later use
1476
- */
1477
- /**
1478
- * Finalizes configuration after all plugins are resolved
1479
- * @param config - Fully resolved Vite config
1480
- */
1481
- configResolved: function configResolved(config) {
1482
- viteConfig = config;
1483
- },
1484
- /**
1485
- * Configures dev server middleware to handle manifest requests
1486
- * @param server - Vite dev server instance
1487
- */
1488
- configureServer: function configureServer(server) {
1489
- server.middlewares.use(function (req, res, next) {
1490
- var _req$url;
1491
- if (!mfManifestName) {
1492
- next();
1493
- return;
1494
- }
1495
- if (((_req$url = req.url) == null ? void 0 : _req$url.replace(/\?.*/, '')) === (viteConfig.base + mfManifestName).replace(/^\/?/, '/')) {
1496
- res.setHeader('Content-Type', 'application/json');
1497
- res.setHeader('Access-Control-Allow-Origin', '*');
1498
- res.end(JSON.stringify(_extends({}, generateMFManifest({}), {
1499
- id: name,
1500
- name: name,
1501
- metaData: {
1502
- name: name,
1503
- type: 'app',
1504
- buildInfo: {
1505
- buildVersion: '1.0.0',
1506
- buildName: name
1507
- },
1508
- remoteEntry: {
1509
- name: filename,
1510
- path: '',
1511
- type: 'module'
1512
- },
1513
- ssrRemoteEntry: {
1514
- name: filename,
1515
- path: '',
1516
- type: 'module'
1517
- },
1518
- types: {
1519
- path: '',
1520
- name: ''
1521
- },
1522
- globalName: name,
1523
- pluginVersion: '0.2.5',
1524
- publicPath: publicPath
1525
- }
1526
- })));
1527
- } else {
1528
- next();
1529
- }
1530
- });
1531
- }
1532
- }, {
1533
- name: 'module-federation-manifest',
1534
- enforce: 'post',
1535
- /**
1536
- * Initial plugin configuration
1537
- * @param config - Vite config object
1538
- * @param command - Current Vite command (serve/build)
1539
- */
1540
- config: function config(_config, _ref) {
1541
- var command = _ref.command;
1542
- if (!_config.build) _config.build = {};
1543
- if (!_config.build.manifest) {
1544
- _config.build.manifest = _config.build.manifest || !!manifestOptions;
1545
- }
1546
- _command = command;
1547
- _originalConfigBase = _config.base;
1548
- },
1549
- configResolved: function configResolved(config) {
1550
- root = config.root;
1551
- var base = config.base;
1552
- if (_command === 'serve') {
1553
- base = (config.server.origin || '') + config.base;
1554
- }
1555
- publicPath = resolvePublicPath(mfOptions, base, _originalConfigBase);
1556
- },
1557
- /**
1558
- * Generates the module federation manifest file
1559
- * @param options - Rollup output options
1560
- * @param bundle - Generated bundle assets
1561
- */
1562
- generateBundle: function generateBundle(options, bundle) {
1563
- try {
1564
- var _this = this;
1565
- if (!mfManifestName) return Promise.resolve();
1566
- var filesMap = {};
1567
- // First pass: Find remoteEntry file
1568
- for (var _i = 0, _Object$entries = Object.entries(bundle); _i < _Object$entries.length; _i++) {
1569
- var _Object$entries$_i = _Object$entries[_i],
1570
- _ = _Object$entries$_i[0],
1571
- fileData = _Object$entries$_i[1];
1572
- if (mfOptions.filename.replace(/[\[\]]/g, '_').replace(/\.[^/.]+$/, '') === fileData.name || fileData.name === 'remoteEntry') {
1573
- remoteEntryFile = fileData.fileName;
1574
- break; // We can break early since we only need to find remoteEntry once
1575
- }
1576
- }
1577
- // Second pass: Collect all CSS assets
1578
- var allCssAssets = mfOptions.bundleAllCSS ? collectCssAssets(bundle) : new Set();
1579
- var exposesModules = Object.keys(mfOptions.exposes).map(function (item) {
1580
- return mfOptions.exposes[item]["import"];
1581
- });
1582
- // Process exposed modules
1583
- processModuleAssets(bundle, filesMap, function (modulePath) {
1584
- var absoluteModulePath = path.resolve(root, modulePath);
1585
- return exposesModules.find(function (exposeModule) {
1586
- var exposePath = path.resolve(root, exposeModule);
1587
- // First try exact path match
1588
- if (absoluteModulePath === exposePath) {
1589
- return true;
1590
- }
1591
- // Then try path match without known extensions
1592
- var getPathWithoutKnownExt = function getPathWithoutKnownExt(filePath) {
1593
- var ext = path.extname(filePath);
1594
- return JS_EXTENSIONS.includes(ext) ? path.join(path.dirname(filePath), path.basename(filePath, ext)) : filePath;
1595
- };
1596
- var modulePathNoExt = getPathWithoutKnownExt(absoluteModulePath);
1597
- var exposePathNoExt = getPathWithoutKnownExt(exposePath);
1598
- return modulePathNoExt === exposePathNoExt;
1599
- });
1600
- });
1601
- // Process shared modules
1602
- return Promise.resolve(buildFileToShareKeyMap(getUsedShares(), _this.resolve.bind(_this))).then(function (fileToShareKey) {
1603
- processModuleAssets(bundle, filesMap, function (modulePath) {
1604
- return fileToShareKey.get(modulePath);
1605
- });
1606
- // Add all CSS assets to every export if bundleAllCSS is enabled
1607
- if (mfOptions.bundleAllCSS) {
1608
- addCssAssetsToAllExports(filesMap, allCssAssets);
1609
- }
1610
- // Final deduplication of all assets
1611
- filesMap = deduplicateAssets(filesMap);
1612
- _this.emitFile({
1613
- type: 'asset',
1614
- fileName: mfManifestName,
1615
- source: JSON.stringify(generateMFManifest(filesMap))
1616
- });
1617
- });
1618
- } catch (e) {
1619
- return Promise.reject(e);
1620
- }
1621
- }
1622
- }];
1623
- /**
1624
- * Generates the final manifest JSON structure
1625
- * @param preloadMap - Map of module assets to include
1626
- * @returns Complete manifest object
1627
- */
1628
- function generateMFManifest(preloadMap) {
1629
- var options = getNormalizeModuleFederationOptions();
1630
- var name = options.name;
1631
- var remoteEntry = {
1632
- name: remoteEntryFile,
1633
- path: '',
1634
- type: 'module'
1635
- };
1636
- // Process remotes
1637
- var remotes = Array.from(Object.entries(getUsedRemotesMap())).flatMap(function (_ref2) {
1638
- var remoteKey = _ref2[0],
1639
- modules = _ref2[1];
1640
- return Array.from(modules).map(function (moduleKey) {
1641
- return {
1642
- federationContainerName: options.remotes[remoteKey].entry,
1643
- moduleName: moduleKey.replace(remoteKey, '').replace('/', ''),
1644
- alias: remoteKey,
1645
- entry: '*'
1646
- };
1647
- });
1648
- });
1649
- // Process shared dependencies
1650
- var shared = Array.from(getUsedShares()).map(function (shareKey) {
1651
- var shareItem = getNormalizeShareItem(shareKey);
1652
- var assets = preloadMap[shareKey] || createEmptyAssetMap();
1653
- return {
1654
- id: name + ":" + shareKey,
1655
- name: shareKey,
1656
- version: shareItem.version,
1657
- requiredVersion: shareItem.shareConfig.requiredVersion,
1658
- assets: {
1659
- js: {
1660
- async: assets.js.async,
1661
- sync: assets.js.sync
1662
- },
1663
- css: {
1664
- async: assets.css.async,
1665
- sync: assets.css.sync
1666
- }
1667
- }
1668
- };
1669
- }).filter(Boolean);
1670
- // Process exposed modules
1671
- var exposes = Object.entries(options.exposes).map(function (_ref3) {
1672
- var key = _ref3[0],
1673
- value = _ref3[1];
1674
- var formatKey = key.replace('./', '');
1675
- var sourceFile = value["import"];
1676
- var assets = preloadMap[sourceFile] || createEmptyAssetMap();
1677
- return {
1678
- id: name + ":" + formatKey,
1679
- name: formatKey,
1680
- assets: {
1681
- js: {
1682
- async: assets.js.async,
1683
- sync: assets.js.sync
1684
- },
1685
- css: {
1686
- async: assets.css.async,
1687
- sync: assets.css.sync
1688
- }
1689
- },
1690
- path: key
1691
- };
1692
- }).filter(Boolean);
1693
- return {
1694
- id: name,
1695
- name: name,
1696
- metaData: _extends({
1697
- name: name,
1698
- type: 'app',
1699
- buildInfo: {
1700
- buildVersion: '1.0.0',
1701
- buildName: name
1702
- },
1703
- remoteEntry: remoteEntry,
1704
- ssrRemoteEntry: remoteEntry,
1705
- types: {
1706
- path: '',
1707
- name: ''
1708
- },
1709
- globalName: name,
1710
- pluginVersion: '0.2.5'
1711
- }, !!getPublicPath ? {
1712
- getPublicPath: getPublicPath
1713
- } : {
1714
- publicPath: publicPath
1715
- }),
1716
- shared: shared,
1717
- remotes: remotes,
1718
- exposes: exposes
1719
- };
1720
- }
1721
- };
1722
-
1723
- var _resolve, _parseTimeout;
1724
- var promise = new Promise(function (resolve, reject) {
1725
- _resolve = function _resolve(v) {
1726
- clearTimeout(_parseTimeout);
1727
- _parseTimeout = null;
1728
- resolve(v);
1729
- };
1730
- });
1731
- function setParseTimeout(timeout) {
1732
- if (!_parseTimeout) {
1733
- _parseTimeout = setTimeout(function () {
1734
- console.warn("Parse timeout (" + timeout + "s) - forcing resolve");
1735
- _resolve(1);
1736
- }, timeout * 1000);
1737
- }
1738
- }
1739
- var parsePromise = promise;
1740
- var exposesParseEnd = false;
1741
- var parseStartSet = new Set();
1742
- var parseEndSet = new Set();
1743
- function pluginModuleParseEnd (excludeFn, options) {
1744
- setParseTimeout(options.moduleParseTimeout);
1745
- return [{
1746
- name: '_',
1747
- apply: 'serve',
1748
- config: function config() {
1749
- // No waiting in development mode
1750
- _resolve(1);
1751
- }
1752
- }, {
1753
- enforce: 'pre',
1754
- name: 'parseStart',
1755
- apply: 'build',
1756
- load: function load(id) {
1757
- if (excludeFn(id)) {
1758
- return;
1759
- }
1760
- parseStartSet.add(id);
1761
- }
1762
- }, {
1763
- enforce: 'post',
1764
- name: 'parseEnd',
1765
- apply: 'build',
1766
- moduleParsed: function moduleParsed(module) {
1767
- var id = module.id;
1768
- if (id === VIRTUAL_EXPOSES) {
1769
- // When the entry JS file is empty and only contains exposes export code, it’s necessary to wait for the exposes modules to be resolved in order to collect the dependencies being used.
1770
- exposesParseEnd = true;
1771
- }
1772
- if (excludeFn(id)) {
1773
- return;
1774
- }
1775
- parseEndSet.add(id);
1776
- if (exposesParseEnd && parseStartSet.size === parseEndSet.size) {
1777
- _resolve(1);
1778
- }
1779
- }
1780
- }];
1781
- }
1782
-
1783
- var filter = createFilter();
1784
- function pluginProxyRemoteEntry () {
1785
- var viteConfig, _command;
1786
- return {
1787
- name: 'proxyRemoteEntry',
1788
- enforce: 'post',
1789
- configResolved: function configResolved(config) {
1790
- viteConfig = config;
1791
- },
1792
- config: function config(_config, _ref) {
1793
- var command = _ref.command;
1794
- _command = command;
1795
- },
1796
- resolveId: function resolveId(id) {
1797
- if (id === REMOTE_ENTRY_ID) {
1798
- return REMOTE_ENTRY_ID;
1799
- }
1800
- if (id === VIRTUAL_EXPOSES) {
1801
- return VIRTUAL_EXPOSES;
1802
- }
1803
- if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1804
- return id;
1805
- }
1806
- },
1807
- load: function load(id) {
1808
- if (id === REMOTE_ENTRY_ID) {
1809
- return parsePromise.then(function (_) {
1810
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1811
- });
1812
- }
1813
- if (id === VIRTUAL_EXPOSES) {
1814
- return generateExposes();
1815
- }
1816
- if (_command === 'serve' && id.includes(getHostAutoInitPath())) {
1817
- return id;
1818
- }
1819
- },
1820
- transform: function transform(code, id) {
1821
- var transformedCode = function () {
1822
- if (!filter(id)) return;
1823
- if (id.includes(REMOTE_ENTRY_ID)) {
1824
- return parsePromise.then(function (_) {
1825
- return generateRemoteEntry(getNormalizeModuleFederationOptions());
1826
- });
1827
- }
1828
- if (id === VIRTUAL_EXPOSES) {
1829
- return generateExposes();
1830
- }
1831
- if (id.includes(getHostAutoInitPath())) {
1832
- var options = getNormalizeModuleFederationOptions();
1833
- if (_command === 'serve') {
1834
- var _viteConfig$server, _viteConfig$server2;
1835
- var host = typeof ((_viteConfig$server = viteConfig.server) == null ? void 0 : _viteConfig$server.host) === 'string' && viteConfig.server.host !== '0.0.0.0' ? viteConfig.server.host : 'localhost';
1836
- var publicPath = JSON.stringify(resolvePublicPath(options, viteConfig.base) + options.filename);
1837
- return "\n const origin = (window && " + !options.ignoreOrigin + ") ? window.origin : \"//" + host + ":" + ((_viteConfig$server2 = viteConfig.server) == null ? void 0 : _viteConfig$server2.port) + "\"\n const remoteEntryPromise = await import(origin + " + publicPath + ")\n // __tla only serves as a hack for vite-plugin-top-level-await.\n Promise.resolve(remoteEntryPromise)\n .then(remoteEntry => {\n return Promise.resolve(remoteEntry.__tla)\n .then(remoteEntry.init).catch(remoteEntry.init)\n })\n ";
1838
- }
1839
- return code;
1840
- }
1841
- }();
1842
- return mapCodeToCodeWithSourcemap(transformedCode);
1843
- }
1844
- };
1845
- }
1846
-
1847
- createFilter();
1848
- function pluginProxyRemotes (options) {
1849
- var remotes = options.remotes;
1850
- return {
1851
- name: 'proxyRemotes',
1852
- config: function config(_config, _ref) {
1853
- var _command = _ref.command;
1854
- Object.keys(remotes).forEach(function (key) {
1855
- var remote = remotes[key];
1856
- _config.resolve.alias.push({
1857
- find: new RegExp("^(" + remote.name + "(/.*|$))"),
1858
- replacement: '$1',
1859
- customResolver: function customResolver(source) {
1860
- var remoteModule = getRemoteVirtualModule(source, _command);
1861
- addUsedRemote(remote.name, source);
1862
- return remoteModule.getPath();
1863
- }
1864
- });
1865
- });
1866
- }
1867
- };
1868
- }
1869
-
1870
- /**
1871
- * example:
1872
- * const store = new PromiseStore<number>();
1873
- * store.get("example").then((result) => {
1874
- * console.log("Result from example:", result); // 42
1875
- * });
1876
- * setTimeout(() => {
1877
- * store.set("example", Promise.resolve(42));
1878
- * }, 2000);
1879
- */
1880
- var PromiseStore = /*#__PURE__*/function () {
1881
- function PromiseStore() {
1882
- this.promiseMap = new Map();
1883
- this.resolveMap = new Map();
1884
- }
1885
- var _proto = PromiseStore.prototype;
1886
- _proto.set = function set(id, promise) {
1887
- if (this.resolveMap.has(id)) {
1888
- promise.then(this.resolveMap.get(id));
1889
- this.resolveMap["delete"](id);
1890
- }
1891
- this.promiseMap.set(id, promise);
1892
- };
1893
- _proto.get = function get(id) {
1894
- var _this = this;
1895
- if (this.promiseMap.has(id)) {
1896
- return this.promiseMap.get(id);
1897
- }
1898
- var pendingPromise = new Promise(function (resolve) {
1899
- _this.resolveMap.set(id, resolve);
1900
- });
1901
- this.promiseMap.set(id, pendingPromise);
1902
- return pendingPromise;
1903
- };
1904
- return PromiseStore;
1905
- }();
1906
-
1907
- function proxySharedModule(options) {
1908
- var _options$shared = options.shared,
1909
- shared = _options$shared === void 0 ? {} : _options$shared;
1910
- var _config;
1911
- return [{
1912
- name: 'generateLocalSharedImportMap',
1913
- enforce: 'post',
1914
- load: function load(id) {
1915
- if (id.includes(getLocalSharedImportMapPath())) {
1916
- return parsePromise.then(function (_) {
1917
- return generateLocalSharedImportMap();
1918
- });
1919
- }
1920
- },
1921
- transform: function transform(_, id) {
1922
- if (id.includes(getLocalSharedImportMapPath())) {
1923
- return mapCodeToCodeWithSourcemap(parsePromise.then(function (_) {
1924
- return generateLocalSharedImportMap();
1925
- }));
1926
- }
1927
- }
1928
- }, {
1929
- name: 'proxyPreBuildShared',
1930
- enforce: 'post',
1931
- configResolved: function configResolved(config) {
1932
- _config = config;
1933
- },
1934
- config: function config(_config2, _ref) {
1935
- var _config2$resolve$alia, _config2$resolve$alia2;
1936
- var command = _ref.command;
1937
- (_config2$resolve$alia = _config2.resolve.alias).push.apply(_config2$resolve$alia, Object.keys(shared).map(function (key) {
1938
- var pattern = key.endsWith('/') ? "(^" + key.replace(/\/$/, '') + "(/.+)?$)" : "(^" + key + "$)";
1939
- return {
1940
- // Intercept all shared requests and proxy them to loadShare
1941
- find: new RegExp(pattern),
1942
- replacement: '$1',
1943
- customResolver: function customResolver(source, importer) {
1944
- if (/\.css$/.test(source)) return;
1945
- var loadSharePath = getLoadShareModulePath(source);
1946
- writeLoadShareModule(source, shared[key], command);
1947
- writePreBuildLibPath(source);
1948
- addUsedShares(source);
1949
- writeLocalSharedImportMap();
1950
- return this.resolve(loadSharePath, importer);
1951
- }
1952
- };
1953
- }));
1954
- var savePrebuild = new PromiseStore();
1955
- (_config2$resolve$alia2 = _config2.resolve.alias).push.apply(_config2$resolve$alia2, Object.keys(shared).map(function (key) {
1956
- return command === 'build' ? {
1957
- find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
1958
- replacement: function replacement($1) {
1959
- var module = assertModuleFound(PREBUILD_TAG, $1);
1960
- var pkgName = module.name;
1961
- return pkgName;
1962
- }
1963
- } : {
1964
- find: new RegExp("(.*" + PREBUILD_TAG + ".*)"),
1965
- replacement: '$1',
1966
- customResolver: function customResolver(source, importer) {
1967
- try {
1968
- var _this = this;
1969
- var module = assertModuleFound(PREBUILD_TAG, source);
1970
- var pkgName = module.name;
1971
- return Promise.resolve(_this.resolve(pkgName, importer).then(function (item) {
1972
- return item.id;
1973
- })).then(function (result) {
1974
- if (!result.includes(_config.cacheDir)) {
1975
- // save pre-bunding module id
1976
- savePrebuild.set(pkgName, Promise.resolve(result));
1977
- }
1978
- // Fix localSharedImportMap import id
1979
- var _resolve = _this.resolve;
1980
- return Promise.resolve(savePrebuild.get(pkgName)).then(function (_savePrebuild$get) {
1981
- return Promise.resolve(_resolve.call(_this, _savePrebuild$get, importer));
1982
- });
1983
- });
1984
- } catch (e) {
1985
- return Promise.reject(e);
1986
- }
1987
- }
1988
- };
1989
- }));
1990
- }
1991
- }];
1992
- }
1993
-
1994
- var aliasToArrayPlugin = {
1995
- name: 'alias-transform-plugin',
1996
- config: function config(_config, _ref) {
1997
- if (!_config.resolve) _config.resolve = {};
1998
- if (!_config.resolve.alias) _config.resolve.alias = [];
1999
- var alias = _config.resolve.alias;
2000
- if (typeof alias === 'object' && !Array.isArray(alias)) {
2001
- _config.resolve.alias = Object.entries(alias).map(function (_ref2) {
2002
- var find = _ref2[0],
2003
- replacement = _ref2[1];
2004
- return {
2005
- find: find,
2006
- replacement: replacement
2007
- };
2008
- });
2009
- }
2010
- }
2011
- };
2012
-
2013
- var normalizeOptimizeDepsPlugin = {
2014
- name: 'normalizeOptimizeDeps',
2015
- config: function config(_config, _ref) {
2016
- var optimizeDeps = _config.optimizeDeps;
2017
- if (!optimizeDeps) {
2018
- _config.optimizeDeps = {};
2019
- optimizeDeps = _config.optimizeDeps;
2020
- }
2021
- // todo: fix this workaround
2022
- optimizeDeps.force = true;
2023
- if (!optimizeDeps.include) optimizeDeps.include = [];
2024
- if (!optimizeDeps.needsInterop) optimizeDeps.needsInterop = [];
2025
- }
2026
- };
2027
-
2028
- function federation(mfUserOptions) {
2029
- var options = normalizeModuleFederationOptions(mfUserOptions);
2030
- var name = options.name,
2031
- shared = options.shared,
2032
- filename = options.filename,
2033
- hostInitInjectLocation = options.hostInitInjectLocation;
2034
- if (!name) throw new Error('name is required');
2035
- return [{
2036
- name: 'vite:module-federation-config',
2037
- enforce: 'pre',
2038
- configResolved: function configResolved(config) {
2039
- // Set root path
2040
- VirtualModule.setRoot(config.root);
2041
- // Ensure virtual package directory exists
2042
- VirtualModule.ensureVirtualPackageExists();
2043
- initVirtualModules();
2044
- }
2045
- }, aliasToArrayPlugin, checkAliasConflicts({
2046
- shared: shared
2047
- }), normalizeOptimizeDepsPlugin].concat(pluginDts(options), addEntry({
2048
- entryName: 'remoteEntry',
2049
- entryPath: REMOTE_ENTRY_ID,
2050
- fileName: filename
2051
- }), addEntry({
2052
- entryName: 'hostInit',
2053
- entryPath: getHostAutoInitPath(),
2054
- inject: hostInitInjectLocation
2055
- }), addEntry({
2056
- entryName: 'virtualExposes',
2057
- entryPath: VIRTUAL_EXPOSES
2058
- }), [pluginProxyRemoteEntry(), pluginProxyRemotes(options)], pluginModuleParseEnd(function (id) {
2059
- return id.includes(getHostAutoInitImportId()) || id.includes(REMOTE_ENTRY_ID) || id.includes(VIRTUAL_EXPOSES) || id.includes(getLocalSharedImportMapPath());
2060
- }, {
2061
- moduleParseTimeout: options.moduleParseTimeout
2062
- }), proxySharedModule({
2063
- shared: shared
2064
- }), [PluginDevProxyModuleTopLevelAwait(), {
2065
- name: 'module-federation-vite',
2066
- enforce: 'post',
2067
- // @ts-expect-error
2068
- // used to expose plugin options: https://github.com/rolldown/rolldown/discussions/2577#discussioncomment-11137593
2069
- _options: options,
2070
- config: function config(_config, _ref) {
2071
- var _config$optimizeDeps, _config$optimizeDeps2, _config$optimizeDeps3, _config$optimizeDeps4;
2072
- // TODO: singleton
2073
- _config.resolve.alias.push({
2074
- find: '@module-federation/runtime',
2075
- replacement: options.implementation
2076
- });
2077
- _config.build = defu(_config.build || {}, {
2078
- commonjsOptions: {
2079
- strictRequires: 'auto'
2080
- }
2081
- });
2082
- var virtualDir = options.virtualModuleDir || '__mf__virtual';
2083
- (_config$optimizeDeps = _config.optimizeDeps) == null || (_config$optimizeDeps = _config$optimizeDeps.include) == null || _config$optimizeDeps.push('@module-federation/runtime');
2084
- (_config$optimizeDeps2 = _config.optimizeDeps) == null || (_config$optimizeDeps2 = _config$optimizeDeps2.include) == null || _config$optimizeDeps2.push(virtualDir);
2085
- (_config$optimizeDeps3 = _config.optimizeDeps) == null || (_config$optimizeDeps3 = _config$optimizeDeps3.needsInterop) == null || _config$optimizeDeps3.push(virtualDir);
2086
- (_config$optimizeDeps4 = _config.optimizeDeps) == null || (_config$optimizeDeps4 = _config$optimizeDeps4.needsInterop) == null || _config$optimizeDeps4.push(getLocalSharedImportMapPath());
2087
- }
2088
- }], Manifest());
2089
- }
2090
-
2091
- export { federation };