@module-federation/data-prefetch 0.0.0-next-20240617071542

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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,10 @@
1
+ @module-federation/data-prefetch
2
+
3
+ ## 0.0.0-next-20240617071542
4
+
5
+ ### Patch Changes
6
+
7
+ - Updated dependencies [103cd07]
8
+ - Updated dependencies [364f2bc]
9
+ - @module-federation/runtime@0.0.0-next-20240617071542
10
+ - @module-federation/sdk@0.0.0-next-20240617071542
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 ScriptedAlchemy LLC (Zack Jackson) Zhou Shaw (zhouxiao)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ Vmok Interface Prefetch
2
+ https://vmok.bytedance.net/guide/performance/prefetch.html
@@ -0,0 +1,39 @@
1
+ import { moduleFederationPlugin } from '@module-federation/sdk';
2
+
3
+ interface BabelPluginOptions {
4
+ hook_id: string;
5
+ import_pkg: string;
6
+ attribute: string;
7
+ mf_name: string;
8
+ exposes: moduleFederationPlugin.ModuleFederationPluginOptions['exposes'];
9
+ }
10
+ declare const _default: (babel: {
11
+ types: any;
12
+ }, options: BabelPluginOptions) => {
13
+ visitor?: undefined;
14
+ } | {
15
+ visitor: {
16
+ ImportDeclaration(nodePath: {
17
+ node: {
18
+ source: {
19
+ value: any;
20
+ };
21
+ specifiers: any;
22
+ };
23
+ }, state: {
24
+ file: {
25
+ opts: {
26
+ filename: any;
27
+ };
28
+ };
29
+ }): void;
30
+ CallExpression(nodePath: {
31
+ node: {
32
+ callee: any;
33
+ arguments: string | any[];
34
+ };
35
+ }): void;
36
+ };
37
+ };
38
+
39
+ export { _default as default };
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+
26
+ // src/cli/babel.ts
27
+ var babel_exports = {};
28
+ __export(babel_exports, {
29
+ default: () => babel_default
30
+ });
31
+ module.exports = __toCommonJS(babel_exports);
32
+ var import_path = __toESM(require("path"));
33
+ var attribute = "id";
34
+ var hookId = "usePrefetch";
35
+ var importPackage = "@module-federation/data-prefetch/react";
36
+ var babel_default = (babel, options) => {
37
+ const t = babel.types;
38
+ let shouldHandle = false;
39
+ let scope = "";
40
+ const { mf_name: name, exposes } = options;
41
+ if (!exposes) {
42
+ return {};
43
+ }
44
+ const exposesKey = Object.keys(exposes);
45
+ const processedExposes = exposesKey.map((expose) => ({
46
+ key: expose.replace(".", ""),
47
+ value: import_path.default.resolve(
48
+ typeof exposes[expose] === "string" ? exposes[expose] : exposes[expose].import
49
+ )
50
+ }));
51
+ return {
52
+ visitor: {
53
+ ImportDeclaration(nodePath, state) {
54
+ const source = nodePath.node.source.value;
55
+ const { specifiers } = nodePath.node;
56
+ const { filename } = state.file.opts;
57
+ if (source === importPackage) {
58
+ shouldHandle = specifiers.some(
59
+ (specifier) => specifier.imported && specifier.imported.name === hookId && processedExposes.find(
60
+ (expose) => expose.value === filename && (scope = expose.key)
61
+ )
62
+ );
63
+ }
64
+ },
65
+ CallExpression(nodePath) {
66
+ if (shouldHandle && t.isIdentifier(nodePath.node.callee, { name: hookId }) && nodePath.node.arguments.length > 0) {
67
+ const objectExpression = nodePath.node.arguments[0];
68
+ if (objectExpression && t.isObjectExpression(objectExpression) && !objectExpression.properties.find(
69
+ (p) => p.key.name === attribute
70
+ )) {
71
+ objectExpression.properties.push(
72
+ t.objectProperty(
73
+ t.identifier(attribute),
74
+ t.stringLiteral(name + scope)
75
+ )
76
+ );
77
+ }
78
+ }
79
+ }
80
+ }
81
+ };
82
+ };
83
+ // Annotate the CommonJS export names for ESM import in node:
84
+ 0 && (module.exports = {});
@@ -0,0 +1,11 @@
1
+ import { moduleFederationPlugin } from '@module-federation/sdk';
2
+ import { WebpackPluginInstance, Compiler } from 'webpack';
3
+
4
+ declare class PrefetchPlugin implements WebpackPluginInstance {
5
+ options: moduleFederationPlugin.ModuleFederationPluginOptions;
6
+ private _reWriteExports;
7
+ constructor(options: moduleFederationPlugin.ModuleFederationPluginOptions);
8
+ apply(compiler: Compiler): void;
9
+ }
10
+
11
+ export { PrefetchPlugin };
@@ -0,0 +1,165 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
22
+ mod
23
+ ));
24
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
25
+
26
+ // src/cli/index.ts
27
+ var cli_exports = {};
28
+ __export(cli_exports, {
29
+ PrefetchPlugin: () => PrefetchPlugin
30
+ });
31
+ module.exports = __toCommonJS(cli_exports);
32
+ var import_path2 = __toESM(require("path"));
33
+ var import_fs_extra2 = __toESM(require("fs-extra"));
34
+ var import_sdk2 = require("@module-federation/sdk");
35
+
36
+ // src/common/constant.ts
37
+ var TEMP_DIR = ".mf";
38
+
39
+ // src/common/node-utils.ts
40
+ var import_path = __toESM(require("path"));
41
+ var import_fs_extra = __toESM(require("fs-extra"));
42
+ var fileExistsWithCaseSync = (filepath) => {
43
+ const dir = import_path.default.dirname(filepath);
44
+ if (filepath === "/" || filepath === ".") {
45
+ return true;
46
+ }
47
+ const filenames = import_fs_extra.default.readdirSync(dir);
48
+ if (filenames.indexOf(import_path.default.basename(filepath)) === -1) {
49
+ return false;
50
+ }
51
+ return fileExistsWithCaseSync(dir);
52
+ };
53
+ var fixPrefetchPath = (exposePath) => {
54
+ const pathExt = [".js", ".ts"];
55
+ const extReg = /\.(ts|js|tsx|jsx)$/;
56
+ if (extReg.test(exposePath)) {
57
+ return pathExt.map((ext) => exposePath.replace(extReg, `.prefetch${ext}`));
58
+ } else {
59
+ return pathExt.map((ext) => exposePath + `.prefetch${ext}`);
60
+ }
61
+ };
62
+
63
+ // src/common/runtime-utils.ts
64
+ var import_sdk = require("@module-federation/sdk");
65
+ var getPrefetchId = (id) => (0, import_sdk.encodeName)(`${id}/${import_sdk.MFPrefetchCommon.identifier}`);
66
+
67
+ // src/cli/index.ts
68
+ var addTemplate = (name) => `
69
+ export default function () {
70
+ let hasInit = false;
71
+ return {
72
+ name: 'data-prefetch-init-plugin',
73
+ beforeInit(args) {
74
+ if (!hasInit) {
75
+ hasInit = true;
76
+ globalThis.__FEDERATION__ = globalThis.__FEDERATION__ || {};
77
+ globalThis.__FEDERATION__['${import_sdk2.MFPrefetchCommon.globalKey}'] = globalThis.__FEDERATION__['${import_sdk2.MFPrefetchCommon.globalKey}'] || {
78
+ entryLoading: {},
79
+ instance: new Map(),
80
+ __PREFETCH_EXPORTS__: {},
81
+ };
82
+ globalThis.__FEDERATION__['${import_sdk2.MFPrefetchCommon.globalKey}']['${import_sdk2.MFPrefetchCommon.exportsKey}'] = globalThis.__FEDERATION__['${import_sdk2.MFPrefetchCommon.globalKey}']['${import_sdk2.MFPrefetchCommon.exportsKey}'] || {};
83
+ globalThis.__FEDERATION__['${import_sdk2.MFPrefetchCommon.globalKey}']['${import_sdk2.MFPrefetchCommon.exportsKey}']['${name}'] = import('./bootstrap');
84
+ }
85
+ return args;
86
+ }
87
+ }
88
+ }
89
+ `;
90
+ var PrefetchPlugin = class {
91
+ constructor(options) {
92
+ this.options = options;
93
+ this._reWriteExports = "";
94
+ }
95
+ apply(compiler) {
96
+ const { name, exposes } = this.options;
97
+ if (!exposes) {
98
+ return;
99
+ }
100
+ if (!compiler.options.context) {
101
+ throw new Error("compiler.options.context is not defined");
102
+ }
103
+ const prefetchs = [];
104
+ const exposeAlias = Object.keys(exposes);
105
+ exposeAlias.forEach((alias) => {
106
+ let exposePath;
107
+ const exposeValue = exposes[alias];
108
+ if (typeof exposeValue === "string") {
109
+ exposePath = exposeValue;
110
+ } else {
111
+ exposePath = exposeValue.import;
112
+ }
113
+ const targetPaths = fixPrefetchPath(exposePath);
114
+ for (const pathItem of targetPaths) {
115
+ const absolutePath = import_path2.default.resolve(compiler.options.context, pathItem);
116
+ if (fileExistsWithCaseSync(absolutePath)) {
117
+ prefetchs.push(pathItem);
118
+ const absoluteAlias = alias.replace(".", "");
119
+ this._reWriteExports += `export * as ${getPrefetchId(
120
+ `${name}${absoluteAlias}`
121
+ )} from '${absolutePath}';
122
+ `;
123
+ break;
124
+ }
125
+ }
126
+ });
127
+ const { runtimePlugins } = this.options;
128
+ if (!Array.isArray(runtimePlugins)) {
129
+ this.options.runtimePlugins = [];
130
+ }
131
+ this.options.runtimePlugins.push(
132
+ import_path2.default.resolve(__dirname, "../esm/plugin.js")
133
+ );
134
+ if (!this._reWriteExports) {
135
+ return;
136
+ }
137
+ const encodedName = (0, import_sdk2.encodeName)(name);
138
+ const asyncEntryPath = import_path2.default.resolve(
139
+ compiler.options.context,
140
+ `node_modules/${TEMP_DIR}/${encodedName}/bootstrap.js`
141
+ );
142
+ const tempDirRealPath = import_path2.default.resolve(
143
+ compiler.options.context,
144
+ "node_modules",
145
+ TEMP_DIR
146
+ );
147
+ if (!import_fs_extra2.default.existsSync(tempDirRealPath)) {
148
+ import_fs_extra2.default.mkdirSync(tempDirRealPath);
149
+ }
150
+ if (!import_fs_extra2.default.existsSync(`${tempDirRealPath}/${encodedName}`)) {
151
+ import_fs_extra2.default.mkdirSync(`${tempDirRealPath}/${encodedName}`);
152
+ }
153
+ import_fs_extra2.default.writeFileSync(asyncEntryPath, this._reWriteExports);
154
+ const prefetchEntry = import_path2.default.resolve(
155
+ compiler.options.context,
156
+ `node_modules/${TEMP_DIR}/${encodedName}/${import_sdk2.MFPrefetchCommon.fileName}`
157
+ );
158
+ import_fs_extra2.default.writeFileSync(prefetchEntry, addTemplate(name));
159
+ this.options.runtimePlugins.push(prefetchEntry);
160
+ }
161
+ };
162
+ // Annotate the CommonJS export names for ESM import in node:
163
+ 0 && (module.exports = {
164
+ PrefetchPlugin
165
+ });
@@ -0,0 +1,136 @@
1
+ import {
2
+ logger_default
3
+ } from "./chunk-TTJJJ2WZ.js";
4
+ import {
5
+ MFDataPrefetch
6
+ } from "./chunk-JEPJP5O3.js";
7
+ import {
8
+ getSignalFromManifest
9
+ } from "./chunk-EWCGK4XA.js";
10
+
11
+ // src/plugin.ts
12
+ import { getResourceUrl } from "@module-federation/sdk";
13
+ var loadingArray = [];
14
+ var prefetchPlugin = () => ({
15
+ name: "data-prefetch-runtime-plugin",
16
+ afterResolve(options) {
17
+ const { remoteSnapshot, remoteInfo, id, origin } = options;
18
+ const snapshot = remoteSnapshot;
19
+ const { name } = remoteInfo;
20
+ const prefetchOptions = {
21
+ name,
22
+ remote: remoteInfo,
23
+ origin,
24
+ remoteSnapshot: snapshot
25
+ };
26
+ const signal = getSignalFromManifest(snapshot);
27
+ if (!signal) {
28
+ return options;
29
+ }
30
+ const instance = MFDataPrefetch.getInstance(name) || new MFDataPrefetch(prefetchOptions);
31
+ let prefetchUrl;
32
+ if (snapshot.prefetchEntry) {
33
+ prefetchUrl = getResourceUrl(snapshot, snapshot.prefetchEntry);
34
+ }
35
+ const exist = loadingArray.find((loading) => loading.id === id);
36
+ if (exist) {
37
+ return options;
38
+ }
39
+ const promise = instance.loadEntry(prefetchUrl).then(async () => {
40
+ const projectExports = instance.getProjectExports();
41
+ if (projectExports instanceof Promise) {
42
+ await projectExports;
43
+ }
44
+ const exports = instance.getExposeExports(id);
45
+ logger_default.info(`1. Start Prefetch: ${id} - ${performance.now()}`);
46
+ const result = Object.keys(exports).map((k) => {
47
+ const value = instance.prefetch({
48
+ id,
49
+ functionId: k
50
+ });
51
+ const functionId = k;
52
+ return {
53
+ value,
54
+ functionId
55
+ };
56
+ });
57
+ return result;
58
+ });
59
+ loadingArray.push({
60
+ id,
61
+ promise
62
+ });
63
+ return options;
64
+ },
65
+ async onLoad(options) {
66
+ var _a;
67
+ const { remote, id } = options;
68
+ const { name } = remote;
69
+ const promise = (_a = loadingArray.find((loading) => loading.id === id)) == null ? void 0 : _a.promise;
70
+ if (promise) {
71
+ const prefetch = await promise;
72
+ const prefetchValue = prefetch.map((result) => result.value);
73
+ await Promise.all(prefetchValue);
74
+ const instance = MFDataPrefetch.getInstance(name);
75
+ prefetch.forEach((result) => {
76
+ const { value, functionId } = result;
77
+ instance.memorize(id + functionId, value);
78
+ });
79
+ }
80
+ return options;
81
+ },
82
+ handlePreloadModule(options) {
83
+ const { remoteSnapshot, name, id, preloadConfig, origin, remote } = options;
84
+ const snapshot = remoteSnapshot;
85
+ const signal = getSignalFromManifest(snapshot);
86
+ if (!signal) {
87
+ return options;
88
+ }
89
+ const prefetchOptions = {
90
+ name,
91
+ origin,
92
+ remote,
93
+ remoteSnapshot: snapshot
94
+ };
95
+ const instance = MFDataPrefetch.getInstance(name) || new MFDataPrefetch(prefetchOptions);
96
+ let prefetchUrl;
97
+ if (snapshot.prefetchEntry) {
98
+ prefetchUrl = getResourceUrl(snapshot, snapshot.prefetchEntry);
99
+ }
100
+ if (!preloadConfig.prefetchInterface) {
101
+ instance.loadEntry(prefetchUrl);
102
+ return options;
103
+ }
104
+ const promise = instance.loadEntry(prefetchUrl).then(async () => {
105
+ const projectExports = instance.getProjectExports();
106
+ if (projectExports instanceof Promise) {
107
+ await projectExports;
108
+ }
109
+ const exports = instance.getExposeExports(id);
110
+ logger_default.info(`1. Start Prefetch: ${id} - ${performance.now()}`);
111
+ const result = Object.keys(exports).map((k) => {
112
+ const value = instance.prefetch({
113
+ id,
114
+ functionId: k
115
+ });
116
+ const functionId = k;
117
+ return {
118
+ value,
119
+ functionId
120
+ };
121
+ });
122
+ return result;
123
+ });
124
+ loadingArray.push({
125
+ id,
126
+ promise
127
+ });
128
+ return options;
129
+ }
130
+ });
131
+ var plugin_default = prefetchPlugin;
132
+
133
+ export {
134
+ prefetchPlugin,
135
+ plugin_default
136
+ };
@@ -0,0 +1,32 @@
1
+ // src/common/runtime-utils.ts
2
+ import {
3
+ encodeName,
4
+ MFPrefetchCommon
5
+ } from "@module-federation/sdk";
6
+ var getScope = (id) => {
7
+ const idArray = id.split("/");
8
+ if (idArray.length >= 2) {
9
+ idArray.pop();
10
+ }
11
+ const name = idArray.join("/");
12
+ return name;
13
+ };
14
+ var getPrefetchId = (id) => encodeName(`${id}/${MFPrefetchCommon.identifier}`);
15
+ var getSignalFromManifest = (remoteSnapshot) => {
16
+ if (!remoteSnapshot) {
17
+ return false;
18
+ }
19
+ if (!("prefetchEntry" in remoteSnapshot) && !("prefetchInterface" in remoteSnapshot)) {
20
+ return false;
21
+ }
22
+ if (!remoteSnapshot.prefetchEntry && !remoteSnapshot.prefetchInterface) {
23
+ return false;
24
+ }
25
+ return true;
26
+ };
27
+
28
+ export {
29
+ getScope,
30
+ getPrefetchId,
31
+ getSignalFromManifest
32
+ };
@@ -0,0 +1,160 @@
1
+ import {
2
+ getPrefetchId
3
+ } from "./chunk-EWCGK4XA.js";
4
+
5
+ // src/prefetch.ts
6
+ import {
7
+ getRemoteEntry,
8
+ getRemoteInfo
9
+ } from "@module-federation/runtime";
10
+ import {
11
+ loadScript
12
+ } from "@module-federation/sdk";
13
+ globalThis.__FEDERATION__ ?? (globalThis.__FEDERATION__ = {});
14
+ var _a;
15
+ (_a = globalThis.__FEDERATION__).__PREFETCH__ ?? (_a.__PREFETCH__ = {
16
+ entryLoading: {},
17
+ instance: /* @__PURE__ */ new Map(),
18
+ __PREFETCH_EXPORTS__: {}
19
+ });
20
+ var MFDataPrefetch = class {
21
+ constructor(options) {
22
+ this.prefetchMemory = /* @__PURE__ */ new Map();
23
+ this.recordOutdate = {};
24
+ this._exports = {};
25
+ this._options = options;
26
+ this.global.instance.set(options.name, this);
27
+ }
28
+ get global() {
29
+ return globalThis.__FEDERATION__.__PREFETCH__;
30
+ }
31
+ static getInstance(id) {
32
+ return globalThis.__FEDERATION__.__PREFETCH__.instance.get(id);
33
+ }
34
+ async loadEntry(entry) {
35
+ const { name, remoteSnapshot, remote, origin } = this._options;
36
+ if (entry) {
37
+ const { buildVersion, globalName } = remoteSnapshot;
38
+ const uniqueKey = globalName || `${name}:${buildVersion}`;
39
+ if (!this.global.entryLoading[uniqueKey]) {
40
+ this.global.entryLoading[uniqueKey] = loadScript(entry, {});
41
+ }
42
+ return this.global.entryLoading[uniqueKey];
43
+ } else {
44
+ const remoteInfo = getRemoteInfo(remote);
45
+ const module = origin.moduleCache.get(remoteInfo.name);
46
+ return getRemoteEntry({
47
+ remoteInfo,
48
+ remoteEntryExports: module ? module.remoteEntryExports : void 0,
49
+ createScriptHook: (url) => {
50
+ const res = origin.loaderHook.lifecycle.createScript.emit({
51
+ url
52
+ });
53
+ if (res instanceof HTMLScriptElement) {
54
+ return res;
55
+ }
56
+ return;
57
+ }
58
+ });
59
+ }
60
+ }
61
+ getProjectExports() {
62
+ var _a2;
63
+ if (Object.keys(this._exports).length > 0) {
64
+ return this._exports;
65
+ }
66
+ const { name } = this._options;
67
+ const exportsPromise = (_a2 = globalThis.__FEDERATION__.__PREFETCH__.__PREFETCH_EXPORTS__) == null ? void 0 : _a2[name];
68
+ const resolve = exportsPromise.then(
69
+ (exports = {}) => {
70
+ const memory = {};
71
+ Object.keys(exports).forEach((key) => {
72
+ memory[key] = {};
73
+ const exportVal = exports[key];
74
+ Object.keys(exportVal).reduce(
75
+ (memo, current) => {
76
+ if (current.toLocaleLowerCase().endsWith("prefetch") || current.toLocaleLowerCase() === "default") {
77
+ memo[current] = exportVal[current];
78
+ }
79
+ return memo;
80
+ },
81
+ memory[key]
82
+ );
83
+ });
84
+ this.memorizeExports(memory);
85
+ }
86
+ );
87
+ return resolve;
88
+ }
89
+ memorizeExports(exports) {
90
+ this._exports = exports;
91
+ }
92
+ getExposeExports(id) {
93
+ const prefetchId = getPrefetchId(id);
94
+ const prefetchExports = this._exports[prefetchId];
95
+ return prefetchExports || {};
96
+ }
97
+ prefetch(prefetchOptions) {
98
+ const { id, functionId = "default", refetchParams } = prefetchOptions;
99
+ let prefetchResult;
100
+ const prefetchId = getPrefetchId(id);
101
+ const memorizeId = id + functionId;
102
+ const memory = this.prefetchMemory.get(memorizeId);
103
+ if (!this.checkOutdate(prefetchOptions) && memory) {
104
+ return memory;
105
+ }
106
+ const prefetchExports = this._exports[prefetchId];
107
+ if (!prefetchExports) {
108
+ return;
109
+ }
110
+ const executePrefetch = prefetchExports[functionId];
111
+ if (typeof executePrefetch === "function") {
112
+ if (refetchParams) {
113
+ prefetchResult = executePrefetch(refetchParams);
114
+ } else {
115
+ prefetchResult = executePrefetch();
116
+ }
117
+ } else {
118
+ throw new Error(
119
+ `[Module Federation Data Prefetch]: No prefetch function called ${functionId} export in prefetch file`
120
+ );
121
+ }
122
+ this.memorize(memorizeId, prefetchResult);
123
+ return prefetchResult;
124
+ }
125
+ memorize(id, value) {
126
+ this.prefetchMemory.set(id, value);
127
+ }
128
+ markOutdate(markOptions, isOutdate) {
129
+ const { id, functionId = "default" } = markOptions;
130
+ if (!this.recordOutdate[id]) {
131
+ this.recordOutdate[id] = {};
132
+ }
133
+ this.recordOutdate[id][functionId] = isOutdate;
134
+ }
135
+ checkOutdate(outdateOptions) {
136
+ const { id, functionId = "default", cacheStrategy } = outdateOptions;
137
+ if (typeof cacheStrategy === "function") {
138
+ return cacheStrategy();
139
+ }
140
+ if (!this.recordOutdate[id]) {
141
+ this.recordOutdate[id] = {};
142
+ }
143
+ if (this.recordOutdate[id][functionId]) {
144
+ this.markOutdate(
145
+ {
146
+ id,
147
+ functionId
148
+ },
149
+ false
150
+ );
151
+ return true;
152
+ } else {
153
+ return false;
154
+ }
155
+ }
156
+ };
157
+
158
+ export {
159
+ MFDataPrefetch
160
+ };
@@ -0,0 +1,32 @@
1
+ import {
2
+ MFDataPrefetch
3
+ } from "./chunk-JEPJP5O3.js";
4
+ import {
5
+ getScope
6
+ } from "./chunk-EWCGK4XA.js";
7
+
8
+ // src/universal/index.ts
9
+ function prefetch(options) {
10
+ const { id, functionId } = options;
11
+ const mfScope = getScope(id);
12
+ const prefetchInstance = MFDataPrefetch.getInstance(mfScope) || new MFDataPrefetch({
13
+ name: mfScope
14
+ });
15
+ const res = prefetchInstance.getProjectExports();
16
+ if (res instanceof Promise) {
17
+ const promise = res.then(() => {
18
+ const result = prefetchInstance.prefetch(options);
19
+ prefetchInstance.memorize(id + functionId, result);
20
+ return result;
21
+ });
22
+ return promise;
23
+ } else {
24
+ const result = prefetchInstance.prefetch(options);
25
+ prefetchInstance.memorize(id + functionId, result);
26
+ return result;
27
+ }
28
+ }
29
+
30
+ export {
31
+ prefetch
32
+ };