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