@module-federation/bridge-react 0.0.0-next-20250701091154 → 0.0.0-next-20250701093604

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 (60) hide show
  1. package/CHANGELOG.md +6 -10
  2. package/__tests__/bridge.spec.tsx +7 -7
  3. package/dist/{bridge-base-P6pEjY1q.js → bridge-base-BoshEggF.mjs} +1 -1
  4. package/dist/{bridge-base-BBH982Tz.cjs → bridge-base-UGCwcMnG.js} +1 -1
  5. package/dist/data-fetch-runtime-plugin.cjs.js +73 -0
  6. package/dist/data-fetch-runtime-plugin.d.ts +6 -0
  7. package/dist/data-fetch-runtime-plugin.es.js +74 -0
  8. package/dist/data-fetch-server-middleware.cjs.js +163 -0
  9. package/dist/data-fetch-server-middleware.d.ts +6 -0
  10. package/dist/data-fetch-server-middleware.es.js +164 -0
  11. package/dist/data-fetch-utils.cjs.js +1271 -0
  12. package/dist/data-fetch-utils.d.ts +77 -0
  13. package/dist/data-fetch-utils.es.js +1273 -0
  14. package/dist/index-C0fDZB5b.js +45 -0
  15. package/dist/index-CqxytsLY.mjs +46 -0
  16. package/dist/index.cjs.js +434 -9
  17. package/dist/index.d.ts +142 -0
  18. package/dist/index.es.js +437 -11
  19. package/dist/index.esm-BCeUd-x9.mjs +418 -0
  20. package/dist/index.esm-j_1sIRzg.js +417 -0
  21. package/dist/inject-data-fetch-CAvi-gSf.js +79 -0
  22. package/dist/inject-data-fetch-errCdqBS.mjs +80 -0
  23. package/dist/lazy-utils.cjs.js +24 -0
  24. package/dist/lazy-utils.d.ts +140 -0
  25. package/dist/lazy-utils.es.js +24 -0
  26. package/dist/router-v5.cjs.js +1 -1
  27. package/dist/router-v5.es.js +1 -1
  28. package/dist/router-v6.cjs.js +1 -1
  29. package/dist/router-v6.es.js +1 -1
  30. package/dist/router.cjs.js +1 -1
  31. package/dist/router.es.js +1 -1
  32. package/dist/utils-Bk8hGjjF.mjs +2016 -0
  33. package/dist/utils-iEVlDmyk.js +2015 -0
  34. package/dist/v18.cjs.js +1 -1
  35. package/dist/v18.es.js +1 -1
  36. package/dist/v19.cjs.js +1 -1
  37. package/dist/v19.es.js +1 -1
  38. package/package.json +45 -5
  39. package/src/index.ts +30 -1
  40. package/src/lazy/AwaitDataFetch.tsx +176 -0
  41. package/src/lazy/constant.ts +30 -0
  42. package/src/lazy/createLazyComponent.tsx +393 -0
  43. package/src/lazy/data-fetch/cache.ts +296 -0
  44. package/src/lazy/data-fetch/call-data-fetch.ts +13 -0
  45. package/src/lazy/data-fetch/data-fetch-server-middleware.ts +196 -0
  46. package/src/lazy/data-fetch/index.ts +15 -0
  47. package/src/lazy/data-fetch/inject-data-fetch.ts +109 -0
  48. package/src/lazy/data-fetch/prefetch.ts +102 -0
  49. package/src/lazy/data-fetch/runtime-plugin.ts +116 -0
  50. package/src/lazy/index.ts +31 -0
  51. package/src/lazy/logger.ts +6 -0
  52. package/src/lazy/types.ts +75 -0
  53. package/src/lazy/utils.ts +372 -0
  54. package/src/lazy/wrapNoSSR.tsx +10 -0
  55. package/src/remote/component.tsx +3 -3
  56. package/src/remote/create.tsx +17 -4
  57. package/tsconfig.json +1 -1
  58. package/vite.config.ts +13 -0
  59. package/dist/index-Cv3p6r66.cjs +0 -235
  60. package/dist/index-D4yt7Udv.js +0 -236
@@ -0,0 +1,393 @@
1
+ import React, { ReactNode, useState, useEffect } from 'react';
2
+ import logger from './logger';
3
+ import { AwaitDataFetch, transformError } from './AwaitDataFetch';
4
+ import {
5
+ fetchData,
6
+ getDataFetchItem,
7
+ getDataFetchMapKey,
8
+ getDataFetchInfo,
9
+ getLoadedRemoteInfos,
10
+ setDataFetchItemLoadedStatus,
11
+ wrapDataFetchId,
12
+ } from './utils';
13
+ import {
14
+ DATA_FETCH_ERROR_PREFIX,
15
+ DATA_FETCH_FUNCTION,
16
+ FS_HREF,
17
+ LOAD_REMOTE_ERROR_PREFIX,
18
+ MF_DATA_FETCH_TYPE,
19
+ } from './constant';
20
+
21
+ import type { ErrorInfo } from './AwaitDataFetch';
22
+ import type { DataFetchParams, NoSSRRemoteInfo } from './types';
23
+ import type { FederationHost, getInstance } from '@module-federation/runtime';
24
+
25
+ export type IProps = {
26
+ id: string;
27
+ instance: ReturnType<typeof getInstance>;
28
+ injectScript?: boolean;
29
+ injectLink?: boolean;
30
+ };
31
+
32
+ export type CreateLazyComponentOptions<T, E extends keyof T> = {
33
+ loader: () => Promise<T>;
34
+ instance: ReturnType<typeof getInstance>;
35
+ loading: React.ReactNode;
36
+ fallback: ReactNode | ((errorInfo: ErrorInfo) => ReactNode);
37
+ export?: E;
38
+ dataFetchParams?: DataFetchParams;
39
+ noSSR?: boolean;
40
+ cacheData?: boolean;
41
+ };
42
+
43
+ type ReactKey = { key?: React.Key | null };
44
+
45
+ function getTargetModuleInfo(id: string, instance?: FederationHost) {
46
+ if (!instance) {
47
+ return;
48
+ }
49
+ const loadedRemoteInfo = getLoadedRemoteInfos(id, instance);
50
+ if (!loadedRemoteInfo) {
51
+ return;
52
+ }
53
+ const snapshot = loadedRemoteInfo.snapshot;
54
+ if (!snapshot) {
55
+ return;
56
+ }
57
+ const publicPath =
58
+ 'publicPath' in snapshot
59
+ ? snapshot.publicPath
60
+ : 'getPublicPath' in snapshot
61
+ ? new Function(snapshot.getPublicPath)()
62
+ : '';
63
+ if (!publicPath) {
64
+ return;
65
+ }
66
+ const modules = 'modules' in snapshot ? snapshot.modules : [];
67
+ const targetModule = modules.find(
68
+ (m) => m.modulePath === loadedRemoteInfo.expose,
69
+ );
70
+ if (!targetModule) {
71
+ return;
72
+ }
73
+
74
+ const remoteEntry = 'remoteEntry' in snapshot ? snapshot.remoteEntry : '';
75
+ if (!remoteEntry) {
76
+ return;
77
+ }
78
+ return {
79
+ module: targetModule,
80
+ publicPath,
81
+ remoteEntry,
82
+ };
83
+ }
84
+
85
+ export function collectSSRAssets(options: IProps) {
86
+ const {
87
+ id,
88
+ injectLink = true,
89
+ injectScript = false,
90
+ } = typeof options === 'string' ? { id: options } : options;
91
+ const links: React.ReactNode[] = [];
92
+ const scripts: React.ReactNode[] = [];
93
+ const instance = options.instance;
94
+ if (!instance || (!injectLink && !injectScript)) {
95
+ return [...scripts, ...links];
96
+ }
97
+
98
+ const moduleAndPublicPath = getTargetModuleInfo(id, instance);
99
+ if (!moduleAndPublicPath) {
100
+ return [...scripts, ...links];
101
+ }
102
+ const { module: targetModule, publicPath, remoteEntry } = moduleAndPublicPath;
103
+ if (injectLink) {
104
+ [...targetModule.assets.css.sync, ...targetModule.assets.css.async]
105
+ .sort()
106
+ .forEach((file, index) => {
107
+ links.push(
108
+ <link
109
+ key={`${file.split('.')[0]}_${index}`}
110
+ href={`${publicPath}${file}`}
111
+ rel="stylesheet"
112
+ type="text/css"
113
+ />,
114
+ );
115
+ });
116
+ }
117
+
118
+ if (injectScript) {
119
+ scripts.push(
120
+ <script
121
+ async={true}
122
+ key={remoteEntry.split('.')[0]}
123
+ src={`${publicPath}${remoteEntry}`}
124
+ crossOrigin="anonymous"
125
+ />,
126
+ );
127
+ [...targetModule.assets.js.sync].sort().forEach((file, index) => {
128
+ scripts.push(
129
+ <script
130
+ key={`${file.split('.')[0]}_${index}`}
131
+ async={true}
132
+ src={`${publicPath}${file}`}
133
+ crossOrigin="anonymous"
134
+ />,
135
+ );
136
+ });
137
+ }
138
+
139
+ return [...scripts, ...links];
140
+ }
141
+
142
+ function getServerNeedRemoteInfo(
143
+ loadedRemoteInfo: ReturnType<typeof getLoadedRemoteInfos>,
144
+ id: string,
145
+ noSSR?: boolean,
146
+ ): NoSSRRemoteInfo | undefined {
147
+ if (
148
+ noSSR ||
149
+ (typeof window !== 'undefined' && window.location.href !== window[FS_HREF])
150
+ ) {
151
+ if (!loadedRemoteInfo?.version) {
152
+ throw new Error(`${loadedRemoteInfo?.name} version is empty`);
153
+ }
154
+ const { snapshot } = loadedRemoteInfo;
155
+ if (!snapshot) {
156
+ throw new Error(`${loadedRemoteInfo?.name} snapshot is empty`);
157
+ }
158
+ const dataFetchItem = getDataFetchItem(id);
159
+ const isFetchServer =
160
+ dataFetchItem?.[0]?.[1] === MF_DATA_FETCH_TYPE.FETCH_SERVER;
161
+
162
+ if (
163
+ isFetchServer &&
164
+ (!('ssrPublicPath' in snapshot) || !snapshot.ssrPublicPath)
165
+ ) {
166
+ throw new Error(
167
+ `ssrPublicPath is required while fetching ${loadedRemoteInfo?.name} data in SSR project!`,
168
+ );
169
+ }
170
+
171
+ if (
172
+ isFetchServer &&
173
+ (!('ssrRemoteEntry' in snapshot) || !snapshot.ssrRemoteEntry)
174
+ ) {
175
+ throw new Error(
176
+ `ssrRemoteEntry is required while loading ${loadedRemoteInfo?.name} data loader in SSR project!`,
177
+ );
178
+ }
179
+
180
+ return {
181
+ name: loadedRemoteInfo.name,
182
+ version: loadedRemoteInfo.version,
183
+ ssrPublicPath:
184
+ 'ssrPublicPath' in snapshot ? snapshot.ssrPublicPath || '' : '',
185
+ ssrRemoteEntry:
186
+ 'ssrRemoteEntry' in snapshot ? snapshot.ssrRemoteEntry || '' : '',
187
+ globalName: loadedRemoteInfo.entryGlobalName,
188
+ };
189
+ }
190
+ return undefined;
191
+ }
192
+
193
+ export function createLazyComponent<T, E extends keyof T>(
194
+ options: CreateLazyComponentOptions<T, E>,
195
+ ) {
196
+ const { instance, cacheData } = options;
197
+ if (!instance) {
198
+ throw new Error('instance is required for createLazyComponent!');
199
+ }
200
+ let dataCache: unknown = null;
201
+
202
+ type ComponentType = T[E] extends (...args: any) => any
203
+ ? Parameters<T[E]>[0] extends undefined
204
+ ? ReactKey
205
+ : Parameters<T[E]>[0] & ReactKey
206
+ : ReactKey;
207
+ const exportName = options?.export || 'default';
208
+
209
+ const callLoader = async () => {
210
+ logger.debug('callLoader start', Date.now());
211
+ const m = (await options.loader()) as Record<string, React.FC> &
212
+ Record<symbol, string>;
213
+ logger.debug('callLoader end', Date.now());
214
+ if (!m) {
215
+ throw new Error('load remote failed');
216
+ }
217
+ return m;
218
+ };
219
+
220
+ const getData = async (noSSR?: boolean) => {
221
+ let loadedRemoteInfo: ReturnType<typeof getLoadedRemoteInfos>;
222
+ let moduleId: string;
223
+ try {
224
+ const m = await callLoader();
225
+ moduleId = m && m[Symbol.for('mf_module_id')];
226
+ if (!moduleId) {
227
+ throw new Error('moduleId is empty');
228
+ }
229
+ loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);
230
+ if (!loadedRemoteInfo) {
231
+ throw new Error(`can not find loaded remote('${moduleId}') info!`);
232
+ }
233
+ } catch (e) {
234
+ const errMsg = `${LOAD_REMOTE_ERROR_PREFIX}${e}`;
235
+ logger.debug(e);
236
+ throw new Error(errMsg);
237
+ }
238
+ let dataFetchMapKey: string | undefined;
239
+ try {
240
+ dataFetchMapKey = getDataFetchMapKey(
241
+ getDataFetchInfo({
242
+ name: loadedRemoteInfo.name,
243
+ alias: loadedRemoteInfo.alias,
244
+ id: moduleId,
245
+ remoteSnapshot: loadedRemoteInfo.snapshot,
246
+ }),
247
+ { name: instance.name, version: instance.options.version },
248
+ );
249
+ logger.debug('getData dataFetchMapKey: ', dataFetchMapKey);
250
+ if (!dataFetchMapKey) {
251
+ return;
252
+ }
253
+ const data = await fetchData(
254
+ dataFetchMapKey,
255
+ {
256
+ ...options.dataFetchParams,
257
+ isDowngrade: false,
258
+ },
259
+ getServerNeedRemoteInfo(loadedRemoteInfo, dataFetchMapKey, noSSR),
260
+ );
261
+ setDataFetchItemLoadedStatus(dataFetchMapKey);
262
+ logger.debug('get data res: \n', data);
263
+ dataCache = data;
264
+ return data;
265
+ } catch (err) {
266
+ const errMsg = `${DATA_FETCH_ERROR_PREFIX}${wrapDataFetchId(dataFetchMapKey)}${err}`;
267
+ logger.debug(errMsg);
268
+ throw new Error(errMsg);
269
+ }
270
+ };
271
+
272
+ const LazyComponent = React.lazy(async () => {
273
+ const m = await callLoader();
274
+ const moduleId = m && m[Symbol.for('mf_module_id')];
275
+ const loadedRemoteInfo = getLoadedRemoteInfos(moduleId, instance);
276
+ loadedRemoteInfo?.snapshot;
277
+ const dataFetchMapKey = loadedRemoteInfo
278
+ ? getDataFetchMapKey(
279
+ getDataFetchInfo({
280
+ name: loadedRemoteInfo.name,
281
+ alias: loadedRemoteInfo.alias,
282
+ id: moduleId,
283
+ remoteSnapshot: loadedRemoteInfo.snapshot,
284
+ }),
285
+ { name: instance.name, version: instance?.options.version },
286
+ )
287
+ : undefined;
288
+ logger.debug('LazyComponent dataFetchMapKey: ', dataFetchMapKey);
289
+
290
+ const assets = collectSSRAssets({
291
+ id: moduleId,
292
+ instance,
293
+ });
294
+
295
+ const Com = m[exportName] as React.FC<ComponentType>;
296
+ if (exportName in m && typeof Com === 'function') {
297
+ return {
298
+ default: (props: Omit<ComponentType, 'key'> & { mfData?: unknown }) => (
299
+ <>
300
+ {globalThis.FEDERATION_SSR && dataFetchMapKey && (
301
+ <script
302
+ suppressHydrationWarning
303
+ dangerouslySetInnerHTML={{
304
+ __html: String.raw`
305
+ globalThis['${DATA_FETCH_FUNCTION}'] = globalThis['${DATA_FETCH_FUNCTION}'] || [];
306
+ globalThis['${DATA_FETCH_FUNCTION}'].push(['${dataFetchMapKey}',${JSON.stringify(props.mfData)}]);
307
+ `,
308
+ }}
309
+ ></script>
310
+ )}
311
+ {globalThis.FEDERATION_SSR && assets}
312
+ <Com {...props} />
313
+ </>
314
+ ),
315
+ };
316
+ } else {
317
+ throw Error(
318
+ `Make sure that ${moduleId} has the correct export when export is ${String(
319
+ exportName,
320
+ )}`,
321
+ );
322
+ // eslint-disable-next-line max-lines
323
+ }
324
+ });
325
+
326
+ return (props: ComponentType) => {
327
+ const { key, ...args } = props;
328
+ if (cacheData && dataCache) {
329
+ // @ts-expect-error ignore
330
+ return <LazyComponent {...args} mfData={dataCache} />;
331
+ }
332
+ if (!options.noSSR) {
333
+ return (
334
+ <AwaitDataFetch
335
+ resolve={getData(options.noSSR)}
336
+ loading={options.loading}
337
+ errorElement={options.fallback}
338
+ >
339
+ {/* @ts-expect-error ignore */}
340
+ {(data) => <LazyComponent {...args} mfData={data} />}
341
+ </AwaitDataFetch>
342
+ );
343
+ } else {
344
+ // Client-side rendering logic
345
+ const [data, setData] = useState<unknown>(null);
346
+ const [loading, setLoading] = useState<boolean>(true);
347
+ const [error, setError] = useState<ErrorInfo | null>(null);
348
+
349
+ useEffect(() => {
350
+ let isMounted = true;
351
+ const fetchDataAsync = async () => {
352
+ try {
353
+ setLoading(true);
354
+ const result = await getData(options.noSSR);
355
+ if (isMounted) {
356
+ setData(result);
357
+ }
358
+ } catch (e) {
359
+ if (isMounted) {
360
+ setError(transformError(e as Error));
361
+ }
362
+ } finally {
363
+ if (isMounted) {
364
+ setLoading(false);
365
+ }
366
+ }
367
+ };
368
+
369
+ fetchDataAsync();
370
+
371
+ return () => {
372
+ isMounted = false;
373
+ };
374
+ }, []);
375
+
376
+ if (loading) {
377
+ return <>{options.loading}</>;
378
+ }
379
+
380
+ if (error) {
381
+ return (
382
+ <>
383
+ {typeof options.fallback === 'function'
384
+ ? options.fallback(error)
385
+ : options.fallback}
386
+ </>
387
+ );
388
+ }
389
+ // @ts-expect-error ignore
390
+ return <LazyComponent {...args} mfData={data} />;
391
+ }
392
+ };
393
+ }
@@ -0,0 +1,296 @@
1
+ import { LRUCache } from 'lru-cache';
2
+ import { getDataFetchCache } from '../utils';
3
+
4
+ import type {
5
+ CacheConfig,
6
+ CacheItem,
7
+ DataFetch,
8
+ DataFetchParams,
9
+ } from '../types';
10
+
11
+ export const CacheSize = {
12
+ KB: 1024,
13
+ MB: 1024 * 1024,
14
+ GB: 1024 * 1024 * 1024,
15
+ } as const;
16
+
17
+ export const CacheTime = {
18
+ SECOND: 1000,
19
+ MINUTE: 60 * 1000,
20
+ HOUR: 60 * 60 * 1000,
21
+ DAY: 24 * 60 * 60 * 1000,
22
+ WEEK: 7 * 24 * 60 * 60 * 1000,
23
+ MONTH: 30 * 24 * 60 * 60 * 1000,
24
+ } as const;
25
+
26
+ export type CacheStatus = 'hit' | 'stale' | 'miss';
27
+
28
+ export interface CacheStatsInfo {
29
+ status: CacheStatus;
30
+ key: string | symbol;
31
+ params: DataFetchParams;
32
+ result: any;
33
+ }
34
+
35
+ interface CacheOptions {
36
+ tag?: string | string[];
37
+ maxAge?: number;
38
+ revalidate?: number;
39
+ getKey?: <Args extends any[]>(...args: Args) => string;
40
+ customKey?: <Args extends any[]>(options: {
41
+ params: Args;
42
+ fn: (...args: Args) => any;
43
+ generatedKey: string;
44
+ }) => string | symbol;
45
+ onCache?: (info: CacheStatsInfo) => boolean;
46
+ }
47
+
48
+ function getTagKeyMap() {
49
+ const dataFetchCache = getDataFetchCache();
50
+ if (!dataFetchCache || !dataFetchCache.tagKeyMap) {
51
+ const tagKeyMap = new Map<string, Set<string>>();
52
+ globalThis.__MF_DATA_FETCH_CACHE__ ||= {};
53
+ globalThis.__MF_DATA_FETCH_CACHE__.tagKeyMap = tagKeyMap;
54
+ return tagKeyMap;
55
+ }
56
+ return dataFetchCache.tagKeyMap;
57
+ }
58
+
59
+ function addTagKeyRelation(tag: string, key: string) {
60
+ const tagKeyMap = getTagKeyMap();
61
+ let keys = tagKeyMap.get(tag);
62
+ if (!keys) {
63
+ keys = new Set();
64
+ tagKeyMap.set(tag, keys);
65
+ }
66
+ keys.add(key);
67
+ }
68
+
69
+ function getCacheConfig() {
70
+ const dataFetchCache = getDataFetchCache();
71
+ if (!dataFetchCache || !dataFetchCache.cacheConfig) {
72
+ const cacheConfig: CacheConfig = {
73
+ maxSize: CacheSize.GB,
74
+ };
75
+ globalThis.__MF_DATA_FETCH_CACHE__ ||= {};
76
+ globalThis.__MF_DATA_FETCH_CACHE__.cacheConfig = cacheConfig;
77
+ return cacheConfig;
78
+ }
79
+ return dataFetchCache.cacheConfig;
80
+ }
81
+
82
+ export function configureCache(config: CacheConfig): void {
83
+ const cacheConfig = getCacheConfig();
84
+ Object.assign(cacheConfig, config);
85
+ }
86
+
87
+ function getLRUCache() {
88
+ const dataFetchCache = getDataFetchCache();
89
+ const cacheConfig = getCacheConfig();
90
+
91
+ if (!dataFetchCache || !dataFetchCache.cacheStore) {
92
+ const cacheStore = new LRUCache<string, Map<string, CacheItem<any>>>({
93
+ maxSize: cacheConfig.maxSize ?? CacheSize.GB,
94
+ sizeCalculation: (value: Map<string, CacheItem<any>>): number => {
95
+ if (!value.size) {
96
+ return 1;
97
+ }
98
+
99
+ let size = 0;
100
+ for (const [k, item] of value.entries()) {
101
+ size += k.length * 2;
102
+ size += estimateObjectSize(item.data);
103
+ size += 8;
104
+ }
105
+ return size;
106
+ },
107
+ updateAgeOnGet: true,
108
+ updateAgeOnHas: true,
109
+ });
110
+ globalThis.__MF_DATA_FETCH_CACHE__ ||= {};
111
+ globalThis.__MF_DATA_FETCH_CACHE__.cacheStore = cacheStore;
112
+ return cacheStore;
113
+ }
114
+
115
+ return dataFetchCache.cacheStore;
116
+ }
117
+
118
+ function estimateObjectSize(data: unknown): number {
119
+ const type = typeof data;
120
+
121
+ if (type === 'number') return 8;
122
+ if (type === 'boolean') return 4;
123
+ if (type === 'string') return Math.max((data as string).length * 2, 1);
124
+ if (data === null || data === undefined) return 1;
125
+
126
+ if (ArrayBuffer.isView(data)) {
127
+ return Math.max(data.byteLength, 1);
128
+ }
129
+
130
+ if (Array.isArray(data)) {
131
+ return Math.max(
132
+ data.reduce((acc, item) => acc + estimateObjectSize(item), 0),
133
+ 1,
134
+ );
135
+ }
136
+
137
+ if (data instanceof Map || data instanceof Set) {
138
+ return 1024;
139
+ }
140
+
141
+ if (data instanceof Date) {
142
+ return 8;
143
+ }
144
+
145
+ if (type === 'object') {
146
+ return Math.max(
147
+ Object.entries(data).reduce(
148
+ (acc, [key, value]) => acc + key.length * 2 + estimateObjectSize(value),
149
+ 0,
150
+ ),
151
+ 1,
152
+ );
153
+ }
154
+
155
+ return 1;
156
+ }
157
+
158
+ export function generateKey(dataFetchOptions: DataFetchParams): string {
159
+ return JSON.stringify(dataFetchOptions, (_, value) => {
160
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
161
+ return Object.keys(value)
162
+ .sort()
163
+ .reduce((result: Record<string, unknown>, key) => {
164
+ result[key] = value[key];
165
+ return result;
166
+ }, {});
167
+ }
168
+ return value;
169
+ });
170
+ }
171
+
172
+ export function cache<T>(
173
+ fn: DataFetch<T>,
174
+ options?: CacheOptions,
175
+ ): DataFetch<T> {
176
+ const {
177
+ tag = 'default',
178
+ maxAge = CacheTime.MINUTE * 5,
179
+ revalidate = 0,
180
+ onCache,
181
+ getKey,
182
+ } = options || {};
183
+
184
+ const tags = Array.isArray(tag) ? tag : [tag];
185
+
186
+ return async (dataFetchOptions) => {
187
+ // if downgrade, skip cache
188
+ if (dataFetchOptions.isDowngrade || !dataFetchOptions._id) {
189
+ return fn(dataFetchOptions);
190
+ }
191
+ const store = getLRUCache();
192
+
193
+ const now = Date.now();
194
+ const storeKey = dataFetchOptions._id;
195
+ const cacheKey = getKey
196
+ ? getKey(dataFetchOptions)
197
+ : generateKey(dataFetchOptions);
198
+
199
+ tags.forEach((t) => addTagKeyRelation(t, cacheKey));
200
+
201
+ let cacheStore = store.get(cacheKey);
202
+ if (!cacheStore) {
203
+ cacheStore = new Map();
204
+ }
205
+
206
+ const cached = cacheStore.get(storeKey);
207
+ if (cached) {
208
+ const age = now - cached.timestamp;
209
+
210
+ if (age < maxAge) {
211
+ if (onCache) {
212
+ const useCache = onCache({
213
+ status: 'hit',
214
+ key: cacheKey,
215
+ params: dataFetchOptions,
216
+ result: cached.data,
217
+ });
218
+ if (!useCache) {
219
+ return fn(dataFetchOptions);
220
+ }
221
+ }
222
+ return cached.data;
223
+ }
224
+
225
+ if (revalidate > 0 && age < maxAge + revalidate) {
226
+ if (onCache) {
227
+ onCache({
228
+ status: 'stale',
229
+ key: cacheKey,
230
+ params: dataFetchOptions,
231
+ result: cached.data,
232
+ });
233
+ }
234
+
235
+ if (!cached.isRevalidating) {
236
+ cached.isRevalidating = true;
237
+ Promise.resolve().then(async () => {
238
+ try {
239
+ const newData = await fn(dataFetchOptions);
240
+ cacheStore!.set(storeKey, {
241
+ data: newData,
242
+ timestamp: Date.now(),
243
+ isRevalidating: false,
244
+ });
245
+
246
+ store.set(cacheKey, cacheStore!);
247
+ } catch (error) {
248
+ cached.isRevalidating = false;
249
+ console.error('Background revalidation failed:', error);
250
+ }
251
+ });
252
+ }
253
+ return cached.data;
254
+ }
255
+ }
256
+
257
+ const data = await fn(dataFetchOptions);
258
+ cacheStore.set(storeKey, {
259
+ data,
260
+ timestamp: now,
261
+ isRevalidating: false,
262
+ });
263
+ store.set(cacheKey, cacheStore);
264
+
265
+ if (onCache) {
266
+ onCache({
267
+ status: 'miss',
268
+ key: cacheKey,
269
+ params: dataFetchOptions,
270
+ result: data,
271
+ });
272
+ }
273
+
274
+ return data;
275
+ };
276
+ }
277
+
278
+ export function revalidateTag(tag: string): void {
279
+ const tagKeyMap = getTagKeyMap();
280
+ const keys = tagKeyMap.get(tag);
281
+ const lruCache = getLRUCache();
282
+ if (keys) {
283
+ keys.forEach((key) => {
284
+ lruCache?.delete(key);
285
+ });
286
+ }
287
+ }
288
+
289
+ export function clearStore(): void {
290
+ const lruCache = getLRUCache();
291
+ const tagKeyMap = getTagKeyMap();
292
+
293
+ lruCache?.clear();
294
+ delete globalThis.__MF_DATA_FETCH_CACHE__?.cacheStore;
295
+ tagKeyMap.clear();
296
+ }
@@ -0,0 +1,13 @@
1
+ import { DATA_FETCH_FUNCTION } from '../constant';
2
+ import { dataFetchFunction } from './inject-data-fetch';
3
+
4
+ export async function callDataFetch() {
5
+ const dataFetch = globalThis[DATA_FETCH_FUNCTION];
6
+ if (dataFetch) {
7
+ await Promise.all(
8
+ dataFetch.map(async (options) => {
9
+ await dataFetchFunction(options);
10
+ }),
11
+ );
12
+ }
13
+ }