@module-federation/esbuild 0.0.0-next-20240523224941

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.
@@ -0,0 +1,1086 @@
1
+ import esbuild$1 from 'esbuild';
2
+ import { rollup } from 'rollup';
3
+ import pluginNodeResolve from '@rollup/plugin-node-resolve';
4
+ import { externals } from 'rollup-plugin-node-externals';
5
+ import fs__default from 'fs';
6
+ import path__default from 'path';
7
+ import commonjs from '@rollup/plugin-commonjs';
8
+ import replace from '@rollup/plugin-replace';
9
+ import 'acorn';
10
+ import { promisify } from 'util';
11
+ import enhancedResolve from 'enhanced-resolve';
12
+ import * as moduleLexer from 'cjs-module-lexer';
13
+ import { f as federationBuilder } from './federation-builder.esm.js';
14
+ import 'npmlog';
15
+
16
+ function getAugmentedNamespace(n) {
17
+ if (n.__esModule) return n;
18
+ var a = Object.defineProperty({}, '__esModule', {
19
+ value: true
20
+ });
21
+ Object.keys(n).forEach(function(k) {
22
+ var d = Object.getOwnPropertyDescriptor(n, k);
23
+ Object.defineProperty(a, k, d.get ? d : {
24
+ enumerable: true,
25
+ get: function get() {
26
+ return n[k];
27
+ }
28
+ });
29
+ });
30
+ return a;
31
+ }
32
+
33
+ const resolve = promisify(enhancedResolve.create({
34
+ mainFields: [
35
+ 'browser',
36
+ 'module',
37
+ 'main'
38
+ ]
39
+ }));
40
+ let lexerInitialized = false;
41
+ async function getExports(modulePath) {
42
+ if (!lexerInitialized) {
43
+ await moduleLexer.init();
44
+ lexerInitialized = true;
45
+ }
46
+ try {
47
+ const exports = [];
48
+ const paths = [];
49
+ const resolvedPath = await resolve(process.cwd(), modulePath);
50
+ if (typeof resolvedPath === 'string') {
51
+ paths.push(resolvedPath);
52
+ }
53
+ while(paths.length > 0){
54
+ const currentPath = paths.pop();
55
+ if (currentPath) {
56
+ const results = moduleLexer.parse(await fs__default.readFileSync(currentPath, 'utf8'));
57
+ exports.push(...results.exports);
58
+ for (const reexport of results.reexports){
59
+ const resolvedPath = await resolve(path__default.dirname(currentPath), reexport);
60
+ if (typeof resolvedPath === 'string') {
61
+ paths.push(resolvedPath);
62
+ }
63
+ }
64
+ }
65
+ }
66
+ /**
67
+ * 追加default
68
+ */ if (!exports.includes('default')) {
69
+ exports.push('default');
70
+ }
71
+ return exports;
72
+ } catch (e) {
73
+ console.log(e);
74
+ return [
75
+ 'default'
76
+ ];
77
+ }
78
+ }
79
+
80
+ var version = "0.0.1";
81
+
82
+ function _extends$2() {
83
+ _extends$2 = Object.assign || function(target) {
84
+ for(var i = 1; i < arguments.length; i++){
85
+ var source = arguments[i];
86
+ for(var key in source){
87
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
88
+ target[key] = source[key];
89
+ }
90
+ }
91
+ }
92
+ return target;
93
+ };
94
+ return _extends$2.apply(this, arguments);
95
+ }
96
+ const writeRemoteManifest = async (config, result)=>{
97
+ if (result.errors && result.errors.length > 0) {
98
+ console.warn('Build errors detected, skipping writeRemoteManifest.');
99
+ return;
100
+ }
101
+ let packageJson;
102
+ try {
103
+ const packageJsonPath = await resolve(process.cwd(), '/package.json') || '';
104
+ packageJson = require(packageJsonPath);
105
+ } catch (e) {
106
+ packageJson = {
107
+ name: config.name
108
+ };
109
+ }
110
+ const mfConfig = config;
111
+ var _process_env_NODE_ENV;
112
+ const envType = process.env['NODE_ENV'] === 'development' ? 'local' : (_process_env_NODE_ENV = process.env['NODE_ENV']) != null ? _process_env_NODE_ENV : '';
113
+ const publicPath = config.publicPath || 'auto';
114
+ let containerName = '';
115
+ const outputMap = Object.entries(result.metafile.outputs).reduce((acc, [chunkKey, chunkValue])=>{
116
+ const { entryPoint } = chunkValue;
117
+ const key = entryPoint || chunkKey;
118
+ if (key.startsWith('container:') && key.endsWith(mfConfig.filename)) {
119
+ containerName = key;
120
+ }
121
+ acc[key] = _extends$2({}, chunkValue, {
122
+ chunk: chunkKey
123
+ });
124
+ return acc;
125
+ }, {});
126
+ if (!outputMap[containerName]) return;
127
+ const outputMapWithoutExt = Object.entries(result.metafile.outputs).reduce((acc, [chunkKey, chunkValue])=>{
128
+ const { entryPoint } = chunkValue;
129
+ const key = entryPoint || chunkKey;
130
+ const trimKey = key.substring(0, key.lastIndexOf('.')) || key;
131
+ acc[trimKey] = _extends$2({}, chunkValue, {
132
+ chunk: chunkKey
133
+ });
134
+ return acc;
135
+ }, {});
136
+ const getChunks = (meta, outputMap)=>{
137
+ const assets = {
138
+ js: {
139
+ async: [],
140
+ sync: []
141
+ },
142
+ css: {
143
+ async: [],
144
+ sync: []
145
+ }
146
+ };
147
+ if (meta == null ? void 0 : meta.imports) {
148
+ meta.imports.forEach((imp)=>{
149
+ const importMeta = outputMap[imp.path];
150
+ if (importMeta && importMeta.kind !== 'dynamic-import') {
151
+ const childAssets = getChunks(importMeta, outputMap);
152
+ assets.js.async.push(...childAssets.js.async);
153
+ assets.js.sync.push(...childAssets.js.sync);
154
+ assets.css.async.push(...childAssets.css.async);
155
+ assets.css.sync.push(...childAssets.css.sync);
156
+ }
157
+ });
158
+ const assetType = meta.chunk.endsWith('.js') ? 'js' : 'css';
159
+ const syncOrAsync = meta.kind === 'dynamic-import' ? 'async' : 'sync';
160
+ assets[assetType][syncOrAsync].push(meta.chunk);
161
+ }
162
+ return assets;
163
+ };
164
+ const shared = mfConfig.shared ? await Promise.all(Object.entries(mfConfig.shared).map(async ([pkg, config])=>{
165
+ const meta = outputMap['esm-shares:' + pkg];
166
+ const chunks = getChunks(meta, outputMap);
167
+ let { version } = config;
168
+ if (!version) {
169
+ try {
170
+ const packageJsonPath = await resolve(process.cwd(), `${pkg}/package.json`);
171
+ if (packageJsonPath) {
172
+ version = JSON.parse(fs__default.readFileSync(packageJsonPath, 'utf-8')).version;
173
+ }
174
+ } catch (e) {
175
+ console.warn(`Can't resolve ${pkg} version automatically, consider setting "version" manually`);
176
+ }
177
+ }
178
+ return {
179
+ id: `${mfConfig.name}:${pkg}`,
180
+ name: pkg,
181
+ version: version || config.version,
182
+ singleton: config.singleton || false,
183
+ requiredVersion: config.requiredVersion || '*',
184
+ assets: chunks
185
+ };
186
+ })) : [];
187
+ const remotes = mfConfig.remotes ? Object.entries(mfConfig.remotes).map(([alias, remote])=>{
188
+ const [federationContainerName, entry] = remote.includes('@') ? remote.split('@') : [
189
+ alias,
190
+ remote
191
+ ];
192
+ return {
193
+ federationContainerName,
194
+ moduleName: '',
195
+ alias,
196
+ entry
197
+ };
198
+ }) : [];
199
+ const exposes = mfConfig.exposes ? await Promise.all(Object.entries(mfConfig.exposes).map(async ([expose, value])=>{
200
+ const exposedFound = outputMapWithoutExt[value.replace('./', '')];
201
+ const chunks = getChunks(exposedFound, outputMap);
202
+ return {
203
+ id: `${mfConfig.name}:${expose.replace(/^\.\//, '')}`,
204
+ name: expose.replace(/^\.\//, ''),
205
+ assets: chunks,
206
+ path: expose
207
+ };
208
+ })) : [];
209
+ const types = {
210
+ path: '',
211
+ name: '',
212
+ zip: '@mf-types.zip',
213
+ api: '@mf-types.d.ts'
214
+ };
215
+ var _packageJson_name;
216
+ const manifest = {
217
+ id: mfConfig.name,
218
+ name: mfConfig.name,
219
+ metaData: {
220
+ name: mfConfig.name,
221
+ type: 'app',
222
+ buildInfo: {
223
+ buildVersion: envType,
224
+ buildName: ((_packageJson_name = packageJson.name) != null ? _packageJson_name : 'default').replace(/[^a-zA-Z0-9]/g, '_')
225
+ },
226
+ remoteEntry: {
227
+ name: mfConfig.filename,
228
+ path: outputMap[containerName] ? path__default.dirname(outputMap[containerName].chunk) : '',
229
+ type: 'esm'
230
+ },
231
+ types,
232
+ globalName: mfConfig.name,
233
+ pluginVersion: version,
234
+ publicPath
235
+ },
236
+ shared,
237
+ remotes,
238
+ exposes
239
+ };
240
+ const manifestPath = path__default.join(path__default.dirname(outputMap[containerName].chunk), 'mf-manifest.json');
241
+ fs__default.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2), 'utf-8');
242
+ };
243
+
244
+ const createContainerCode = `
245
+ import bundler_runtime_base from '@module-federation/webpack-bundler-runtime';
246
+ // import instantiatePatch from "./federation.js";
247
+
248
+ const createContainer = (federationOptions) => {
249
+ // await instantiatePatch(federationOptions, true);
250
+ const {exposes, name, remotes = [], shared, plugins} = federationOptions;
251
+
252
+ const __webpack_modules__ = {
253
+ "./node_modules/.federation/entry.1f2288102e035e2ed66b2efaf60ad043.js": (module, __webpack_exports__, __webpack_require__) => {
254
+ __webpack_require__.r(__webpack_exports__);
255
+ const bundler_runtime = __webpack_require__.n(bundler_runtime_base);
256
+ const prevFederation = __webpack_require__.federation;
257
+ __webpack_require__.federation = {};
258
+ for (const key in bundler_runtime()) {
259
+ __webpack_require__.federation[key] = bundler_runtime()[key];
260
+ }
261
+ for (const key in prevFederation) {
262
+ __webpack_require__.federation[key] = prevFederation[key];
263
+ }
264
+ if (!__webpack_require__.federation.instance) {
265
+ const pluginsToAdd = plugins || [];
266
+ __webpack_require__.federation.initOptions.plugins = __webpack_require__.federation.initOptions.plugins ?
267
+ __webpack_require__.federation.initOptions.plugins.concat(pluginsToAdd) : pluginsToAdd;
268
+ __webpack_require__.federation.instance = __webpack_require__.federation.runtime.init(__webpack_require__.federation.initOptions);
269
+ if (__webpack_require__.federation.attachShareScopeMap) {
270
+ __webpack_require__.federation.attachShareScopeMap(__webpack_require__);
271
+ }
272
+ if (__webpack_require__.federation.installInitialConsumes) {
273
+ __webpack_require__.federation.installInitialConsumes();
274
+ }
275
+ }
276
+ },
277
+
278
+ "webpack/container/entry/createContainer": (module, exports, __webpack_require__) => {
279
+ const moduleMap = {};
280
+ for (const key in exposes) {
281
+ if (Object.prototype.hasOwnProperty.call(exposes, key)) {
282
+ moduleMap[key] = () => Promise.resolve(exposes[key]()).then(m => () => m);
283
+ }
284
+ }
285
+
286
+ const get = (module, getScope) => {
287
+ __webpack_require__.R = getScope;
288
+ getScope = (
289
+ __webpack_require__.o(moduleMap, module)
290
+ ? moduleMap[module]()
291
+ : Promise.resolve().then(() => {
292
+ throw new Error("Module '" + module + "' does not exist in container.");
293
+ })
294
+ );
295
+ __webpack_require__.R = undefined;
296
+ return getScope;
297
+ };
298
+ const init = (shareScope, initScope, remoteEntryInitOptions) => {
299
+ return __webpack_require__.federation.bundlerRuntime.initContainerEntry({
300
+ webpackRequire: __webpack_require__,
301
+ shareScope: shareScope,
302
+ initScope: initScope,
303
+ remoteEntryInitOptions: remoteEntryInitOptions,
304
+ shareScopeKey: "default"
305
+ });
306
+ };
307
+ __webpack_require__("./node_modules/.federation/entry.1f2288102e035e2ed66b2efaf60ad043.js");
308
+
309
+ // This exports getters to disallow modifications
310
+ __webpack_require__.d(exports, {
311
+ get: () => get,
312
+ init: () => init,
313
+ moduleMap: () => moduleMap,
314
+ });
315
+ }
316
+ };
317
+
318
+ const __webpack_module_cache__ = {};
319
+
320
+ const __webpack_require__ = (moduleId) => {
321
+ let cachedModule = __webpack_module_cache__[moduleId];
322
+ if (cachedModule !== undefined) {
323
+ return cachedModule.exports;
324
+ }
325
+ let module = __webpack_module_cache__[moduleId] = {
326
+ id: moduleId,
327
+ loaded: false,
328
+ exports: {}
329
+ };
330
+
331
+ const execOptions = {
332
+ id: moduleId,
333
+ module: module,
334
+ factory: __webpack_modules__[moduleId],
335
+ require: __webpack_require__
336
+ };
337
+ __webpack_require__.i.forEach(handler => {
338
+ handler(execOptions);
339
+ });
340
+ module = execOptions.module;
341
+ execOptions.factory.call(module.exports, module, module.exports, execOptions.require);
342
+
343
+ module.loaded = true;
344
+
345
+ return module.exports;
346
+ };
347
+
348
+ __webpack_require__.m = __webpack_modules__;
349
+ __webpack_require__.c = __webpack_module_cache__;
350
+ __webpack_require__.i = [];
351
+
352
+ if (!__webpack_require__.federation) {
353
+ __webpack_require__.federation = {
354
+ initOptions: {
355
+ "name": name,
356
+ "remotes": remotes.map(remote => ({
357
+ "type": remote.type,
358
+ "alias": remote.alias,
359
+ "name": remote.name,
360
+ "entry": remote.entry,
361
+ "shareScope": remote.shareScope || "default"
362
+ }))
363
+ },
364
+ chunkMatcher: () => true,
365
+ rootOutputDir: "",
366
+ initialConsumes: undefined,
367
+ bundlerRuntimeOptions: {}
368
+ };
369
+ }
370
+
371
+ __webpack_require__.n = (module) => {
372
+ const getter = module && module.__esModule ? () => module['default'] : () => module;
373
+ __webpack_require__.d(getter, {a: getter});
374
+ return getter;
375
+ };
376
+
377
+ __webpack_require__.d = (exports, definition) => {
378
+ for (const key in definition) {
379
+ if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
380
+ Object.defineProperty(exports, key, {enumerable: true, get: definition[key]});
381
+ }
382
+ }
383
+ };
384
+
385
+ __webpack_require__.f = {};
386
+
387
+ __webpack_require__.g = (() => {
388
+ if (typeof globalThis === 'object') return globalThis;
389
+ try {
390
+ return this || new Function('return this')();
391
+ } catch (e) {
392
+ if (typeof window === 'object') return window;
393
+ }
394
+ })();
395
+
396
+ __webpack_require__.o = (obj, prop) => Object.prototype.hasOwnProperty.call(obj, prop);
397
+
398
+ __webpack_require__.r = (exports) => {
399
+ if (typeof Symbol !== 'undefined' && Symbol.toStringTag) {
400
+ Object.defineProperty(exports, Symbol.toStringTag, {value: 'Module'});
401
+ }
402
+ Object.defineProperty(exports, '__esModule', {value: true});
403
+ };
404
+
405
+ __webpack_require__.federation.initOptions.shared = shared;
406
+ __webpack_require__.S = {};
407
+ const initPromises = {};
408
+ const initTokens = {};
409
+ __webpack_require__.I = (name, initScope) => {
410
+ return __webpack_require__.federation.bundlerRuntime.I({
411
+ shareScopeName: name,
412
+ webpackRequire: __webpack_require__,
413
+ initPromises: initPromises,
414
+ initTokens: initTokens,
415
+ initScope: initScope,
416
+ });
417
+ };
418
+
419
+ const __webpack_exports__ = __webpack_require__("webpack/container/entry/createContainer");
420
+ const __webpack_exports__get = __webpack_exports__.get;
421
+ const __webpack_exports__init = __webpack_exports__.init;
422
+ const __webpack_exports__moduleMap = __webpack_exports__.moduleMap;
423
+ return __webpack_exports__;
424
+ }`;
425
+
426
+ //replace with createContainer from bundler runtime
427
+ //@ts-ignore
428
+ const buildContainerHost = ({ config })=>{
429
+ const { name, remotes = {}, shared = {}, exposes = {} } = config;
430
+ const remoteConfigs = Object.entries(remotes).map(([remoteAlias, remote])=>({
431
+ type: 'esm',
432
+ name: remoteAlias,
433
+ entry: remote.entry,
434
+ alias: remoteAlias
435
+ }));
436
+ const sharedConfig = Object.entries(shared).reduce((acc, [pkg, config])=>{
437
+ var _config_requiredVersion;
438
+ const version = ((_config_requiredVersion = config.requiredVersion) == null ? void 0 : _config_requiredVersion.replace(/^[^0-9]/, '')) || '';
439
+ acc += `${JSON.stringify(pkg)}: {
440
+ "package": "${pkg}",
441
+ "version": "${version}",
442
+ "scope": "default",
443
+ "get": async () => import('federationShare/${pkg}'),
444
+ "shareConfig": {
445
+ "singleton": ${config.singleton},
446
+ "requiredVersion": "${config.requiredVersion}",
447
+ "eager": ${config.eager},
448
+ "strictVersion": ${config.strictVersion}
449
+ }
450
+ },\n`;
451
+ return acc;
452
+ }, '{') + '}';
453
+ let exposesConfig = Object.entries(exposes).map(([exposeName, exposePath])=>`${JSON.stringify(exposeName)}: async () => await import('${exposePath}')`).join(',\n');
454
+ exposesConfig = `{${exposesConfig}}`;
455
+ const injectedContent = `
456
+ export const moduleMap = '__MODULE_MAP__';
457
+
458
+ function appendImportMap(importMap) {
459
+ const script = document.createElement('script');
460
+ script.type = 'importmap-shim';
461
+ script.innerHTML = JSON.stringify(importMap);
462
+ document.head.appendChild(script);
463
+ }
464
+
465
+ export const createVirtualRemoteModule = (name, ref, exports) => {
466
+ const genExports = exports.map(e =>
467
+ e === 'default' ? 'export default mfLsZJ92.default' : \`export const \${e} = mfLsZJ92[\${JSON.stringify(e)}];\`
468
+ ).join('');
469
+
470
+ const loadRef = \`const mfLsZJ92 = await container.loadRemote(\${JSON.stringify(ref)});\`;
471
+
472
+ return \`
473
+ const container = __FEDERATION__.__INSTANCES__.find(container => container.name === name) || __FEDERATION__.__INSTANCES__[0];
474
+ \${loadRef}
475
+ \${genExports}
476
+ \`;
477
+ };
478
+
479
+ function encodeInlineESM(code) {
480
+ const encodedCode = encodeURIComponent(code);
481
+ return \`data:text/javascript;charset=utf-8,\${encodedCode}\`;
482
+ }
483
+
484
+ const runtimePlugin = () => ({
485
+ name: 'import-maps-plugin',
486
+ async init(args) {
487
+ const remotePrefetch = args.options.remotes.map(async (remote) => {
488
+ if (remote.type === 'esm') {
489
+ await import(remote.entry);
490
+ }
491
+ });
492
+
493
+
494
+ await Promise.all(remotePrefetch);
495
+
496
+ console.log('module map',moduleMap);
497
+ const map = Object.keys(moduleMap).reduce((acc, expose) => {
498
+ const importMap = importShim.getImportMap().imports;
499
+ const key = args.origin.name + expose.replace('.', '');
500
+ if (!importMap[key]) {
501
+ const encodedModule = encodeInlineESM(
502
+ createVirtualRemoteModule(args.origin.name, key, moduleMap[expose].exports)
503
+ );
504
+ acc[key] = encodedModule;
505
+ }
506
+ return acc;
507
+ }, {});
508
+ await importShim.addImportMap({ imports: map });
509
+ console.log('final map', importShim.getImportMap());
510
+
511
+ return args;
512
+ }
513
+ });
514
+
515
+ const createdContainer = await createContainer({
516
+ name: ${JSON.stringify(name)},
517
+ exposes: ${exposesConfig},
518
+ remotes: ${JSON.stringify(remoteConfigs)},
519
+ shared: ${sharedConfig},
520
+ plugins: [runtimePlugin()],
521
+ });
522
+
523
+ export const get = createdContainer.get;
524
+ export const init = createdContainer.init;
525
+ `;
526
+ //replace with createContainer from bundler runtime - import it in the string as a dep etc
527
+ return [
528
+ createContainerCode,
529
+ injectedContent
530
+ ].join('\n');
531
+ };
532
+ const createContainerPlugin = (config)=>({
533
+ name: 'createContainer',
534
+ setup (build) {
535
+ const { externals, config: { filename } } = config;
536
+ const filter = new RegExp([
537
+ filename
538
+ ].map((name)=>`${name}$`).join('|'));
539
+ const sharedExternals = new RegExp(externals.map((name)=>`${name}$`).join('|'));
540
+ build.onResolve({
541
+ filter
542
+ }, async (args)=>({
543
+ path: args.path,
544
+ namespace: 'container',
545
+ pluginData: {
546
+ kind: args.kind,
547
+ resolveDir: args.resolveDir
548
+ }
549
+ }));
550
+ build.onResolve({
551
+ filter: /^federationShare/
552
+ }, async (args)=>({
553
+ path: args.path.replace('federationShare/', ''),
554
+ namespace: 'esm-shares',
555
+ pluginData: {
556
+ kind: args.kind,
557
+ resolveDir: args.resolveDir
558
+ }
559
+ }));
560
+ build.onResolve({
561
+ filter: sharedExternals
562
+ }, (args)=>{
563
+ if (args.namespace === 'esm-shares') return null;
564
+ return {
565
+ path: args.path,
566
+ namespace: 'virtual-share-module',
567
+ pluginData: {
568
+ kind: args.kind,
569
+ resolveDir: args.resolveDir
570
+ }
571
+ };
572
+ });
573
+ build.onResolve({
574
+ filter: /.*/,
575
+ namespace: 'esm-shares'
576
+ }, (args)=>{
577
+ if (sharedExternals.test(args.path)) {
578
+ return {
579
+ path: args.path,
580
+ namespace: 'virtual-share-module',
581
+ pluginData: {
582
+ kind: args.kind,
583
+ resolveDir: args.resolveDir
584
+ }
585
+ };
586
+ }
587
+ return {
588
+ path: args.path,
589
+ namespace: 'esm-shares',
590
+ pluginData: {
591
+ kind: args.kind,
592
+ resolveDir: args.resolveDir
593
+ }
594
+ };
595
+ });
596
+ build.onLoad({
597
+ filter,
598
+ namespace: 'container'
599
+ }, async (args)=>({
600
+ contents: buildContainerHost(config),
601
+ loader: 'js',
602
+ resolveDir: args.pluginData.resolveDir
603
+ }));
604
+ }
605
+ });
606
+
607
+ // Builds the federation host code
608
+ const buildFederationHost = ()=>{
609
+ const { name, remotes, shared } = federationBuilder.config;
610
+ const remoteConfigs = remotes ? JSON.stringify(Object.entries(remotes).map(([remoteAlias, remote])=>({
611
+ name: remoteAlias,
612
+ entry: remote,
613
+ alias: remoteAlias,
614
+ type: 'esm'
615
+ }))) : '[]';
616
+ const sharedConfig = Object.entries(shared != null ? shared : {}).reduce((acc, [pkg, config])=>{
617
+ var _config_requiredVersion;
618
+ const version = ((_config_requiredVersion = config.requiredVersion) == null ? void 0 : _config_requiredVersion.replace(/^[^0-9]/, '')) || '';
619
+ acc += `${JSON.stringify(pkg)}: {
620
+ "package": "${pkg}",
621
+ "version": "${version}",
622
+ "scope": "default",
623
+ "get": async () => await import('federationShare/${pkg}'),
624
+ "shareConfig": {
625
+ "singleton": ${config.singleton},
626
+ "requiredVersion": "${config.requiredVersion}",
627
+ "eager": ${config.eager},
628
+ "strictVersion": ${config.strictVersion}
629
+ }
630
+ },\n`;
631
+ return acc;
632
+ }, '{') + '}';
633
+ return `
634
+ import { init as initFederationHost } from "@module-federation/runtime";
635
+
636
+ export const createVirtualRemoteModule = (name, ref, exports) => {
637
+ const genExports = exports.map(e =>
638
+ e === 'default'
639
+ ? 'export default mfLsZJ92.default;'
640
+ : \`export const \${e} = mfLsZJ92[\${JSON.stringify(e)}];\`
641
+ ).join('');
642
+
643
+ const loadRef = \`const mfLsZJ92 = await container.loadRemote(\${JSON.stringify(ref)});\`;
644
+
645
+ return \`
646
+ const container = __FEDERATION__.__INSTANCES__.find(container => container.name === name) || __FEDERATION__.__INSTANCES__[0];
647
+ \${loadRef}
648
+ \${genExports}
649
+ \`;
650
+ };
651
+
652
+ function encodeInlineESM(code) {
653
+ return 'data:text/javascript;charset=utf-8,' + encodeURIComponent(code);
654
+ }
655
+
656
+ const runtimePlugin = () => ({
657
+ name: 'import-maps-plugin',
658
+ async init(args) {
659
+ const remotePrefetch = args.options.remotes.map(async (remote) => {
660
+ console.log('remote', remote);
661
+ if (remote.type === 'esm') {
662
+ await import(remote.entry);
663
+ }
664
+ });
665
+
666
+ await Promise.all(remotePrefetch);
667
+ if (typeof moduleMap !== 'undefined') {
668
+ const map = Object.keys(moduleMap).reduce((acc, expose) => {
669
+ const importMap = importShim.getImportMap().imports;
670
+ const key = args.origin.name + expose.replace('.', '');
671
+ if (!importMap[key]) {
672
+ const encodedModule = encodeInlineESM(
673
+ createVirtualRemoteModule(args.origin.name, key, moduleMap[expose].exports)
674
+ );
675
+ acc[key] = encodedModule;
676
+ }
677
+ return acc;
678
+ }, {});
679
+
680
+ await importShim.addImportMap({ imports: map });
681
+ }
682
+
683
+ return args;
684
+ }
685
+ });
686
+
687
+ initFederationHost({
688
+ name: ${JSON.stringify(name)},
689
+ remotes: ${remoteConfigs},
690
+ shared: ${sharedConfig},
691
+ plugins: [runtimePlugin()],
692
+ });
693
+ `;
694
+ };
695
+ const initializeHostPlugin = {
696
+ name: 'host-initialization',
697
+ setup (build) {
698
+ build.onResolve({
699
+ filter: /federation-host/
700
+ }, (args)=>({
701
+ path: args.path,
702
+ namespace: 'federation-host',
703
+ pluginData: {
704
+ kind: args.kind,
705
+ resolveDir: args.resolveDir
706
+ }
707
+ }));
708
+ build.onLoad({
709
+ filter: /.*/,
710
+ namespace: 'federation-host'
711
+ }, async (args)=>({
712
+ contents: buildFederationHost(),
713
+ resolveDir: args.pluginData.resolveDir
714
+ }));
715
+ build.onLoad({
716
+ filter: /.*\.(ts|js|mjs)$/,
717
+ namespace: 'file'
718
+ }, async (args)=>{
719
+ if (!build.initialOptions.entryPoints.some((e)=>args.path.includes(e))) return;
720
+ const contents = await fs__default.promises.readFile(args.path, 'utf8');
721
+ return {
722
+ contents: buildFederationHost() + contents
723
+ };
724
+ });
725
+ }
726
+ };
727
+
728
+ // relys on import map since i dont know the named exports of a remote to return.
729
+ const createVirtualRemoteModule = (name, ref)=>`
730
+ export * from ${JSON.stringify('federationRemote/' + ref)}
731
+ `;
732
+ const linkRemotesPlugin = {
733
+ name: 'linkRemotes',
734
+ setup (build) {
735
+ //@ts-ignore
736
+ const remotes = federationBuilder.config.remotes || {};
737
+ const filter = new RegExp(Object.keys(remotes).reduce((acc, key)=>{
738
+ if (!key) return acc;
739
+ acc.push(`^${key}`);
740
+ return acc;
741
+ }, []).join('|'));
742
+ build.onResolve({
743
+ filter: filter
744
+ }, async (args)=>{
745
+ return {
746
+ path: args.path,
747
+ namespace: 'remote-module'
748
+ };
749
+ });
750
+ build.onResolve({
751
+ filter: /^federationRemote/
752
+ }, async (args)=>{
753
+ return {
754
+ path: args.path.replace('federationRemote/', ''),
755
+ external: true,
756
+ namespace: 'externals'
757
+ };
758
+ });
759
+ build.onLoad({
760
+ filter,
761
+ namespace: 'remote-module'
762
+ }, async (args)=>{
763
+ return {
764
+ contents: createVirtualRemoteModule(federationBuilder.config.name, args.path),
765
+ loader: 'js',
766
+ resolveDir: path__default.dirname(args.path)
767
+ };
768
+ });
769
+ }
770
+ };
771
+
772
+ function _extends$1() {
773
+ _extends$1 = Object.assign || function(target) {
774
+ for(var i = 1; i < arguments.length; i++){
775
+ var source = arguments[i];
776
+ for(var key in source){
777
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
778
+ target[key] = source[key];
779
+ }
780
+ }
781
+ }
782
+ return target;
783
+ };
784
+ return _extends$1.apply(this, arguments);
785
+ }
786
+ // Creates a virtual module for sharing dependencies
787
+ const createVirtualShareModule = (name, ref, exports)=>`
788
+ const container = __FEDERATION__.__INSTANCES__.find(container => container.name === ${JSON.stringify(name)}) || __FEDERATION__.__INSTANCES__[0]
789
+
790
+ const mfLsZJ92 = await container.loadShare(${JSON.stringify(ref)})
791
+
792
+ ${exports.map((e)=>e === 'default' ? `export default mfLsZJ92.default` : `export const ${e} = mfLsZJ92[${JSON.stringify(e)}];`).join('\n')}
793
+ `;
794
+ // Plugin to initialize the federation host
795
+ // Plugin to transform CommonJS modules to ESM
796
+ const cjsToEsmPlugin = {
797
+ name: 'cjs-to-esm',
798
+ setup (build) {
799
+ build.onLoad({
800
+ filter: /.*/,
801
+ namespace: 'esm-shares'
802
+ }, async (args)=>{
803
+ const { transform } = await eval("import('@chialab/cjs-to-esm')");
804
+ const resolver = await resolve(args.pluginData.resolveDir, args.path);
805
+ if (typeof resolver !== 'string') {
806
+ throw new Error(`Unable to resolve path: ${args.path}`);
807
+ }
808
+ const fileContent = fs__default.readFileSync(resolver, 'utf-8');
809
+ const { code } = await transform(fileContent);
810
+ return {
811
+ contents: code,
812
+ loader: 'js',
813
+ resolveDir: path__default.dirname(resolver),
814
+ pluginData: _extends$1({}, args.pluginData, {
815
+ path: resolver
816
+ })
817
+ };
818
+ });
819
+ }
820
+ };
821
+ // Plugin to link shared dependencies
822
+ const linkSharedPlugin = {
823
+ name: 'linkShared',
824
+ setup (build) {
825
+ const filter = new RegExp(federationBuilder.externals.map((name)=>`${name}$`).join('|'));
826
+ build.onLoad({
827
+ filter,
828
+ namespace: 'virtual-share-module'
829
+ }, async (args)=>{
830
+ const exp = await getExports(args.path);
831
+ return {
832
+ contents: createVirtualShareModule(federationBuilder.config.name, args.path, exp),
833
+ loader: 'js',
834
+ resolveDir: path__default.dirname(args.path)
835
+ };
836
+ });
837
+ }
838
+ };
839
+ // Main module federation plugin
840
+ const moduleFederationPlugin = (config)=>({
841
+ name: 'module-federation',
842
+ setup (build) {
843
+ build.initialOptions.metafile = true;
844
+ const pluginStack = [];
845
+ const remotes = Object.keys(federationBuilder.config.remotes || {}).length;
846
+ const shared = Object.keys(federationBuilder.config.shared || {}).length;
847
+ const exposes = Object.keys(federationBuilder.config.exposes || {}).length;
848
+ const entryPoints = build.initialOptions.entryPoints;
849
+ const filename = federationBuilder.config.filename || 'remoteEntry.js';
850
+ if (remotes) {
851
+ pluginStack.push(linkRemotesPlugin);
852
+ }
853
+ if (shared) {
854
+ pluginStack.push(linkSharedPlugin);
855
+ }
856
+ if (!entryPoints) {
857
+ build.initialOptions.entryPoints = [];
858
+ }
859
+ if (exposes) {
860
+ if (Array.isArray(entryPoints)) {
861
+ //@ts-ignore
862
+ entryPoints.push(filename);
863
+ } else if (entryPoints && typeof entryPoints === 'object') {
864
+ entryPoints[filename] = filename;
865
+ } else {
866
+ build.initialOptions.entryPoints = [
867
+ filename
868
+ ];
869
+ }
870
+ }
871
+ [
872
+ initializeHostPlugin,
873
+ createContainerPlugin(config),
874
+ cjsToEsmPlugin,
875
+ ...pluginStack
876
+ ].forEach((plugin)=>plugin.setup(build));
877
+ build.onEnd(async (result)=>{
878
+ if (!result.metafile) return;
879
+ if (exposes) {
880
+ const exposedConfig = federationBuilder.config.exposes || {};
881
+ const remoteFile = federationBuilder.config.filename;
882
+ const exposedEntries = {};
883
+ const outputMapWithoutExt = Object.entries(result.metafile.outputs).reduce((acc, [chunkKey, chunkValue])=>{
884
+ //@ts-ignore
885
+ const { entryPoint } = chunkValue;
886
+ const key = entryPoint || chunkKey;
887
+ const trimKey = key.substring(0, key.lastIndexOf('.')) || key;
888
+ //@ts-ignore
889
+ acc[trimKey] = _extends$1({}, chunkValue, {
890
+ chunk: chunkKey
891
+ });
892
+ return acc;
893
+ }, {});
894
+ for (const [expose, value] of Object.entries(exposedConfig)){
895
+ //@ts-ignore
896
+ const exposedFound = outputMapWithoutExt[value.replace('./', '')];
897
+ if (exposedFound) {
898
+ exposedEntries[expose] = {
899
+ entryPoint: exposedFound.entryPoint,
900
+ exports: exposedFound.exports
901
+ };
902
+ }
903
+ }
904
+ for (const [outputPath, value] of Object.entries(result.metafile.outputs)){
905
+ if (!value.entryPoint) continue;
906
+ if (!value.entryPoint.startsWith('container:')) continue;
907
+ if (!value.entryPoint.endsWith(remoteFile)) continue;
908
+ const container = fs__default.readFileSync(outputPath, 'utf-8');
909
+ const withExports = container.replace('"__MODULE_MAP__"', `${JSON.stringify(exposedEntries)}`).replace("'__MODULE_MAP__'", `${JSON.stringify(exposedEntries)}`);
910
+ fs__default.writeFileSync(outputPath, withExports, 'utf-8');
911
+ }
912
+ }
913
+ await writeRemoteManifest(federationBuilder.config, result);
914
+ console.log(`build ended with ${result.errors.length} errors`);
915
+ });
916
+ }
917
+ });
918
+
919
+ function _extends() {
920
+ _extends = Object.assign || function(target) {
921
+ for(var i = 1; i < arguments.length; i++){
922
+ var source = arguments[i];
923
+ for(var key in source){
924
+ if (Object.prototype.hasOwnProperty.call(source, key)) {
925
+ target[key] = source[key];
926
+ }
927
+ }
928
+ }
929
+ return target;
930
+ };
931
+ return _extends.apply(this, arguments);
932
+ }
933
+ function createEsBuildAdapter(config) {
934
+ if (!config.compensateExports) {
935
+ config.compensateExports = [
936
+ new RegExp('/react/')
937
+ ];
938
+ }
939
+ return async (options)=>{
940
+ const { entryPoints, external, outdir, hash, packageInfos, name, plugins = [] } = options;
941
+ // TODO: Do we need to prepare packages anymore as esbuild has evolved?
942
+ for (const entryPoint of entryPoints){
943
+ const isPkg = entryPoint.fileName.includes('node_modules');
944
+ const pkgName = isPkg ? inferePkgName(entryPoint.fileName) : '';
945
+ const tmpFolder = `node_modules/.tmp/${pkgName}`;
946
+ if (isPkg) {
947
+ await prepareNodePackage(entryPoint.fileName, external, tmpFolder, config, !!options.dev, name);
948
+ entryPoint.fileName = tmpFolder;
949
+ }
950
+ }
951
+ const ctx = await esbuild$1.context({
952
+ entryPoints: entryPoints.map((ep)=>({
953
+ in: ep.fileName,
954
+ out: path__default.parse(ep.outName).name
955
+ })),
956
+ write: false,
957
+ outdir,
958
+ entryNames: '[name]',
959
+ external,
960
+ loader: config.loader,
961
+ bundle: true,
962
+ splitting: true,
963
+ sourcemap: options.dev,
964
+ minify: !options.dev,
965
+ format: 'esm',
966
+ target: [
967
+ 'esnext'
968
+ ],
969
+ plugins: [
970
+ ...config.plugins,
971
+ ...plugins
972
+ ],
973
+ metafile: true,
974
+ define: {
975
+ MF_CURRENT_HOST: JSON.stringify(name)
976
+ }
977
+ });
978
+ const result = await ctx.rebuild();
979
+ result.outputFiles = result.outputFiles.reduce((acc, file, index)=>{
980
+ const sharedPack = packageInfos ? packageInfos[index] : null;
981
+ if (!sharedPack) {
982
+ acc.push(file);
983
+ return acc;
984
+ }
985
+ const fileName = path__default.basename(file.path);
986
+ const filePath = path__default.join(outdir, fileName);
987
+ const relative = path__default.relative(process.cwd(), file.path);
988
+ const metadata = result.metafile.outputs[relative];
989
+ const replc = filePath.replace(filePath, 'mf_' + fileName);
990
+ acc.push(_extends({}, file, {
991
+ path: replc
992
+ }));
993
+ const vm = createVirtualShareModule(name, sharedPack.packageName, metadata.exports);
994
+ acc.push(_extends({}, file, {
995
+ contents: vm
996
+ }));
997
+ return acc;
998
+ }, []);
999
+ const writtenFiles = writeResult(result, outdir);
1000
+ ctx.dispose();
1001
+ return writtenFiles.map((fileName)=>({
1002
+ fileName
1003
+ }));
1004
+ };
1005
+ }
1006
+ function writeResult(result, outdir) {
1007
+ const outputFiles = result.outputFiles || [];
1008
+ const writtenFiles = [];
1009
+ for (const outFile of outputFiles){
1010
+ const fileName = path__default.basename(outFile.path);
1011
+ const filePath = path__default.join(outdir, fileName);
1012
+ fs__default.mkdirSync(path__default.dirname(filePath), {
1013
+ recursive: true
1014
+ });
1015
+ fs__default.writeFileSync(filePath, outFile.contents);
1016
+ writtenFiles.push(filePath);
1017
+ }
1018
+ return writtenFiles;
1019
+ }
1020
+ async function prepareNodePackage(entryPoint, external, tmpFolder, config, dev, name) {
1021
+ if (config.fileReplacements) {
1022
+ entryPoint = replaceEntryPoint(entryPoint, normalize(config.fileReplacements));
1023
+ }
1024
+ const env = dev ? 'development' : 'production';
1025
+ const result = await rollup({
1026
+ input: entryPoint,
1027
+ plugins: [
1028
+ commonjs(),
1029
+ externals({
1030
+ include: external
1031
+ }),
1032
+ pluginNodeResolve(),
1033
+ replace({
1034
+ true: true,
1035
+ values: {
1036
+ 'process.env.NODE_ENV': `"${env}"`,
1037
+ MF_CURRENT_HOST: JSON.stringify(name)
1038
+ }
1039
+ })
1040
+ ]
1041
+ });
1042
+ await result.write({
1043
+ format: 'esm',
1044
+ file: tmpFolder,
1045
+ sourcemap: dev,
1046
+ exports: 'named'
1047
+ });
1048
+ }
1049
+ function inferePkgName(entryPoint) {
1050
+ return entryPoint.replace(/.*?node_modules/g, '').replace(/[^A-Za-z0-9.]/g, '_');
1051
+ }
1052
+ function normalize(config) {
1053
+ const result = {};
1054
+ for(const key in config){
1055
+ if (typeof config[key] === 'string') {
1056
+ result[key] = {
1057
+ file: config[key]
1058
+ };
1059
+ } else {
1060
+ result[key] = config[key];
1061
+ }
1062
+ }
1063
+ return result;
1064
+ }
1065
+ function replaceEntryPoint(entryPoint, fileReplacements) {
1066
+ entryPoint = entryPoint.replace(/\\/g, '/');
1067
+ for(const key in fileReplacements){
1068
+ entryPoint = entryPoint.replace(new RegExp(`${key}$`), fileReplacements[key].file);
1069
+ }
1070
+ return entryPoint;
1071
+ }
1072
+
1073
+ var adapter = /*#__PURE__*/Object.freeze({
1074
+ __proto__: null,
1075
+ createEsBuildAdapter: createEsBuildAdapter,
1076
+ getExports: getExports,
1077
+ resolve: resolve,
1078
+ moduleFederationPlugin: moduleFederationPlugin
1079
+ });
1080
+
1081
+ var require$$0 = /*@__PURE__*/ getAugmentedNamespace(adapter);
1082
+
1083
+ const Adapter = require$$0;
1084
+ var esbuild = Adapter;
1085
+
1086
+ export { esbuild as default };