Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support node esmodule and mf-manifest esmodule #2934

Merged
Merged
Show file tree
Hide file tree
Changes from 18 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"nx": "nx",
"commit": "cz",
"docs": "typedoc",
"f": "nx format:write",
"lint": "nx run-many --target=lint",
"test": "nx run-many --target=test",
"build": "nx run-many --target=build --parallel=5 --projects=tag:type:pkg",
Expand Down
2 changes: 1 addition & 1 deletion packages/runtime/src/plugins/generate-preload-assets.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ export const generatePreloadAssetsPlugin: () => FederationRuntimePlugin =
moduleInfo: {
name: remoteInfo.name,
entry: remote.entry,
type: 'global',
type: remoteInfo.type || 'global',
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider providing a default value for the type property to ensure it always has a valid value, even if remoteInfo.type is undefined:

Suggested change
type: remoteInfo.type || 'global',
type: remoteInfo.type || 'global',

This change ensures that the type property will always have a value, defaulting to 'global' if remoteInfo.type is not provided. This can help prevent potential issues down the line if the code assumes type is always defined.

entryGlobalName: '',
shareScope: '',
},
Expand Down
4 changes: 2 additions & 2 deletions packages/runtime/src/utils/load.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ async function loadEntryNode({
remoteInfo: RemoteInfo;
createScriptHook: FederationHost['loaderHook']['lifecycle']['createScript'];
}) {
const { entry, entryGlobalName: globalName, name } = remoteInfo;
const { entry, entryGlobalName: globalName, name, type } = remoteInfo;
const { entryExports: remoteEntryExports } = getRemoteEntryExports(
name,
globalName,
Expand All @@ -158,7 +158,7 @@ async function loadEntryNode({
}

return loadScriptNode(entry, {
attrs: { name, globalName },
attrs: { name, globalName, type },
createScriptHook: (url, attrs) => {
const res = createScriptHook.emit({ url, attrs });

Expand Down
4 changes: 2 additions & 2 deletions packages/sdk/src/dom.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,9 @@ export function createScript(info: {
}

if (!script) {
const attrs = info.attrs;
script = document.createElement('script');
script.type = 'text/javascript';
script.type = attrs?.['type'] === 'module' ? 'module' : 'text/javascript';
script.src = info.url;
let createScriptRes: CreateScriptHookReturnDom = undefined;
if (info.createScriptHook) {
Expand All @@ -65,7 +66,6 @@ export function createScript(info: {
}
}
}
const attrs = info.attrs;
if (attrs && !createScriptRes) {
Object.keys(attrs).forEach((name) => {
if (script) {
Expand Down
3 changes: 2 additions & 1 deletion packages/sdk/src/generateSnapshotFromManifest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,8 @@ export function generateSnapshotFromManifest(
ssrRemoteEntry.name,
);
remoteSnapshot.ssrRemoteEntry = fullSSRRemoteEntry;
remoteSnapshot.ssrRemoteEntryType = 'commonjs-module';
remoteSnapshot.ssrRemoteEntryType =
ssrRemoteEntry.type || 'commonjs-module';
}

return remoteSnapshot;
Expand Down
65 changes: 64 additions & 1 deletion packages/sdk/src/node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -132,7 +132,26 @@ export function createScriptNode(
};

getFetch()
.then((f) => handleScriptFetch(f, urlObj))
.then(async (f) => {
if (attrs?.['type'] === 'esm' || attrs?.['type'] === 'module') {
return loadModule(urlObj.href, {
fetch: f,
vm: await importNodeModule<typeof import('vm')>('vm'),
})
.then(async (module) => {
await module.evaluate();
cb(undefined, module.namespace);
})
.catch((e) => {
cb(
e instanceof Error
? e
: new Error(`Script execution error: ${e}`),
);
});
}
handleScriptFetch(f, urlObj);
})
.catch((err) => {
cb(err);
});
Expand Down Expand Up @@ -165,3 +184,47 @@ export function loadScriptNode(
);
});
}

async function loadModule(
url: string,
options: {
vm: any;
fetch: any;
},
parentContext?: any,
) {
const { fetch, vm } = options;
const context =
parentContext ||
vm.createContext({
...global,
Event,
URL,
URLSearchParams,
TextDecoder,
TextEncoder,
console,
require: eval('require'),
__dirname,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

bundler will transform these into strings in other targets, like browser etc. cant use short hand

Suggested change
__dirname,
__dirname: __dirname,
__filename: __filename,

__filename,
});
const response = await fetch(url);
const code = await response.text();

const module: any = new vm.SourceTextModule(code, {
context,
Copy link
Member

@ScriptedAlchemy ScriptedAlchemy Sep 26, 2024

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I do not think you should pass a custom VM context to the module. Attempting to copy the global context does not work for many cases, there are many more primitives than just

  Event,
      URL,
      URLSearchParams,
      TextDecoder,
      TextEncoder,
      console,

if you pass no context, then it will run in the current context and should operate like runInThisContext does for Script

// @ts-ignore
importModuleDynamically: async (specifier, script) => {
const resolvedUrl = new URL(specifier, url).href;
return loadModule(resolvedUrl, options, context);
},
});

await module.link(async (specifier: string) => {
const resolvedUrl = new URL(specifier, url).href;
const module = await loadModule(resolvedUrl, options, context);
return module;
});

return module;
}
Loading