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