@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.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2023-present zhouxiao(zhoushaw)
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,331 @@
1
+ # @module-federation/retry-plugin
2
+
3
+ > A robust retry plugin for Module Federation that provides automatic retry mechanisms for failed module requests with domain rotation, cache-busting, and comprehensive error handling.
4
+
5
+ ## Features
6
+
7
+ - 🔄 **Automatic Retry**: Automatically retries failed fetch and script requests
8
+ - 🌐 **Domain Rotation**: Rotate through multiple domains for better reliability
9
+ - ⚡ **Cache Busting**: Add query parameters to bypass cache issues
10
+ - 📊 **Lifecycle Callbacks**: Comprehensive callbacks for retry events
11
+ - 🎯 **Flexible Configuration**: Highly configurable retry strategies
12
+ - 🔧 **TypeScript Support**: Full TypeScript support with type definitions
13
+
14
+ ## Installation
15
+
16
+ ```bash
17
+ npm install @module-federation/retry-plugin
18
+ # or
19
+ yarn add @module-federation/retry-plugin
20
+ # or
21
+ pnpm add @module-federation/retry-plugin
22
+ ```
23
+
24
+ ## Basic Usage
25
+
26
+ ### Runtime Plugin Registration
27
+
28
+ ```ts
29
+ import { createInstance } from '@module-federation/enhanced/runtime';
30
+ import { RetryPlugin } from '@module-federation/retry-plugin';
31
+
32
+ const mf = createInstance({
33
+ name: 'host',
34
+ remotes: [
35
+ {
36
+ name: 'remote1',
37
+ entry: 'http://localhost:2001/mf-manifest.json',
38
+ },
39
+ ],
40
+ plugins: [
41
+ RetryPlugin({
42
+ retryTimes: 3,
43
+ retryDelay: 1000,
44
+ domains: ['https://cdn1.example.com', 'https://cdn2.example.com'],
45
+ manifestDomains: ['https://domain1.example.com', 'https://domain2.example.com'],
46
+ addQuery: ({ times, originalQuery }) => `${originalQuery}&retry=${times}`,
47
+ onRetry: ({ times, url }) => console.log('Retrying...', times, url),
48
+ onSuccess: ({ url }) => console.log('Success!', url),
49
+ onError: ({ url }) => console.log('Failed!', url),
50
+ }),
51
+ ],
52
+ });
53
+ ```
54
+
55
+ ### Build Plugin Registration
56
+
57
+ ```ts
58
+ // webpack.config.js
59
+ import { ModuleFederationPlugin } from '@module-federation/webpack';
60
+ import { RetryPlugin } from '@module-federation/retry-plugin';
61
+
62
+ export default {
63
+ plugins: [
64
+ new ModuleFederationPlugin({
65
+ name: 'host',
66
+ remotes: {
67
+ remote1: 'remote1@http://localhost:2001/mf-manifest.json',
68
+ },
69
+ runtimePlugins: [path.join(__dirname, './src/runtime-plugin/retry.ts')],
70
+ }),
71
+ ],
72
+ };
73
+ ```
74
+
75
+ ```ts
76
+ // src/runtime-plugin/retry.ts
77
+ import { RetryPlugin } from '@module-federation/retry-plugin';
78
+
79
+ export default () =>
80
+ RetryPlugin({
81
+ retryTimes: 3,
82
+ retryDelay: 1000,
83
+ domains: ['https://cdn1.example.com', 'https://cdn2.example.com'],
84
+ manifestDomains: ['https://domain1.example.com', 'https://domain2.example.com'],
85
+ addQuery: ({ times, originalQuery }) => `${originalQuery}&retry=${times}`,
86
+ onRetry: ({ times, url }) => console.log('Retrying...', times, url),
87
+ onSuccess: ({ url }) => console.log('Success!', url),
88
+ onError: ({ url }) => console.log('Failed!', url),
89
+ });
90
+ ```
91
+
92
+ ## Configuration Options
93
+
94
+ ### CommonRetryOptions
95
+
96
+ | Option | Type | Default | Description |
97
+ | ----------------- | --------------------------------------- | ----------- | ------------------------------------------------------------------------------------------------ |
98
+ | `retryTimes` | `number` | `3` | Number of retry attempts |
99
+ | `retryDelay` | `number \| (attempt: number) => number` | `1000` | Delay between retries in milliseconds, or a function returning delay per 1-indexed retry attempt |
100
+ | `successTimes` | `number` | `0` | Number of successful requests required |
101
+ | `domains` | `string[]` | `[]` | Alternative domains for script resources |
102
+ | `manifestDomains` | `string[]` | `[]` | Alternative domains for manifest files |
103
+ | `addQuery` | `boolean \| function` | `false` | Add query parameters for cache busting |
104
+ | `fetchOptions` | `RequestInit` | `{}` | Additional fetch options |
105
+ | `onRetry` | `function` | `undefined` | Callback when retry occurs |
106
+ | `onSuccess` | `function` | `undefined` | Callback when request succeeds |
107
+ | `onError` | `function` | `undefined` | Callback when all retries fail |
108
+
109
+ ### addQuery Function
110
+
111
+ ```ts
112
+ addQuery: ({ times, originalQuery }) => {
113
+ // Add retry count and timestamp for cache busting
114
+ const separator = originalQuery ? '&' : '?';
115
+ return `${originalQuery}${separator}retry=${times}&t=${Date.now()}`;
116
+ };
117
+ ```
118
+
119
+ ### Callback Functions
120
+
121
+ ```ts
122
+ onRetry: ({ times, domains, url, tagName }) => {
123
+ console.log(`Retry attempt ${times} for ${url}`);
124
+ console.log(`Available domains: ${domains?.join(', ')}`);
125
+ },
126
+
127
+ onSuccess: ({ domains, url, tagName }) => {
128
+ console.log(`Successfully loaded ${url}`);
129
+ console.log(`Used domain: ${domains?.[0]}`);
130
+ },
131
+
132
+ onError: ({ domains, url, tagName }) => {
133
+ console.error(`Failed to load ${url} after all retries`);
134
+ console.error(`Tried domains: ${domains?.join(', ')}`);
135
+ }
136
+ ```
137
+
138
+ ## Advanced Examples
139
+
140
+ ### Custom Retry Strategy
141
+
142
+ ```ts
143
+ RetryPlugin({
144
+ retryTimes: 5,
145
+ retryDelay: (attempt) => 1000 * 2 ** (attempt - 1), // Exponential backoff: 1s, 2s, 4s, ...
146
+ domains: ['https://cdn1.example.com', 'https://cdn2.example.com', 'https://cdn3.example.com'],
147
+ manifestDomains: ['https://api1.example.com', 'https://api2.example.com'],
148
+ addQuery: ({ times, originalQuery }) => {
149
+ const params = new URLSearchParams(originalQuery);
150
+ params.set('retry', times.toString());
151
+ params.set('cache_bust', Date.now().toString());
152
+ return params.toString();
153
+ },
154
+ onRetry: ({ times, url, domains }) => {
155
+ console.log(`Retry ${times}/5 for ${url}`);
156
+ console.log(`Trying domain: ${domains?.[times % domains.length]}`);
157
+ },
158
+ onSuccess: ({ url, domains }) => {
159
+ console.log(`✅ Successfully loaded ${url}`);
160
+ console.log(`✅ Used domain: ${domains?.[0]}`);
161
+ },
162
+ onError: ({ url, domains }) => {
163
+ console.error(`❌ Failed to load ${url} after all retries`);
164
+ console.error(`❌ Tried all domains: ${domains?.join(', ')}`);
165
+ },
166
+ });
167
+ ```
168
+
169
+ ### Error Handling with Fallback
170
+
171
+ ```ts
172
+ RetryPlugin({
173
+ retryTimes: 3,
174
+ retryDelay: 1000,
175
+ domains: ['https://cdn1.example.com', 'https://cdn2.example.com'],
176
+ onError: ({ url, domains }) => {
177
+ // Log error for monitoring
178
+ console.error('Module loading failed:', { url, domains });
179
+
180
+ // Send error to monitoring service
181
+ if (window.gtag) {
182
+ window.gtag('event', 'module_load_error', {
183
+ event_category: 'module_federation',
184
+ event_label: url,
185
+ value: domains?.length || 0,
186
+ });
187
+ }
188
+
189
+ // Show user-friendly error message
190
+ const errorElement = document.createElement('div');
191
+ errorElement.className = 'module-load-error';
192
+ errorElement.innerHTML = `
193
+ <div style="padding: 16px; border: 1px solid #ffa39e; border-radius: 4px; background: #fff1f0; color: #cf1322;">
194
+ <h4>Module Loading Failed</h4>
195
+ <p>Unable to load module: ${url}</p>
196
+ <p>Please refresh the page to try again.</p>
197
+ </div>
198
+ `;
199
+ document.body.appendChild(errorElement);
200
+ },
201
+ });
202
+ ```
203
+
204
+ ### Production Configuration
205
+
206
+ ```ts
207
+ RetryPlugin({
208
+ retryTimes: 3,
209
+ retryDelay: 1000,
210
+ domains: ['https://cdn1.prod.example.com', 'https://cdn2.prod.example.com', 'https://cdn3.prod.example.com'],
211
+ manifestDomains: ['https://api1.prod.example.com', 'https://api2.prod.example.com'],
212
+ addQuery: ({ times, originalQuery }) => {
213
+ const params = new URLSearchParams(originalQuery);
214
+ params.set('retry', times.toString());
215
+ params.set('v', process.env.BUILD_VERSION || '1.0.0');
216
+ return params.toString();
217
+ },
218
+ fetchOptions: {
219
+ cache: 'no-cache',
220
+ headers: {
221
+ 'X-Requested-With': 'ModuleFederation',
222
+ },
223
+ },
224
+ onRetry: ({ times, url }) => {
225
+ // Only log in development
226
+ if (process.env.NODE_ENV === 'development') {
227
+ console.log(`Retry ${times} for ${url}`);
228
+ }
229
+ },
230
+ onSuccess: ({ url }) => {
231
+ // Track successful loads
232
+ if (window.analytics) {
233
+ window.analytics.track('module_loaded', { url });
234
+ }
235
+ },
236
+ onError: ({ url, domains }) => {
237
+ // Send error to monitoring service
238
+ if (window.errorReporting) {
239
+ window.errorReporting.captureException(new Error(`Module loading failed: ${url}`), { extra: { domains, url } });
240
+ }
241
+ },
242
+ });
243
+ ```
244
+
245
+ ## How It Works
246
+
247
+ 1. **Fetch Retry**: Intercepts failed fetch requests for manifest files and retries with domain rotation
248
+ 2. **Script Retry**: Intercepts failed script loading and retries with alternative domains
249
+ 3. **Domain Rotation**: Cycles through provided domains to find working alternatives
250
+ 4. **Cache Busting**: Adds query parameters to prevent cache-related issues
251
+ 5. **Lifecycle Hooks**: Provides callbacks for monitoring and debugging
252
+
253
+ ## Error Scenarios Handled
254
+
255
+ - Network timeouts and connection errors
256
+ - DNS resolution failures
257
+ - Server errors (5xx status codes)
258
+ - CDN failures and regional issues
259
+ - Cache-related loading problems
260
+ - CORS and security policy violations
261
+
262
+ ## Browser Support
263
+
264
+ - Chrome 60+
265
+ - Firefox 55+
266
+ - Safari 12+
267
+ - Edge 79+
268
+
269
+ ## TypeScript Support
270
+
271
+ The plugin includes full TypeScript definitions:
272
+
273
+ ```ts
274
+ import { RetryPlugin, type CommonRetryOptions } from '@module-federation/retry-plugin';
275
+
276
+ const options: CommonRetryOptions = {
277
+ retryTimes: 3,
278
+ retryDelay: 1000,
279
+ domains: ['https://cdn1.example.com'],
280
+ onRetry: ({ times, url }) => {
281
+ console.log(`Retry ${times} for ${url}`);
282
+ },
283
+ };
284
+
285
+ const plugin = RetryPlugin(options);
286
+ ```
287
+
288
+ ## Migration Guide
289
+
290
+ ### From v0.18.x to v0.19.x
291
+
292
+ The plugin configuration has been simplified. The old `fetch` and `script` configuration objects are deprecated:
293
+
294
+ ```ts
295
+ // ❌ Old way (deprecated)
296
+ RetryPlugin({
297
+ fetch: {
298
+ url: 'http://localhost:2008/not-exist-mf-manifest.json',
299
+ fallback: () => 'http://localhost:2001/mf-manifest.json',
300
+ },
301
+ script: {
302
+ url: 'http://localhost:2001/static/js/async/src_App_tsx.js',
303
+ customCreateScript: (url, attrs) => {
304
+ /* ... */
305
+ },
306
+ },
307
+ });
308
+
309
+ // ✅ New way
310
+ RetryPlugin({
311
+ retryTimes: 3,
312
+ retryDelay: 1000,
313
+ domains: ['http://localhost:2001'],
314
+ manifestDomains: ['http://localhost:2001'],
315
+ addQuery: ({ times, originalQuery }) => `${originalQuery}&retry=${times}`,
316
+ });
317
+ ```
318
+
319
+ ## Contributing
320
+
321
+ Contributions are welcome! Please read our [contributing guidelines](https://github.com/module-federation/core/blob/main/CONTRIBUTING.md) and submit pull requests to our [GitHub repository](https://github.com/module-federation/core).
322
+
323
+ ## License
324
+
325
+ `@module-federation/retry-plugin` is [MIT licensed](https://github.com/module-federation/core/blob/main/packages/retry-plugin/LICENSE).
326
+
327
+ ## Related
328
+
329
+ - [Module Federation Documentation](https://module-federation.io/)
330
+ - [Module Federation Runtime](https://www.npmjs.com/package/@module-federation/runtime)
331
+ - [Module Federation Enhanced](https://www.npmjs.com/package/@module-federation/enhanced)