@module-federation/retry-plugin 0.0.0-chore-bump-node-22-20260710161714

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.
@@ -0,0 +1,113 @@
1
+ import { ModuleFederationRuntimePlugin } from "@module-federation/runtime";
2
+
3
+ //#region src/types.d.ts
4
+ type CommonRetryOptions = {
5
+ /**
6
+ * retry request options
7
+ */
8
+ fetchOptions?: RequestInit;
9
+ /**
10
+ * retry times
11
+ */
12
+ retryTimes?: number;
13
+ /**
14
+ * retry success times
15
+ */
16
+ successTimes?: number;
17
+ /**
18
+ * retry delay in milliseconds, or a function that returns delay per attempt.
19
+ * When a function, `attempt` is 1-indexed (the nth retry, not the initial call).
20
+ */
21
+ retryDelay?: number | ((attempt: number) => number);
22
+ /**
23
+ * retry path
24
+ */
25
+ getRetryPath?: (url: string) => string;
26
+ /**
27
+ * add query parameter
28
+ */
29
+ addQuery?: boolean | ((context: {
30
+ times: number;
31
+ originalQuery: string;
32
+ }) => string);
33
+ /**
34
+ * retry domains
35
+ */
36
+ domains?: string[];
37
+ /**
38
+ * retry manifest domains
39
+ */
40
+ manifestDomains?: string[];
41
+ /**
42
+ * retry callback
43
+ */
44
+ onRetry?: ({
45
+ times,
46
+ domains,
47
+ url
48
+ }: {
49
+ times?: number;
50
+ domains?: string[];
51
+ url?: string;
52
+ tagName?: string;
53
+ }) => void;
54
+ /**
55
+ * retry success callback
56
+ */
57
+ onSuccess?: ({
58
+ domains,
59
+ url,
60
+ tagName
61
+ }: {
62
+ domains?: string[];
63
+ url?: string;
64
+ tagName?: string;
65
+ }) => void;
66
+ /**
67
+ * retry failure callback
68
+ */
69
+ onError?: ({
70
+ domains,
71
+ url,
72
+ tagName
73
+ }: {
74
+ domains?: string[];
75
+ url?: string;
76
+ tagName?: string;
77
+ }) => void;
78
+ };
79
+ type FetchRetryOptions = {
80
+ url?: string;
81
+ fetchOptions?: RequestInit;
82
+ } & CommonRetryOptions;
83
+ type ScriptRetryOptions = {
84
+ retryOptions: CommonRetryOptions;
85
+ retryFn: (...args: any[]) => Promise<any> | (() => Promise<any>);
86
+ beforeExecuteRetry?: (...args: any[]) => void;
87
+ };
88
+ //#endregion
89
+ //#region src/utils.d.ts
90
+ declare function rewriteWithNextDomain(currentUrl: string, domains?: string[]): string | null;
91
+ declare function appendRetryCountQuery(url: string, retryIndex: number, key?: string): string;
92
+ declare function getRetryUrl(baseUrl: string, opts?: {
93
+ domains?: string[];
94
+ addQuery?: boolean | ((context: {
95
+ times: number;
96
+ originalQuery: string;
97
+ }) => string);
98
+ retryIndex?: number;
99
+ queryKey?: string;
100
+ }): string;
101
+ /**
102
+ * Extract domain/host info from a URL and combine it with path/query from another URL
103
+ * This is useful for domain rotation while preserving original path and query parameters
104
+ * @param domainUrl - URL containing the target domain/host
105
+ * @param pathQueryUrl - URL containing the target path and query parameters
106
+ * @returns Combined URL with domain from domainUrl and path/query from pathQueryUrl
107
+ */
108
+ declare function combineUrlDomainWithPathQuery(domainUrl: string, pathQueryUrl: string): string;
109
+ //#endregion
110
+ //#region src/index.d.ts
111
+ declare const RetryPlugin: (params?: CommonRetryOptions) => ModuleFederationRuntimePlugin;
112
+ //#endregion
113
+ export { type CommonRetryOptions, type FetchRetryOptions, RetryPlugin, type ScriptRetryOptions, appendRetryCountQuery, combineUrlDomainWithPathQuery, getRetryUrl, rewriteWithNextDomain };
package/dist/index.js ADDED
@@ -0,0 +1,312 @@
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
2
+ let _module_federation_sdk = require("@module-federation/sdk");
3
+
4
+ //#region src/constant.ts
5
+ const defaultRetries = 3;
6
+ const defaultRetryDelay = 1e3;
7
+ const PLUGIN_IDENTIFIER = "[ Module Federation RetryPlugin ]";
8
+ const ERROR_ABANDONED = "The request failed and has now been abandoned";
9
+ const RUNTIME_008 = "RUNTIME-008";
10
+
11
+ //#endregion
12
+ //#region src/logger.ts
13
+ const logger = (0, _module_federation_sdk.createLogger)(PLUGIN_IDENTIFIER);
14
+
15
+ //#endregion
16
+ //#region src/utils.ts
17
+ function rewriteWithNextDomain(currentUrl, domains) {
18
+ if (!domains || domains.length === 0) return null;
19
+ try {
20
+ const u = new URL(currentUrl);
21
+ const currentHostname = u.hostname;
22
+ const currentPort = u.port;
23
+ const currentHost = `${currentHostname}${currentPort ? `:${currentPort}` : ""}`;
24
+ const normalized = domains.map((d) => {
25
+ try {
26
+ const du = new URL(d.startsWith("http") ? d : `https://${d}`);
27
+ return {
28
+ hostname: du.hostname,
29
+ port: du.port,
30
+ protocol: du.protocol
31
+ };
32
+ } catch {
33
+ return {
34
+ hostname: d,
35
+ port: "",
36
+ protocol: u.protocol
37
+ };
38
+ }
39
+ }).filter((d) => !!d.hostname);
40
+ if (normalized.length === 0) return null;
41
+ let idx = -1;
42
+ for (let i = normalized.length - 1; i >= 0; i--) if (`${normalized[i].hostname}${normalized[i].port ? `:${normalized[i].port}` : ""}` === currentHost) {
43
+ idx = i;
44
+ break;
45
+ }
46
+ const total = normalized.length;
47
+ for (let step = 1; step <= total; step++) {
48
+ const candidate = normalized[((idx >= 0 ? idx : -1) + step) % total];
49
+ if (`${candidate.hostname}${candidate.port ? `:${candidate.port}` : ""}` !== currentHost) {
50
+ u.hostname = candidate.hostname;
51
+ if (candidate.port !== void 0 && candidate.port !== null && candidate.port !== "") u.port = candidate.port;
52
+ else u.port = "";
53
+ u.protocol = candidate.protocol || u.protocol;
54
+ return u.toString();
55
+ }
56
+ }
57
+ return null;
58
+ } catch {
59
+ return null;
60
+ }
61
+ }
62
+ function appendRetryCountQuery(url, retryIndex, key = "retryCount") {
63
+ try {
64
+ const u = new URL(url);
65
+ u.searchParams.delete(key);
66
+ u.searchParams.set(key, String(retryIndex));
67
+ return u.toString();
68
+ } catch {
69
+ return url;
70
+ }
71
+ }
72
+ function getRetryUrl(baseUrl, opts = {}) {
73
+ const { domains, addQuery, retryIndex = 0, queryKey = "retryCount" } = opts;
74
+ let cleanBaseUrl = baseUrl;
75
+ try {
76
+ const urlObj = new URL(baseUrl);
77
+ urlObj.searchParams.delete(queryKey);
78
+ cleanBaseUrl = urlObj.toString();
79
+ } catch {}
80
+ let nextUrl = rewriteWithNextDomain(cleanBaseUrl, domains) ?? cleanBaseUrl;
81
+ if (retryIndex > 0 && addQuery) try {
82
+ const u = new URL(nextUrl);
83
+ const originalUrl = new URL(baseUrl);
84
+ originalUrl.searchParams.delete(queryKey);
85
+ const originalQuery = originalUrl.search.startsWith("?") ? originalUrl.search.slice(1) : originalUrl.search;
86
+ if (typeof addQuery === "function") {
87
+ const newQuery = addQuery({
88
+ times: retryIndex,
89
+ originalQuery
90
+ });
91
+ u.search = newQuery ? `?${newQuery.replace(/^\?/, "")}` : "";
92
+ nextUrl = u.toString();
93
+ } else if (addQuery === true) {
94
+ u.searchParams.delete(queryKey);
95
+ u.searchParams.set(queryKey, String(retryIndex));
96
+ nextUrl = u.toString();
97
+ }
98
+ } catch {
99
+ if (addQuery === true) nextUrl = appendRetryCountQuery(nextUrl, retryIndex, queryKey);
100
+ }
101
+ return nextUrl;
102
+ }
103
+ /**
104
+ * Extract domain/host info from a URL and combine it with path/query from another URL
105
+ * This is useful for domain rotation while preserving original path and query parameters
106
+ * @param domainUrl - URL containing the target domain/host
107
+ * @param pathQueryUrl - URL containing the target path and query parameters
108
+ * @returns Combined URL with domain from domainUrl and path/query from pathQueryUrl
109
+ */
110
+ function combineUrlDomainWithPathQuery(domainUrl, pathQueryUrl) {
111
+ try {
112
+ const domainUrlObj = new URL(domainUrl);
113
+ const pathQueryUrlObj = new URL(pathQueryUrl);
114
+ domainUrlObj.pathname = pathQueryUrlObj.pathname;
115
+ domainUrlObj.search = pathQueryUrlObj.search;
116
+ return domainUrlObj.toString();
117
+ } catch {
118
+ return pathQueryUrl;
119
+ }
120
+ }
121
+
122
+ //#endregion
123
+ //#region src/fetch-retry.ts
124
+ function autoParseResponse(url, response) {
125
+ try {
126
+ const parsed = new URL(url);
127
+ if (parsed.pathname.endsWith(".js") || parsed.pathname.endsWith(".cjs") || parsed.pathname.endsWith(".mjs")) return response.text();
128
+ return response.json();
129
+ } catch (error) {
130
+ return response.json();
131
+ }
132
+ }
133
+ async function fetchRetry(params, lastRequestUrl, originalTotal) {
134
+ const { url, fetchOptions = {}, retryTimes = defaultRetries, retryDelay = defaultRetryDelay, domains, addQuery, onRetry, onSuccess, onError } = params;
135
+ if (!url) throw new Error(`${PLUGIN_IDENTIFIER}: url is required in fetchWithRetry`);
136
+ const total = originalTotal ?? params.retryTimes ?? defaultRetries;
137
+ const isFirstAttempt = !lastRequestUrl;
138
+ let baseUrl = url;
139
+ if (!isFirstAttempt && lastRequestUrl) baseUrl = combineUrlDomainWithPathQuery(lastRequestUrl, url);
140
+ let requestUrl = baseUrl;
141
+ if (!isFirstAttempt) requestUrl = getRetryUrl(baseUrl, {
142
+ domains,
143
+ addQuery,
144
+ retryIndex: total - retryTimes,
145
+ queryKey: "retryCount"
146
+ });
147
+ try {
148
+ if (!isFirstAttempt) {
149
+ const attemptIndex = total - retryTimes;
150
+ const delay = typeof retryDelay === "function" ? retryDelay(attemptIndex) : retryDelay;
151
+ if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
152
+ }
153
+ const response = await fetch(requestUrl, fetchOptions);
154
+ const responseClone = response.clone();
155
+ if (!response.ok) throw new Error(`${PLUGIN_IDENTIFIER}: Request failed: ${response.status} ${response.statusText || ""} | url: ${requestUrl}`);
156
+ await autoParseResponse(requestUrl, responseClone).catch((error) => {
157
+ throw new Error(`${PLUGIN_IDENTIFIER}: JSON parse failed: ${error?.message || String(error)} | url: ${requestUrl}`);
158
+ });
159
+ if (!isFirstAttempt) onSuccess && requestUrl && onSuccess({
160
+ domains,
161
+ url: requestUrl,
162
+ tagName: "fetch"
163
+ });
164
+ return response;
165
+ } catch (error) {
166
+ if (retryTimes <= 0) {
167
+ const attemptedRetries = total - retryTimes;
168
+ if (!isFirstAttempt && attemptedRetries > 0) {
169
+ onError && onError({
170
+ domains,
171
+ url: requestUrl,
172
+ tagName: "fetch"
173
+ });
174
+ logger.log(`${PLUGIN_IDENTIFIER}: retry failed, no retries left for url: ${requestUrl}`);
175
+ }
176
+ throw new Error(`${RUNTIME_008}: ${PLUGIN_IDENTIFIER}: ${ERROR_ABANDONED} | url: ${requestUrl}`);
177
+ } else {
178
+ const nextIndex = total - retryTimes + 1;
179
+ const predictedNextUrl = getRetryUrl(combineUrlDomainWithPathQuery(requestUrl, url), {
180
+ domains,
181
+ addQuery,
182
+ retryIndex: nextIndex,
183
+ queryKey: "retryCount"
184
+ });
185
+ onRetry && onRetry({
186
+ times: nextIndex,
187
+ domains,
188
+ url: predictedNextUrl,
189
+ tagName: "fetch"
190
+ });
191
+ logger.log(`${PLUGIN_IDENTIFIER}: Trying again. Number of retries left: ${retryTimes - 1}`);
192
+ return await fetchRetry({
193
+ ...params,
194
+ retryTimes: retryTimes - 1
195
+ }, requestUrl, total);
196
+ }
197
+ }
198
+ }
199
+
200
+ //#endregion
201
+ //#region src/script-retry.ts
202
+ function scriptRetry({ retryOptions, retryFn, beforeExecuteRetry = () => {} }) {
203
+ return async function(params) {
204
+ let retryWrapper;
205
+ let lastRequestUrl;
206
+ let originalUrl;
207
+ const { retryTimes = defaultRetries, retryDelay = defaultRetryDelay, domains, addQuery, onRetry, onSuccess, onError } = retryOptions || {};
208
+ let attempts = 0;
209
+ const maxAttempts = retryTimes;
210
+ while (attempts < maxAttempts) try {
211
+ beforeExecuteRetry();
212
+ const delay = typeof retryDelay === "function" ? retryDelay(attempts + 1) : retryDelay;
213
+ if (delay > 0) await new Promise((resolve) => setTimeout(resolve, delay));
214
+ const retryIndex = attempts + 1;
215
+ retryWrapper = await retryFn({
216
+ ...params,
217
+ getEntryUrl: (url) => {
218
+ if (!originalUrl) originalUrl = url;
219
+ let baseUrl = originalUrl;
220
+ if (lastRequestUrl) baseUrl = combineUrlDomainWithPathQuery(lastRequestUrl, originalUrl);
221
+ const next = getRetryUrl(baseUrl, {
222
+ domains,
223
+ addQuery,
224
+ retryIndex,
225
+ queryKey: "retryCount"
226
+ });
227
+ onRetry && onRetry({
228
+ times: retryIndex,
229
+ domains,
230
+ url: next,
231
+ tagName: "script"
232
+ });
233
+ lastRequestUrl = next;
234
+ return next;
235
+ }
236
+ });
237
+ onSuccess && lastRequestUrl && onSuccess({
238
+ domains,
239
+ url: lastRequestUrl,
240
+ tagName: "script"
241
+ });
242
+ break;
243
+ } catch (error) {
244
+ attempts++;
245
+ if (attempts >= maxAttempts) {
246
+ onError && lastRequestUrl && onError({
247
+ domains,
248
+ url: lastRequestUrl,
249
+ tagName: "script"
250
+ });
251
+ throw new Error(`${PLUGIN_IDENTIFIER}: ${ERROR_ABANDONED} | url: ${lastRequestUrl || "unknown"}`);
252
+ }
253
+ }
254
+ return retryWrapper;
255
+ };
256
+ }
257
+
258
+ //#endregion
259
+ //#region src/index.ts
260
+ const RetryPlugin = (params) => {
261
+ if (params?.fetch || params?.script) logger.warn(`${PLUGIN_IDENTIFIER}: params is ${params}, fetch or script config is deprecated, please use the new config style. See docs: https://module-federation.io/plugin/plugins/retry-plugin.html`);
262
+ const { fetchOptions = {}, retryTimes = defaultRetries, successTimes = 0, retryDelay = defaultRetryDelay, domains = [], manifestDomains = [], addQuery, onRetry, onSuccess, onError } = params || {};
263
+ return {
264
+ name: "retry-plugin",
265
+ async fetch(manifestUrl, options) {
266
+ return fetchRetry({
267
+ url: manifestUrl,
268
+ fetchOptions: {
269
+ ...options,
270
+ ...fetchOptions
271
+ },
272
+ domains: manifestDomains || domains,
273
+ addQuery,
274
+ onRetry,
275
+ onSuccess,
276
+ onError,
277
+ retryTimes,
278
+ successTimes,
279
+ retryDelay
280
+ });
281
+ },
282
+ async loadEntryError({ getRemoteEntry, origin, remoteInfo, remoteEntryExports, globalLoading, uniqueKey }) {
283
+ const beforeExecuteRetry = () => {
284
+ delete globalLoading[uniqueKey];
285
+ };
286
+ return await scriptRetry({
287
+ retryOptions: {
288
+ retryTimes,
289
+ retryDelay,
290
+ domains,
291
+ addQuery,
292
+ onRetry,
293
+ onSuccess,
294
+ onError
295
+ },
296
+ retryFn: getRemoteEntry,
297
+ beforeExecuteRetry
298
+ })({
299
+ origin,
300
+ remoteInfo,
301
+ remoteEntryExports
302
+ });
303
+ }
304
+ };
305
+ };
306
+
307
+ //#endregion
308
+ exports.RetryPlugin = RetryPlugin;
309
+ exports.appendRetryCountQuery = appendRetryCountQuery;
310
+ exports.combineUrlDomainWithPathQuery = combineUrlDomainWithPathQuery;
311
+ exports.getRetryUrl = getRetryUrl;
312
+ exports.rewriteWithNextDomain = rewriteWithNextDomain;
package/package.json ADDED
@@ -0,0 +1,51 @@
1
+ {
2
+ "name": "@module-federation/retry-plugin",
3
+ "version": "0.0.0-chore-bump-node-22-20260710161714",
4
+ "author": "danpeen <dapeen.feng@gmail.com>",
5
+ "main": "./dist/index.js",
6
+ "module": "./dist/esm/index.js",
7
+ "types": "./dist/index.d.ts",
8
+ "license": "MIT",
9
+ "repository": {
10
+ "type": "git",
11
+ "url": "git+https://github.com/module-federation/core.git",
12
+ "directory": "packages/retry-plugin"
13
+ },
14
+ "publishConfig": {
15
+ "access": "public"
16
+ },
17
+ "files": [
18
+ "dist/",
19
+ "README.md"
20
+ ],
21
+ "exports": {
22
+ ".": {
23
+ "types": "./dist/index.d.ts",
24
+ "import": "./dist/esm/index.js",
25
+ "require": "./dist/index.js"
26
+ }
27
+ },
28
+ "typesVersions": {
29
+ "*": {
30
+ ".": [
31
+ "./dist/index.d.ts"
32
+ ]
33
+ }
34
+ },
35
+ "peerDependencies": {
36
+ "@module-federation/runtime": "0.0.0-chore-bump-node-22-20260710161714"
37
+ },
38
+ "devDependencies": {
39
+ "@module-federation/runtime": "0.0.0-chore-bump-node-22-20260710161714"
40
+ },
41
+ "dependencies": {
42
+ "@module-federation/sdk": "0.0.0-chore-bump-node-22-20260710161714"
43
+ },
44
+ "scripts": {
45
+ "build": "tsdown --config tsdown.config.ts && cp *.md dist",
46
+ "test": "rstest -u",
47
+ "lint": "ESLINT_USE_FLAT_CONFIG=false pnpm exec eslint --ignore-pattern node_modules \"**/*.ts\" \"package.json\"",
48
+ "build-debug": "FEDERATION_DEBUG=true pnpm run build",
49
+ "pre-release": "pnpm run test && pnpm run build"
50
+ }
51
+ }