@module-federation/sdk 2.1.0 → 2.2.1

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 (45) hide show
  1. package/README.md +9 -3
  2. package/dist/createModuleFederationConfig.d.ts +0 -2
  3. package/dist/dom.cjs +15 -1
  4. package/dist/dom.cjs.map +1 -1
  5. package/dist/dom.d.ts +0 -2
  6. package/dist/dom.js +15 -1
  7. package/dist/dom.js.map +1 -1
  8. package/dist/env.cjs +3 -1
  9. package/dist/env.cjs.map +1 -1
  10. package/dist/env.d.ts +2 -1
  11. package/dist/env.js +3 -2
  12. package/dist/env.js.map +1 -1
  13. package/dist/generateSnapshotFromManifest.d.ts +0 -2
  14. package/dist/index.cjs +15 -0
  15. package/dist/index.d.ts +4 -3
  16. package/dist/index.js +4 -2
  17. package/dist/node.cjs.map +1 -1
  18. package/dist/node.d.ts +0 -2
  19. package/dist/node.js.map +1 -1
  20. package/dist/types/index.d.ts +2 -1
  21. package/dist/types/plugins/ConsumeSharedPlugin.cjs +13 -0
  22. package/dist/types/plugins/ConsumeSharedPlugin.cjs.map +1 -0
  23. package/dist/types/plugins/ConsumeSharedPlugin.d.ts +109 -0
  24. package/dist/types/plugins/ConsumeSharedPlugin.js +8 -0
  25. package/dist/types/plugins/ConsumeSharedPlugin.js.map +1 -0
  26. package/dist/types/plugins/ContainerPlugin.cjs.map +1 -1
  27. package/dist/types/plugins/ContainerPlugin.d.ts +15 -13
  28. package/dist/types/plugins/ContainerPlugin.js.map +1 -1
  29. package/dist/types/plugins/ContainerReferencePlugin.cjs.map +1 -1
  30. package/dist/types/plugins/ContainerReferencePlugin.d.ts +4 -3
  31. package/dist/types/plugins/ContainerReferencePlugin.js.map +1 -1
  32. package/dist/types/plugins/ModuleFederationPlugin.cjs.map +1 -1
  33. package/dist/types/plugins/ModuleFederationPlugin.d.ts +213 -190
  34. package/dist/types/plugins/ModuleFederationPlugin.js.map +1 -1
  35. package/dist/types/plugins/ProvideSharedPlugin.cjs +13 -0
  36. package/dist/types/plugins/ProvideSharedPlugin.cjs.map +1 -0
  37. package/dist/types/plugins/ProvideSharedPlugin.d.ts +97 -0
  38. package/dist/types/plugins/ProvideSharedPlugin.js +8 -0
  39. package/dist/types/plugins/ProvideSharedPlugin.js.map +1 -0
  40. package/dist/types/plugins/SharePlugin.cjs.map +1 -1
  41. package/dist/types/plugins/SharePlugin.d.ts +9 -12
  42. package/dist/types/plugins/SharePlugin.js.map +1 -1
  43. package/dist/types/plugins/index.d.ts +3 -1
  44. package/dist/utils.d.ts +0 -2
  45. package/package.json +20 -1
package/README.md CHANGED
@@ -11,7 +11,7 @@
11
11
  // The SDK can be used to parse entry strings, encode and decode module names, and generate filenames for exposed modules and shared packages.
12
12
  // It also includes a logger for debugging and environment detection utilities.
13
13
  // Additionally, it provides a function to generate a snapshot from a manifest and environment detection utilities.
14
- import { parseEntry, encodeName, decodeName, generateExposeFilename, generateShareFilename, createLogger, isBrowserEnv, isDebugMode, getProcessEnv, generateSnapshotFromManifest } from '@module-federation/sdk';
14
+ import { parseEntry, encodeName, decodeName, generateExposeFilename, generateShareFilename, createLogger, isBrowserEnv, isBrowserEnvValue, isDebugMode, getProcessEnv, generateSnapshotFromManifest } from '@module-federation/sdk';
15
15
 
16
16
  // Parse an entry string into a RemoteEntryInfo object
17
17
  parseEntry('entryString');
@@ -32,7 +32,8 @@ generateShareFilename('packageName', true);
32
32
  const logger = createLogger('identifier');
33
33
 
34
34
  // Check if the current environment is a browser
35
- isBrowserEnv();
35
+ const inBrowser = isBrowserEnv();
36
+ const inBrowserStatic = isBrowserEnvValue;
36
37
 
37
38
  // Check if the current environment is in debug mode
38
39
  isDebugMode();
@@ -76,9 +77,14 @@ generateSnapshotFromManifest(manifest, options);
76
77
 
77
78
  ### isBrowserEnv
78
79
 
79
- - Type: `isBrowserEnv()`
80
+ - Type: `isBrowserEnv(): boolean`
80
81
  - Checks if the current environment is a browser.
81
82
 
83
+ ### isBrowserEnvValue
84
+
85
+ - Type: `isBrowserEnvValue: boolean`
86
+ - Static browser environment flag (tree-shakable when ENV_TARGET is defined).
87
+
82
88
  ### isDebugMode
83
89
 
84
90
  - Type: `isDebugMode()`
@@ -1,6 +1,4 @@
1
1
  import { ModuleFederationPluginOptions } from "./types/plugins/ModuleFederationPlugin.js";
2
- import "./types/plugins/index.js";
3
-
4
2
  //#region src/createModuleFederationConfig.d.ts
5
3
  declare const createModuleFederationConfig: (options: ModuleFederationPluginOptions) => ModuleFederationPluginOptions;
6
4
  //#endregion
package/dist/dom.cjs CHANGED
@@ -49,10 +49,24 @@ function createScript(info) {
49
49
  }
50
50
  });
51
51
  }
52
+ let executionError = null;
53
+ const executionErrorHandler = typeof window !== "undefined" ? (evt) => {
54
+ if (evt.filename && isStaticResourcesEqual(evt.filename, info.url)) {
55
+ const err = /* @__PURE__ */ new Error(`ScriptExecutionError: Script "${info.url}" loaded but threw a runtime error during execution: ${evt.message} (${evt.filename}:${evt.lineno}:${evt.colno})`);
56
+ err.name = "ScriptExecutionError";
57
+ executionError = err;
58
+ }
59
+ } : null;
60
+ if (executionErrorHandler) window.addEventListener("error", executionErrorHandler);
52
61
  const onScriptComplete = async (prev, event) => {
53
62
  clearTimeout(timeoutId);
63
+ if (executionErrorHandler) window.removeEventListener("error", executionErrorHandler);
54
64
  const onScriptCompleteCallback = () => {
55
- if (event?.type === "error") info?.onErrorCallback && info?.onErrorCallback(event);
65
+ if (event?.type === "error") {
66
+ const networkError = /* @__PURE__ */ new Error(`ScriptNetworkError: Failed to load script "${info.url}" - the script URL is unreachable or the server returned an error (network failure, 404, CORS, etc.)`);
67
+ networkError.name = "ScriptNetworkError";
68
+ info?.onErrorCallback && info?.onErrorCallback(networkError);
69
+ } else if (executionError) info?.onErrorCallback && info?.onErrorCallback(executionError);
56
70
  else info?.cb && info?.cb();
57
71
  };
58
72
  if (script) {
package/dist/dom.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"dom.cjs","names":["warn"],"sources":["../src/dom.ts"],"sourcesContent":["import type { CreateScriptHookDom, CreateScriptHookReturnDom } from './types';\nimport { warn } from './utils';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport async function safeWrapper<T extends (...args: Array<any>) => any>(\n callback: T,\n disableWarn?: boolean,\n): Promise<ReturnType<T> | undefined> {\n try {\n const res = await callback();\n return res;\n } catch (e) {\n !disableWarn && warn(e);\n return;\n }\n}\n\nexport function isStaticResourcesEqual(url1: string, url2: string): boolean {\n const REG_EXP = /^(https?:)?\\/\\//i;\n // Transform url1 and url2 into relative paths\n const relativeUrl1 = url1.replace(REG_EXP, '').replace(/\\/$/, '');\n const relativeUrl2 = url2.replace(REG_EXP, '').replace(/\\/$/, '');\n // Check if the relative paths are identical\n return relativeUrl1 === relativeUrl2;\n}\n\nexport function createScript(info: {\n url: string;\n cb?: (value: void | PromiseLike<void>) => void;\n onErrorCallback?: (error: Error) => void;\n attrs?: Record<string, any>;\n needDeleteScript?: boolean;\n createScriptHook?: CreateScriptHookDom;\n}): { script: HTMLScriptElement; needAttach: boolean } {\n // Retrieve the existing script element by its src attribute\n let script: HTMLScriptElement | null = null;\n let needAttach = true;\n let timeout = 20000;\n let timeoutId: NodeJS.Timeout;\n const scripts = document.getElementsByTagName('script');\n\n for (let i = 0; i < scripts.length; i++) {\n const s = scripts[i];\n const scriptSrc = s.getAttribute('src');\n if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {\n script = s;\n needAttach = false;\n break;\n }\n }\n\n if (!script) {\n const attrs = info.attrs;\n script = document.createElement('script');\n script.type = attrs?.['type'] === 'module' ? 'module' : 'text/javascript';\n let createScriptRes: CreateScriptHookReturnDom = undefined;\n if (info.createScriptHook) {\n createScriptRes = info.createScriptHook(info.url, info.attrs);\n\n if (createScriptRes instanceof HTMLScriptElement) {\n script = createScriptRes;\n } else if (typeof createScriptRes === 'object') {\n if ('script' in createScriptRes && createScriptRes.script) {\n script = createScriptRes.script;\n }\n if ('timeout' in createScriptRes && createScriptRes.timeout) {\n timeout = createScriptRes.timeout;\n }\n }\n }\n if (!script.src) {\n script.src = info.url;\n }\n if (attrs && !createScriptRes) {\n Object.keys(attrs).forEach((name) => {\n if (script) {\n if (name === 'async' || name === 'defer') {\n script[name] = attrs[name];\n // Attributes that do not exist are considered overridden\n } else if (!script.getAttribute(name)) {\n script.setAttribute(name, attrs[name]);\n }\n }\n });\n }\n }\n\n const onScriptComplete = async (\n prev: OnErrorEventHandler | GlobalEventHandlers['onload'] | null,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event: any,\n ): Promise<void> => {\n clearTimeout(timeoutId);\n const onScriptCompleteCallback = () => {\n if (event?.type === 'error') {\n info?.onErrorCallback && info?.onErrorCallback(event);\n } else {\n info?.cb && info?.cb();\n }\n };\n\n // Prevent memory leaks in IE.\n if (script) {\n script.onerror = null;\n script.onload = null;\n safeWrapper(() => {\n const { needDeleteScript = true } = info;\n if (needDeleteScript) {\n script?.parentNode && script.parentNode.removeChild(script);\n }\n });\n if (prev && typeof prev === 'function') {\n const result = (prev as any)(event);\n if (result instanceof Promise) {\n const res = await result;\n onScriptCompleteCallback();\n return res;\n }\n onScriptCompleteCallback();\n return result;\n }\n }\n onScriptCompleteCallback();\n };\n\n script.onerror = onScriptComplete.bind(null, script.onerror);\n script.onload = onScriptComplete.bind(null, script.onload);\n\n timeoutId = setTimeout(() => {\n onScriptComplete(\n null,\n new Error(`Remote script \"${info.url}\" time-outed.`),\n );\n }, timeout);\n\n return { script, needAttach };\n}\n\nexport function createLink(info: {\n url: string;\n cb?: (value: void | PromiseLike<void>) => void;\n onErrorCallback?: (error: Error) => void;\n attrs: Record<string, string>;\n needDeleteLink?: boolean;\n createLinkHook?: (\n url: string,\n attrs?: Record<string, any>,\n ) => HTMLLinkElement | void;\n}) {\n // <link rel=\"preload\" href=\"script.js\" as=\"script\">\n\n // Retrieve the existing script element by its src attribute\n let link: HTMLLinkElement | null = null;\n let needAttach = true;\n const links = document.getElementsByTagName('link');\n for (let i = 0; i < links.length; i++) {\n const l = links[i];\n const linkHref = l.getAttribute('href');\n const linkRel = l.getAttribute('rel');\n if (\n linkHref &&\n isStaticResourcesEqual(linkHref, info.url) &&\n linkRel === info.attrs['rel']\n ) {\n link = l;\n needAttach = false;\n break;\n }\n }\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('href', info.url);\n\n let createLinkRes: void | HTMLLinkElement = undefined;\n const attrs = info.attrs;\n\n if (info.createLinkHook) {\n createLinkRes = info.createLinkHook(info.url, attrs);\n if (createLinkRes instanceof HTMLLinkElement) {\n link = createLinkRes;\n }\n }\n\n if (attrs && !createLinkRes) {\n Object.keys(attrs).forEach((name) => {\n if (link && !link.getAttribute(name)) {\n link.setAttribute(name, attrs[name]);\n }\n });\n }\n }\n\n const onLinkComplete = (\n prev: OnErrorEventHandler | GlobalEventHandlers['onload'] | null,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event: any,\n ): void => {\n const onLinkCompleteCallback = () => {\n if (event?.type === 'error') {\n info?.onErrorCallback && info?.onErrorCallback(event);\n } else {\n info?.cb && info?.cb();\n }\n };\n // Prevent memory leaks in IE.\n if (link) {\n link.onerror = null;\n link.onload = null;\n safeWrapper(() => {\n const { needDeleteLink = true } = info;\n if (needDeleteLink) {\n link?.parentNode && link.parentNode.removeChild(link);\n }\n });\n if (prev) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const res = (prev as any)(event);\n onLinkCompleteCallback();\n return res;\n }\n }\n onLinkCompleteCallback();\n };\n\n link.onerror = onLinkComplete.bind(null, link.onerror);\n link.onload = onLinkComplete.bind(null, link.onload);\n\n return { link, needAttach };\n}\n\nexport function loadScript(\n url: string,\n info: {\n attrs?: Record<string, any>;\n createScriptHook?: CreateScriptHookDom;\n },\n) {\n const { attrs = {}, createScriptHook } = info;\n return new Promise<void>((resolve, reject) => {\n const { script, needAttach } = createScript({\n url,\n cb: resolve,\n onErrorCallback: reject,\n attrs: {\n fetchpriority: 'high',\n ...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K,YAAY,OAAO;GAC/C"}
1
+ {"version":3,"file":"dom.cjs","names":["warn"],"sources":["../src/dom.ts"],"sourcesContent":["import type { CreateScriptHookDom, CreateScriptHookReturnDom } from './types';\nimport { warn } from './utils';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport async function safeWrapper<T extends (...args: Array<any>) => any>(\n callback: T,\n disableWarn?: boolean,\n): Promise<ReturnType<T> | undefined> {\n try {\n const res = await callback();\n return res;\n } catch (e) {\n !disableWarn && warn(e);\n return;\n }\n}\n\nexport function isStaticResourcesEqual(url1: string, url2: string): boolean {\n const REG_EXP = /^(https?:)?\\/\\//i;\n // Transform url1 and url2 into relative paths\n const relativeUrl1 = url1.replace(REG_EXP, '').replace(/\\/$/, '');\n const relativeUrl2 = url2.replace(REG_EXP, '').replace(/\\/$/, '');\n // Check if the relative paths are identical\n return relativeUrl1 === relativeUrl2;\n}\n\nexport function createScript(info: {\n url: string;\n cb?: (value: void | PromiseLike<void>) => void;\n onErrorCallback?: (error: Error) => void;\n attrs?: Record<string, any>;\n needDeleteScript?: boolean;\n createScriptHook?: CreateScriptHookDom;\n}): { script: HTMLScriptElement; needAttach: boolean } {\n // Retrieve the existing script element by its src attribute\n let script: HTMLScriptElement | null = null;\n let needAttach = true;\n let timeout = 20000;\n let timeoutId: NodeJS.Timeout;\n const scripts = document.getElementsByTagName('script');\n\n for (let i = 0; i < scripts.length; i++) {\n const s = scripts[i];\n const scriptSrc = s.getAttribute('src');\n if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {\n script = s;\n needAttach = false;\n break;\n }\n }\n\n if (!script) {\n const attrs = info.attrs;\n script = document.createElement('script');\n script.type = attrs?.['type'] === 'module' ? 'module' : 'text/javascript';\n let createScriptRes: CreateScriptHookReturnDom = undefined;\n if (info.createScriptHook) {\n createScriptRes = info.createScriptHook(info.url, info.attrs);\n\n if (createScriptRes instanceof HTMLScriptElement) {\n script = createScriptRes;\n } else if (typeof createScriptRes === 'object') {\n if ('script' in createScriptRes && createScriptRes.script) {\n script = createScriptRes.script;\n }\n if ('timeout' in createScriptRes && createScriptRes.timeout) {\n timeout = createScriptRes.timeout;\n }\n }\n }\n if (!script.src) {\n script.src = info.url;\n }\n if (attrs && !createScriptRes) {\n Object.keys(attrs).forEach((name) => {\n if (script) {\n if (name === 'async' || name === 'defer') {\n script[name] = attrs[name];\n // Attributes that do not exist are considered overridden\n } else if (!script.getAttribute(name)) {\n script.setAttribute(name, attrs[name]);\n }\n }\n });\n }\n }\n\n // Capture JS runtime errors thrown by this script's IIFE during execution.\n // The browser still fires onload even when the script throws, so without this\n // listener the execution error would silently become an uncaught global exception.\n let executionError: Error | null = null;\n const executionErrorHandler =\n typeof window !== 'undefined'\n ? (evt: ErrorEvent) => {\n if (evt.filename && isStaticResourcesEqual(evt.filename, info.url)) {\n const err = new Error(\n `ScriptExecutionError: Script \"${info.url}\" loaded but threw a runtime error during execution: ${evt.message} (${evt.filename}:${evt.lineno}:${evt.colno})`,\n );\n err.name = 'ScriptExecutionError';\n executionError = err;\n }\n }\n : null;\n if (executionErrorHandler) {\n window.addEventListener('error', executionErrorHandler);\n }\n\n const onScriptComplete = async (\n prev: OnErrorEventHandler | GlobalEventHandlers['onload'] | null,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event: any,\n ): Promise<void> => {\n clearTimeout(timeoutId);\n if (executionErrorHandler) {\n window.removeEventListener('error', executionErrorHandler);\n }\n const onScriptCompleteCallback = () => {\n if (event?.type === 'error') {\n const networkError = new Error(\n `ScriptNetworkError: Failed to load script \"${info.url}\" - the script URL is unreachable or the server returned an error (network failure, 404, CORS, etc.)`,\n );\n networkError.name = 'ScriptNetworkError';\n info?.onErrorCallback && info?.onErrorCallback(networkError);\n } else if (executionError) {\n // Script fetched OK (onload fired) but IIFE threw during execution.\n info?.onErrorCallback && info?.onErrorCallback(executionError);\n } else {\n info?.cb && info?.cb();\n }\n };\n\n // Prevent memory leaks in IE.\n if (script) {\n script.onerror = null;\n script.onload = null;\n safeWrapper(() => {\n const { needDeleteScript = true } = info;\n if (needDeleteScript) {\n script?.parentNode && script.parentNode.removeChild(script);\n }\n });\n if (prev && typeof prev === 'function') {\n const result = (prev as any)(event);\n if (result instanceof Promise) {\n const res = await result;\n onScriptCompleteCallback();\n return res;\n }\n onScriptCompleteCallback();\n return result;\n }\n }\n onScriptCompleteCallback();\n };\n\n script.onerror = onScriptComplete.bind(null, script.onerror);\n script.onload = onScriptComplete.bind(null, script.onload);\n\n timeoutId = setTimeout(() => {\n onScriptComplete(\n null,\n new Error(`Remote script \"${info.url}\" time-outed.`),\n );\n }, timeout);\n\n return { script, needAttach };\n}\n\nexport function createLink(info: {\n url: string;\n cb?: (value: void | PromiseLike<void>) => void;\n onErrorCallback?: (error: Error) => void;\n attrs: Record<string, string>;\n needDeleteLink?: boolean;\n createLinkHook?: (\n url: string,\n attrs?: Record<string, any>,\n ) => HTMLLinkElement | void;\n}) {\n // <link rel=\"preload\" href=\"script.js\" as=\"script\">\n\n // Retrieve the existing script element by its src attribute\n let link: HTMLLinkElement | null = null;\n let needAttach = true;\n const links = document.getElementsByTagName('link');\n for (let i = 0; i < links.length; i++) {\n const l = links[i];\n const linkHref = l.getAttribute('href');\n const linkRel = l.getAttribute('rel');\n if (\n linkHref &&\n isStaticResourcesEqual(linkHref, info.url) &&\n linkRel === info.attrs['rel']\n ) {\n link = l;\n needAttach = false;\n break;\n }\n }\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('href', info.url);\n\n let createLinkRes: void | HTMLLinkElement = undefined;\n const attrs = info.attrs;\n\n if (info.createLinkHook) {\n createLinkRes = info.createLinkHook(info.url, attrs);\n if (createLinkRes instanceof HTMLLinkElement) {\n link = createLinkRes;\n }\n }\n\n if (attrs && !createLinkRes) {\n Object.keys(attrs).forEach((name) => {\n if (link && !link.getAttribute(name)) {\n link.setAttribute(name, attrs[name]);\n }\n });\n }\n }\n\n const onLinkComplete = (\n prev: OnErrorEventHandler | GlobalEventHandlers['onload'] | null,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event: any,\n ): void => {\n const onLinkCompleteCallback = () => {\n if (event?.type === 'error') {\n info?.onErrorCallback && info?.onErrorCallback(event);\n } else {\n info?.cb && info?.cb();\n }\n };\n // Prevent memory leaks in IE.\n if (link) {\n link.onerror = null;\n link.onload = null;\n safeWrapper(() => {\n const { needDeleteLink = true } = info;\n if (needDeleteLink) {\n link?.parentNode && link.parentNode.removeChild(link);\n }\n });\n if (prev) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const res = (prev as any)(event);\n onLinkCompleteCallback();\n return res;\n }\n }\n onLinkCompleteCallback();\n };\n\n link.onerror = onLinkComplete.bind(null, link.onerror);\n link.onload = onLinkComplete.bind(null, link.onload);\n\n return { link, needAttach };\n}\n\nexport function loadScript(\n url: string,\n info: {\n attrs?: Record<string, any>;\n createScriptHook?: CreateScriptHookDom;\n },\n) {\n const { attrs = {}, createScriptHook } = info;\n return new Promise<void>((resolve, reject) => {\n const { script, needAttach } = createScript({\n url,\n cb: resolve,\n onErrorCallback: reject,\n attrs: {\n fetchpriority: 'high',\n ...attrs,\n },\n createScriptHook,\n needDeleteScript: true,\n });\n needAttach && document.head.appendChild(script);\n });\n}\n"],"mappings":";;;AAGA,eAAsB,YACpB,UACA,aACoC;AACpC,KAAI;AAEF,SADY,MAAM,UAAU;UAErB,GAAG;AACV,GAAC,eAAeA,mBAAK,EAAE;AACvB;;;AAIJ,SAAgB,uBAAuB,MAAc,MAAuB;CAC1E,MAAM,UAAU;AAKhB,QAHqB,KAAK,QAAQ,SAAS,GAAG,CAAC,QAAQ,OAAO,GAAG,KAC5C,KAAK,QAAQ,SAAS,GAAG,CAAC,QAAQ,OAAO,GAAG;;AAKnE,SAAgB,aAAa,MAO0B;CAErD,IAAI,SAAmC;CACvC,IAAI,aAAa;CACjB,IAAI,UAAU;CACd,IAAI;CACJ,MAAM,UAAU,SAAS,qBAAqB,SAAS;AAEvD,MAAK,IAAI,IAAI,GAA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GAC/C"}
package/dist/dom.d.ts CHANGED
@@ -1,6 +1,4 @@
1
1
  import { CreateScriptHookDom } from "./types/hooks.js";
2
- import "./types/index.js";
3
-
4
2
  //#region src/dom.d.ts
5
3
  declare function safeWrapper<T extends (...args: Array<any>) => any>(callback: T, disableWarn?: boolean): Promise<ReturnType<T> | undefined>;
6
4
  declare function isStaticResourcesEqual(url1: string, url2: string): boolean;
package/dist/dom.js CHANGED
@@ -49,10 +49,24 @@ function createScript(info) {
49
49
  }
50
50
  });
51
51
  }
52
+ let executionError = null;
53
+ const executionErrorHandler = typeof window !== "undefined" ? (evt) => {
54
+ if (evt.filename && isStaticResourcesEqual(evt.filename, info.url)) {
55
+ const err = /* @__PURE__ */ new Error(`ScriptExecutionError: Script "${info.url}" loaded but threw a runtime error during execution: ${evt.message} (${evt.filename}:${evt.lineno}:${evt.colno})`);
56
+ err.name = "ScriptExecutionError";
57
+ executionError = err;
58
+ }
59
+ } : null;
60
+ if (executionErrorHandler) window.addEventListener("error", executionErrorHandler);
52
61
  const onScriptComplete = async (prev, event) => {
53
62
  clearTimeout(timeoutId);
63
+ if (executionErrorHandler) window.removeEventListener("error", executionErrorHandler);
54
64
  const onScriptCompleteCallback = () => {
55
- if (event?.type === "error") info?.onErrorCallback && info?.onErrorCallback(event);
65
+ if (event?.type === "error") {
66
+ const networkError = /* @__PURE__ */ new Error(`ScriptNetworkError: Failed to load script "${info.url}" - the script URL is unreachable or the server returned an error (network failure, 404, CORS, etc.)`);
67
+ networkError.name = "ScriptNetworkError";
68
+ info?.onErrorCallback && info?.onErrorCallback(networkError);
69
+ } else if (executionError) info?.onErrorCallback && info?.onErrorCallback(executionError);
56
70
  else info?.cb && info?.cb();
57
71
  };
58
72
  if (script) {
package/dist/dom.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"dom.js","names":[],"sources":["../src/dom.ts"],"sourcesContent":["import type { CreateScriptHookDom, CreateScriptHookReturnDom } from './types';\nimport { warn } from './utils';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport async function safeWrapper<T extends (...args: Array<any>) => any>(\n callback: T,\n disableWarn?: boolean,\n): Promise<ReturnType<T> | undefined> {\n try {\n const res = await callback();\n return res;\n } catch (e) {\n !disableWarn && warn(e);\n return;\n }\n}\n\nexport function isStaticResourcesEqual(url1: string, url2: string): boolean {\n const REG_EXP = /^(https?:)?\\/\\//i;\n // Transform url1 and url2 into relative paths\n const relativeUrl1 = url1.replace(REG_EXP, '').replace(/\\/$/, '');\n const relativeUrl2 = url2.replace(REG_EXP, '').replace(/\\/$/, '');\n // Check if the relative paths are identical\n return relativeUrl1 === relativeUrl2;\n}\n\nexport function createScript(info: {\n url: string;\n cb?: (value: void | PromiseLike<void>) => void;\n onErrorCallback?: (error: Error) => void;\n attrs?: Record<string, any>;\n needDeleteScript?: boolean;\n createScriptHook?: CreateScriptHookDom;\n}): { script: HTMLScriptElement; needAttach: boolean } {\n // Retrieve the existing script element by its src attribute\n let script: HTMLScriptElement | null = null;\n let needAttach = true;\n let timeout = 20000;\n let timeoutId: NodeJS.Timeout;\n const scripts = document.getElementsByTagName('script');\n\n for (let i = 0; i < scripts.length; i++) {\n const s = scripts[i];\n const scriptSrc = s.getAttribute('src');\n if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {\n script = s;\n needAttach = false;\n break;\n }\n }\n\n if (!script) {\n const attrs = info.attrs;\n script = document.createElement('script');\n script.type = attrs?.['type'] === 'module' ? 'module' : 'text/javascript';\n let createScriptRes: CreateScriptHookReturnDom = undefined;\n if (info.createScriptHook) {\n createScriptRes = info.createScriptHook(info.url, info.attrs);\n\n if (createScriptRes instanceof HTMLScriptElement) {\n script = createScriptRes;\n } else if (typeof createScriptRes === 'object') {\n if ('script' in createScriptRes && createScriptRes.script) {\n script = createScriptRes.script;\n }\n if ('timeout' in createScriptRes && createScriptRes.timeout) {\n timeout = createScriptRes.timeout;\n }\n }\n }\n if (!script.src) {\n script.src = info.url;\n }\n if (attrs && !createScriptRes) {\n Object.keys(attrs).forEach((name) => {\n if (script) {\n if (name === 'async' || name === 'defer') {\n script[name] = attrs[name];\n // Attributes that do not exist are considered overridden\n } else if (!script.getAttribute(name)) {\n script.setAttribute(name, attrs[name]);\n }\n }\n });\n }\n }\n\n const onScriptComplete = async (\n prev: OnErrorEventHandler | GlobalEventHandlers['onload'] | null,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event: any,\n ): Promise<void> => {\n clearTimeout(timeoutId);\n const onScriptCompleteCallback = () => {\n if (event?.type === 'error') {\n info?.onErrorCallback && info?.onErrorCallback(event);\n } else {\n info?.cb && info?.cb();\n }\n };\n\n // Prevent memory leaks in IE.\n if (script) {\n script.onerror = null;\n script.onload = null;\n safeWrapper(() => {\n const { needDeleteScript = true } = info;\n if (needDeleteScript) {\n script?.parentNode && script.parentNode.removeChild(script);\n }\n });\n if (prev && typeof prev === 'function') {\n const result = (prev as any)(event);\n if (result instanceof Promise) {\n const res = await result;\n onScriptCompleteCallback();\n return res;\n }\n onScriptCompleteCallback();\n return result;\n }\n }\n onScriptCompleteCallback();\n };\n\n script.onerror = onScriptComplete.bind(null, script.onerror);\n script.onload = onScriptComplete.bind(null, script.onload);\n\n timeoutId = setTimeout(() => {\n onScriptComplete(\n null,\n new Error(`Remote script \"${info.url}\" time-outed.`),\n );\n }, timeout);\n\n return { script, needAttach };\n}\n\nexport function createLink(info: {\n url: string;\n cb?: (value: void | PromiseLike<void>) => void;\n onErrorCallback?: (error: Error) => void;\n attrs: Record<string, string>;\n needDeleteLink?: boolean;\n createLinkHook?: (\n url: string,\n attrs?: Record<string, any>,\n ) => HTMLLinkElement | void;\n}) {\n // <link rel=\"preload\" href=\"script.js\" as=\"script\">\n\n // Retrieve the existing script element by its src attribute\n let link: HTMLLinkElement | null = null;\n let needAttach = true;\n const links = document.getElementsByTagName('link');\n for (let i = 0; i < links.length; i++) {\n const l = links[i];\n const linkHref = l.getAttribute('href');\n const linkRel = l.getAttribute('rel');\n if (\n linkHref &&\n isStaticResourcesEqual(linkHref, info.url) &&\n linkRel === info.attrs['rel']\n ) {\n link = l;\n needAttach = false;\n break;\n }\n }\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('href', info.url);\n\n let createLinkRes: void | HTMLLinkElement = undefined;\n const attrs = info.attrs;\n\n if (info.createLinkHook) {\n createLinkRes = info.createLinkHook(info.url, attrs);\n if (createLinkRes instanceof HTMLLinkElement) {\n link = createLinkRes;\n }\n }\n\n if (attrs && !createLinkRes) {\n Object.keys(attrs).forEach((name) => {\n if (link && !link.getAttribute(name)) {\n link.setAttribute(name, attrs[name]);\n }\n });\n }\n }\n\n const onLinkComplete = (\n prev: OnErrorEventHandler | GlobalEventHandlers['onload'] | null,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event: any,\n ): void => {\n const onLinkCompleteCallback = () => {\n if (event?.type === 'error') {\n info?.onErrorCallback && info?.onErrorCallback(event);\n } else {\n info?.cb && info?.cb();\n }\n };\n // Prevent memory leaks in IE.\n if (link) {\n link.onerror = null;\n link.onload = null;\n safeWrapper(() => {\n const { needDeleteLink = true } = info;\n if (needDeleteLink) {\n link?.parentNode && link.parentNode.removeChild(link);\n }\n });\n if (prev) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const res = (prev as any)(event);\n onLinkCompleteCallback();\n return res;\n }\n }\n onLinkCompleteCallback();\n };\n\n link.onerror = onLinkComplete.bind(null, link.onerror);\n link.onload = onLinkComplete.bind(null, link.onload);\n\n return { link, needAttach };\n}\n\nexport function loadScript(\n url: string,\n info: {\n attrs?: Record<string, any>;\n createScriptHook?: CreateScriptHookDom;\n },\n) {\n const { attrs = {}, createScriptHook } = info;\n return new Promise<void>((resolve, reject) => {\n const { script, needAttach } = createScript({\n url,\n cb: resolve,\n onErrorCallback: reject,\n attrs: {\n fetchpriority: 'high',\n ...attrs,\n },\n createScriptHook,\n needDeleteScript: true,\n });\n needAttach && document.head.appendChild(script);\n });\n}\n"],"mappings":";;;AAGA,eAAsB,Y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CreateScriptHookReturnDom } from './types';\nimport { warn } from './utils';\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport async function safeWrapper<T extends (...args: Array<any>) => any>(\n callback: T,\n disableWarn?: boolean,\n): Promise<ReturnType<T> | undefined> {\n try {\n const res = await callback();\n return res;\n } catch (e) {\n !disableWarn && warn(e);\n return;\n }\n}\n\nexport function isStaticResourcesEqual(url1: string, url2: string): boolean {\n const REG_EXP = /^(https?:)?\\/\\//i;\n // Transform url1 and url2 into relative paths\n const relativeUrl1 = url1.replace(REG_EXP, '').replace(/\\/$/, '');\n const relativeUrl2 = url2.replace(REG_EXP, '').replace(/\\/$/, '');\n // Check if the relative paths are identical\n return relativeUrl1 === relativeUrl2;\n}\n\nexport function createScript(info: {\n url: string;\n cb?: (value: void | PromiseLike<void>) => void;\n onErrorCallback?: (error: Error) => void;\n attrs?: Record<string, any>;\n needDeleteScript?: boolean;\n createScriptHook?: CreateScriptHookDom;\n}): { script: HTMLScriptElement; needAttach: boolean } {\n // Retrieve the existing script element by its src attribute\n let script: HTMLScriptElement | null = null;\n let needAttach = true;\n let timeout = 20000;\n let timeoutId: NodeJS.Timeout;\n const scripts = document.getElementsByTagName('script');\n\n for (let i = 0; i < scripts.length; i++) {\n const s = scripts[i];\n const scriptSrc = s.getAttribute('src');\n if (scriptSrc && isStaticResourcesEqual(scriptSrc, info.url)) {\n script = s;\n needAttach = false;\n break;\n }\n }\n\n if (!script) {\n const attrs = info.attrs;\n script = document.createElement('script');\n script.type = attrs?.['type'] === 'module' ? 'module' : 'text/javascript';\n let createScriptRes: CreateScriptHookReturnDom = undefined;\n if (info.createScriptHook) {\n createScriptRes = info.createScriptHook(info.url, info.attrs);\n\n if (createScriptRes instanceof HTMLScriptElement) {\n script = createScriptRes;\n } else if (typeof createScriptRes === 'object') {\n if ('script' in createScriptRes && createScriptRes.script) {\n script = createScriptRes.script;\n }\n if ('timeout' in createScriptRes && createScriptRes.timeout) {\n timeout = createScriptRes.timeout;\n }\n }\n }\n if (!script.src) {\n script.src = info.url;\n }\n if (attrs && !createScriptRes) {\n Object.keys(attrs).forEach((name) => {\n if (script) {\n if (name === 'async' || name === 'defer') {\n script[name] = attrs[name];\n // Attributes that do not exist are considered overridden\n } else if (!script.getAttribute(name)) {\n script.setAttribute(name, attrs[name]);\n }\n }\n });\n }\n }\n\n // Capture JS runtime errors thrown by this script's IIFE during execution.\n // The browser still fires onload even when the script throws, so without this\n // listener the execution error would silently become an uncaught global exception.\n let executionError: Error | null = null;\n const executionErrorHandler =\n typeof window !== 'undefined'\n ? (evt: ErrorEvent) => {\n if (evt.filename && isStaticResourcesEqual(evt.filename, info.url)) {\n const err = new Error(\n `ScriptExecutionError: Script \"${info.url}\" loaded but threw a runtime error during execution: ${evt.message} (${evt.filename}:${evt.lineno}:${evt.colno})`,\n );\n err.name = 'ScriptExecutionError';\n executionError = err;\n }\n }\n : null;\n if (executionErrorHandler) {\n window.addEventListener('error', executionErrorHandler);\n }\n\n const onScriptComplete = async (\n prev: OnErrorEventHandler | GlobalEventHandlers['onload'] | null,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event: any,\n ): Promise<void> => {\n clearTimeout(timeoutId);\n if (executionErrorHandler) {\n window.removeEventListener('error', executionErrorHandler);\n }\n const onScriptCompleteCallback = () => {\n if (event?.type === 'error') {\n const networkError = new Error(\n `ScriptNetworkError: Failed to load script \"${info.url}\" - the script URL is unreachable or the server returned an error (network failure, 404, CORS, etc.)`,\n );\n networkError.name = 'ScriptNetworkError';\n info?.onErrorCallback && info?.onErrorCallback(networkError);\n } else if (executionError) {\n // Script fetched OK (onload fired) but IIFE threw during execution.\n info?.onErrorCallback && info?.onErrorCallback(executionError);\n } else {\n info?.cb && info?.cb();\n }\n };\n\n // Prevent memory leaks in IE.\n if (script) {\n script.onerror = null;\n script.onload = null;\n safeWrapper(() => {\n const { needDeleteScript = true } = info;\n if (needDeleteScript) {\n script?.parentNode && script.parentNode.removeChild(script);\n }\n });\n if (prev && typeof prev === 'function') {\n const result = (prev as any)(event);\n if (result instanceof Promise) {\n const res = await result;\n onScriptCompleteCallback();\n return res;\n }\n onScriptCompleteCallback();\n return result;\n }\n }\n onScriptCompleteCallback();\n };\n\n script.onerror = onScriptComplete.bind(null, script.onerror);\n script.onload = onScriptComplete.bind(null, script.onload);\n\n timeoutId = setTimeout(() => {\n onScriptComplete(\n null,\n new Error(`Remote script \"${info.url}\" time-outed.`),\n );\n }, timeout);\n\n return { script, needAttach };\n}\n\nexport function createLink(info: {\n url: string;\n cb?: (value: void | PromiseLike<void>) => void;\n onErrorCallback?: (error: Error) => void;\n attrs: Record<string, string>;\n needDeleteLink?: boolean;\n createLinkHook?: (\n url: string,\n attrs?: Record<string, any>,\n ) => HTMLLinkElement | void;\n}) {\n // <link rel=\"preload\" href=\"script.js\" as=\"script\">\n\n // Retrieve the existing script element by its src attribute\n let link: HTMLLinkElement | null = null;\n let needAttach = true;\n const links = document.getElementsByTagName('link');\n for (let i = 0; i < links.length; i++) {\n const l = links[i];\n const linkHref = l.getAttribute('href');\n const linkRel = l.getAttribute('rel');\n if (\n linkHref &&\n isStaticResourcesEqual(linkHref, info.url) &&\n linkRel === info.attrs['rel']\n ) {\n link = l;\n needAttach = false;\n break;\n }\n }\n\n if (!link) {\n link = document.createElement('link');\n link.setAttribute('href', info.url);\n\n let createLinkRes: void | HTMLLinkElement = undefined;\n const attrs = info.attrs;\n\n if (info.createLinkHook) {\n createLinkRes = info.createLinkHook(info.url, attrs);\n if (createLinkRes instanceof HTMLLinkElement) {\n link = createLinkRes;\n }\n }\n\n if (attrs && !createLinkRes) {\n Object.keys(attrs).forEach((name) => {\n if (link && !link.getAttribute(name)) {\n link.setAttribute(name, attrs[name]);\n }\n });\n }\n }\n\n const onLinkComplete = (\n prev: OnErrorEventHandler | GlobalEventHandlers['onload'] | null,\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n event: any,\n ): void => {\n const onLinkCompleteCallback = () => {\n if (event?.type === 'error') {\n info?.onErrorCallback && info?.onErrorCallback(event);\n } else {\n info?.cb && info?.cb();\n }\n };\n // Prevent memory leaks in IE.\n if (link) {\n link.onerror = null;\n link.onload = null;\n safeWrapper(() => {\n const { needDeleteLink = true } = info;\n if (needDeleteLink) {\n link?.parentNode && link.parentNode.removeChild(link);\n }\n });\n if (prev) {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const res = (prev as any)(event);\n onLinkCompleteCallback();\n return res;\n }\n }\n onLinkCompleteCallback();\n };\n\n link.onerror = onLinkComplete.bind(null, link.onerror);\n link.onload = onLinkComplete.bind(null, link.onload);\n\n return { link, needAttach };\n}\n\nexport function loadScript(\n url: string,\n info: {\n attrs?: Record<string, any>;\n createScriptHook?: CreateScriptHookDom;\n },\n) {\n const { attrs = {}, createScriptHook } = info;\n return new Promise<void>((resolve, reject) => {\n const { script, needAttach } = createScript({\n url,\n cb: resolve,\n onErrorCallback: reject,\n attrs: {\n fetchpriority: 'high',\n ...attrs,\n },\n createScriptHook,\n needDeleteScript: true,\n });\n needAttach && document.head.appendChild(script);\n });\n}\n"],"mappings":";;;AAGA,eAAsB,YACpB,UACA,aACoC;AACpC,KAAI;AAEF,SADY,MAAM,UAAU;UAErB,GAAG;AACV,GAAC,eAAe,KAAK,EAAE;AACvB;;;AAIJ,SAAgB,uBAAuB,MAAc,MAAuB;CAC1E,MAAM,UAAU;AAKhB,QAHqB,KAAK,QAAQ,SAAS,GAAG,CAAC,QAAQ,OAAO,GAAG,KAC5C,KAAK,QAAQ,SAAS,GAAG,CAAC,QAAQ,OAAO,GAAG;;AAKnE,SAAgB,aAAa,MAO0B;CAErD,IAAI,SAAmC;CACvC,IAAI,aAAa;CACjB,IAAI,UAAU;CACd,IAAI;CACJ,MAAM,UAAU,SAAS,qBAAqB,SAAS;AAEvD,MAAK,IAAI,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;EACvC,MAAM,IAAI,QAAQ;EAClB,MAAM,YAAY,EAAE,aAAa,MAAM;AACvC,MAAI,aAA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isBrowserEnvValue = typeof ENV_TARGET !== "undefined" ? ENV_TARGET === "web" : typeof window !== "undefined" && typeof window.document !== "undefined";
4
5
  function isBrowserEnv() {
5
- return typeof window !== "undefined" && typeof window.document !== "undefined";
6
+ return isBrowserEnvValue;
6
7
  }
7
8
  function isReactNativeEnv() {
8
9
  return typeof navigator !== "undefined" && navigator?.product === "ReactNative";
@@ -27,6 +28,7 @@ const getProcessEnv = function() {
27
28
  //#endregion
28
29
  exports.getProcessEnv = getProcessEnv;
29
30
  exports.isBrowserEnv = isBrowserEnv;
31
+ exports.isBrowserEnvValue = isBrowserEnvValue;
30
32
  exports.isDebugMode = isDebugMode;
31
33
  exports.isReactNativeEnv = isReactNativeEnv;
32
34
  //# sourceMappingURL=env.cjs.map
package/dist/env.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"env.cjs","names":["BROWSER_LOG_KEY"],"sources":["../src/env.ts"],"sourcesContent":["import { BROWSER_LOG_KEY } from './constant';\n\ndeclare global {\n // eslint-disable-next-line no-var\n var FEDERATION_DEBUG: string | undefined;\n}\n\nfunction isBrowserEnv(): boolean {\n return (\n typeof window !== 'undefined' && typeof window.document !== 'undefined'\n );\n}\n\nfunction isReactNativeEnv(): boolean {\n return (\n typeof navigator !== 'undefined' && navigator?.product === 'ReactNative'\n );\n}\n\nfunction isBrowserDebug() {\n try {\n if (isBrowserEnv() && window.localStorage) {\n return Boolean(localStorage.getItem(BROWSER_LOG_KEY));\n }\n } catch (error) {\n return false;\n }\n return false;\n}\n\nfunction isDebugMode(): boolean {\n if (\n typeof process !== 'undefined' &&\n process.env &&\n process.env['FEDERATION_DEBUG']\n ) {\n return Boolean(process.env['FEDERATION_DEBUG']);\n }\n\n if (typeof FEDERATION_DEBUG !== 'undefined' && Boolean(FEDERATION_DEBUG)) {\n return true;\n }\n\n return isBrowserDebug();\n}\n\nconst getProcessEnv = function (): Record<string, string | undefined> {\n return typeof process !== 'undefined' && process.env ? process.env : {};\n};\n\nexport { isBrowserEnv, isReactNativeEnv, isDebugMode, getProcessEnv };\n"],"mappings":";;;AAOA,SAAS,eAAwB;AAC/B,QACE,OAAO,WAAW,eAAe,OAAO,OAAO,aAAa;;AAIhE,SAAS,mBAA4B;AACnC,QACE,OAAO,cAAc,eAAe,WAAW,YAAY;;AAI/D,SAAS,iBAAiB;AACxB,KAAI;AACF,MAAI,cAAc,IAAI,OAAO,aAC3B,QAAO,QAAQ,aAAa,QAAQA,iCAAgB,CAAC;UAEhD,OAAO;AACd,SAAO;;AAET,QAAO;;AAGT,SAAS,cAAuB;AAC9B,KACE,OAAO,YAAY,eACnB,QAAQ,OACR,QAAQ,IAAI,oBAEZ,QAAO,QAAQ,QAAQ,IAAI,oBAAoB;AAGjD,KAAI,OAAO,qBAAqB,eAAe,QAAQ,iBAAiB,CACtE,QAAO;AAGT,QAAO,gBAAgB;;AAGzB,MAAM,gBAAgB,WAAgD;AACpE,QAAO,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,MAAM,EAAE"}
1
+ {"version":3,"file":"env.cjs","names":["BROWSER_LOG_KEY"],"sources":["../src/env.ts"],"sourcesContent":["import { BROWSER_LOG_KEY } from './constant';\n\ndeclare global {\n // eslint-disable-next-line no-var\n var FEDERATION_DEBUG: string | undefined;\n}\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst isBrowserEnvValue =\n typeof ENV_TARGET !== 'undefined'\n ? ENV_TARGET === 'web'\n : typeof window !== 'undefined' && typeof window.document !== 'undefined';\n\nfunction isBrowserEnv(): boolean {\n return isBrowserEnvValue;\n}\n\nfunction isReactNativeEnv(): boolean {\n return (\n typeof navigator !== 'undefined' && navigator?.product === 'ReactNative'\n );\n}\n\nfunction isBrowserDebug() {\n try {\n if (isBrowserEnv() && window.localStorage) {\n return Boolean(localStorage.getItem(BROWSER_LOG_KEY));\n }\n } catch (error) {\n return false;\n }\n return false;\n}\n\nfunction isDebugMode(): boolean {\n if (\n typeof process !== 'undefined' &&\n process.env &&\n process.env['FEDERATION_DEBUG']\n ) {\n return Boolean(process.env['FEDERATION_DEBUG']);\n }\n\n if (typeof FEDERATION_DEBUG !== 'undefined' && Boolean(FEDERATION_DEBUG)) {\n return true;\n }\n\n return isBrowserDebug();\n}\n\nconst getProcessEnv = function (): Record<string, string | undefined> {\n return typeof process !== 'undefined' && process.env ? process.env : {};\n};\n\nexport {\n isBrowserEnv,\n isBrowserEnvValue,\n isReactNativeEnv,\n isDebugMode,\n getProcessEnv,\n};\n"],"mappings":";;;AAUA,MAAM,oBACJ,OAAO,eAAe,cAClB,eAAe,QACf,OAAO,WAAW,eAAe,OAAO,OAAO,aAAa;AAElE,SAAS,eAAwB;AAC/B,QAAO;;AAGT,SAAS,mBAA4B;AACnC,QACE,OAAO,cAAc,eAAe,WAAW,YAAY;;AAI/D,SAAS,iBAAiB;AACxB,KAAI;AACF,MAAI,cAAc,IAAI,OAAO,aAC3B,QAAO,QAAQ,aAAa,QAAQA,iCAAgB,CAAC;UAEhD,OAAO;AACd,SAAO;;AAET,QAAO;;AAGT,SAAS,cAAuB;AAC9B,KACE,OAAO,YAAY,eACnB,QAAQ,OACR,QAAQ,IAAI,oBAEZ,QAAO,QAAQ,QAAQ,IAAI,oBAAoB;AAGjD,KAAI,OAAO,qBAAqB,eAAe,QAAQ,iBAAiB,CACtE,QAAO;AAGT,QAAO,gBAAgB;;AAGzB,MAAM,gBAAgB,WAAgD;AACpE,QAAO,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,MAAM,EAAE"}
package/dist/env.d.ts CHANGED
@@ -2,10 +2,11 @@
2
2
  declare global {
3
3
  var FEDERATION_DEBUG: string | undefined;
4
4
  }
5
+ declare const isBrowserEnvValue: boolean;
5
6
  declare function isBrowserEnv(): boolean;
6
7
  declare function isReactNativeEnv(): boolean;
7
8
  declare function isDebugMode(): boolean;
8
9
  declare const getProcessEnv: () => Record<string, string | undefined>;
9
10
  //#endregion
10
- export { getProcessEnv, isBrowserEnv, isDebugMode, isReactNativeEnv };
11
+ export { getProcessEnv, isBrowserEnv, isBrowserEnvValue, isDebugMode, isReactNativeEnv };
11
12
  //# sourceMappingURL=env.d.ts.map
package/dist/env.js CHANGED
@@ -1,8 +1,9 @@
1
1
  import { BROWSER_LOG_KEY } from "./constant.js";
2
2
 
3
3
  //#region src/env.ts
4
+ const isBrowserEnvValue = typeof ENV_TARGET !== "undefined" ? ENV_TARGET === "web" : typeof window !== "undefined" && typeof window.document !== "undefined";
4
5
  function isBrowserEnv() {
5
- return typeof window !== "undefined" && typeof window.document !== "undefined";
6
+ return isBrowserEnvValue;
6
7
  }
7
8
  function isReactNativeEnv() {
8
9
  return typeof navigator !== "undefined" && navigator?.product === "ReactNative";
@@ -25,5 +26,5 @@ const getProcessEnv = function() {
25
26
  };
26
27
 
27
28
  //#endregion
28
- export { getProcessEnv, isBrowserEnv, isDebugMode, isReactNativeEnv };
29
+ export { getProcessEnv, isBrowserEnv, isBrowserEnvValue, isDebugMode, isReactNativeEnv };
29
30
  //# sourceMappingURL=env.js.map
package/dist/env.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"env.js","names":[],"sources":["../src/env.ts"],"sourcesContent":["import { BROWSER_LOG_KEY } from './constant';\n\ndeclare global {\n // eslint-disable-next-line no-var\n var FEDERATION_DEBUG: string | undefined;\n}\n\nfunction isBrowserEnv(): boolean {\n return (\n typeof window !== 'undefined' && typeof window.document !== 'undefined'\n );\n}\n\nfunction isReactNativeEnv(): boolean {\n return (\n typeof navigator !== 'undefined' && navigator?.product === 'ReactNative'\n );\n}\n\nfunction isBrowserDebug() {\n try {\n if (isBrowserEnv() && window.localStorage) {\n return Boolean(localStorage.getItem(BROWSER_LOG_KEY));\n }\n } catch (error) {\n return false;\n }\n return false;\n}\n\nfunction isDebugMode(): boolean {\n if (\n typeof process !== 'undefined' &&\n process.env &&\n process.env['FEDERATION_DEBUG']\n ) {\n return Boolean(process.env['FEDERATION_DEBUG']);\n }\n\n if (typeof FEDERATION_DEBUG !== 'undefined' && Boolean(FEDERATION_DEBUG)) {\n return true;\n }\n\n return isBrowserDebug();\n}\n\nconst getProcessEnv = function (): Record<string, string | undefined> {\n return typeof process !== 'undefined' && process.env ? process.env : {};\n};\n\nexport { isBrowserEnv, isReactNativeEnv, isDebugMode, getProcessEnv };\n"],"mappings":";;;AAOA,SAAS,eAAwB;AAC/B,QACE,OAAO,WAAW,eAAe,OAAO,OAAO,aAAa;;AAIhE,SAAS,mBAA4B;AACnC,QACE,OAAO,cAAc,eAAe,WAAW,YAAY;;AAI/D,SAAS,iBAAiB;AACxB,KAAI;AACF,MAAI,cAAc,IAAI,OAAO,aAC3B,QAAO,QAAQ,aAAa,QAAQ,gBAAgB,CAAC;UAEhD,OAAO;AACd,SAAO;;AAET,QAAO;;AAGT,SAAS,cAAuB;AAC9B,KACE,OAAO,YAAY,eACnB,QAAQ,OACR,QAAQ,IAAI,oBAEZ,QAAO,QAAQ,QAAQ,IAAI,oBAAoB;AAGjD,KAAI,OAAO,qBAAqB,eAAe,QAAQ,iBAAiB,CACtE,QAAO;AAGT,QAAO,gBAAgB;;AAGzB,MAAM,gBAAgB,WAAgD;AACpE,QAAO,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,MAAM,EAAE"}
1
+ {"version":3,"file":"env.js","names":[],"sources":["../src/env.ts"],"sourcesContent":["import { BROWSER_LOG_KEY } from './constant';\n\ndeclare global {\n // eslint-disable-next-line no-var\n var FEDERATION_DEBUG: string | undefined;\n}\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst isBrowserEnvValue =\n typeof ENV_TARGET !== 'undefined'\n ? ENV_TARGET === 'web'\n : typeof window !== 'undefined' && typeof window.document !== 'undefined';\n\nfunction isBrowserEnv(): boolean {\n return isBrowserEnvValue;\n}\n\nfunction isReactNativeEnv(): boolean {\n return (\n typeof navigator !== 'undefined' && navigator?.product === 'ReactNative'\n );\n}\n\nfunction isBrowserDebug() {\n try {\n if (isBrowserEnv() && window.localStorage) {\n return Boolean(localStorage.getItem(BROWSER_LOG_KEY));\n }\n } catch (error) {\n return false;\n }\n return false;\n}\n\nfunction isDebugMode(): boolean {\n if (\n typeof process !== 'undefined' &&\n process.env &&\n process.env['FEDERATION_DEBUG']\n ) {\n return Boolean(process.env['FEDERATION_DEBUG']);\n }\n\n if (typeof FEDERATION_DEBUG !== 'undefined' && Boolean(FEDERATION_DEBUG)) {\n return true;\n }\n\n return isBrowserDebug();\n}\n\nconst getProcessEnv = function (): Record<string, string | undefined> {\n return typeof process !== 'undefined' && process.env ? process.env : {};\n};\n\nexport {\n isBrowserEnv,\n isBrowserEnvValue,\n isReactNativeEnv,\n isDebugMode,\n getProcessEnv,\n};\n"],"mappings":";;;AAUA,MAAM,oBACJ,OAAO,eAAe,cAClB,eAAe,QACf,OAAO,WAAW,eAAe,OAAO,OAAO,aAAa;AAElE,SAAS,eAAwB;AAC/B,QAAO;;AAGT,SAAS,mBAA4B;AACnC,QACE,OAAO,cAAc,eAAe,WAAW,YAAY;;AAI/D,SAAS,iBAAiB;AACxB,KAAI;AACF,MAAI,cAAc,IAAI,OAAO,aAC3B,QAAO,QAAQ,aAAa,QAAQ,gBAAgB,CAAC;UAEhD,OAAO;AACd,SAAO;;AAET,QAAO;;AAGT,SAAS,cAAuB;AAC9B,KACE,OAAO,YAAY,eACnB,QAAQ,OACR,QAAQ,IAAI,oBAEZ,QAAO,QAAQ,QAAQ,IAAI,oBAAoB;AAGjD,KAAI,OAAO,qBAAqB,eAAe,QAAQ,iBAAiB,CACtE,QAAO;AAGT,QAAO,gBAAgB;;AAGzB,MAAM,gBAAgB,WAAgD;AACpE,QAAO,OAAO,YAAY,eAAe,QAAQ,MAAM,QAAQ,MAAM,EAAE"}
@@ -1,8 +1,6 @@
1
1
  import { Manifest } from "./types/manifest.js";
2
2
  import { ManifestProvider, ModuleInfo, ProviderModuleInfo } from "./types/snapshot.js";
3
3
  import { ModuleFederationPluginOptions } from "./types/plugins/ModuleFederationPlugin.js";
4
- import "./types/index.js";
5
-
6
4
  //#region src/generateSnapshotFromManifest.d.ts
7
5
  interface IOptions {
8
6
  remotes?: Record<string, string>;
package/dist/index.cjs CHANGED
@@ -4,6 +4,8 @@ const require_ContainerPlugin = require('./types/plugins/ContainerPlugin.cjs');
4
4
  const require_ContainerReferencePlugin = require('./types/plugins/ContainerReferencePlugin.cjs');
5
5
  const require_ModuleFederationPlugin = require('./types/plugins/ModuleFederationPlugin.cjs');
6
6
  const require_SharePlugin = require('./types/plugins/SharePlugin.cjs');
7
+ const require_ConsumeSharedPlugin = require('./types/plugins/ConsumeSharedPlugin.cjs');
8
+ const require_ProvideSharedPlugin = require('./types/plugins/ProvideSharedPlugin.cjs');
7
9
  const require_env = require('./env.cjs');
8
10
  const require_utils = require('./utils.cjs');
9
11
  const require_generateSnapshotFromManifest = require('./generateSnapshotFromManifest.cjs');
@@ -31,6 +33,12 @@ exports.TreeShakingStatus = require_constant.TreeShakingStatus;
31
33
  exports.assert = require_utils.assert;
32
34
  exports.bindLoggerToCompiler = require_logger.bindLoggerToCompiler;
33
35
  exports.composeKeyWithSeparator = require_utils.composeKeyWithSeparator;
36
+ Object.defineProperty(exports, 'consumeSharedPlugin', {
37
+ enumerable: true,
38
+ get: function () {
39
+ return require_ConsumeSharedPlugin.ConsumeSharedPlugin_exports;
40
+ }
41
+ });
34
42
  Object.defineProperty(exports, 'containerPlugin', {
35
43
  enumerable: true,
36
44
  get: function () {
@@ -61,6 +69,7 @@ exports.getResourceUrl = require_utils.getResourceUrl;
61
69
  exports.inferAutoPublicPath = require_generateSnapshotFromManifest.inferAutoPublicPath;
62
70
  exports.infrastructureLogger = require_logger.infrastructureLogger;
63
71
  exports.isBrowserEnv = require_env.isBrowserEnv;
72
+ exports.isBrowserEnvValue = require_env.isBrowserEnvValue;
64
73
  exports.isDebugMode = require_env.isDebugMode;
65
74
  exports.isManifestProvider = require_generateSnapshotFromManifest.isManifestProvider;
66
75
  exports.isReactNativeEnv = require_env.isReactNativeEnv;
@@ -77,6 +86,12 @@ Object.defineProperty(exports, 'moduleFederationPlugin', {
77
86
  });
78
87
  exports.normalizeOptions = require_normalizeOptions.normalizeOptions;
79
88
  exports.parseEntry = require_utils.parseEntry;
89
+ Object.defineProperty(exports, 'provideSharedPlugin', {
90
+ enumerable: true,
91
+ get: function () {
92
+ return require_ProvideSharedPlugin.ProvideSharedPlugin_exports;
93
+ }
94
+ });
80
95
  exports.safeToString = require_utils.safeToString;
81
96
  exports.safeWrapper = require_dom.safeWrapper;
82
97
  Object.defineProperty(exports, 'sharePlugin', {
package/dist/index.d.ts CHANGED
@@ -7,14 +7,15 @@ import { ModuleFederationPlugin_d_exports } from "./types/plugins/ModuleFederati
7
7
  import { ContainerPlugin_d_exports } from "./types/plugins/ContainerPlugin.js";
8
8
  import { ContainerReferencePlugin_d_exports } from "./types/plugins/ContainerReferencePlugin.js";
9
9
  import { SharePlugin_d_exports } from "./types/plugins/SharePlugin.js";
10
+ import { ConsumeSharedPlugin_d_exports } from "./types/plugins/ConsumeSharedPlugin.js";
11
+ import { ProvideSharedPlugin_d_exports } from "./types/plugins/ProvideSharedPlugin.js";
10
12
  import { CreateScriptHook, CreateScriptHookDom, CreateScriptHookNode, CreateScriptHookReturn, CreateScriptHookReturnDom, CreateScriptHookReturnNode, FetchHook } from "./types/hooks.js";
11
- import "./types/index.js";
12
13
  import { assert, composeKeyWithSeparator, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, getResourceUrl, isRequiredVersion, parseEntry, safeToString, warn } from "./utils.js";
13
14
  import { generateSnapshotFromManifest, getManifestFileName, inferAutoPublicPath, isManifestProvider, simpleJoinRemoteEntry } from "./generateSnapshotFromManifest.js";
14
15
  import { InfrastructureLogger, Logger, bindLoggerToCompiler, createInfrastructureLogger, createLogger, infrastructureLogger, logger } from "./logger.js";
15
- import { getProcessEnv, isBrowserEnv, isDebugMode, isReactNativeEnv } from "./env.js";
16
+ import { getProcessEnv, isBrowserEnv, isBrowserEnvValue, isDebugMode, isReactNativeEnv } from "./env.js";
16
17
  import { createLink, createScript, isStaticResourcesEqual, loadScript, safeWrapper } from "./dom.js";
17
18
  import { createScriptNode, loadScriptNode } from "./node.js";
18
19
  import { normalizeOptions } from "./normalizeOptions.js";
19
20
  import { createModuleFederationConfig } from "./createModuleFederationConfig.js";
20
- export { BROWSER_LOG_KEY, BasicProviderModuleInfo, BasicStatsMetaData, ConsumerModuleInfo, ConsumerModuleInfoWithPublicPath, CreateScriptHook, CreateScriptHookDom, CreateScriptHookNode, CreateScriptHookReturn, CreateScriptHookReturnDom, CreateScriptHookReturnNode, ENCODE_NAME_PREFIX, EncodedNameTransformMap, FederationModuleManifest, FetchHook, GlobalModuleInfo, type InfrastructureLogger, type Logger, MANIFEST_EXT, MFModuleType, MFPrefetchCommon, MODULE_DEVTOOL_IDENTIFIER, Manifest, ManifestExpose, ManifestFileName, ManifestModuleInfos, ManifestProvider, ManifestRemote, ManifestRemoteCommonInfo, ManifestShared, MetaDataTypes, Module, ModuleInfo, NameTransformMap, NameTransformSymbol, ProviderModuleInfo, PureConsumerModuleInfo, PureEntryProvider, RemoteEntryInfo, RemoteEntryType, RemoteWithEntry, RemoteWithVersion, ResourceInfo, SEPARATOR, Stats, StatsAssets, StatsBuildInfo, StatsExpose, StatsFileName, StatsMetaData, StatsMetaDataWithGetPublicPath, StatsMetaDataWithPublicPath, StatsModuleInfo, StatsRemote, StatsRemoteVal, StatsRemoteWithEntry, StatsRemoteWithVersion, StatsShared, TEMP_DIR, TreeShakingStatus, assert, bindLoggerToCompiler, composeKeyWithSeparator, ContainerPlugin_d_exports as containerPlugin, ContainerReferencePlugin_d_exports as containerReferencePlugin, createInfrastructureLogger, createLink, createLogger, createModuleFederationConfig, createScript, createScriptNode, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, generateSnapshotFromManifest, getManifestFileName, getProcessEnv, getResourceUrl, inferAutoPublicPath, infrastructureLogger, isBrowserEnv, isDebugMode, isManifestProvider, isReactNativeEnv, isRequiredVersion, isStaticResourcesEqual, loadScript, loadScriptNode, logger, ModuleFederationPlugin_d_exports as moduleFederationPlugin, normalizeOptions, parseEntry, safeToString, safeWrapper, SharePlugin_d_exports as sharePlugin, simpleJoinRemoteEntry, warn };
21
+ export { BROWSER_LOG_KEY, BasicProviderModuleInfo, BasicStatsMetaData, ConsumerModuleInfo, ConsumerModuleInfoWithPublicPath, CreateScriptHook, CreateScriptHookDom, CreateScriptHookNode, CreateScriptHookReturn, CreateScriptHookReturnDom, CreateScriptHookReturnNode, ENCODE_NAME_PREFIX, EncodedNameTransformMap, FederationModuleManifest, FetchHook, GlobalModuleInfo, type InfrastructureLogger, type Logger, MANIFEST_EXT, MFModuleType, MFPrefetchCommon, MODULE_DEVTOOL_IDENTIFIER, Manifest, ManifestExpose, ManifestFileName, ManifestModuleInfos, ManifestProvider, ManifestRemote, ManifestRemoteCommonInfo, ManifestShared, MetaDataTypes, Module, ModuleInfo, NameTransformMap, NameTransformSymbol, ProviderModuleInfo, PureConsumerModuleInfo, PureEntryProvider, RemoteEntryInfo, RemoteEntryType, RemoteWithEntry, RemoteWithVersion, ResourceInfo, SEPARATOR, Stats, StatsAssets, StatsBuildInfo, StatsExpose, StatsFileName, StatsMetaData, StatsMetaDataWithGetPublicPath, StatsMetaDataWithPublicPath, StatsModuleInfo, StatsRemote, StatsRemoteVal, StatsRemoteWithEntry, StatsRemoteWithVersion, StatsShared, TEMP_DIR, TreeShakingStatus, assert, bindLoggerToCompiler, composeKeyWithSeparator, ConsumeSharedPlugin_d_exports as consumeSharedPlugin, ContainerPlugin_d_exports as containerPlugin, ContainerReferencePlugin_d_exports as containerReferencePlugin, createInfrastructureLogger, createLink, createLogger, createModuleFederationConfig, createScript, createScriptNode, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, generateSnapshotFromManifest, getManifestFileName, getProcessEnv, getResourceUrl, inferAutoPublicPath, infrastructureLogger, isBrowserEnv, isBrowserEnvValue, isDebugMode, isManifestProvider, isReactNativeEnv, isRequiredVersion, isStaticResourcesEqual, loadScript, loadScriptNode, logger, ModuleFederationPlugin_d_exports as moduleFederationPlugin, normalizeOptions, parseEntry, ProvideSharedPlugin_d_exports as provideSharedPlugin, safeToString, safeWrapper, SharePlugin_d_exports as sharePlugin, simpleJoinRemoteEntry, warn };
package/dist/index.js CHANGED
@@ -3,7 +3,9 @@ import { ContainerPlugin_exports } from "./types/plugins/ContainerPlugin.js";
3
3
  import { ContainerReferencePlugin_exports } from "./types/plugins/ContainerReferencePlugin.js";
4
4
  import { ModuleFederationPlugin_exports } from "./types/plugins/ModuleFederationPlugin.js";
5
5
  import { SharePlugin_exports } from "./types/plugins/SharePlugin.js";
6
- import { getProcessEnv, isBrowserEnv, isDebugMode, isReactNativeEnv } from "./env.js";
6
+ import { ConsumeSharedPlugin_exports } from "./types/plugins/ConsumeSharedPlugin.js";
7
+ import { ProvideSharedPlugin_exports } from "./types/plugins/ProvideSharedPlugin.js";
8
+ import { getProcessEnv, isBrowserEnv, isBrowserEnvValue, isDebugMode, isReactNativeEnv } from "./env.js";
7
9
  import { assert, composeKeyWithSeparator, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, getResourceUrl, isRequiredVersion, parseEntry, safeToString, warn } from "./utils.js";
8
10
  import { generateSnapshotFromManifest, getManifestFileName, inferAutoPublicPath, isManifestProvider, simpleJoinRemoteEntry } from "./generateSnapshotFromManifest.js";
9
11
  import { bindLoggerToCompiler, createInfrastructureLogger, createLogger, infrastructureLogger, logger } from "./logger.js";
@@ -12,4 +14,4 @@ import { createScriptNode, loadScriptNode } from "./node.js";
12
14
  import { normalizeOptions } from "./normalizeOptions.js";
13
15
  import { createModuleFederationConfig } from "./createModuleFederationConfig.js";
14
16
 
15
- export { BROWSER_LOG_KEY, ENCODE_NAME_PREFIX, EncodedNameTransformMap, FederationModuleManifest, MANIFEST_EXT, MFModuleType, MFPrefetchCommon, MODULE_DEVTOOL_IDENTIFIER, ManifestFileName, NameTransformMap, NameTransformSymbol, SEPARATOR, StatsFileName, TEMP_DIR, TreeShakingStatus, assert, bindLoggerToCompiler, composeKeyWithSeparator, ContainerPlugin_exports as containerPlugin, ContainerReferencePlugin_exports as containerReferencePlugin, createInfrastructureLogger, createLink, createLogger, createModuleFederationConfig, createScript, createScriptNode, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, generateSnapshotFromManifest, getManifestFileName, getProcessEnv, getResourceUrl, inferAutoPublicPath, infrastructureLogger, isBrowserEnv, isDebugMode, isManifestProvider, isReactNativeEnv, isRequiredVersion, isStaticResourcesEqual, loadScript, loadScriptNode, logger, ModuleFederationPlugin_exports as moduleFederationPlugin, normalizeOptions, parseEntry, safeToString, safeWrapper, SharePlugin_exports as sharePlugin, simpleJoinRemoteEntry, warn };
17
+ export { BROWSER_LOG_KEY, ENCODE_NAME_PREFIX, EncodedNameTransformMap, FederationModuleManifest, MANIFEST_EXT, MFModuleType, MFPrefetchCommon, MODULE_DEVTOOL_IDENTIFIER, ManifestFileName, NameTransformMap, NameTransformSymbol, SEPARATOR, StatsFileName, TEMP_DIR, TreeShakingStatus, assert, bindLoggerToCompiler, composeKeyWithSeparator, ConsumeSharedPlugin_exports as consumeSharedPlugin, ContainerPlugin_exports as containerPlugin, ContainerReferencePlugin_exports as containerReferencePlugin, createInfrastructureLogger, createLink, createLogger, createModuleFederationConfig, createScript, createScriptNode, decodeName, encodeName, error, generateExposeFilename, generateShareFilename, generateSnapshotFromManifest, getManifestFileName, getProcessEnv, getResourceUrl, inferAutoPublicPath, infrastructureLogger, isBrowserEnv, isBrowserEnvValue, isDebugMode, isManifestProvider, isReactNativeEnv, isRequiredVersion, isStaticResourcesEqual, loadScript, loadScriptNode, logger, ModuleFederationPlugin_exports as moduleFederationPlugin, normalizeOptions, parseEntry, ProvideSharedPlugin_exports as provideSharedPlugin, safeToString, safeWrapper, SharePlugin_exports as sharePlugin, simpleJoinRemoteEntry, warn };
package/dist/node.cjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.cjs","names":[],"sources":["../src/node.ts"],"sourcesContent":["import { CreateScriptHookNode, FetchHook } from './types';\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst sdkImportCache = new Map<string, Promise<any>>();\n\nfunction importNodeModule<T>(name: string): Promise<T> {\n if (!name) {\n throw new Error('import specifier is required');\n }\n\n // Check cache to prevent infinite recursion\n if (sdkImportCache.has(name)) {\n return sdkImportCache.get(name)!;\n }\n\n const importModule = new Function('name', `return import(name)`);\n const promise = importModule(name)\n .then((res: any) => res as T)\n .catch((error: any) => {\n console.error(`Error importing module ${name}:`, error);\n // Remove from cache on error so it can be retried\n sdkImportCache.delete(name);\n throw error;\n });\n\n // Cache the promise to prevent recursive calls\n sdkImportCache.set(name, promise);\n return promise;\n}\n\nconst loadNodeFetch = async (): Promise<typeof fetch> => {\n const fetchModule =\n await importNodeModule<typeof import('node-fetch')>('node-fetch');\n return (fetchModule.default || fetchModule) as unknown as typeof fetch;\n};\n\nconst lazyLoaderHookFetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n loaderHook?: any,\n): Promise<Response> => {\n const hook = (url: RequestInfo | URL, init: RequestInit) => {\n return loaderHook.lifecycle.fetch.emit(url, init);\n };\n\n const res = await hook(input, init || {});\n if (!res || !(res instanceof Response)) {\n const fetchFunction =\n typeof fetch === 'undefined' ? await loadNodeFetch() : fetch;\n return fetchFunction(input, init || {});\n }\n\n return res;\n};\n\nexport const createScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n if (loaderHook?.createScriptHook) {\n const hookResult = loaderHook.createScriptHook(url);\n if (\n hookResult &&\n typeof hookResult === 'object' &&\n 'url' in hookResult\n ) {\n url = hookResult.url;\n }\n }\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch (e) {\n console.error('Error constructing URL:', e);\n cb(new Error(`Invalid URL: ${e}`));\n return;\n }\n\n const getFetch = async (): Promise<typeof fetch> => {\n if (loaderHook?.fetch) {\n return (input: RequestInfo | URL, init?: RequestInit) =>\n lazyLoaderHookFetch(input, init, loaderHook);\n }\n\n return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;\n };\n\n const handleScriptFetch = async (f: typeof fetch, urlObj: URL) => {\n try {\n const res = await f(urlObj.href);\n const data = await res.text();\n const [path, vm] = await Promise.all([\n importNodeModule<typeof import('path')>('path'),\n importNodeModule<typeof import('vm')>('vm'),\n ]);\n\n const scriptContext = { exports: {}, module: { exports: {} } };\n const urlDirname = urlObj.pathname\n .split('/')\n .slice(0, -1)\n .join('/');\n const filename = path.basename(urlObj.pathname);\n\n const script = new vm.Script(\n `(function(exports, module, require, __dirname, __filename) {${data}\\n})`,\n {\n filename,\n importModuleDynamically:\n //@ts-ignore\n vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ??\n importNodeModule,\n },\n );\n\n let requireFn: NodeRequire;\n if (process.env['IS_ESM_BUILD'] === 'true') {\n const nodeModule =\n await importNodeModule<typeof import('node:module')>(\n 'node:module',\n );\n requireFn = nodeModule.createRequire(\n urlObj.protocol === 'file:' || urlObj.protocol === 'node:'\n ? urlObj.href\n : path.join(process.cwd(), '__mf_require_base__.js'),\n );\n } else {\n requireFn = eval('require') as NodeRequire;\n }\n\n script.runInThisContext()(\n scriptContext.exports,\n scriptContext.module,\n requireFn,\n urlDirname,\n filename,\n );\n const exportedInterface: Record<string, any> =\n scriptContext.module.exports || scriptContext.exports;\n\n if (attrs && exportedInterface && attrs['globalName']) {\n const container =\n exportedInterface[attrs['globalName']] || exportedInterface;\n cb(\n undefined,\n container as keyof typeof scriptContext.module.exports,\n );\n return;\n }\n\n cb(\n undefined,\n exportedInterface as keyof typeof scriptContext.module.exports,\n );\n } catch (e) {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n }\n };\n\n getFetch()\n .then(async (f) => {\n if (attrs?.['type'] === 'esm' || attrs?.['type'] === 'module') {\n return loadModule(urlObj.href, {\n fetch: f,\n vm: await importNodeModule<typeof import('vm')>('vm'),\n })\n .then(async (module) => {\n await module.evaluate();\n cb(undefined, module.namespace);\n })\n .catch((e) => {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n });\n }\n handleScriptFetch(f, urlObj);\n })\n .catch((err) => {\n cb(err);\n });\n }\n : (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n cb(\n new Error('createScriptNode is disabled in non-Node.js environment'),\n );\n };\n\nexport const loadScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n return new Promise<void>((resolve, reject) => {\n createScriptNode(\n url,\n (error, scriptContext) => {\n if (error) {\n reject(error);\n } else {\n const remoteEntryKey =\n info?.attrs?.['globalName'] ||\n `__FEDERATION_${info?.attrs?.['name']}:custom__`;\n const entryExports = ((globalThis as any)[remoteEntryKey] =\n scriptContext);\n resolve(entryExports);\n }\n },\n info.attrs,\n info.loaderHook,\n );\n });\n }\n : (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n throw new Error(\n 'loadScriptNode is disabled in non-Node.js environment',\n );\n };\n\nconst esmModuleCache = new Map<string, any>();\n\nasync function loadModule(\n url: string,\n options: {\n vm: any;\n fetch: any;\n },\n) {\n // Check cache to prevent infinite recursion in ESM loading\n if (esmModuleCache.has(url)) {\n return esmModuleCache.get(url)!;\n }\n\n const { fetch, vm } = options;\n const response = await fetch(url);\n const code = await response.text();\n\n const module: any = new vm.SourceTextModule(code, {\n // @ts-ignore\n importModuleDynamically: async (specifier, script) => {\n const resolvedUrl = new URL(specifier, url).href;\n return loadModule(resolvedUrl, options);\n },\n });\n\n // Cache the module before linking to prevent cycles\n esmModuleCache.set(url, module);\n\n await module.link(async (specifier: string) => {\n const resolvedUrl = new URL(specifier, url).href;\n const module = await loadModule(resolvedUrl, options);\n return module;\n });\n\n return module;\n}\n"],"mappings":";;AAKA,MAAM,iCAAiB,IAAI,KAA2B;AAEtD,SAAS,iBAAoB,MAA0B;AACrD,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,+BAA+B;AAIjD,KAAI,eAAe,IAAI,KAAK,CAC1B,QAAO,eAAe,IAAI,KAAK;CAIjC,MAAM,UADe,IAAI,SAAS,QAAQ,sBAAsB,CACnC,KAAK,CAC/B,MAAM,QAAa,IAAS,CAC5B,OAAO,UAAe;AACrB,UAAQ,MAAM,0BAA0B,KAAK,IAAI,MAAM;AAEvD,iBAAe,OAAO,KAAK;AAC3B,QAAM;GACN;AAGJ,gBAAe,IAAI,MAAM,QAAQ;AACjC,QAAO;;AAGT,MAAM,gBAAgB,YAAmC;CACvD,MAAM,cACJ,MAAM,iBAA8C,aAAa;AACnE,QAAQ,YAAY,WAAW;;AAGjC,MAAM,sBAAsB,OAC1B,OACA,MACA,eACsB;CACtB,MAAM,QAAQ,KAAwB,SAAsB;AAC1D,SAAO,WAAW,UAAU,MAAM,KAAK,KAAK,KAAK;;CAGnD,MAAM,MAAM,MAAM,KAAK,OAAO,QAAQ,EAAE,CAAC;AACzC,KAAI,CAAC,OAAO,EAAE,eAAe,UAG3B,SADE,OAAO,UAAU,cAAc,MAAM,eAAe,GAAG,OACpC,OAAO,QAAQ,EAAE,CAAC;AAGzC,QAAO;;AAGT,MAAa,mBACX,OAAO,eAAe,eAAe,eAAe,SAE9C,KACA,IACA,OACA,eAIG;AACH,KAAI,YAAY,kBAAkB;EAChC,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F,gBAAe,IAAI,KAAK,OAAO;AAE/B,OAAM,OAAO,KAAK,OAAO,cAAsB;EAC7C,MAAM,cAAc,IAAI,IAAI,WAAW,IAAI,CAAC;AAE5C,SADe,MAAM,WAAW,aAAa,QAAQ;GAErD;AAEF,QAAO"}
1
+ {"version":3,"file":"node.cjs","names":[],"sources":["../src/node.ts"],"sourcesContent":["import { CreateScriptHookNode, FetchHook } from './types';\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst sdkImportCache = new Map<string, Promise<any>>();\n\nfunction importNodeModule<T>(name: string): Promise<T> {\n if (!name) {\n throw new Error('import specifier is required');\n }\n\n // Check cache to prevent infinite recursion\n if (sdkImportCache.has(name)) {\n return sdkImportCache.get(name)!;\n }\n\n const importModule = new Function('name', `return import(name)`);\n const promise = importModule(name)\n .then((res: any) => res as T)\n .catch((error: any) => {\n console.error(`Error importing module ${name}:`, error);\n // Remove from cache on error so it can be retried\n sdkImportCache.delete(name);\n throw error;\n });\n\n // Cache the promise to prevent recursive calls\n sdkImportCache.set(name, promise);\n return promise;\n}\n\nconst loadNodeFetch = async (): Promise<typeof fetch> => {\n const fetchModule =\n await importNodeModule<typeof import('node-fetch')>('node-fetch');\n return (fetchModule.default || fetchModule) as unknown as typeof fetch;\n};\n\nconst lazyLoaderHookFetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n loaderHook?: any,\n): Promise<Response> => {\n const hook = (url: RequestInfo | URL, init: RequestInit) => {\n return loaderHook.lifecycle.fetch.emit(url, init);\n };\n\n const res = await hook(input, init || {});\n if (!res || !(res instanceof Response)) {\n const fetchFunction =\n typeof fetch === 'undefined' ? await loadNodeFetch() : fetch;\n return fetchFunction(input, init || {});\n }\n\n return res;\n};\n\nexport const createScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n if (loaderHook?.createScriptHook) {\n const hookResult = loaderHook.createScriptHook(url);\n if (\n hookResult &&\n typeof hookResult === 'object' &&\n 'url' in hookResult\n ) {\n url = hookResult.url;\n }\n }\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch (e) {\n console.error('Error constructing URL:', e);\n cb(new Error(`Invalid URL: ${e}`));\n return;\n }\n\n const getFetch = async (): Promise<typeof fetch> => {\n if (loaderHook?.fetch) {\n return (input: RequestInfo | URL, init?: RequestInit) =>\n lazyLoaderHookFetch(input, init, loaderHook);\n }\n\n return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;\n };\n\n const handleScriptFetch = async (f: typeof fetch, urlObj: URL) => {\n try {\n const res = await f(urlObj.href);\n const data = await res.text();\n const [path, vm] = await Promise.all([\n importNodeModule<typeof import('path')>('path'),\n importNodeModule<typeof import('vm')>('vm'),\n ]);\n\n const scriptContext = { exports: {}, module: { exports: {} } };\n const urlDirname = urlObj.pathname\n .split('/')\n .slice(0, -1)\n .join('/');\n const filename = path.basename(urlObj.pathname);\n\n const script = new vm.Script(\n `(function(exports, module, require, __dirname, __filename) {${data}\\n})`,\n {\n filename,\n importModuleDynamically:\n //@ts-ignore\n vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ??\n importNodeModule,\n },\n );\n\n let requireFn: NodeRequire;\n if (process.env.IS_ESM_BUILD === 'true') {\n const nodeModule =\n await importNodeModule<typeof import('node:module')>(\n 'node:module',\n );\n requireFn = nodeModule.createRequire(\n urlObj.protocol === 'file:' || urlObj.protocol === 'node:'\n ? urlObj.href\n : path.join(process.cwd(), '__mf_require_base__.js'),\n );\n } else {\n requireFn = eval('require') as NodeRequire;\n }\n\n script.runInThisContext()(\n scriptContext.exports,\n scriptContext.module,\n requireFn,\n urlDirname,\n filename,\n );\n const exportedInterface: Record<string, any> =\n scriptContext.module.exports || scriptContext.exports;\n\n if (attrs && exportedInterface && attrs['globalName']) {\n const container =\n exportedInterface[attrs['globalName']] || exportedInterface;\n cb(\n undefined,\n container as keyof typeof scriptContext.module.exports,\n );\n return;\n }\n\n cb(\n undefined,\n exportedInterface as keyof typeof scriptContext.module.exports,\n );\n } catch (e) {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n }\n };\n\n getFetch()\n .then(async (f) => {\n if (attrs?.['type'] === 'esm' || attrs?.['type'] === 'module') {\n return loadModule(urlObj.href, {\n fetch: f,\n vm: await importNodeModule<typeof import('vm')>('vm'),\n })\n .then(async (module) => {\n await module.evaluate();\n cb(undefined, module.namespace);\n })\n .catch((e) => {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n });\n }\n handleScriptFetch(f, urlObj);\n })\n .catch((err) => {\n cb(err);\n });\n }\n : (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n cb(\n new Error('createScriptNode is disabled in non-Node.js environment'),\n );\n };\n\nexport const loadScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n return new Promise<void>((resolve, reject) => {\n createScriptNode(\n url,\n (error, scriptContext) => {\n if (error) {\n reject(error);\n } else {\n const remoteEntryKey =\n info?.attrs?.['globalName'] ||\n `__FEDERATION_${info?.attrs?.['name']}:custom__`;\n const entryExports = ((globalThis as any)[remoteEntryKey] =\n scriptContext);\n resolve(entryExports);\n }\n },\n info.attrs,\n info.loaderHook,\n );\n });\n }\n : (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n throw new Error(\n 'loadScriptNode is disabled in non-Node.js environment',\n );\n };\n\nconst esmModuleCache = new Map<string, any>();\n\nasync function loadModule(\n url: string,\n options: {\n vm: any;\n fetch: any;\n },\n) {\n // Check cache to prevent infinite recursion in ESM loading\n if (esmModuleCache.has(url)) {\n return esmModuleCache.get(url)!;\n }\n\n const { fetch, vm } = options;\n const response = await fetch(url);\n const code = await response.text();\n\n const module: any = new vm.SourceTextModule(code, {\n // @ts-ignore\n importModuleDynamically: async (specifier, script) => {\n const resolvedUrl = new URL(specifier, url).href;\n return loadModule(resolvedUrl, options);\n },\n });\n\n // Cache the module before linking to prevent cycles\n esmModuleCache.set(url, module);\n\n await module.link(async (specifier: string) => {\n const resolvedUrl = new URL(specifier, url).href;\n const module = await loadModule(resolvedUrl, options);\n return module;\n });\n\n return module;\n}\n"],"mappings":";;AAKA,MAAM,iCAAiB,IAAI,KAA2B;AAEtD,SAAS,iBAAoB,MAA0B;AACrD,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,+BAA+B;AAIjD,KAAI,eAAe,IAAI,KAAK,CAC1B,QAAO,eAAe,IAAI,KAAK;CAIjC,MAAM,UADe,IAAI,SAAS,QAAQ,sBAAsB,CACnC,KAAK,CAC/B,MAAM,QAAa,IAAS,CAC5B,OAAO,UAAe;AACrB,UAAQ,MAAM,0BAA0B,KAAK,IAAI,MAAM;AAEvD,iBAAe,OAAO,KAAK;AAC3B,QAAM;GACN;AAGJ,gBAAe,IAAI,MAAM,QAAQ;AACjC,QAAO;;AAGT,MAAM,gBAAgB,YAAmC;CACvD,MAAM,cACJ,MAAM,iBAA8C,aAAa;AACnE,QAAQ,YAAY,WAAW;;AAGjC,MAAM,sBAAsB,OAC1B,OACA,MACA,eACsB;CACtB,MAAM,QAAQ,KAAwB,SAAsB;AAC1D,SAAO,WAAW,UAAU,MAAM,KAAK,KAAK,KAAK;;CAGnD,MAAM,MAAM,MAAM,KAAK,OAAO,QAAQ,EAAE,CAAC;AACzC,KAAI,CAAC,OAAO,EAAE,eAAe,UAG3B,SADE,OAAO,UAAU,cAAc,MAAM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c,IAAI,GAAG,iBAAiB,MAAM,EAEhD,yBAAyB,OAAO,WAAW,WAAW;EACpD,MAAM,cAAc,IAAI,IAAI,WAAW,IAAI,CAAC;AAC5C,SAAO,WAAW,aAAa,QAAQ;IAE1C,CAAC;AAGF,gBAAe,IAAI,KAAK,OAAO;AAE/B,OAAM,OAAO,KAAK,OAAO,cAAsB;EAC7C,MAAM,cAAc,IAAI,IAAI,WAAW,IAAI,CAAC;AAE5C,SADe,MAAM,WAAW,aAAa,QAAQ;GAErD;AAEF,QAAO"}
package/dist/node.d.ts CHANGED
@@ -1,6 +1,4 @@
1
1
  import { CreateScriptHookNode, FetchHook } from "./types/hooks.js";
2
- import "./types/index.js";
3
-
4
2
  //#region src/node.d.ts
5
3
  declare const createScriptNode: (url: string, cb: (error?: Error, scriptContext?: any) => void, attrs?: Record<string, any>, loaderHook?: {
6
4
  createScriptHook?: CreateScriptHookNode;
package/dist/node.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"node.js","names":[],"sources":["../src/node.ts"],"sourcesContent":["import { CreateScriptHookNode, FetchHook } from './types';\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst sdkImportCache = new Map<string, Promise<any>>();\n\nfunction importNodeModule<T>(name: string): Promise<T> {\n if (!name) {\n throw new Error('import specifier is required');\n }\n\n // Check cache to prevent infinite recursion\n if (sdkImportCache.has(name)) {\n return sdkImportCache.get(name)!;\n }\n\n const importModule = new Function('name', `return import(name)`);\n const promise = importModule(name)\n .then((res: any) => res as T)\n .catch((error: any) => {\n console.error(`Error importing module ${name}:`, error);\n // Remove from cache on error so it can be retried\n sdkImportCache.delete(name);\n throw error;\n });\n\n // Cache the promise to prevent recursive calls\n sdkImportCache.set(name, promise);\n return promise;\n}\n\nconst loadNodeFetch = async (): Promise<typeof fetch> => {\n const fetchModule =\n await importNodeModule<typeof import('node-fetch')>('node-fetch');\n return (fetchModule.default || fetchModule) as unknown as typeof fetch;\n};\n\nconst lazyLoaderHookFetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n loaderHook?: any,\n): Promise<Response> => {\n const hook = (url: RequestInfo | URL, init: RequestInit) => {\n return loaderHook.lifecycle.fetch.emit(url, init);\n };\n\n const res = await hook(input, init || {});\n if (!res || !(res instanceof Response)) {\n const fetchFunction =\n typeof fetch === 'undefined' ? await loadNodeFetch() : fetch;\n return fetchFunction(input, init || {});\n }\n\n return res;\n};\n\nexport const createScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n if (loaderHook?.createScriptHook) {\n const hookResult = loaderHook.createScriptHook(url);\n if (\n hookResult &&\n typeof hookResult === 'object' &&\n 'url' in hookResult\n ) {\n url = hookResult.url;\n }\n }\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch (e) {\n console.error('Error constructing URL:', e);\n cb(new Error(`Invalid URL: ${e}`));\n return;\n }\n\n const getFetch = async (): Promise<typeof fetch> => {\n if (loaderHook?.fetch) {\n return (input: RequestInfo | URL, init?: RequestInit) =>\n lazyLoaderHookFetch(input, init, loaderHook);\n }\n\n return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;\n };\n\n const handleScriptFetch = async (f: typeof fetch, urlObj: URL) => {\n try {\n const res = await f(urlObj.href);\n const data = await res.text();\n const [path, vm] = await Promise.all([\n importNodeModule<typeof import('path')>('path'),\n importNodeModule<typeof import('vm')>('vm'),\n ]);\n\n const scriptContext = { exports: {}, module: { exports: {} } };\n const urlDirname = urlObj.pathname\n .split('/')\n .slice(0, -1)\n .join('/');\n const filename = path.basename(urlObj.pathname);\n\n const script = new vm.Script(\n `(function(exports, module, require, __dirname, __filename) {${data}\\n})`,\n {\n filename,\n importModuleDynamically:\n //@ts-ignore\n vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ??\n importNodeModule,\n },\n );\n\n let requireFn: NodeRequire;\n if (process.env['IS_ESM_BUILD'] === 'true') {\n const nodeModule =\n await importNodeModule<typeof import('node:module')>(\n 'node:module',\n );\n requireFn = nodeModule.createRequire(\n urlObj.protocol === 'file:' || urlObj.protocol === 'node:'\n ? urlObj.href\n : path.join(process.cwd(), '__mf_require_base__.js'),\n );\n } else {\n requireFn = eval('require') as NodeRequire;\n }\n\n script.runInThisContext()(\n scriptContext.exports,\n scriptContext.module,\n requireFn,\n urlDirname,\n filename,\n );\n const exportedInterface: Record<string, any> =\n scriptContext.module.exports || scriptContext.exports;\n\n if (attrs && exportedInterface && attrs['globalName']) {\n const container =\n exportedInterface[attrs['globalName']] || exportedInterface;\n cb(\n undefined,\n container as keyof typeof scriptContext.module.exports,\n );\n return;\n }\n\n cb(\n undefined,\n exportedInterface as keyof typeof scriptContext.module.exports,\n );\n } catch (e) {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n }\n };\n\n getFetch()\n .then(async (f) => {\n if (attrs?.['type'] === 'esm' || attrs?.['type'] === 'module') {\n return loadModule(urlObj.href, {\n fetch: f,\n vm: await importNodeModule<typeof import('vm')>('vm'),\n })\n .then(async (module) => {\n await module.evaluate();\n cb(undefined, module.namespace);\n })\n .catch((e) => {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n });\n }\n handleScriptFetch(f, urlObj);\n })\n .catch((err) => {\n cb(err);\n });\n }\n : (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n cb(\n new Error('createScriptNode is disabled in non-Node.js environment'),\n );\n };\n\nexport const loadScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n return new Promise<void>((resolve, reject) => {\n createScriptNode(\n url,\n (error, scriptContext) => {\n if (error) {\n reject(error);\n } else {\n const remoteEntryKey =\n info?.attrs?.['globalName'] ||\n `__FEDERATION_${info?.attrs?.['name']}:custom__`;\n const entryExports = ((globalThis as any)[remoteEntryKey] =\n scriptContext);\n resolve(entryExports);\n }\n },\n info.attrs,\n info.loaderHook,\n );\n });\n }\n : (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n throw new Error(\n 'loadScriptNode is disabled in non-Node.js environment',\n );\n };\n\nconst esmModuleCache = new Map<string, any>();\n\nasync function loadModule(\n url: string,\n options: {\n vm: any;\n fetch: any;\n },\n) {\n // Check cache to prevent infinite recursion in ESM loading\n if (esmModuleCache.has(url)) {\n return esmModuleCache.get(url)!;\n }\n\n const { fetch, vm } = options;\n const response = await fetch(url);\n const code = await response.text();\n\n const module: any = new vm.SourceTextModule(code, {\n // @ts-ignore\n importModuleDynamically: async (specifier, script) => {\n const resolvedUrl = new URL(specifier, url).href;\n return loadModule(resolvedUrl, options);\n },\n });\n\n // Cache the module before linking to prevent cycles\n esmModuleCache.set(url, module);\n\n await module.link(async (specifier: string) => {\n const resolvedUrl = new URL(specifier, url).href;\n const module = await loadModule(resolvedUrl, options);\n return module;\n });\n\n return module;\n}\n"],"mappings":";AAKA,MAAM,iCAAiB,IAAI,KAA2B;AAEtD,SAAS,iBAAoB,MAA0B;AACrD,KAAI,CAAC,KACH,OAAM,IAAI,MAAM,+BAA+B;AAIjD,KAAI,eAAe,IAAI,KAAK,CAC1B,QAAO,eAAe,IAAI,KAAK;CAIjC,MAAM,UADe,IAAI,SAAS,QAAQ,sBAAsB,CACnC,KAAK,CAC/B,MAAM,QAAa,IAAS,CAC5B,OAAO,UAAe;AACrB,UAAQ,MAAM,0BAA0B,KAAK,IAAI,MAAM;AAEvD,iBAAe,OAA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AAe,SAE9C,KACA,SAMG;AACH,QAAO,IAAI,SAAe,SAAS,WAAW;AAC5C,mBACE,MACC,OAAO,kBAAkB;AACxB,OAAI,MACF,QAAO,MAAM;QACR;IACL,MAAM,iBACJ,MAAM,QAAQ,iBACd,gBAAgB,MAAM,QAAQ,QAAQ;AAGxC,YAFsB,AAAC,WAAmB,kBACxC,cACmB;;KAGzB,KAAK,OACL,KAAK,WACN;GACD;KAGF,KACA,SAMG;AACH,OAAM,IAAI,MACR,wDACD;;AAGT,MAAM,iCAAiB,IAAI,KAAkB;AAE7C,eAAe,WACb,KACA,SAIA;AAEA,KAAI,eAAe,IAAI,IAAI,CACzB,QAAO,eAAe,IAAI,IAAI;CAGhC,MAAM,EAAE,OAAO,OAAO;CAEtB,MAAM,OAAO,OADI,MAAM,MAAM,IAAI,EACL,MAAM;CAElC,MAAM,SAAc,IAAI,GAAG,iBAAiB,MAAM,EAEhD,yBAAyB,OAAO,WAAW,WAAW;EACpD,MAAM,cAAc,IAAI,IAAI,WAAW,IAAI,CAAC;AAC5C,SAAO,WAAW,aAAa,QAAQ;IAE1C,CAAC;AAGF,gBAAe,IAAI,KAAK,OAAO;AAE/B,OAAM,OAAO,KAAK,OAAO,cAAsB;EAC7C,MAAM,cAAc,IAAI,IAAI,WAAW,IAAI,CAAC;AAE5C,SADe,MAAM,WAAW,aAAa,QAAQ;GAErD;AAEF,QAAO"}
1
+ {"version":3,"file":"node.js","names":[],"sources":["../src/node.ts"],"sourcesContent":["import { CreateScriptHookNode, FetchHook } from './types';\n\n// Declare the ENV_TARGET constant that will be defined by DefinePlugin\ndeclare const ENV_TARGET: 'web' | 'node';\n\nconst sdkImportCache = new Map<string, Promise<any>>();\n\nfunction importNodeModule<T>(name: string): Promise<T> {\n if (!name) {\n throw new Error('import specifier is required');\n }\n\n // Check cache to prevent infinite recursion\n if (sdkImportCache.has(name)) {\n return sdkImportCache.get(name)!;\n }\n\n const importModule = new Function('name', `return import(name)`);\n const promise = importModule(name)\n .then((res: any) => res as T)\n .catch((error: any) => {\n console.error(`Error importing module ${name}:`, error);\n // Remove from cache on error so it can be retried\n sdkImportCache.delete(name);\n throw error;\n });\n\n // Cache the promise to prevent recursive calls\n sdkImportCache.set(name, promise);\n return promise;\n}\n\nconst loadNodeFetch = async (): Promise<typeof fetch> => {\n const fetchModule =\n await importNodeModule<typeof import('node-fetch')>('node-fetch');\n return (fetchModule.default || fetchModule) as unknown as typeof fetch;\n};\n\nconst lazyLoaderHookFetch = async (\n input: RequestInfo | URL,\n init?: RequestInit,\n loaderHook?: any,\n): Promise<Response> => {\n const hook = (url: RequestInfo | URL, init: RequestInit) => {\n return loaderHook.lifecycle.fetch.emit(url, init);\n };\n\n const res = await hook(input, init || {});\n if (!res || !(res instanceof Response)) {\n const fetchFunction =\n typeof fetch === 'undefined' ? await loadNodeFetch() : fetch;\n return fetchFunction(input, init || {});\n }\n\n return res;\n};\n\nexport const createScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n if (loaderHook?.createScriptHook) {\n const hookResult = loaderHook.createScriptHook(url);\n if (\n hookResult &&\n typeof hookResult === 'object' &&\n 'url' in hookResult\n ) {\n url = hookResult.url;\n }\n }\n\n let urlObj: URL;\n try {\n urlObj = new URL(url);\n } catch (e) {\n console.error('Error constructing URL:', e);\n cb(new Error(`Invalid URL: ${e}`));\n return;\n }\n\n const getFetch = async (): Promise<typeof fetch> => {\n if (loaderHook?.fetch) {\n return (input: RequestInfo | URL, init?: RequestInit) =>\n lazyLoaderHookFetch(input, init, loaderHook);\n }\n\n return typeof fetch === 'undefined' ? loadNodeFetch() : fetch;\n };\n\n const handleScriptFetch = async (f: typeof fetch, urlObj: URL) => {\n try {\n const res = await f(urlObj.href);\n const data = await res.text();\n const [path, vm] = await Promise.all([\n importNodeModule<typeof import('path')>('path'),\n importNodeModule<typeof import('vm')>('vm'),\n ]);\n\n const scriptContext = { exports: {}, module: { exports: {} } };\n const urlDirname = urlObj.pathname\n .split('/')\n .slice(0, -1)\n .join('/');\n const filename = path.basename(urlObj.pathname);\n\n const script = new vm.Script(\n `(function(exports, module, require, __dirname, __filename) {${data}\\n})`,\n {\n filename,\n importModuleDynamically:\n //@ts-ignore\n vm.constants?.USE_MAIN_CONTEXT_DEFAULT_LOADER ??\n importNodeModule,\n },\n );\n\n let requireFn: NodeRequire;\n if (process.env.IS_ESM_BUILD === 'true') {\n const nodeModule =\n await importNodeModule<typeof import('node:module')>(\n 'node:module',\n );\n requireFn = nodeModule.createRequire(\n urlObj.protocol === 'file:' || urlObj.protocol === 'node:'\n ? urlObj.href\n : path.join(process.cwd(), '__mf_require_base__.js'),\n );\n } else {\n requireFn = eval('require') as NodeRequire;\n }\n\n script.runInThisContext()(\n scriptContext.exports,\n scriptContext.module,\n requireFn,\n urlDirname,\n filename,\n );\n const exportedInterface: Record<string, any> =\n scriptContext.module.exports || scriptContext.exports;\n\n if (attrs && exportedInterface && attrs['globalName']) {\n const container =\n exportedInterface[attrs['globalName']] || exportedInterface;\n cb(\n undefined,\n container as keyof typeof scriptContext.module.exports,\n );\n return;\n }\n\n cb(\n undefined,\n exportedInterface as keyof typeof scriptContext.module.exports,\n );\n } catch (e) {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n }\n };\n\n getFetch()\n .then(async (f) => {\n if (attrs?.['type'] === 'esm' || attrs?.['type'] === 'module') {\n return loadModule(urlObj.href, {\n fetch: f,\n vm: await importNodeModule<typeof import('vm')>('vm'),\n })\n .then(async (module) => {\n await module.evaluate();\n cb(undefined, module.namespace);\n })\n .catch((e) => {\n cb(\n e instanceof Error\n ? e\n : new Error(`Script execution error: ${e}`),\n );\n });\n }\n handleScriptFetch(f, urlObj);\n })\n .catch((err) => {\n cb(err);\n });\n }\n : (\n url: string,\n cb: (error?: Error, scriptContext?: any) => void,\n attrs?: Record<string, any>,\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n fetch?: FetchHook;\n },\n ) => {\n cb(\n new Error('createScriptNode is disabled in non-Node.js environment'),\n );\n };\n\nexport const loadScriptNode =\n typeof ENV_TARGET === 'undefined' || ENV_TARGET !== 'web'\n ? (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n return new Promise<void>((resolve, reject) => {\n createScriptNode(\n url,\n (error, scriptContext) => {\n if (error) {\n reject(error);\n } else {\n const remoteEntryKey =\n info?.attrs?.['globalName'] ||\n `__FEDERATION_${info?.attrs?.['name']}:custom__`;\n const entryExports = ((globalThis as any)[remoteEntryKey] =\n scriptContext);\n resolve(entryExports);\n }\n },\n info.attrs,\n info.loaderHook,\n );\n });\n }\n : (\n url: string,\n info: {\n attrs?: Record<string, any>;\n loaderHook?: {\n createScriptHook?: CreateScriptHookNode;\n };\n },\n ) => {\n throw new Error(\n 'loadScriptNode is disabled in non-Node.js environment',\n );\n };\n\nconst esmModuleCache = new Map<string, any>();\n\nasync function loadModule(\n url: string,\n options: {\n vm: any;\n fetch: any;\n },\n) {\n // Check cache to prevent infinite recursion in ESM loading\n if (esmModuleCache.has(url)) {\n return esmModuleCache.get(url)!;\n }\n\n const { fetch, vm } = options;\n const response = await fetch(url);\n const code = await response.text();\n\n const module: any = new vm.SourceTextModule(code, {\n // @ts-ignore\n importModuleDynamically: async (specifier, script) => {\n const resolvedUrl = new URL(specifier, url).href;\n return loadModule(resolvedUrl, options);\n },\n });\n\n // Cache the module before linking to prevent cycles\n esmModuleCache.set(url, module);\n\n await module.link(async (specifier: string) => {\n const resolvedUrl = new URL(specifier, url).href;\n const module = await loadModule(resolvedUrl, options);\n return module;\n });\n\n return module;\n}\n"],"mappings":";AAKA,MAAM,iCAAiB,IAAI,KAA2B;AAEtD,SAAS,iBAAoB,MAA0B;AACrD,KAA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;IAC/B,CACD,OAAO,MAAM;AACZ,MACE,aAAa,QACT,oBACA,IAAI,MAAM,2BAA2B,IAAI,CAC9C;IACD;AAEN,oBAAkB,GAAG,OAAO;GAC5B,CACD,OAAO,QAAQ;AACd,KAAG,IAAI;GACP;KAGJ,KACA,IACA,OACA,eAIG;AACH,oBACE,IAAI,MAAM,0DAA0D,CACrE;;AAGT,MAAa,iBACX,OAAO,eAAe,eAAe,eAAe,SAE9C,KACA,SAMG;AACH,QAAO,IAAI,SAAe,SAAS,WAAW;AAC5C,mBACE,MACC,OAAO,kBAAkB;AACxB,OAAI,MACF,QAAO,MAAM;QACR;IACL,MAAM,iBACJ,MAAM,QAAQ,iBACd,gBAAgB,MAAM,QAAQ,QAAQ;AAGxC,YAFsB,AAAC,WAAmB,kBACxC,cACmB;;KAGzB,KAAK,OACL,KAAK,WACN;GACD;KAGF,KACA,SAMG;AACH,OAAM,IAAI,MACR,wDACD;;AAGT,MAAM,iCAAiB,IAAI,KAAkB;AAE7C,eAAe,WACb,KACA,SAIA;AAEA,KAAI,eAAe,IAAI,IAAI,CACzB,QAAO,eAAe,IAAI,IAAI;CAGhC,MAAM,EAAE,OAAO,OAAO;CAEtB,MAAM,OAAO,OADI,MAAM,MAAM,IAAI,EACL,MAAM;CAElC,MAAM,SAAc,IAAI,GAAG,iBAAiB,MAAM,EAEhD,yBAAyB,OAAO,WAAW,WAAW;EACpD,MAAM,cAAc,IAAI,IAAI,WAAW,IAAI,CAAC;AAC5C,SAAO,WAAW,aAAa,QAAQ;IAE1C,CAAC;AAGF,gBAAe,IAAI,KAAK,OAAO;AAE/B,OAAM,OAAO,KAAK,OAAO,cAAsB;EAC7C,MAAM,cAAc,IAAI,IAAI,WAAW,IAAI,CAAC;AAE5C,SADe,MAAM,WAAW,aAAa,QAAQ;GAErD;AAEF,QAAO"}
@@ -6,5 +6,6 @@ import { ModuleFederationPlugin_d_exports } from "./plugins/ModuleFederationPlug
6
6
  import { ContainerPlugin_d_exports } from "./plugins/ContainerPlugin.js";
7
7
  import { ContainerReferencePlugin_d_exports } from "./plugins/ContainerReferencePlugin.js";
8
8
  import { SharePlugin_d_exports } from "./plugins/SharePlugin.js";
9
- import "./plugins/index.js";
9
+ import { ConsumeSharedPlugin_d_exports } from "./plugins/ConsumeSharedPlugin.js";
10
+ import { ProvideSharedPlugin_d_exports } from "./plugins/ProvideSharedPlugin.js";
10
11
  import { CreateScriptHook, CreateScriptHookDom, CreateScriptHookNode, CreateScriptHookReturn, CreateScriptHookReturnDom, CreateScriptHookReturnNode, FetchHook } from "./hooks.js";
@@ -0,0 +1,13 @@
1
+ const require_runtime = require('../../_virtual/_rolldown/runtime.cjs');
2
+
3
+ //#region src/types/plugins/ConsumeSharedPlugin.ts
4
+ var ConsumeSharedPlugin_exports = /* @__PURE__ */ require_runtime.__exportAll({});
5
+
6
+ //#endregion
7
+ Object.defineProperty(exports, 'ConsumeSharedPlugin_exports', {
8
+ enumerable: true,
9
+ get: function () {
10
+ return ConsumeSharedPlugin_exports;
11
+ }
12
+ });
13
+ //# sourceMappingURL=ConsumeSharedPlugin.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ConsumeSharedPlugin.cjs","names":[],"sources":["../../../src/types/plugins/ConsumeSharedPlugin.ts"],"sourcesContent":["/*\n * This file was automatically generated.\n * DO NOT MODIFY BY HAND.\n * Run `pnpm generate:schema -w` to update.\n */\n\n/**\n * A module that should be consumed from share scope.\n */\nexport type ConsumesItem = string;\n\n/**\n * Advanced configuration for modules that should be consumed from share scope.\n */\nexport interface ConsumesConfig {\n /**\n * Include the fallback module directly instead behind an async request. This allows to use fallback module in initial load too. All possible shared modules need to be eager too.\n */\n eager?: boolean;\n /**\n * Fallback module if no shared module is found in share scope. Defaults to the property name.\n */\n import?: false | ConsumesItem;\n /**\n * Package name to determine required version from description file. This is only needed when package name can't be automatically determined from request.\n */\n packageName?: string;\n /**\n * Version requirement from module in share scope.\n */\n requiredVersion?: false | string;\n /**\n * Module is looked up under this key from the share scope.\n */\n shareKey?: string;\n /**\n * Share scope name.\n */\n shareScope?: string | string[];\n /**\n * Layer in which the shared module should be placed.\n */\n layer?: string;\n /**\n * Layer of the issuer.\n */\n issuerLayer?: string;\n /**\n * Import request to match on\n */\n request?: string;\n /**\n * Allow only a single version of the shared module in share scope (disabled by default).\n */\n singleton?: boolean;\n /**\n * Do not accept shared module if version is not valid (defaults to yes, if local fallback module is available and shared module is not a singleton, otherwise no, has no effect if there is no required version specified).\n */\n strictVersion?: boolean;\n /**\n * Filter consumed modules based on the request path.\n */\n exclude?: IncludeExcludeOptions;\n /**\n * Filter consumed modules based on the request path (only include matches).\n */\n include?: IncludeExcludeOptions;\n /**\n * Enable reconstructed lookup for node_modules paths for this share item\n */\n allowNodeModulesSuffixMatch?: boolean;\n /**\n * Tree shaking mode for the shared module.\n */\n treeShakingMode?: 'server-calc' | 'runtime-infer';\n}\n\n/**\n * Modules that should be consumed from share scope. Property names are used to match requested modules in this compilation. Relative requests are resolved, module requests are matched unresolved, absolute paths will match resolved requests. A trailing slash will match all requests with this prefix. In this case shareKey must also have a trailing slash.\n */\nexport interface ConsumesObject {\n [k: string]: ConsumesConfig | ConsumesItem;\n}\n\n/**\n * Modules that should be consumed from share scope. When provided, property names are used to match requested modules in this compilation.\n */\nexport type Consumes = (ConsumesItem | ConsumesObject)[] | ConsumesObject;\n\nexport interface IncludeExcludeOptions {\n request?: string | RegExp;\n /**\n * Semantic versioning range to match against the module's version.\n */\n version?: string;\n /**\n * Optional specific version string to check against the version range instead of reading package.json.\n */\n fallbackVersion?: string;\n}\n\nexport interface ConsumeSharedPluginOptions {\n consumes: Consumes;\n /**\n * Share scope name used for all consumed modules (defaults to 'default').\n */\n shareScope?: string | string[];\n /**\n * Experimental features configuration\n */\n experiments?: {\n /** Enable reconstructed lookup for node_modules paths */\n allowNodeModulesSuffixMatch?: boolean;\n };\n}\n"],"mappings":""}