@module-federation/esbuild 0.0.81 → 0.0.82

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 (54) hide show
  1. package/dist/build.d.ts +5 -1
  2. package/dist/build.js +481 -0
  3. package/dist/build.mjs +380 -0
  4. package/dist/index.d.ts +2 -2
  5. package/dist/index.js +36 -0
  6. package/dist/index.mjs +2 -0
  7. package/dist/plugin.js +1247 -0
  8. package/dist/{plugin.esm.js → plugin.mjs} +198 -317
  9. package/dist/resolve/esm-resolver.mjs +22 -15
  10. package/package.json +18 -25
  11. package/dist/build.cjs.js +0 -532
  12. package/dist/build.cjs.js.map +0 -1
  13. package/dist/build.esm.js +0 -494
  14. package/dist/build.esm.js.map +0 -1
  15. package/dist/get-externals.cjs.js +0 -22
  16. package/dist/get-externals.cjs.js.map +0 -1
  17. package/dist/get-externals.esm.js +0 -20
  18. package/dist/get-externals.esm.js.map +0 -1
  19. package/dist/index.cjs.js +0 -6
  20. package/dist/index.cjs.js.map +0 -1
  21. package/dist/index.esm.js +0 -4
  22. package/dist/index.esm.js.map +0 -1
  23. package/dist/plugin.cjs.js +0 -1313
  24. package/dist/plugin.cjs.js.map +0 -1
  25. package/dist/plugin.d.ts +0 -1
  26. package/dist/plugin.esm.js.map +0 -1
  27. package/dist/src/build.d.ts +0 -5
  28. package/dist/src/index.d.ts +0 -2
  29. /package/dist/{src/adapters → adapters}/lib/collect-exports.d.ts +0 -0
  30. /package/dist/{src/adapters → adapters}/lib/commonjs.d.ts +0 -0
  31. /package/dist/{src/adapters → adapters}/lib/containerPlugin.d.ts +0 -0
  32. /package/dist/{src/adapters → adapters}/lib/containerReference.d.ts +0 -0
  33. /package/dist/{src/adapters → adapters}/lib/lexer.d.ts +0 -0
  34. /package/dist/{src/adapters → adapters}/lib/linkRemotesPlugin.d.ts +0 -0
  35. /package/dist/{src/adapters → adapters}/lib/manifest.d.ts +0 -0
  36. /package/dist/{src/adapters → adapters}/lib/plugin.d.ts +0 -0
  37. /package/dist/{src/adapters → adapters}/lib/react-replacements.d.ts +0 -0
  38. /package/dist/{src/adapters → adapters}/lib/transform.d.ts +0 -0
  39. /package/dist/{src/adapters → adapters}/lib/utils.d.ts +0 -0
  40. /package/dist/{src/lib → lib}/config/configuration-context.d.ts +0 -0
  41. /package/dist/{src/lib → lib}/config/federation-config.d.ts +0 -0
  42. /package/dist/{src/lib → lib}/config/share-utils.d.ts +0 -0
  43. /package/dist/{src/lib → lib}/config/with-native-federation.d.ts +0 -0
  44. /package/dist/{src/lib → lib}/core/build-adapter.d.ts +0 -0
  45. /package/dist/{src/lib → lib}/core/createContainerTemplate.d.ts +0 -0
  46. /package/dist/{src/lib → lib}/core/default-skip-list.d.ts +0 -0
  47. /package/dist/{src/lib → lib}/core/federation-options.d.ts +0 -0
  48. /package/dist/{src/lib → lib}/core/get-externals.d.ts +0 -0
  49. /package/dist/{src/lib → lib}/core/load-federation-config.d.ts +0 -0
  50. /package/dist/{src/lib → lib}/core/write-federation-info.d.ts +0 -0
  51. /package/dist/{src/lib → lib}/utils/logger.d.ts +0 -0
  52. /package/dist/{src/lib → lib}/utils/mapped-paths.d.ts +0 -0
  53. /package/dist/{src/lib → lib}/utils/normalize.d.ts +0 -0
  54. /package/dist/{src/lib → lib}/utils/package-info.d.ts +0 -0
@@ -1,1313 +0,0 @@
1
- 'use strict';
2
-
3
- var fs = require('fs');
4
- var esModuleLexer = require('es-module-lexer');
5
- var cjsModuleLexer = require('cjs-module-lexer');
6
- var util = require('util');
7
- var enhancedResolve = require('enhanced-resolve');
8
- var path = require('path');
9
- var getExternals = require('./get-externals.cjs.js');
10
-
11
- const resolve = util.promisify(enhancedResolve.create({
12
- mainFields: [
13
- 'browser',
14
- 'module',
15
- 'main'
16
- ]
17
- }));
18
- async function getExports(modulePath) {
19
- await esModuleLexer.init;
20
- await cjsModuleLexer.init;
21
- try {
22
- const exports = [];
23
- const paths = [];
24
- const resolvedPath = await resolve(process.cwd(), modulePath);
25
- if (typeof resolvedPath === 'string') {
26
- paths.push(resolvedPath);
27
- }
28
- while(paths.length > 0){
29
- const currentPath = paths.pop();
30
- if (currentPath) {
31
- const content = await fs.promises.readFile(currentPath, 'utf8');
32
- try {
33
- const { exports: cjsExports } = cjsModuleLexer.parse(content);
34
- exports.push(...cjsExports);
35
- } catch (e) {
36
- const [, esExports] = esModuleLexer.parse(content);
37
- exports.push(...esExports.map((exp)=>exp.n));
38
- }
39
- // TODO: Handle re-exports
40
- }
41
- }
42
- if (!exports.includes('default')) {
43
- exports.push('default');
44
- }
45
- return exports;
46
- } catch (e) {
47
- console.log(e);
48
- return [
49
- 'default'
50
- ];
51
- }
52
- }
53
-
54
- var version = "0.0.81";
55
-
56
- function _extends$1() {
57
- _extends$1 = Object.assign || function(target) {
58
- for(var i = 1; i < arguments.length; i++){
59
- var source = arguments[i];
60
- for(var key in source){
61
- if (Object.prototype.hasOwnProperty.call(source, key)) {
62
- target[key] = source[key];
63
- }
64
- }
65
- }
66
- return target;
67
- };
68
- return _extends$1.apply(this, arguments);
69
- }
70
- const writeRemoteManifest = async (config, result)=>{
71
- var _result_metafile, _result_metafile1;
72
- if (result.errors && result.errors.length > 0) {
73
- console.warn('Build errors detected, skipping writeRemoteManifest.');
74
- return;
75
- }
76
- let packageJson;
77
- try {
78
- const packageJsonPath = await resolve(process.cwd(), '/package.json') || '';
79
- packageJson = require(packageJsonPath);
80
- } catch (e) {
81
- packageJson = {
82
- name: config.name
83
- };
84
- }
85
- var _process_env_NODE_ENV;
86
- const envType = process.env['NODE_ENV'] === 'development' ? 'local' : (_process_env_NODE_ENV = process.env['NODE_ENV']) != null ? _process_env_NODE_ENV : '';
87
- const publicPath = config.publicPath || 'auto';
88
- let containerName = '';
89
- const outputMap = Object.entries(((_result_metafile = result.metafile) == null ? void 0 : _result_metafile.outputs) || {}).reduce((acc, [chunkKey, chunkValue])=>{
90
- const { entryPoint } = chunkValue;
91
- const key = entryPoint || chunkKey;
92
- if (key.startsWith('container:') && key.endsWith(config.filename)) {
93
- containerName = key;
94
- }
95
- acc[key] = _extends$1({}, chunkValue, {
96
- chunk: chunkKey
97
- });
98
- return acc;
99
- }, {});
100
- if (!outputMap[containerName]) return;
101
- const outputMapWithoutExt = Object.entries(((_result_metafile1 = result.metafile) == null ? void 0 : _result_metafile1.outputs) || {}).reduce((acc, [chunkKey, chunkValue])=>{
102
- const { entryPoint } = chunkValue;
103
- const key = entryPoint || chunkKey;
104
- const trimKey = key.substring(0, key.lastIndexOf('.')) || key;
105
- acc[trimKey] = _extends$1({}, chunkValue, {
106
- chunk: chunkKey
107
- });
108
- return acc;
109
- }, {});
110
- const getChunks = (meta, outputMap)=>{
111
- const assets = {
112
- js: {
113
- async: [],
114
- sync: []
115
- },
116
- css: {
117
- async: [],
118
- sync: []
119
- }
120
- };
121
- if (meta == null ? void 0 : meta.imports) {
122
- meta.imports.forEach((imp)=>{
123
- const importMeta = outputMap[imp.path];
124
- if (importMeta && importMeta.kind !== 'dynamic-import') {
125
- const childAssets = getChunks(importMeta, outputMap);
126
- assets.js.async.push(...childAssets.js.async);
127
- assets.js.sync.push(...childAssets.js.sync);
128
- assets.css.async.push(...childAssets.css.async);
129
- assets.css.sync.push(...childAssets.css.sync);
130
- }
131
- });
132
- const assetType = meta.chunk.endsWith('.js') ? 'js' : 'css';
133
- const syncOrAsync = meta.kind === 'dynamic-import' ? 'async' : 'sync';
134
- assets[assetType][syncOrAsync].push(meta.chunk);
135
- }
136
- return assets;
137
- };
138
- const shared = config.shared ? await Promise.all(Object.entries(config.shared).map(async ([pkg, config])=>{
139
- const meta = outputMap['esm-shares:' + pkg];
140
- const chunks = getChunks(meta, outputMap);
141
- let { version } = config;
142
- if (!version) {
143
- try {
144
- const packageJsonPath = await resolve(process.cwd(), `${pkg}/package.json`);
145
- if (packageJsonPath) {
146
- version = JSON.parse(fs.readFileSync(packageJsonPath, 'utf-8')).version;
147
- }
148
- } catch (e) {
149
- console.warn(`Can't resolve ${pkg} version automatically, consider setting "version" manually`);
150
- }
151
- }
152
- return {
153
- id: `${config.name}:${pkg}`,
154
- name: pkg,
155
- version: version || config.version,
156
- singleton: config.singleton || false,
157
- requiredVersion: config.requiredVersion || '*',
158
- assets: chunks
159
- };
160
- })) : [];
161
- const remotes = config.remotes ? Object.entries(config.remotes).map(([alias, remote])=>{
162
- const [federationContainerName, entry] = remote.includes('@') ? remote.split('@') : [
163
- alias,
164
- remote
165
- ];
166
- return {
167
- federationContainerName,
168
- moduleName: '',
169
- alias,
170
- entry
171
- };
172
- }) : [];
173
- const exposes = config.exposes ? await Promise.all(Object.entries(config.exposes).map(async ([expose, value])=>{
174
- const exposedFound = outputMapWithoutExt[value.replace('./', '')];
175
- const chunks = getChunks(exposedFound, outputMap);
176
- return {
177
- id: `${config.name}:${expose.replace(/^\.\//, '')}`,
178
- name: expose.replace(/^\.\//, ''),
179
- assets: chunks,
180
- path: expose
181
- };
182
- })) : [];
183
- const types = {
184
- path: '',
185
- name: '',
186
- zip: '@mf-types.zip',
187
- api: '@mf-types.d.ts'
188
- };
189
- var _packageJson_name;
190
- const manifest = {
191
- id: config.name,
192
- name: config.name,
193
- metaData: {
194
- name: config.name,
195
- type: 'app',
196
- buildInfo: {
197
- buildVersion: envType,
198
- buildName: ((_packageJson_name = packageJson.name) != null ? _packageJson_name : 'default').replace(/[^a-zA-Z0-9]/g, '_')
199
- },
200
- remoteEntry: {
201
- name: config.filename,
202
- path: outputMap[containerName] ? path.dirname(outputMap[containerName].chunk) : '',
203
- type: 'esm'
204
- },
205
- types,
206
- globalName: config.name,
207
- pluginVersion: version,
208
- publicPath
209
- },
210
- shared,
211
- remotes,
212
- exposes
213
- };
214
- const manifestPath = path.join(path.dirname(outputMap[containerName].chunk), 'mf-manifest.json');
215
- fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2), 'utf-8');
216
- };
217
-
218
- const createContainerCode = `
219
- import bundler_runtime_base from '@module-federation/webpack-bundler-runtime';
220
- // import instantiatePatch from "./federation.js";
221
-
222
- const createContainer = (federationOptions) => {
223
- // await instantiatePatch(federationOptions, true);
224
- const {exposes, name, remotes = [], shared, plugins} = federationOptions;
225
-
226
- const __webpack_modules__ = {
227
- "./node_modules/.federation/entry.1f2288102e035e2ed66b2efaf60ad043.js": (module, __webpack_exports__, __webpack_require__) => {
228
- __webpack_require__.r(__webpack_exports__);
229
- const bundler_runtime = __webpack_require__.n(bundler_runtime_base);
230
- const prevFederation = __webpack_require__.federation;
231
- __webpack_require__.federation = {};
232
- for (const key in bundler_runtime()) {
233
- __webpack_require__.federation[key] = bundler_runtime()[key];
234
- }
235
- for (const key in prevFederation) {
236
- __webpack_require__.federation[key] = prevFederation[key];
237
- }
238
- if (!__webpack_require__.federation.instance) {
239
- const pluginsToAdd = plugins || [];
240
- __webpack_require__.federation.initOptions.plugins = __webpack_require__.federation.initOptions.plugins ?
241
- __webpack_require__.federation.initOptions.plugins.concat(pluginsToAdd) : pluginsToAdd;
242
- __webpack_require__.federation.instance = __webpack_require__.federation.runtime.init(__webpack_require__.federation.initOptions);
243
- if (__webpack_require__.federation.attachShareScopeMap) {
244
- __webpack_require__.federation.attachShareScopeMap(__webpack_require__);
245
- }
246
- if (__webpack_require__.federation.installInitialConsumes) {
247
- __webpack_require__.federation.installInitialConsumes();
248
- }
249
- }
250
- },
251
-
252
- "webpack/container/entry/createContainer": (module, exports, __webpack_require__) => {
253
- const moduleMap = {};
254
- for (const key in exposes) {
255
- if (Object.prototype.hasOwnProperty.call(exposes, key)) {
256
- moduleMap[key] = () => Promise.resolve(exposes[key]()).then(m => () => m);
257
- }
258
- }
259
-
260
- const get = (module, getScope) => {
261
- __webpack_require__.R = getScope;
262
- getScope = (
263
- __webpack_require__.o(moduleMap, module)
264
- ? moduleMap[module]()
265
- : Promise.resolve().then(() => {
266
- throw new Error("Module '" + module + "' does not exist in container.");
267
- })
268
- );
269
- __webpack_require__.R = undefined;
270
- return getScope;
271
- };
272
- const init = (shareScope, initScope, remoteEntryInitOptions) => {
273
- return __webpack_require__.federation.bundlerRuntime.initContainerEntry({
274
- webpackRequire: __webpack_require__,
275
- shareScope: shareScope,
276
- initScope: initScope,
277
- remoteEntryInitOptions: remoteEntryInitOptions,
278
- shareScopeKey: "default"
279
- });
280
- };
281
- __webpack_require__("./node_modules/.federation/entry.1f2288102e035e2ed66b2efaf60ad043.js");
282
-
283
- // This exports getters to disallow modifications
284
- __webpack_require__.d(exports, {
285
- get: () => get,
286
- init: () => init,
287
- moduleMap: () => moduleMap,
288
- });
289
- }
290
- };
291
-
292
- const __webpack_module_cache__ = {};
293
-
294
- const __webpack_require__ = (moduleId) => {
295
- let cachedModule = __webpack_module_cache__[moduleId];
296
- if (cachedModule !== undefined) {
297
- return cachedModule.exports;
298
- }
299
- let module = __webpack_module_cache__[moduleId] = {
300
- id: moduleId,
301
- loaded: false,
302
- exports: {}
303
- };
304
-
305
- const execOptions = {
306
- id: moduleId,
307
- module: module,
308
- factory: __webpack_modules__[moduleId],
309
- require: __webpack_require__
310
- };
311
- __webpack_require__.i.forEach(handler => {
312
- handler(execOptions);
313
- });
314
- module = execOptions.module;
315
- execOptions.factory.call(module.exports, module, module.exports, execOptions.require);
316
-
317
- module.loaded = true;
318
-
319
- return module.exports;
320
- };
321
-
322
- __webpack_require__.m = __webpack_modules__;
323
- __webpack_require__.c = __webpack_module_cache__;
324
- __webpack_require__.i = [];
325
-
326
- if (!__webpack_require__.federation) {
327
- __webpack_require__.federation = {
328
- initOptions: {
329
- "name": name,
330
- "remotes": remotes.map(remote => ({
331
- "type": remote.type,
332
- "alias": remote.alias,
333
- "name": remote.name,
334
- "entry": remote.entry,
335
- "shareScope": remote.shareScope || "default"
336
- }))
337
- },
338
- chunkMatcher: () => true,
339
- rootOutputDir: "",
340
- initialConsumes: undefined,
341
- bundlerRuntimeOptions: {}
342
- };
343
- }
344
-
345
- __webpack_require__.n = (module) => {
346
- const getter = module && module.__esModule ? () => module['default'] : () => module;
347
- __webpack_require__.d(getter, {a: getter});
348
- return getter;
349
- };
350
-
351
- __webpack_require__.d = (exports, definition) => {
352
- for (const key in definition) {
353
- if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
354
- Object.defineProperty(exports, key, {enumerable: true, get: definition[key]});
355
- }
356
- }
357
- };
358
-
359
- __webpack_require__.f = {};
360
-
361
- __webpack_require__.g = (() => {
362
- if (typeof globalThis === 'object') return globalThis;
363
- try {
364
- return this || new Function('return this')();
365
- } catch (e) {
366
- if (typeof window === 'object') return window;
367
- }
368
- })();
369
-
370
- __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
371
-
372
- __webpack_require__.r = (exports) => {
373
- if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
374
- Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'});
375
- }
376
- Object.defineProperty(exports, '__esModule', {value: true});
377
- };
378
-
379
- __webpack_require__.federation.initOptions.shared = shared;
380
- __webpack_require__.S = {};
381
- const initPromises = {};
382
- const initTokens = {};
383
- __webpack_require__.I = (name, initScope) => {
384
- return __webpack_require__.federation.bundlerRuntime.I({
385
- shareScopeName: name,
386
- webpackRequire: __webpack_require__,
387
- initPromises: initPromises,
388
- initTokens: initTokens,
389
- initScope: initScope,
390
- });
391
- };
392
-
393
- const __webpack_exports__ = __webpack_require__("webpack/container/entry/createContainer");
394
- const __webpack_exports__get = __webpack_exports__.get;
395
- const __webpack_exports__init = __webpack_exports__.init;
396
- const __webpack_exports__moduleMap = __webpack_exports__.moduleMap;
397
- return __webpack_exports__;
398
- }`;
399
-
400
- const buildContainerHost = (config)=>{
401
- const { name, remotes = {}, shared = {}, exposes = {} } = config;
402
- const remoteConfigs = Object.entries(remotes).map(([remoteAlias, remote])=>({
403
- type: 'esm',
404
- name: remoteAlias,
405
- entry: remote.entry,
406
- alias: remoteAlias
407
- }));
408
- const sharedConfig = Object.entries(shared).reduce((acc, [pkg, config])=>{
409
- var _config_requiredVersion;
410
- const version = ((_config_requiredVersion = config.requiredVersion) == null ? void 0 : _config_requiredVersion.replace(/^[^0-9]/, '')) || '';
411
- acc += `${JSON.stringify(pkg)}: {
412
- "package": "${pkg}",
413
- "version": "${version}",
414
- "scope": "default",
415
- "get": async () => import('federationShare/${pkg}'),
416
- "shareConfig": {
417
- "singleton": ${config.singleton},
418
- "requiredVersion": "${config.requiredVersion}",
419
- "eager": ${config.eager},
420
- "strictVersion": ${config.strictVersion}
421
- }
422
- },\n`;
423
- return acc;
424
- }, '{') + '}';
425
- let exposesConfig = Object.entries(exposes).map(([exposeName, exposePath])=>`${JSON.stringify(exposeName)}: async () => await import('${exposePath}')`).join(',\n');
426
- exposesConfig = `{${exposesConfig}}`;
427
- const injectedContent = `
428
- export const moduleMap = '__MODULE_MAP__';
429
-
430
- function appendImportMap(importMap) {
431
- const script = document.createElement('script');
432
- script.type = 'importmap-shim';
433
- script.innerHTML = JSON.stringify(importMap);
434
- document.head.appendChild(script);
435
- }
436
-
437
- export const createVirtualRemoteModule = (name, ref, exports) => {
438
- const genExports = exports.map(e =>
439
- e === 'default' ? 'export default mfLsZJ92.default' : \`export const \${e} = mfLsZJ92[\${JSON.stringify(e)}];\`
440
- ).join('');
441
-
442
- const loadRef = \`const mfLsZJ92 = await container.loadRemote(\${JSON.stringify(ref)});\`;
443
-
444
- return \`
445
- const container = __FEDERATION__.__INSTANCES__.find(container => container.name === name) || __FEDERATION__.__INSTANCES__[0];
446
- \${loadRef}
447
- \${genExports}
448
- \`;
449
- };
450
-
451
- function encodeInlineESM(code) {
452
- const encodedCode = encodeURIComponent(code);
453
- return \`data:text/javascript;charset=utf-8,\${encodedCode}\`;
454
- }
455
-
456
- const runtimePlugin = () => ({
457
- name: 'import-maps-plugin',
458
- async init(args) {
459
-
460
- const remotePrefetch = args.options.remotes.map(async (remote) => {
461
- if (remote.type === 'esm') {
462
- await import(remote.entry);
463
- }
464
- });
465
-
466
-
467
- await Promise.all(remotePrefetch);
468
-
469
- const map = Object.keys(moduleMap).reduce((acc, expose) => {
470
- const importMap = importShim.getImportMap().imports;
471
- const key = args.origin.name + expose.replace('.', '');
472
- if (!importMap[key]) {
473
- const encodedModule = encodeInlineESM(
474
- createVirtualRemoteModule(args.origin.name, key, moduleMap[expose].exports)
475
- );
476
- acc[key] = encodedModule;
477
- }
478
- return acc;
479
- }, {});
480
- await importShim.addImportMap({ imports: map });
481
-
482
- return args;
483
- }
484
- });
485
-
486
- const createdContainer = await createContainer({
487
- name: ${JSON.stringify(name)},
488
- exposes: ${exposesConfig},
489
- remotes: ${JSON.stringify(remoteConfigs)},
490
- shared: ${sharedConfig},
491
- plugins: [runtimePlugin()],
492
- });
493
-
494
- export const get = createdContainer.get;
495
- export const init = createdContainer.init;
496
- `;
497
- //replace with createContainer from bundler runtime - import it in the string as a dep etc
498
- return [
499
- createContainerCode,
500
- injectedContent
501
- ].join('\n');
502
- };
503
- const createContainerPlugin = (config)=>({
504
- name: 'createContainer',
505
- setup (build) {
506
- const { filename } = config;
507
- const filter = new RegExp([
508
- filename
509
- ].map((name)=>`${name}$`).join('|'));
510
- const hasShared = Object.keys(config.shared || {}).length;
511
- const shared = Object.keys(config.shared || {}).map((name)=>`${name}$`).join('|');
512
- const sharedExternals = new RegExp(shared);
513
- build.onResolve({
514
- filter
515
- }, async (args)=>({
516
- path: args.path,
517
- namespace: 'container',
518
- pluginData: {
519
- kind: args.kind,
520
- resolveDir: args.resolveDir
521
- }
522
- }));
523
- build.onResolve({
524
- filter: /^federationShare/
525
- }, async (args)=>({
526
- path: args.path.replace('federationShare/', ''),
527
- namespace: 'esm-shares',
528
- pluginData: {
529
- kind: args.kind,
530
- resolveDir: args.resolveDir
531
- }
532
- }));
533
- if (hasShared) {
534
- build.onResolve({
535
- filter: sharedExternals
536
- }, (args)=>{
537
- if (args.namespace === 'esm-shares') return null;
538
- return {
539
- path: args.path,
540
- namespace: 'virtual-share-module',
541
- pluginData: {
542
- kind: args.kind,
543
- resolveDir: args.resolveDir
544
- }
545
- };
546
- });
547
- build.onResolve({
548
- filter: /.*/,
549
- namespace: 'esm-shares'
550
- }, async (args)=>{
551
- if (sharedExternals.test(args.path)) {
552
- return {
553
- path: args.path,
554
- namespace: 'virtual-share-module',
555
- pluginData: {
556
- kind: args.kind,
557
- resolveDir: args.resolveDir
558
- }
559
- };
560
- }
561
- return undefined;
562
- });
563
- }
564
- build.onLoad({
565
- filter,
566
- namespace: 'container'
567
- }, async (args)=>({
568
- contents: buildContainerHost(config),
569
- loader: 'js',
570
- resolveDir: args.pluginData.resolveDir
571
- }));
572
- }
573
- });
574
-
575
- // Builds the federation host code
576
- const buildFederationHost = (config)=>{
577
- const { name, remotes, shared } = config;
578
- const remoteConfigs = remotes ? JSON.stringify(Object.entries(remotes).map(([remoteAlias, remote])=>({
579
- name: remoteAlias,
580
- entry: remote,
581
- alias: remoteAlias,
582
- type: 'esm'
583
- }))) : '[]';
584
- const sharedConfig = Object.entries(shared != null ? shared : {}).reduce((acc, [pkg, config])=>{
585
- var _config_requiredVersion;
586
- const version = ((_config_requiredVersion = config.requiredVersion) == null ? void 0 : _config_requiredVersion.replace(/^[^0-9]/, '')) || '';
587
- acc += `${JSON.stringify(pkg)}: {
588
- "package": "${pkg}",
589
- "version": "${version}",
590
- "scope": "default",
591
- "get": async () => await import('federationShare/${pkg}'),
592
- "shareConfig": {
593
- "singleton": ${config.singleton},
594
- "requiredVersion": "${config.requiredVersion}",
595
- "eager": ${config.eager},
596
- "strictVersion": ${config.strictVersion}
597
- }
598
- },\n`;
599
- return acc;
600
- }, '{') + '}';
601
- return `
602
- import { init as initFederationHost } from "@module-federation/runtime";
603
-
604
- const createVirtualRemoteModule = (name, ref, exports) => {
605
- const genExports = exports.map(e =>
606
- e === 'default'
607
- ? 'export default mfLsZJ92.default;'
608
- : \`export const \${e} = mfLsZJ92[\${JSON.stringify(e)}];\`
609
- ).join('');
610
-
611
- const loadRef = \`const mfLsZJ92 = await container.loadRemote(\${JSON.stringify(ref)});\`;
612
-
613
- return \`
614
- const container = __FEDERATION__.__INSTANCES__.find(container => container.name === name) || __FEDERATION__.__INSTANCES__[0];
615
- \${loadRef}
616
- \${genExports}
617
- \`;
618
- };
619
-
620
- function encodeInlineESM(code) {
621
- return 'data:text/javascript;charset=utf-8,' + encodeURIComponent(code);
622
- }
623
-
624
- const runtimePlugin = () => ({
625
- name: 'import-maps-plugin',
626
- async init(args) {
627
- const remotePrefetch = args.options.remotes.map(async (remote) => {
628
- console.log('remote', remote);
629
- if (remote.type === 'esm') {
630
- await import(remote.entry);
631
- }
632
- });
633
-
634
- await Promise.all(remotePrefetch);
635
- if (typeof moduleMap !== 'undefined') {
636
- const map = Object.keys(moduleMap).reduce((acc, expose) => {
637
- const importMap = importShim.getImportMap().imports;
638
- const key = args.origin.name + expose.replace('.', '');
639
- if (!importMap[key]) {
640
- const encodedModule = encodeInlineESM(
641
- createVirtualRemoteModule(args.origin.name, key, moduleMap[expose].exports)
642
- );
643
- acc[key] = encodedModule;
644
- }
645
- return acc;
646
- }, {});
647
-
648
- await importShim.addImportMap({ imports: map });
649
- }
650
-
651
- return args;
652
- }
653
- });
654
-
655
- const mfHoZJ92 = initFederationHost({
656
- name: ${JSON.stringify(name)},
657
- remotes: ${remoteConfigs},
658
- shared: ${sharedConfig},
659
- plugins: [runtimePlugin()],
660
- });
661
-
662
- await Promise.all(mfHoZJ92.initializeSharing('default', 'version-first'));
663
-
664
-
665
- `;
666
- };
667
- const initializeHostPlugin = (config)=>({
668
- name: 'host-initialization',
669
- setup (build) {
670
- build.onResolve({
671
- filter: /federation-host/
672
- }, (args)=>({
673
- path: args.path,
674
- namespace: 'federation-host',
675
- pluginData: {
676
- kind: args.kind,
677
- resolveDir: args.resolveDir
678
- }
679
- }));
680
- build.onLoad({
681
- filter: /.*/,
682
- namespace: 'federation-host'
683
- }, async (args)=>({
684
- contents: buildFederationHost(config),
685
- resolveDir: args.pluginData.resolveDir
686
- }));
687
- // Add custom loaders
688
- const loaders = build.initialOptions.loader || {};
689
- // Apply custom loaders
690
- for (const [ext, loader] of Object.entries(loaders)){
691
- build.onLoad({
692
- filter: new RegExp(`\\${ext}$`),
693
- namespace: 'file'
694
- }, async (args)=>{
695
- const contents = await fs.promises.readFile(args.path, 'utf8');
696
- return {
697
- contents: buildFederationHost(config) + contents,
698
- loader
699
- };
700
- });
701
- }
702
- // Fallback loader for files not matched by custom loaders
703
- const fallbackFilter = new RegExp(Object.keys(loaders).map((ext)=>`\\${ext}$`).join('|'));
704
- build.onLoad({
705
- filter: /.*\.(ts|js|mjs)$/,
706
- namespace: 'file'
707
- }, //@ts-ignore
708
- async (args)=>{
709
- if (!fallbackFilter.test(args.path)) {
710
- if (!build.initialOptions.entryPoints.some((e)=>args.path.includes(e))) {
711
- return;
712
- }
713
- const contents = await fs.promises.readFile(args.path, 'utf8');
714
- return {
715
- contents: 'import "federation-host"; \n ' + contents
716
- };
717
- }
718
- });
719
- }
720
- });
721
-
722
- // relys on import map since i dont know the named exports of a remote to return.
723
- const createVirtualRemoteModule$1 = (name, ref)=>`
724
- export * from ${JSON.stringify('federationRemote/' + ref)}
725
- `;
726
- const linkRemotesPlugin = (config)=>({
727
- name: 'linkRemotes',
728
- setup (build) {
729
- const remotes = config.remotes || {};
730
- const filter = new RegExp(Object.keys(remotes).reduce((acc, key)=>{
731
- if (!key) return acc;
732
- acc.push(`^${key}`);
733
- return acc;
734
- }, []).join('|'));
735
- build.onResolve({
736
- filter: filter
737
- }, async (args)=>{
738
- return {
739
- path: args.path,
740
- namespace: 'remote-module'
741
- };
742
- });
743
- build.onResolve({
744
- filter: /^federationRemote/
745
- }, async (args)=>{
746
- return {
747
- path: args.path.replace('federationRemote/', ''),
748
- external: true,
749
- namespace: 'externals'
750
- };
751
- });
752
- build.onLoad({
753
- filter,
754
- namespace: 'remote-module'
755
- }, async (args)=>{
756
- return {
757
- contents: createVirtualRemoteModule$1(config.name, args.path),
758
- loader: 'js',
759
- resolveDir: path.dirname(args.path)
760
- };
761
- });
762
- }
763
- });
764
-
765
- // simplified from acorn (MIT license)
766
- function isNewLine(code) {
767
- return code === 10 || code === 13 || code === 0x2028 || code === 0x2029;
768
- }
769
- function codePointToString(ch) {
770
- if (ch <= 0xffff) return String.fromCharCode(ch);
771
- ch -= 0x10000;
772
- return String.fromCharCode((ch >> 10) + 0xd800, (ch & 0x03ff) + 0xdc00);
773
- }
774
- class Lexer {
775
- readString(input, pos) {
776
- if (pos >= input.length) return null;
777
- this.input = input;
778
- this.pos = pos;
779
- const quote = this.input.charCodeAt(pos);
780
- if (!(quote === 34 || quote === 39)) return null;
781
- let out = '';
782
- let chunkStart = ++this.pos;
783
- //eslint-disable-next-line no-constant-condition
784
- while(true){
785
- if (this.pos >= this.input.length) return null;
786
- const ch = this.input.charCodeAt(this.pos);
787
- if (ch === quote) break;
788
- if (ch === 92) {
789
- out += this.input.slice(chunkStart, this.pos);
790
- const escaped = this.readEscapedChar();
791
- if (escaped === null) return null;
792
- out += escaped;
793
- chunkStart = this.pos;
794
- } else {
795
- if (isNewLine(ch)) return null;
796
- ++this.pos;
797
- }
798
- }
799
- out += this.input.slice(chunkStart, this.pos++);
800
- return out;
801
- }
802
- readEscapedChar() {
803
- const ch = this.input.charCodeAt(++this.pos);
804
- let code;
805
- ++this.pos;
806
- switch(ch){
807
- case 110:
808
- return '\n';
809
- case 114:
810
- return '\r';
811
- case 120:
812
- code = this.readHexChar(2);
813
- if (code === null) return null;
814
- return String.fromCharCode(code);
815
- case 117:
816
- code = this.readCodePoint();
817
- if (code === null) return null;
818
- return codePointToString(code);
819
- case 116:
820
- return '\t';
821
- case 98:
822
- return '\b';
823
- case 118:
824
- return '\u000b';
825
- case 102:
826
- return '\f';
827
- //@ts-ignore
828
- case 13:
829
- if (this.input.charCodeAt(this.pos) === 10) {
830
- ++this.pos;
831
- }
832
- // fall through
833
- case 10:
834
- return '';
835
- case 56:
836
- case 57:
837
- return null;
838
- default:
839
- if (ch >= 48 && ch <= 55) {
840
- const match = this.input.slice(this.pos - 1, this.pos + 2).match(/^[0-7]+/);
841
- if (match === null) return null;
842
- let octalStr = match[0];
843
- let octal = parseInt(octalStr, 8);
844
- if (octal > 255) {
845
- octalStr = octalStr.slice(0, -1);
846
- octal = parseInt(octalStr, 8);
847
- }
848
- this.pos += octalStr.length - 1;
849
- const nextCh = this.input.charCodeAt(this.pos);
850
- if (octalStr !== '0' || nextCh === 56 || nextCh === 57) return null;
851
- return String.fromCharCode(octal);
852
- }
853
- if (isNewLine(ch)) return '';
854
- return String.fromCharCode(ch);
855
- }
856
- }
857
- readInt(radix, len) {
858
- const start = this.pos;
859
- let total = 0;
860
- for(let i = 0; i < len; ++i, ++this.pos){
861
- const code = this.input.charCodeAt(this.pos);
862
- let val;
863
- if (code >= 97) {
864
- val = code - 97 + 10;
865
- } else if (code >= 65) {
866
- val = code - 65 + 10;
867
- } else if (code >= 48 && code <= 57) {
868
- val = code - 48;
869
- } else {
870
- val = Infinity;
871
- }
872
- if (val >= radix) break;
873
- total = total * radix + val;
874
- }
875
- if (this.pos === start || len != null && this.pos - start !== len) return null;
876
- return total;
877
- }
878
- readHexChar(len) {
879
- return this.readInt(16, len);
880
- }
881
- readCodePoint() {
882
- const ch = this.input.charCodeAt(this.pos);
883
- let code;
884
- if (ch === 123) {
885
- ++this.pos;
886
- code = this.readHexChar(this.input.indexOf('}', this.pos) - this.pos);
887
- ++this.pos;
888
- if (code && code > 0x10ffff) return null;
889
- } else {
890
- code = this.readHexChar(4);
891
- }
892
- return code;
893
- }
894
- constructor(){
895
- this.input = '';
896
- this.pos = 0;
897
- }
898
- }
899
-
900
- function orderedUniq(array) {
901
- // prettier-ignore
902
- const ret = [], visited = new Set();
903
- for (const val of array)if (!visited.has(val)) visited.add(val), ret.push(val);
904
- return ret;
905
- }
906
- function cachedReduce(array, reducer, s) {
907
- // prettier-ignore
908
- const cache = [
909
- s
910
- ];
911
- let cacheLen = 1, last = s;
912
- return (len)=>{
913
- while(cacheLen <= len)cacheLen = cache.push(last = reducer(last, array[cacheLen - 1]));
914
- return cache[len];
915
- };
916
- }
917
- // from @rollup/pluginutils
918
- const reservedWords = 'break case class catch const continue debugger default delete do else export extends finally for function if import in instanceof let new return super switch this throw try typeof var void while with yield enum await implements package protected static interface private public';
919
- const builtin = 'arguments Infinity NaN undefined null true false eval uneval isFinite isNaN parseFloat parseInt decodeURI decodeURIComponent encodeURI encodeURIComponent escape unescape Object Function Boolean Symbol Error EvalError InternalError RangeError ReferenceError SyntaxError TypeError URIError Number Math Date String RegExp Array Int8Array Uint8Array Uint8ClampedArray Int16Array Uint16Array Int32Array Uint32Array Float32Array Float64Array Map Set WeakMap WeakSet SIMD ArrayBuffer DataView JSON Promise Generator GeneratorFunction Reflect Proxy Intl';
920
- const forbiddenIdentifiers = new Set(`${reservedWords} ${builtin}`.split(' '));
921
- forbiddenIdentifiers.add('');
922
- const makeLegalIdentifier = function makeLegalIdentifier(str) {
923
- let identifier = str.replace(/-(\w)/g, (_, letter)=>letter.toUpperCase()).replace(/[^$_a-zA-Z0-9]/g, '_');
924
- if (/\d/.test(identifier[0]) || forbiddenIdentifiers.has(identifier)) {
925
- identifier = `_${identifier}`;
926
- }
927
- return identifier || '_';
928
- };
929
-
930
- function commonjs({ filter = /\.c?js$/, transform = true, transformConfig, requireReturnsDefault = true, ignore } = {}) {
931
- const init_cjs_module_lexer = transform ? import('cjs-module-lexer') : undefined;
932
- const use_default_export = typeof requireReturnsDefault === 'function' ? requireReturnsDefault : (_path)=>requireReturnsDefault;
933
- const is_ignored = typeof ignore === 'function' ? ignore : Array.isArray(ignore) ? (path)=>ignore.includes(path) : ()=>false;
934
- return {
935
- name: 'commonjs',
936
- setup ({ onLoad, esbuild, initialOptions }) {
937
- let esbuild_shim;
938
- const require_esbuild = ()=>esbuild || esbuild_shim || (esbuild_shim = require('esbuild'));
939
- const read = fs.promises.readFile;
940
- const lexer = new Lexer();
941
- //@ts-ignore
942
- onLoad({
943
- filter: filter
944
- }, async (args)=>{
945
- let parseCJS;
946
- if (init_cjs_module_lexer) {
947
- const { init, parse } = await init_cjs_module_lexer;
948
- await init();
949
- parseCJS = parse;
950
- }
951
- let contents;
952
- try {
953
- //@ts-ignore
954
- contents = await read(args.path, 'utf8');
955
- } catch (e) {
956
- return null;
957
- }
958
- const willTransform = transform === true || typeof transform === 'function' && transform(args.path);
959
- let cjsExports;
960
- try {
961
- if (parseCJS && willTransform) {
962
- // move sourcemap to the end of the transformed file
963
- const sourcemapIndex = contents.lastIndexOf('//# sourceMappingURL=');
964
- let sourcemap;
965
- if (sourcemapIndex !== -1) {
966
- sourcemap = contents.slice(sourcemapIndex);
967
- const sourcemapEnd = sourcemap.indexOf('\n');
968
- if (sourcemapEnd !== -1 && sourcemap.slice(sourcemapEnd + 1).trimStart().length > 0) {
969
- // if there's code after sourcemap, it is invalid, don't do this.
970
- sourcemap = undefined;
971
- } else {
972
- contents = contents.slice(0, sourcemapIndex);
973
- }
974
- }
975
- // transform commonjs to es modules, easy mode
976
- cjsExports = parseCJS(contents);
977
- let { behavior, exports, sideEffects } = typeof willTransform === 'object' ? willTransform : {};
978
- var _transformConfig_behavior;
979
- behavior != null ? behavior : behavior = (_transformConfig_behavior = transformConfig == null ? void 0 : transformConfig.behavior) != null ? _transformConfig_behavior : 'node';
980
- exports = orderedUniq(cjsExports.exports.concat(exports != null ? exports : []));
981
- var _transformConfig_sideEffects;
982
- sideEffects != null ? sideEffects : sideEffects = (_transformConfig_sideEffects = transformConfig == null ? void 0 : transformConfig.sideEffects) != null ? _transformConfig_sideEffects : true;
983
- let exportDefault = behavior === 'node' ? 'export default exports;' : 'export default exports.__esModule ? exports.default : exports;';
984
- let exportsMap = exports.map((e)=>[
985
- e,
986
- makeLegalIdentifier(e)
987
- ]);
988
- if (exportsMap.some(([e])=>e === 'default')) {
989
- if (behavior === 'node') {
990
- exportsMap = exportsMap.filter(([e])=>e !== 'default');
991
- } else {
992
- exportDefault = '';
993
- }
994
- }
995
- const reexports = cjsExports.reexports.map((e)=>`export * from ${JSON.stringify(e)};`).join('');
996
- let transformed;
997
- if (sideEffects === false) {
998
- transformed = [
999
- // make sure we don't manipulate the first line so that sourcemap is fine
1000
- reexports + 'var mod, exports = /* @__PURE__ */ ((exports, module) => {' + contents,
1001
- 'return module.exports})((mod = { exports: {} }).exports, mod); ' + exportDefault
1002
- ];
1003
- if (exportsMap.length > 0) {
1004
- for (const [e, name] of exportsMap){
1005
- transformed.push(`var ${name} = /* @__PURE__ */ (() => exports[${JSON.stringify(e)}])();`);
1006
- }
1007
- transformed.push(`export { ${exportsMap.map(([e, name])=>e === name ? e : `${name} as ${JSON.stringify(e)}`).join(', ')} };`);
1008
- }
1009
- } else {
1010
- transformed = [
1011
- reexports + 'var exports = {}, module = { exports }; {' + contents,
1012
- '}; exports = module.exports; ' + exportDefault
1013
- ];
1014
- if (exportsMap.length > 0) {
1015
- transformed.push(`var { ${exportsMap.map(([e, name])=>e === name ? e : `${JSON.stringify(e)}: ${name}`).join(', ')} } = exports;`, `export { ${exportsMap.map(([e, name])=>e === name ? e : `${name} as ${JSON.stringify(e)}`).join(', ')} };`);
1016
- }
1017
- }
1018
- contents = transformed.join('\n') + (sourcemap ? '\n' + sourcemap : '');
1019
- }
1020
- } catch (e) {
1021
- return null;
1022
- }
1023
- function makeName(path) {
1024
- let name = `__import_${makeLegalIdentifier(path)}`;
1025
- if (contents.includes(name)) {
1026
- let suffix = 2;
1027
- while(contents.includes(`${name}${suffix}`))suffix++;
1028
- name = `${name}${suffix}`;
1029
- }
1030
- return name;
1031
- }
1032
- let warnings;
1033
- try {
1034
- ({ warnings } = await require_esbuild().transform(contents, {
1035
- format: 'esm',
1036
- logLevel: 'silent'
1037
- }));
1038
- } catch (err) {
1039
- ({ warnings } = err);
1040
- }
1041
- const lines = contents.split('\n');
1042
- const getOffset = cachedReduce(lines, (a, b)=>a + 1 + b.length, 0);
1043
- if (warnings && (warnings = warnings.filter((e)=>e.text.includes('"require" to "esm"'))).length) {
1044
- const edits = [];
1045
- let imports = [];
1046
- for (const { location } of warnings){
1047
- if (location === null) continue;
1048
- const { line, lineText, column, length } = location;
1049
- const leftBrace = column + length + 1;
1050
- const path = lexer.readString(lineText, leftBrace);
1051
- if (path === null || is_ignored(path)) continue;
1052
- const rightBrace = lineText.indexOf(')', leftBrace + 2 + path.length) + 1;
1053
- const name = makeName(path);
1054
- let import_statement;
1055
- if (use_default_export(path)) {
1056
- import_statement = `import ${name} from ${JSON.stringify(path)};`;
1057
- } else {
1058
- import_statement = `import * as ${name} from ${JSON.stringify(path)};`;
1059
- }
1060
- const offset = getOffset(line - 1);
1061
- edits.push([
1062
- offset + column,
1063
- offset + rightBrace,
1064
- name
1065
- ]);
1066
- imports.push(import_statement);
1067
- }
1068
- if (imports.length === 0) return null;
1069
- imports = orderedUniq(imports);
1070
- let offset = 0;
1071
- for (const [start, end, name] of edits){
1072
- contents = contents.slice(0, start + offset) + name + contents.slice(end + offset);
1073
- offset += name.length - (end - start);
1074
- }
1075
- // if we have transformed this module (i.e. having `cjsExports`), don't make the file commonjs
1076
- contents = [
1077
- ...imports,
1078
- cjsExports ? 'exports;' : '',
1079
- contents
1080
- ].join('');
1081
- return {
1082
- contents
1083
- };
1084
- }
1085
- });
1086
- }
1087
- };
1088
- }
1089
-
1090
- function _extends() {
1091
- _extends = Object.assign || function(target) {
1092
- for(var i = 1; i < arguments.length; i++){
1093
- var source = arguments[i];
1094
- for(var key in source){
1095
- if (Object.prototype.hasOwnProperty.call(source, key)) {
1096
- target[key] = source[key];
1097
- }
1098
- }
1099
- }
1100
- return target;
1101
- };
1102
- return _extends.apply(this, arguments);
1103
- }
1104
- // Creates a virtual module for sharing dependencies
1105
- const createVirtualShareModule = (name, ref, exports)=>`
1106
- const container = __FEDERATION__.__INSTANCES__.find(container => container.name === ${JSON.stringify(name)}) || __FEDERATION__.__INSTANCES__[0]
1107
-
1108
- const mfLsZJ92 = await container.loadShare(${JSON.stringify(ref)})
1109
-
1110
- ${exports.map((e)=>e === 'default' ? `export default mfLsZJ92.default` : `export const ${e} = mfLsZJ92[${JSON.stringify(e)}];`).join('\n')}
1111
- `;
1112
- const createVirtualRemoteModule = (name, ref)=>`
1113
- export * from ${JSON.stringify('federationRemote/' + ref)}
1114
- `;
1115
- // Plugin to transform CommonJS modules to ESM
1116
- const cjsToEsmPlugin = {
1117
- name: 'cjs-to-esm',
1118
- setup (build) {
1119
- build.onLoad({
1120
- filter: /.*/,
1121
- namespace: 'esm-shares'
1122
- }, async (args)=>{
1123
- var _build_initialOptions_external;
1124
- let esbuild_shim;
1125
- const require_esbuild = ()=>build.esbuild || esbuild_shim || (esbuild_shim = require('esbuild'));
1126
- const packageBuilder = await require_esbuild().build(_extends({}, build.initialOptions, {
1127
- external: (_build_initialOptions_external = build.initialOptions.external) == null ? void 0 : _build_initialOptions_external.filter((e)=>{
1128
- if (e.includes('*')) {
1129
- const prefix = e.split('*')[0];
1130
- return !args.path.startsWith(prefix);
1131
- }
1132
- return e !== args.path;
1133
- }),
1134
- entryPoints: [
1135
- args.path
1136
- ],
1137
- plugins: [
1138
- commonjs({
1139
- filter: /.*/
1140
- })
1141
- ],
1142
- write: false
1143
- }));
1144
- return {
1145
- contents: packageBuilder.outputFiles[0].text,
1146
- loader: 'js',
1147
- resolveDir: args.pluginData.resolveDir
1148
- };
1149
- });
1150
- }
1151
- };
1152
- // Plugin to link shared dependencies
1153
- const linkSharedPlugin = (config)=>({
1154
- name: 'linkShared',
1155
- setup (build) {
1156
- const filter = new RegExp(Object.keys(config.shared || {}).map((name)=>`${name}$`).join('|'));
1157
- build.onResolve({
1158
- filter
1159
- }, (args)=>{
1160
- if (args.namespace === 'esm-shares') return null;
1161
- return {
1162
- path: args.path,
1163
- namespace: 'virtual-share-module',
1164
- pluginData: {
1165
- kind: args.kind,
1166
- resolveDir: args.resolveDir
1167
- }
1168
- };
1169
- });
1170
- build.onResolve({
1171
- filter: /.*/,
1172
- namespace: 'esm-shares'
1173
- }, (args)=>{
1174
- if (filter.test(args.path)) {
1175
- return {
1176
- path: args.path,
1177
- namespace: 'virtual-share-module',
1178
- pluginData: {
1179
- kind: args.kind,
1180
- resolveDir: args.resolveDir
1181
- }
1182
- };
1183
- }
1184
- if (filter.test(args.importer)) {
1185
- return {
1186
- path: args.path,
1187
- namespace: 'esm-shares',
1188
- pluginData: {
1189
- kind: args.kind,
1190
- resolveDir: args.resolveDir
1191
- }
1192
- };
1193
- }
1194
- return undefined;
1195
- });
1196
- build.onResolve({
1197
- filter: /^federationShare/
1198
- }, async (args)=>({
1199
- path: args.path.replace('federationShare/', ''),
1200
- namespace: 'esm-shares',
1201
- pluginData: {
1202
- kind: args.kind,
1203
- resolveDir: args.resolveDir
1204
- }
1205
- }));
1206
- build.onLoad({
1207
- filter,
1208
- namespace: 'virtual-share-module'
1209
- }, async (args)=>{
1210
- const exp = await getExports(args.path);
1211
- return {
1212
- contents: createVirtualShareModule(config.name, args.path, exp),
1213
- loader: 'js',
1214
- resolveDir: path.dirname(args.path)
1215
- };
1216
- });
1217
- }
1218
- });
1219
- // Main module federation plugin
1220
- const moduleFederationPlugin = (config)=>({
1221
- name: 'module-federation',
1222
- setup (build) {
1223
- build.initialOptions.metafile = true;
1224
- const externals = getExternals.getExternals(config);
1225
- if (build.initialOptions.external) {
1226
- build.initialOptions.external = [
1227
- ...new Set([
1228
- ...build.initialOptions.external,
1229
- ...externals
1230
- ])
1231
- ];
1232
- } else {
1233
- build.initialOptions.external = externals;
1234
- }
1235
- const pluginStack = [];
1236
- const remotes = Object.keys(config.remotes || {}).length;
1237
- const shared = Object.keys(config.shared || {}).length;
1238
- const exposes = Object.keys(config.exposes || {}).length;
1239
- const entryPoints = build.initialOptions.entryPoints;
1240
- const filename = config.filename || 'remoteEntry.js';
1241
- if (remotes) {
1242
- pluginStack.push(linkRemotesPlugin(config));
1243
- }
1244
- if (shared) {
1245
- pluginStack.push(linkSharedPlugin(config));
1246
- }
1247
- if (!entryPoints) {
1248
- build.initialOptions.entryPoints = [];
1249
- }
1250
- if (exposes) {
1251
- if (Array.isArray(entryPoints)) {
1252
- entryPoints.push(filename);
1253
- } else if (entryPoints && typeof entryPoints === 'object') {
1254
- entryPoints[filename] = filename;
1255
- } else {
1256
- build.initialOptions.entryPoints = [
1257
- filename
1258
- ];
1259
- }
1260
- }
1261
- [
1262
- initializeHostPlugin(config),
1263
- createContainerPlugin(config),
1264
- cjsToEsmPlugin,
1265
- ...pluginStack
1266
- ].forEach((plugin)=>plugin.setup(build));
1267
- build.onEnd(async (result)=>{
1268
- if (!result.metafile) return;
1269
- if (exposes) {
1270
- const exposedConfig = config.exposes || {};
1271
- const remoteFile = config.filename;
1272
- const exposedEntries = {};
1273
- const outputMapWithoutExt = Object.entries(result.metafile.outputs).reduce((acc, [chunkKey, chunkValue])=>{
1274
- //@ts-ignore
1275
- const { entryPoint } = chunkValue;
1276
- const key = entryPoint || chunkKey;
1277
- const trimKey = key.substring(0, key.lastIndexOf('.')) || key;
1278
- //@ts-ignore
1279
- acc[trimKey] = _extends({}, chunkValue, {
1280
- chunk: chunkKey
1281
- });
1282
- return acc;
1283
- }, {});
1284
- for (const [expose, value] of Object.entries(exposedConfig)){
1285
- const exposedFound = //@ts-ignore
1286
- outputMapWithoutExt[value.replace('./', '')] || //@ts-ignore
1287
- outputMapWithoutExt[expose.replace('./', '')];
1288
- if (exposedFound) {
1289
- exposedEntries[expose] = {
1290
- entryPoint: exposedFound.entryPoint,
1291
- exports: exposedFound.exports
1292
- };
1293
- }
1294
- }
1295
- for (const [outputPath, value] of Object.entries(result.metafile.outputs)){
1296
- if (!value.entryPoint) continue;
1297
- if (!value.entryPoint.startsWith('container:')) continue;
1298
- if (!value.entryPoint.endsWith(remoteFile)) continue;
1299
- const container = fs.readFileSync(outputPath, 'utf-8');
1300
- const withExports = container.replace('"__MODULE_MAP__"', `${JSON.stringify(exposedEntries)}`).replace("'__MODULE_MAP__'", `${JSON.stringify(exposedEntries)}`);
1301
- fs.writeFileSync(outputPath, withExports, 'utf-8');
1302
- }
1303
- }
1304
- await writeRemoteManifest(config, result);
1305
- console.log(`build ended with ${result.errors.length} errors`);
1306
- });
1307
- }
1308
- });
1309
-
1310
- exports.createVirtualRemoteModule = createVirtualRemoteModule;
1311
- exports.createVirtualShareModule = createVirtualShareModule;
1312
- exports.moduleFederationPlugin = moduleFederationPlugin;
1313
- //# sourceMappingURL=plugin.cjs.js.map