@module-federation/esbuild 0.0.95 → 0.0.97

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 (61) hide show
  1. package/dist/adapters/lib/collect-exports.js +151 -0
  2. package/dist/adapters/lib/collect-exports.mjs +87 -0
  3. package/dist/adapters/lib/commonjs.js +260 -0
  4. package/dist/adapters/lib/commonjs.mjs +209 -0
  5. package/dist/adapters/lib/containerPlugin.js +232 -0
  6. package/dist/adapters/lib/containerPlugin.mjs +182 -0
  7. package/dist/adapters/lib/containerReference.js +219 -0
  8. package/dist/adapters/lib/containerReference.mjs +154 -0
  9. package/dist/adapters/lib/lexer.js +184 -0
  10. package/dist/adapters/lib/lexer.mjs +138 -0
  11. package/dist/adapters/lib/linkRemotesPlugin.js +115 -0
  12. package/dist/adapters/lib/linkRemotesPlugin.mjs +50 -0
  13. package/dist/adapters/lib/manifest.js +229 -0
  14. package/dist/adapters/lib/manifest.mjs +168 -0
  15. package/dist/adapters/lib/plugin.js +339 -0
  16. package/dist/adapters/lib/plugin.mjs +282 -0
  17. package/dist/adapters/lib/react-replacements.js +81 -0
  18. package/dist/adapters/lib/react-replacements.mjs +35 -0
  19. package/dist/adapters/lib/transform.js +169 -0
  20. package/dist/adapters/lib/transform.mjs +120 -0
  21. package/dist/adapters/lib/utils.js +83 -0
  22. package/dist/adapters/lib/utils.mjs +33 -0
  23. package/dist/build.js +131 -473
  24. package/dist/build.mjs +13 -380
  25. package/dist/index.js +41 -26
  26. package/dist/index.mjs +4 -1
  27. package/dist/lib/config/configuration-context.js +70 -0
  28. package/dist/lib/config/configuration-context.mjs +20 -0
  29. package/dist/lib/config/federation-config.js +31 -0
  30. package/dist/lib/config/federation-config.mjs +4 -0
  31. package/dist/lib/config/share-utils.js +339 -0
  32. package/dist/lib/config/share-utils.mjs +254 -0
  33. package/dist/lib/config/with-native-federation.js +118 -0
  34. package/dist/lib/config/with-native-federation.mjs +71 -0
  35. package/dist/lib/core/build-adapter.js +70 -0
  36. package/dist/lib/core/build-adapter.mjs +18 -0
  37. package/dist/lib/core/createContainerTemplate.js +231 -0
  38. package/dist/lib/core/createContainerTemplate.mjs +185 -0
  39. package/dist/lib/core/default-skip-list.js +99 -0
  40. package/dist/lib/core/default-skip-list.mjs +47 -0
  41. package/dist/lib/core/federation-options.js +31 -0
  42. package/dist/lib/core/federation-options.mjs +4 -0
  43. package/dist/lib/core/get-externals.js +65 -0
  44. package/dist/lib/core/get-externals.mjs +19 -0
  45. package/dist/lib/core/load-federation-config.js +69 -0
  46. package/dist/lib/core/load-federation-config.mjs +20 -0
  47. package/dist/lib/core/write-federation-info.js +65 -0
  48. package/dist/lib/core/write-federation-info.mjs +16 -0
  49. package/dist/lib/utils/logger.js +111 -0
  50. package/dist/lib/utils/logger.mjs +46 -0
  51. package/dist/lib/utils/mapped-paths.js +94 -0
  52. package/dist/lib/utils/mapped-paths.mjs +46 -0
  53. package/dist/lib/utils/normalize.js +63 -0
  54. package/dist/lib/utils/normalize.mjs +17 -0
  55. package/dist/lib/utils/package-info.js +324 -0
  56. package/dist/lib/utils/package-info.mjs +265 -0
  57. package/dist/plugin.d.ts +1 -0
  58. package/dist/plugin.js +79 -1231
  59. package/dist/plugin.mjs +2 -1187
  60. package/dist/resolve/esm-resolver.mjs +15 -22
  61. package/package.json +2 -2
@@ -0,0 +1,209 @@
1
+ import * as __WEBPACK_EXTERNAL_MODULE_esbuild__ from "esbuild";
2
+ import { promises } from "fs";
3
+ import { Lexer } from "./lexer.mjs";
4
+ import { cachedReduce, makeLegalIdentifier, orderedUniq } from "./utils.mjs";
5
+ var __webpack_modules__ = ({
6
+ "esbuild": (function (module) {
7
+
8
+ module.exports = __WEBPACK_EXTERNAL_MODULE_esbuild__;
9
+
10
+
11
+ }),
12
+
13
+ });
14
+ /************************************************************************/
15
+ // The module cache
16
+ var __webpack_module_cache__ = {};
17
+
18
+ // The require function
19
+ function __webpack_require__(moduleId) {
20
+
21
+ // Check if module is in cache
22
+ var cachedModule = __webpack_module_cache__[moduleId];
23
+ if (cachedModule !== undefined) {
24
+ return cachedModule.exports;
25
+ }
26
+ // Create a new module (and put it into the cache)
27
+ var module = (__webpack_module_cache__[moduleId] = {
28
+ exports: {}
29
+ });
30
+ // Execute the module function
31
+ __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
32
+
33
+ // Return the exports of the module
34
+ return module.exports;
35
+
36
+ }
37
+
38
+ /************************************************************************/
39
+
40
+ ;// CONCATENATED MODULE: external "fs"
41
+
42
+ ;// CONCATENATED MODULE: external "./lexer.mjs"
43
+
44
+ ;// CONCATENATED MODULE: external "./utils.mjs"
45
+
46
+ ;// CONCATENATED MODULE: ./src/adapters/lib/commonjs.ts
47
+
48
+
49
+
50
+ function commonjs_commonjs({ filter = /\.c?js$/, transform = true, transformConfig, requireReturnsDefault = true, ignore } = {}) {
51
+ const init_cjs_module_lexer = transform ? import("cjs-module-lexer") : undefined;
52
+ const use_default_export = typeof requireReturnsDefault === 'function' ? requireReturnsDefault : (_path)=>requireReturnsDefault;
53
+ const is_ignored = typeof ignore === 'function' ? ignore : Array.isArray(ignore) ? (path)=>ignore.includes(path) : ()=>false;
54
+ return {
55
+ name: 'commonjs',
56
+ setup ({ onLoad, esbuild, initialOptions }) {
57
+ let esbuild_shim;
58
+ const require_esbuild = ()=>esbuild || (esbuild_shim ||= __webpack_require__("esbuild"));
59
+ const read = promises.readFile;
60
+ const lexer = new Lexer();
61
+ //@ts-ignore
62
+ onLoad({
63
+ filter: filter
64
+ }, async (args)=>{
65
+ let parseCJS;
66
+ if (init_cjs_module_lexer) {
67
+ const { init, parse } = await init_cjs_module_lexer;
68
+ await init();
69
+ parseCJS = parse;
70
+ }
71
+ let contents;
72
+ try {
73
+ //@ts-ignore
74
+ contents = await read(args.path, 'utf8');
75
+ } catch {
76
+ return null;
77
+ }
78
+ const willTransform = transform === true || typeof transform === 'function' && transform(args.path);
79
+ let cjsExports;
80
+ try {
81
+ if (parseCJS && willTransform) {
82
+ // move sourcemap to the end of the transformed file
83
+ const sourcemapIndex = contents.lastIndexOf('//# sourceMappingURL=');
84
+ let sourcemap;
85
+ if (sourcemapIndex !== -1) {
86
+ sourcemap = contents.slice(sourcemapIndex);
87
+ const sourcemapEnd = sourcemap.indexOf('\n');
88
+ if (sourcemapEnd !== -1 && sourcemap.slice(sourcemapEnd + 1).trimStart().length > 0) {
89
+ // if there's code after sourcemap, it is invalid, don't do this.
90
+ sourcemap = undefined;
91
+ } else {
92
+ contents = contents.slice(0, sourcemapIndex);
93
+ }
94
+ }
95
+ // transform commonjs to es modules, easy mode
96
+ cjsExports = parseCJS(contents);
97
+ let { behavior, exports, sideEffects } = typeof willTransform === 'object' ? willTransform : {};
98
+ behavior ??= (transformConfig === null || transformConfig === void 0 ? void 0 : transformConfig.behavior) ?? 'node';
99
+ exports = orderedUniq(cjsExports.exports.concat(exports ?? []));
100
+ sideEffects ??= (transformConfig === null || transformConfig === void 0 ? void 0 : transformConfig.sideEffects) ?? true;
101
+ let exportDefault = behavior === 'node' ? 'export default exports;' : 'export default exports.__esModule ? exports.default : exports;';
102
+ let exportsMap = exports.map((e)=>[
103
+ e,
104
+ makeLegalIdentifier(e)
105
+ ]);
106
+ if (exportsMap.some(([e])=>e === 'default')) {
107
+ if (behavior === 'node') {
108
+ exportsMap = exportsMap.filter(([e])=>e !== 'default');
109
+ } else {
110
+ exportDefault = '';
111
+ }
112
+ }
113
+ const reexports = cjsExports.reexports.map((e)=>`export * from ${JSON.stringify(e)};`).join('');
114
+ let transformed;
115
+ if (sideEffects === false) {
116
+ transformed = [
117
+ // make sure we don't manipulate the first line so that sourcemap is fine
118
+ reexports + 'var mod, exports = /* @__PURE__ */ ((exports, module) => {' + contents,
119
+ 'return module.exports})((mod = { exports: {} }).exports, mod); ' + exportDefault
120
+ ];
121
+ if (exportsMap.length > 0) {
122
+ for (const [e, name] of exportsMap){
123
+ transformed.push(`var ${name} = /* @__PURE__ */ (() => exports[${JSON.stringify(e)}])();`);
124
+ }
125
+ transformed.push(`export { ${exportsMap.map(([e, name])=>e === name ? e : `${name} as ${JSON.stringify(e)}`).join(', ')} };`);
126
+ }
127
+ } else {
128
+ transformed = [
129
+ reexports + 'var exports = {}, module = { exports }; {' + contents,
130
+ '}; exports = module.exports; ' + exportDefault
131
+ ];
132
+ if (exportsMap.length > 0) {
133
+ 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(', ')} };`);
134
+ }
135
+ }
136
+ contents = transformed.join('\n') + (sourcemap ? '\n' + sourcemap : '');
137
+ }
138
+ } catch (e) {
139
+ return null;
140
+ }
141
+ function makeName(path) {
142
+ let name = `__import_${makeLegalIdentifier(path)}`;
143
+ if (contents.includes(name)) {
144
+ let suffix = 2;
145
+ while(contents.includes(`${name}${suffix}`))suffix++;
146
+ name = `${name}${suffix}`;
147
+ }
148
+ return name;
149
+ }
150
+ let warnings;
151
+ try {
152
+ ({ warnings } = await require_esbuild().transform(contents, {
153
+ format: 'esm',
154
+ logLevel: 'silent'
155
+ }));
156
+ } catch (err) {
157
+ ({ warnings } = err);
158
+ }
159
+ const lines = contents.split('\n');
160
+ const getOffset = cachedReduce(lines, (a, b)=>a + 1 + b.length, 0);
161
+ if (warnings && (warnings = warnings.filter((e)=>e.text.includes('"require" to "esm"'))).length) {
162
+ const edits = [];
163
+ let imports = [];
164
+ for (const { location } of warnings){
165
+ if (location === null) continue;
166
+ const { line, lineText, column, length } = location;
167
+ const leftBrace = column + length + 1;
168
+ const path = lexer.readString(lineText, leftBrace);
169
+ if (path === null || is_ignored(path)) continue;
170
+ const rightBrace = lineText.indexOf(')', leftBrace + 2 + path.length) + 1;
171
+ const name = makeName(path);
172
+ let import_statement;
173
+ if (use_default_export(path)) {
174
+ import_statement = `import ${name} from ${JSON.stringify(path)};`;
175
+ } else {
176
+ import_statement = `import * as ${name} from ${JSON.stringify(path)};`;
177
+ }
178
+ const offset = getOffset(line - 1);
179
+ edits.push([
180
+ offset + column,
181
+ offset + rightBrace,
182
+ name
183
+ ]);
184
+ imports.push(import_statement);
185
+ }
186
+ if (imports.length === 0) return null;
187
+ imports = orderedUniq(imports);
188
+ let offset = 0;
189
+ for (const [start, end, name] of edits){
190
+ contents = contents.slice(0, start + offset) + name + contents.slice(end + offset);
191
+ offset += name.length - (end - start);
192
+ }
193
+ // if we have transformed this module (i.e. having `cjsExports`), don't make the file commonjs
194
+ contents = [
195
+ ...imports,
196
+ cjsExports ? 'exports;' : '',
197
+ contents
198
+ ].join('');
199
+ return {
200
+ contents
201
+ };
202
+ }
203
+ });
204
+ }
205
+ };
206
+ }
207
+ /* ESM default export */ const commonjs = (commonjs_commonjs);
208
+
209
+ export { commonjs_commonjs as commonjs, commonjs as default };
@@ -0,0 +1,232 @@
1
+ "use strict";
2
+ const __rslib_import_meta_url__ = /*#__PURE__*/ (function () {
3
+ return typeof document === 'undefined'
4
+ ? new (require('url'.replace('', '')).URL)('file:' + __filename).href
5
+ : (document.currentScript && document.currentScript.src) ||
6
+ new URL('main.js', document.baseURI).href;
7
+ })();
8
+ ;
9
+ // The require scope
10
+ var __webpack_require__ = {};
11
+
12
+ /************************************************************************/
13
+ // webpack/runtime/define_property_getters
14
+ (() => {
15
+ __webpack_require__.d = (exports, definition) => {
16
+ for(var key in definition) {
17
+ if(__webpack_require__.o(definition, key) && !__webpack_require__.o(exports, key)) {
18
+ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] });
19
+ }
20
+ }
21
+ };
22
+ })();
23
+ // webpack/runtime/has_own_property
24
+ (() => {
25
+ __webpack_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop))
26
+ })();
27
+ // webpack/runtime/make_namespace_object
28
+ (() => {
29
+ // define __esModule on exports
30
+ __webpack_require__.r = (exports) => {
31
+ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) {
32
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
33
+ }
34
+ Object.defineProperty(exports, '__esModule', { value: true });
35
+ };
36
+ })();
37
+ /************************************************************************/
38
+ var __webpack_exports__ = {};
39
+ // ESM COMPAT FLAG
40
+ __webpack_require__.r(__webpack_exports__);
41
+
42
+ // EXPORTS
43
+ __webpack_require__.d(__webpack_exports__, {
44
+ createContainerPlugin: () => (/* binding */ createContainerPlugin)
45
+ });
46
+
47
+ ;// CONCATENATED MODULE: external "../../lib/core/createContainerTemplate.js"
48
+ const createContainerTemplate_js_namespaceObject = require("../../lib/core/createContainerTemplate.js");
49
+ ;// CONCATENATED MODULE: ./src/adapters/lib/containerPlugin.ts
50
+
51
+ const buildContainerHost = (config)=>{
52
+ const { name, remotes = {}, shared = {}, exposes = {} } = config;
53
+ const remoteConfigs = Object.entries(remotes).map(([remoteAlias, remote])=>({
54
+ type: 'esm',
55
+ name: remoteAlias,
56
+ entry: remote.entry,
57
+ alias: remoteAlias
58
+ }));
59
+ const sharedConfig = Object.entries(shared).reduce((acc, [pkg, config])=>{
60
+ var _config_requiredVersion;
61
+ const version = ((_config_requiredVersion = config.requiredVersion) === null || _config_requiredVersion === void 0 ? void 0 : _config_requiredVersion.replace(/^[^0-9]/, '')) || '';
62
+ acc += `${JSON.stringify(pkg)}: {
63
+ "package": "${pkg}",
64
+ "version": "${version}",
65
+ "scope": "default",
66
+ "get": async () => import('federationShare/${pkg}'),
67
+ "shareConfig": {
68
+ "singleton": ${config.singleton},
69
+ "requiredVersion": "${config.requiredVersion}",
70
+ "eager": ${config.eager},
71
+ "strictVersion": ${config.strictVersion}
72
+ }
73
+ },\n`;
74
+ return acc;
75
+ }, '{') + '}';
76
+ let exposesConfig = Object.entries(exposes).map(([exposeName, exposePath])=>`${JSON.stringify(exposeName)}: async () => await import('${exposePath}')`).join(',\n');
77
+ exposesConfig = `{${exposesConfig}}`;
78
+ const injectedContent = `
79
+ export const moduleMap = '__MODULE_MAP__';
80
+
81
+ function appendImportMap(importMap) {
82
+ const script = document.createElement('script');
83
+ script.type = 'importmap-shim';
84
+ script.innerHTML = JSON.stringify(importMap);
85
+ document.head.appendChild(script);
86
+ }
87
+
88
+ export const createVirtualRemoteModule = (name, ref, exports) => {
89
+ const genExports = exports.map(e =>
90
+ e === 'default' ? 'export default mfLsZJ92.default' : \`export const \${e} = mfLsZJ92[\${JSON.stringify(e)}];\`
91
+ ).join('');
92
+
93
+ const loadRef = \`const mfLsZJ92 = await container.loadRemote(\${JSON.stringify(ref)});\`;
94
+
95
+ return \`
96
+ const container = __FEDERATION__.__INSTANCES__.find(container => container.name === name) || __FEDERATION__.__INSTANCES__[0];
97
+ \${loadRef}
98
+ \${genExports}
99
+ \`;
100
+ };
101
+
102
+ function encodeInlineESM(code) {
103
+ const encodedCode = encodeURIComponent(code);
104
+ return \`data:text/javascript;charset=utf-8,\${encodedCode}\`;
105
+ }
106
+
107
+ const runtimePlugin = () => ({
108
+ name: 'import-maps-plugin',
109
+ async init(args) {
110
+
111
+ const remotePrefetch = args.options.remotes.map(async (remote) => {
112
+ if (remote.type === 'esm') {
113
+ await import(remote.entry);
114
+ }
115
+ });
116
+
117
+
118
+ await Promise.all(remotePrefetch);
119
+
120
+ const map = Object.keys(moduleMap).reduce((acc, expose) => {
121
+ const importMap = importShim.getImportMap().imports;
122
+ const key = args.origin.name + expose.replace('.', '');
123
+ if (!importMap[key]) {
124
+ const encodedModule = encodeInlineESM(
125
+ createVirtualRemoteModule(args.origin.name, key, moduleMap[expose].exports)
126
+ );
127
+ acc[key] = encodedModule;
128
+ }
129
+ return acc;
130
+ }, {});
131
+ await importShim.addImportMap({ imports: map });
132
+
133
+ return args;
134
+ }
135
+ });
136
+
137
+ const createdContainer = await createContainer({
138
+ name: ${JSON.stringify(name)},
139
+ exposes: ${exposesConfig},
140
+ remotes: ${JSON.stringify(remoteConfigs)},
141
+ shared: ${sharedConfig},
142
+ plugins: [runtimePlugin()],
143
+ });
144
+
145
+ export const get = createdContainer.get;
146
+ export const init = createdContainer.init;
147
+ `;
148
+ //replace with createContainer from bundler runtime - import it in the string as a dep etc
149
+ return [
150
+ createContainerTemplate_js_namespaceObject.createContainerCode,
151
+ injectedContent
152
+ ].join('\n');
153
+ };
154
+ const createContainerPlugin = (config)=>({
155
+ name: 'createContainer',
156
+ setup (build) {
157
+ const { filename } = config;
158
+ const filter = new RegExp([
159
+ filename
160
+ ].map((name)=>`${name}$`).join('|'));
161
+ const hasShared = Object.keys(config.shared || {}).length;
162
+ const shared = Object.keys(config.shared || {}).map((name)=>`${name}$`).join('|');
163
+ const sharedExternals = new RegExp(shared);
164
+ build.onResolve({
165
+ filter
166
+ }, async (args)=>({
167
+ path: args.path,
168
+ namespace: 'container',
169
+ pluginData: {
170
+ kind: args.kind,
171
+ resolveDir: args.resolveDir
172
+ }
173
+ }));
174
+ build.onResolve({
175
+ filter: /^federationShare/
176
+ }, async (args)=>({
177
+ path: args.path.replace('federationShare/', ''),
178
+ namespace: 'esm-shares',
179
+ pluginData: {
180
+ kind: args.kind,
181
+ resolveDir: args.resolveDir
182
+ }
183
+ }));
184
+ if (hasShared) {
185
+ build.onResolve({
186
+ filter: sharedExternals
187
+ }, (args)=>{
188
+ if (args.namespace === 'esm-shares') return null;
189
+ return {
190
+ path: args.path,
191
+ namespace: 'virtual-share-module',
192
+ pluginData: {
193
+ kind: args.kind,
194
+ resolveDir: args.resolveDir
195
+ }
196
+ };
197
+ });
198
+ build.onResolve({
199
+ filter: /.*/,
200
+ namespace: 'esm-shares'
201
+ }, async (args)=>{
202
+ if (sharedExternals.test(args.path)) {
203
+ return {
204
+ path: args.path,
205
+ namespace: 'virtual-share-module',
206
+ pluginData: {
207
+ kind: args.kind,
208
+ resolveDir: args.resolveDir
209
+ }
210
+ };
211
+ }
212
+ return undefined;
213
+ });
214
+ }
215
+ build.onLoad({
216
+ filter,
217
+ namespace: 'container'
218
+ }, async (args)=>({
219
+ contents: buildContainerHost(config),
220
+ loader: 'js',
221
+ resolveDir: args.pluginData.resolveDir
222
+ }));
223
+ }
224
+ });
225
+
226
+ exports.createContainerPlugin = __webpack_exports__.createContainerPlugin;
227
+ for(var __webpack_i__ in __webpack_exports__) {
228
+ if(["createContainerPlugin"].indexOf(__webpack_i__) === -1) {
229
+ exports[__webpack_i__] = __webpack_exports__[__webpack_i__];
230
+ }
231
+ }
232
+ Object.defineProperty(exports, '__esModule', { value: true });
@@ -0,0 +1,182 @@
1
+ import { createContainerCode } from "../../lib/core/createContainerTemplate.mjs";
2
+
3
+ ;// CONCATENATED MODULE: external "../../lib/core/createContainerTemplate.mjs"
4
+
5
+ ;// CONCATENATED MODULE: ./src/adapters/lib/containerPlugin.ts
6
+
7
+ const buildContainerHost = (config)=>{
8
+ const { name, remotes = {}, shared = {}, exposes = {} } = config;
9
+ const remoteConfigs = Object.entries(remotes).map(([remoteAlias, remote])=>({
10
+ type: 'esm',
11
+ name: remoteAlias,
12
+ entry: remote.entry,
13
+ alias: remoteAlias
14
+ }));
15
+ const sharedConfig = Object.entries(shared).reduce((acc, [pkg, config])=>{
16
+ var _config_requiredVersion;
17
+ const version = ((_config_requiredVersion = config.requiredVersion) === null || _config_requiredVersion === void 0 ? void 0 : _config_requiredVersion.replace(/^[^0-9]/, '')) || '';
18
+ acc += `${JSON.stringify(pkg)}: {
19
+ "package": "${pkg}",
20
+ "version": "${version}",
21
+ "scope": "default",
22
+ "get": async () => import('federationShare/${pkg}'),
23
+ "shareConfig": {
24
+ "singleton": ${config.singleton},
25
+ "requiredVersion": "${config.requiredVersion}",
26
+ "eager": ${config.eager},
27
+ "strictVersion": ${config.strictVersion}
28
+ }
29
+ },\n`;
30
+ return acc;
31
+ }, '{') + '}';
32
+ let exposesConfig = Object.entries(exposes).map(([exposeName, exposePath])=>`${JSON.stringify(exposeName)}: async () => await import('${exposePath}')`).join(',\n');
33
+ exposesConfig = `{${exposesConfig}}`;
34
+ const injectedContent = `
35
+ export const moduleMap = '__MODULE_MAP__';
36
+
37
+ function appendImportMap(importMap) {
38
+ const script = document.createElement('script');
39
+ script.type = 'importmap-shim';
40
+ script.innerHTML = JSON.stringify(importMap);
41
+ document.head.appendChild(script);
42
+ }
43
+
44
+ export const createVirtualRemoteModule = (name, ref, exports) => {
45
+ const genExports = exports.map(e =>
46
+ e === 'default' ? 'export default mfLsZJ92.default' : \`export const \${e} = mfLsZJ92[\${JSON.stringify(e)}];\`
47
+ ).join('');
48
+
49
+ const loadRef = \`const mfLsZJ92 = await container.loadRemote(\${JSON.stringify(ref)});\`;
50
+
51
+ return \`
52
+ const container = __FEDERATION__.__INSTANCES__.find(container => container.name === name) || __FEDERATION__.__INSTANCES__[0];
53
+ \${loadRef}
54
+ \${genExports}
55
+ \`;
56
+ };
57
+
58
+ function encodeInlineESM(code) {
59
+ const encodedCode = encodeURIComponent(code);
60
+ return \`data:text/javascript;charset=utf-8,\${encodedCode}\`;
61
+ }
62
+
63
+ const runtimePlugin = () => ({
64
+ name: 'import-maps-plugin',
65
+ async init(args) {
66
+
67
+ const remotePrefetch = args.options.remotes.map(async (remote) => {
68
+ if (remote.type === 'esm') {
69
+ await import(remote.entry);
70
+ }
71
+ });
72
+
73
+
74
+ await Promise.all(remotePrefetch);
75
+
76
+ const map = Object.keys(moduleMap).reduce((acc, expose) => {
77
+ const importMap = importShim.getImportMap().imports;
78
+ const key = args.origin.name + expose.replace('.', '');
79
+ if (!importMap[key]) {
80
+ const encodedModule = encodeInlineESM(
81
+ createVirtualRemoteModule(args.origin.name, key, moduleMap[expose].exports)
82
+ );
83
+ acc[key] = encodedModule;
84
+ }
85
+ return acc;
86
+ }, {});
87
+ await importShim.addImportMap({ imports: map });
88
+
89
+ return args;
90
+ }
91
+ });
92
+
93
+ const createdContainer = await createContainer({
94
+ name: ${JSON.stringify(name)},
95
+ exposes: ${exposesConfig},
96
+ remotes: ${JSON.stringify(remoteConfigs)},
97
+ shared: ${sharedConfig},
98
+ plugins: [runtimePlugin()],
99
+ });
100
+
101
+ export const get = createdContainer.get;
102
+ export const init = createdContainer.init;
103
+ `;
104
+ //replace with createContainer from bundler runtime - import it in the string as a dep etc
105
+ return [
106
+ createContainerCode,
107
+ injectedContent
108
+ ].join('\n');
109
+ };
110
+ const createContainerPlugin = (config)=>({
111
+ name: 'createContainer',
112
+ setup (build) {
113
+ const { filename } = config;
114
+ const filter = new RegExp([
115
+ filename
116
+ ].map((name)=>`${name}$`).join('|'));
117
+ const hasShared = Object.keys(config.shared || {}).length;
118
+ const shared = Object.keys(config.shared || {}).map((name)=>`${name}$`).join('|');
119
+ const sharedExternals = new RegExp(shared);
120
+ build.onResolve({
121
+ filter
122
+ }, async (args)=>({
123
+ path: args.path,
124
+ namespace: 'container',
125
+ pluginData: {
126
+ kind: args.kind,
127
+ resolveDir: args.resolveDir
128
+ }
129
+ }));
130
+ build.onResolve({
131
+ filter: /^federationShare/
132
+ }, async (args)=>({
133
+ path: args.path.replace('federationShare/', ''),
134
+ namespace: 'esm-shares',
135
+ pluginData: {
136
+ kind: args.kind,
137
+ resolveDir: args.resolveDir
138
+ }
139
+ }));
140
+ if (hasShared) {
141
+ build.onResolve({
142
+ filter: sharedExternals
143
+ }, (args)=>{
144
+ if (args.namespace === 'esm-shares') return null;
145
+ return {
146
+ path: args.path,
147
+ namespace: 'virtual-share-module',
148
+ pluginData: {
149
+ kind: args.kind,
150
+ resolveDir: args.resolveDir
151
+ }
152
+ };
153
+ });
154
+ build.onResolve({
155
+ filter: /.*/,
156
+ namespace: 'esm-shares'
157
+ }, async (args)=>{
158
+ if (sharedExternals.test(args.path)) {
159
+ return {
160
+ path: args.path,
161
+ namespace: 'virtual-share-module',
162
+ pluginData: {
163
+ kind: args.kind,
164
+ resolveDir: args.resolveDir
165
+ }
166
+ };
167
+ }
168
+ return undefined;
169
+ });
170
+ }
171
+ build.onLoad({
172
+ filter,
173
+ namespace: 'container'
174
+ }, async (args)=>({
175
+ contents: buildContainerHost(config),
176
+ loader: 'js',
177
+ resolveDir: args.pluginData.resolveDir
178
+ }));
179
+ }
180
+ });
181
+
182
+ export { createContainerPlugin };