@rsbuild/plugin-assets-retry 1.0.3 → 1.0.4

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/dist/index.cjs CHANGED
@@ -1,8 +1,8 @@
1
1
  var __webpack_modules__ = {
2
- "../../node_modules/.pnpm/randombytes@2.1.0/node_modules/randombytes/index.js": function(module, __unused_webpack_exports, __webpack_require__) {
3
- module.exports = __webpack_require__("crypto")/* .randomBytes */ .randomBytes;
2
+ "../../node_modules/.pnpm/randombytes@2.1.0/node_modules/randombytes/index.js": function(module1, __unused_webpack_exports, __webpack_require__) {
3
+ module1.exports = __webpack_require__("crypto")/* .randomBytes */ .randomBytes;
4
4
  },
5
- "../../node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js": function(module, __unused_webpack_exports, __webpack_require__) {
5
+ "../../node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js": function(module1, __unused_webpack_exports, __webpack_require__) {
6
6
  "use strict";
7
7
  /*
8
8
  Copyright (c) 2014, Yahoo! Inc. All rights reserved.
@@ -44,7 +44,7 @@ See the accompanying LICENSE file for terms.
44
44
  for(var key in obj)if ("function" == typeof obj[key]) functionKeys.push(key);
45
45
  for(var i = 0; i < functionKeys.length; i++)delete obj[functionKeys[i]];
46
46
  }
47
- module.exports = function serialize(obj, options) {
47
+ module1.exports = function serialize(obj, options) {
48
48
  options || (options = {});
49
49
  // Backwards-compatibility for `space` as the second argument.
50
50
  if ('number' == typeof options || 'string' == typeof options) options = {
@@ -149,9 +149,9 @@ See the accompanying LICENSE file for terms.
149
149
  });
150
150
  };
151
151
  },
152
- crypto: function(module) {
152
+ crypto: function(module1) {
153
153
  "use strict";
154
- module.exports = require("crypto");
154
+ module1.exports = require("crypto");
155
155
  }
156
156
  };
157
157
  /************************************************************************/ // The module cache
@@ -162,22 +162,22 @@ function __webpack_require__(moduleId) {
162
162
  var cachedModule = __webpack_module_cache__[moduleId];
163
163
  if (void 0 !== cachedModule) return cachedModule.exports;
164
164
  // Create a new module (and put it into the cache)
165
- var module = __webpack_module_cache__[moduleId] = {
165
+ var module1 = __webpack_module_cache__[moduleId] = {
166
166
  exports: {}
167
167
  };
168
168
  // Execute the module function
169
- __webpack_modules__[moduleId](module, module.exports, __webpack_require__);
169
+ __webpack_modules__[moduleId](module1, module1.exports, __webpack_require__);
170
170
  // Return the exports of the module
171
- return module.exports;
171
+ return module1.exports;
172
172
  }
173
173
  /************************************************************************/ // webpack/runtime/compat_get_default_export
174
174
  (()=>{
175
- // getDefaultExport function for compatibility with non-harmony modules
176
- __webpack_require__.n = function(module) {
177
- var getter = module && module.__esModule ? function() {
178
- return module['default'];
175
+ // getDefaultExport function for compatibility with non-ESM modules
176
+ __webpack_require__.n = function(module1) {
177
+ var getter = module1 && module1.__esModule ? function() {
178
+ return module1['default'];
179
179
  } : function() {
180
- return module;
180
+ return module1;
181
181
  };
182
182
  __webpack_require__.d(getter, {
183
183
  a: getter
@@ -227,6 +227,7 @@ function __webpack_require__(moduleId) {
227
227
  var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
228
228
  const external_node_path_namespaceObject = require("node:path");
229
229
  var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
230
+ const external_node_url_namespaceObject = require("node:url");
230
231
  const core_namespaceObject = require("@rsbuild/core");
231
232
  // EXTERNAL MODULE: ../../node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js
232
233
  var serialize_javascript = __webpack_require__("../../node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js");
@@ -241,20 +242,23 @@ function __webpack_require__(moduleId) {
241
242
  else obj[key] = value;
242
243
  return obj;
243
244
  }
245
+ const AsyncChunkRetryPlugin_dirname = external_node_path_default().dirname((0, external_node_url_namespaceObject.fileURLToPath)(/*#__PURE__*/ function() {
246
+ return 'undefined' == typeof document ? new (module.require('url'.replace('', ''))).URL('file:' + __filename).href : document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href;
247
+ }()));
244
248
  // https://github.com/web-infra-dev/rspack/pull/5370
245
- function appendWebpackScript(module, appendSource) {
249
+ function appendWebpackScript(module1, appendSource) {
246
250
  try {
247
- const originSource = module.getGeneratedCode();
248
- module.getGeneratedCode = ()=>`${originSource}\n${appendSource}`;
251
+ const originSource = module1.getGeneratedCode();
252
+ module1.getGeneratedCode = ()=>`${originSource}\n${appendSource}`;
249
253
  } catch (err) {
250
254
  console.error('Failed to modify Webpack RuntimeModule');
251
255
  throw err;
252
256
  }
253
257
  }
254
- function appendRspackScript(module, appendSource) {
258
+ function appendRspackScript(module1, appendSource) {
255
259
  try {
256
- const source = module.source.source.toString();
257
- module.source.source = Buffer.from(`${source}\n${appendSource}`, 'utf-8');
260
+ const source = module1.source.source.toString();
261
+ module1.source.source = Buffer.from(`${source}\n${appendSource}`, 'utf-8');
258
262
  } catch (err) {
259
263
  console.error('Failed to modify Rspack RuntimeModule');
260
264
  throw err;
@@ -270,23 +274,23 @@ function __webpack_require__(moduleId) {
270
274
  getRawRuntimeRetryCode() {
271
275
  const { RuntimeGlobals } = core_namespaceObject.rspack;
272
276
  const filename = 'asyncChunkRetry';
273
- const runtimeFilePath = external_node_path_default().join(__dirname, 'runtime', this.options.minify ? `${filename}.min.js` : `${filename}.js`);
277
+ const runtimeFilePath = external_node_path_default().join(AsyncChunkRetryPlugin_dirname, 'runtime', this.options.minify ? `${filename}.min.js` : `${filename}.js`);
274
278
  const rawText = external_node_fs_default().readFileSync(runtimeFilePath, 'utf-8');
275
279
  return rawText.replaceAll('__RUNTIME_GLOBALS_REQUIRE__', RuntimeGlobals.require).replaceAll('__RUNTIME_GLOBALS_ENSURE_CHUNK__', RuntimeGlobals.ensureChunk).replaceAll('__RUNTIME_GLOBALS_GET_CHUNK_SCRIPT_FILENAME__', RuntimeGlobals.getChunkScriptFilename).replaceAll('__RUNTIME_GLOBALS_GET_CSS_FILENAME__', RuntimeGlobals.getChunkCssFilename).replaceAll('__RUNTIME_GLOBALS_GET_MINI_CSS_EXTRACT_FILENAME__', '__webpack_require__.miniCssF').replaceAll('__RUNTIME_GLOBALS_PUBLIC_PATH__', RuntimeGlobals.publicPath).replaceAll('__RUNTIME_GLOBALS_LOAD_SCRIPT__', RuntimeGlobals.loadScript).replaceAll('__RETRY_OPTIONS__', serialize_javascript_default()(this.runtimeOptions));
276
280
  }
277
281
  apply(compiler) {
278
282
  compiler.hooks.thisCompilation.tap(this.name, (compilation)=>{
279
- compilation.hooks.runtimeModule.tap(this.name, (module)=>{
283
+ compilation.hooks.runtimeModule.tap(this.name, (module1)=>{
280
284
  var _module_constructor;
281
285
  const { isRspack } = this.options;
282
- const constructorName = isRspack ? module.constructorName : null === (_module_constructor = module.constructor) || void 0 === _module_constructor ? void 0 : _module_constructor.name;
283
- const isPublicPathModule = 'publicPath' === module.name || 'PublicPathRuntimeModule' === constructorName || 'AutoPublicPathRuntimeModule' === constructorName;
286
+ const constructorName = isRspack ? module1.constructorName : null === (_module_constructor = module1.constructor) || void 0 === _module_constructor ? void 0 : _module_constructor.name;
287
+ const isPublicPathModule = 'publicPath' === module1.name || 'PublicPathRuntimeModule' === constructorName || 'AutoPublicPathRuntimeModule' === constructorName;
284
288
  if (!isPublicPathModule) return;
285
289
  const runtimeCode = this.getRawRuntimeRetryCode();
286
290
  // Rspack currently does not have module.addRuntimeModule on the js side,
287
291
  // so we insert our runtime code after PublicPathRuntimeModule or AutoPublicPathRuntimeModule.
288
- if (isRspack) appendRspackScript(module, runtimeCode);
289
- else appendWebpackScript(module, runtimeCode);
292
+ if (isRspack) appendRspackScript(module1, runtimeCode);
293
+ else appendWebpackScript(module1, runtimeCode);
290
294
  });
291
295
  });
292
296
  }
@@ -306,23 +310,24 @@ function __webpack_require__(moduleId) {
306
310
  ]);
307
311
  }
308
312
  }
313
+ const src_dirname = external_node_path_default().dirname((0, external_node_url_namespaceObject.fileURLToPath)(/*#__PURE__*/ function() {
314
+ return 'undefined' == typeof document ? new (module.require('url'.replace('', ''))).URL('file:' + __filename).href : document.currentScript && document.currentScript.src || new URL('main.js', document.baseURI).href;
315
+ }()));
309
316
  const PLUGIN_ASSETS_RETRY_NAME = 'rsbuild:assets-retry';
310
317
  async function getRetryCode(options) {
311
318
  const filename = 'initialChunkRetry';
312
319
  const { minify, inlineScript: _, ...restOptions } = options;
313
- const runtimeFilePath = external_node_path_default().join(__dirname, 'runtime', minify ? `${filename}.min.js` : `${filename}.js`);
320
+ const runtimeFilePath = external_node_path_default().join(src_dirname, 'runtime', minify ? `${filename}.min.js` : `${filename}.js`);
314
321
  const runtimeCode = await external_node_fs_default().promises.readFile(runtimeFilePath, 'utf-8');
315
322
  return `(function(){${runtimeCode};init(${serialize_javascript_default()(restOptions)});})()`;
316
323
  }
317
- const pluginAssetsRetry = function() {
318
- let userOptions = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
319
- return {
324
+ const pluginAssetsRetry = (userOptions = {})=>({
320
325
  name: PLUGIN_ASSETS_RETRY_NAME,
321
326
  setup (api) {
322
327
  const { inlineScript = true } = userOptions;
323
328
  const getScriptPath = (environment)=>{
324
329
  const distDir = environment.config.output.distPath.js;
325
- return external_node_path_default().posix.join(distDir, "assets-retry.1-0-3.js");
330
+ return external_node_path_default().posix.join(distDir, "assets-retry.1-0-4.js");
326
331
  };
327
332
  const formatOptions = (config)=>{
328
333
  const options = {
@@ -337,8 +342,7 @@ function __webpack_require__(moduleId) {
337
342
  }
338
343
  return options;
339
344
  };
340
- if (inlineScript) api.modifyHTMLTags(async (param, param1)=>{
341
- let { headTags, bodyTags } = param, { environment } = param1;
345
+ if (inlineScript) api.modifyHTMLTags(async ({ headTags, bodyTags }, { environment })=>{
342
346
  const code = await getRetryCode(formatOptions(environment.config));
343
347
  headTags.unshift({
344
348
  tag: 'script',
@@ -351,8 +355,7 @@ function __webpack_require__(moduleId) {
351
355
  };
352
356
  });
353
357
  else {
354
- api.modifyHTMLTags(async (param, param1)=>{
355
- let { headTags, bodyTags } = param, { assetPrefix, environment } = param1;
358
+ api.modifyHTMLTags(async ({ headTags, bodyTags }, { assetPrefix, environment })=>{
356
359
  const scriptPath = getScriptPath(environment);
357
360
  const url = (0, core_namespaceObject.ensureAssetPrefix)(scriptPath, assetPrefix);
358
361
  headTags.unshift({
@@ -368,15 +371,13 @@ function __webpack_require__(moduleId) {
368
371
  });
369
372
  api.processAssets({
370
373
  stage: 'additional'
371
- }, async (param)=>{
372
- let { sources, compilation, environment } = param;
374
+ }, async ({ sources, compilation, environment })=>{
373
375
  const scriptPath = getScriptPath(environment);
374
376
  const code = await getRetryCode(formatOptions(environment.config));
375
377
  compilation.emitAsset(scriptPath, new sources.RawSource(code));
376
378
  });
377
379
  }
378
- api.modifyBundlerChain(async (chain, param)=>{
379
- let { environment } = param;
380
+ api.modifyBundlerChain(async (chain, { environment })=>{
380
381
  const { config, htmlPaths } = environment;
381
382
  if (!userOptions || 0 === Object.keys(htmlPaths).length) return;
382
383
  const options = formatOptions(config);
@@ -389,8 +390,7 @@ function __webpack_require__(moduleId) {
389
390
  ]);
390
391
  });
391
392
  }
392
- };
393
- };
393
+ });
394
394
  })();
395
395
  var __webpack_export_target__ = exports;
396
396
  for(var i in __webpack_exports__)__webpack_export_target__[i] = __webpack_exports__[i];
package/dist/index.js CHANGED
@@ -1,8 +1,7 @@
1
- import { fileURLToPath as __webpack_fileURLToPath__ } from "url";
2
- import { dirname as __webpack_dirname__ } from "path";
3
1
  import * as __WEBPACK_EXTERNAL_MODULE_crypto__ from "crypto";
4
2
  import * as __WEBPACK_EXTERNAL_MODULE_node_fs__ from "node:fs";
5
3
  import * as __WEBPACK_EXTERNAL_MODULE_node_path__ from "node:path";
4
+ import * as __WEBPACK_EXTERNAL_MODULE_node_url__ from "node:url";
6
5
  import * as __WEBPACK_EXTERNAL_MODULE__rsbuild_core__ from "@rsbuild/core";
7
6
  var __webpack_modules__ = {
8
7
  "../../node_modules/.pnpm/randombytes@2.1.0/node_modules/randombytes/index.js": function(module, __unused_webpack_exports, __webpack_require__) {
@@ -176,7 +175,7 @@ function __webpack_require__(moduleId) {
176
175
  }
177
176
  /************************************************************************/ // webpack/runtime/compat_get_default_export
178
177
  (()=>{
179
- // getDefaultExport function for compatibility with non-harmony modules
178
+ // getDefaultExport function for compatibility with non-ESM modules
180
179
  __webpack_require__.n = function(module) {
181
180
  var getter = module && module.__esModule ? function() {
182
181
  return module['default'];
@@ -207,7 +206,6 @@ function __webpack_require__(moduleId) {
207
206
  // EXTERNAL MODULE: ../../node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js
208
207
  var serialize_javascript = __webpack_require__("../../node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js");
209
208
  var serialize_javascript_default = /*#__PURE__*/ __webpack_require__.n(serialize_javascript);
210
- var AsyncChunkRetryPlugin_dirname = __webpack_dirname__(__webpack_fileURLToPath__(import.meta.url));
211
209
  function _define_property(obj, key, value) {
212
210
  if (key in obj) Object.defineProperty(obj, key, {
213
211
  value: value,
@@ -218,6 +216,7 @@ function _define_property(obj, key, value) {
218
216
  else obj[key] = value;
219
217
  return obj;
220
218
  }
219
+ const AsyncChunkRetryPlugin_dirname = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].dirname((0, __WEBPACK_EXTERNAL_MODULE_node_url__.fileURLToPath)(import.meta.url));
221
220
  // https://github.com/web-infra-dev/rspack/pull/5370
222
221
  function appendWebpackScript(module, appendSource) {
223
222
  try {
@@ -283,7 +282,7 @@ class AsyncChunkRetryPlugin {
283
282
  ]);
284
283
  }
285
284
  }
286
- var src_dirname = __webpack_dirname__(__webpack_fileURLToPath__(import.meta.url));
285
+ const src_dirname = __WEBPACK_EXTERNAL_MODULE_node_path__["default"].dirname((0, __WEBPACK_EXTERNAL_MODULE_node_url__.fileURLToPath)(import.meta.url));
287
286
  const PLUGIN_ASSETS_RETRY_NAME = 'rsbuild:assets-retry';
288
287
  async function getRetryCode(options) {
289
288
  const filename = 'initialChunkRetry';
@@ -292,15 +291,13 @@ async function getRetryCode(options) {
292
291
  const runtimeCode = await __WEBPACK_EXTERNAL_MODULE_node_fs__["default"].promises.readFile(runtimeFilePath, 'utf-8');
293
292
  return `(function(){${runtimeCode};init(${serialize_javascript_default()(restOptions)});})()`;
294
293
  }
295
- const pluginAssetsRetry = function() {
296
- let userOptions = arguments.length > 0 && void 0 !== arguments[0] ? arguments[0] : {};
297
- return {
294
+ const pluginAssetsRetry = (userOptions = {})=>({
298
295
  name: PLUGIN_ASSETS_RETRY_NAME,
299
296
  setup (api) {
300
297
  const { inlineScript = true } = userOptions;
301
298
  const getScriptPath = (environment)=>{
302
299
  const distDir = environment.config.output.distPath.js;
303
- return __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.join(distDir, "assets-retry.1-0-3.js");
300
+ return __WEBPACK_EXTERNAL_MODULE_node_path__["default"].posix.join(distDir, "assets-retry.1-0-4.js");
304
301
  };
305
302
  const formatOptions = (config)=>{
306
303
  const options = {
@@ -315,8 +312,7 @@ const pluginAssetsRetry = function() {
315
312
  }
316
313
  return options;
317
314
  };
318
- if (inlineScript) api.modifyHTMLTags(async (param, param1)=>{
319
- let { headTags, bodyTags } = param, { environment } = param1;
315
+ if (inlineScript) api.modifyHTMLTags(async ({ headTags, bodyTags }, { environment })=>{
320
316
  const code = await getRetryCode(formatOptions(environment.config));
321
317
  headTags.unshift({
322
318
  tag: 'script',
@@ -329,8 +325,7 @@ const pluginAssetsRetry = function() {
329
325
  };
330
326
  });
331
327
  else {
332
- api.modifyHTMLTags(async (param, param1)=>{
333
- let { headTags, bodyTags } = param, { assetPrefix, environment } = param1;
328
+ api.modifyHTMLTags(async ({ headTags, bodyTags }, { assetPrefix, environment })=>{
334
329
  const scriptPath = getScriptPath(environment);
335
330
  const url = (0, __WEBPACK_EXTERNAL_MODULE__rsbuild_core__.ensureAssetPrefix)(scriptPath, assetPrefix);
336
331
  headTags.unshift({
@@ -346,15 +341,13 @@ const pluginAssetsRetry = function() {
346
341
  });
347
342
  api.processAssets({
348
343
  stage: 'additional'
349
- }, async (param)=>{
350
- let { sources, compilation, environment } = param;
344
+ }, async ({ sources, compilation, environment })=>{
351
345
  const scriptPath = getScriptPath(environment);
352
346
  const code = await getRetryCode(formatOptions(environment.config));
353
347
  compilation.emitAsset(scriptPath, new sources.RawSource(code));
354
348
  });
355
349
  }
356
- api.modifyBundlerChain(async (chain, param)=>{
357
- let { environment } = param;
350
+ api.modifyBundlerChain(async (chain, { environment })=>{
358
351
  const { config, htmlPaths } = environment;
359
352
  if (!userOptions || 0 === Object.keys(htmlPaths).length) return;
360
353
  const options = formatOptions(config);
@@ -367,6 +360,5 @@ const pluginAssetsRetry = function() {
367
360
  ]);
368
361
  });
369
362
  }
370
- };
371
- };
363
+ });
372
364
  export { PLUGIN_ASSETS_RETRY_NAME, pluginAssetsRetry };
@@ -73,8 +73,12 @@ function getNextRetryUrl(existRetryTimes, nextDomain, originalSrcUrl) {
73
73
  var absolutePath = getAbsolutePathFromUrl(originalSrcUrl);
74
74
  return nextDomain + absolutePath + getUrlRetryQuery(existRetryTimes, getQueryFromUrl(originalSrcUrl));
75
75
  }
76
- function getCurrentRetry(chunkId) {
77
- return retryCollector[chunkId];
76
+
77
+ // shared between ensureChunk and loadScript
78
+ var globalCurrRetrying = {};
79
+ function getCurrentRetry(chunkId, existRetryTimes) {
80
+ var _retryCollector$chunk;
81
+ return (_retryCollector$chunk = retryCollector[chunkId]) === null || _retryCollector$chunk === void 0 ? void 0 : _retryCollector$chunk[existRetryTimes];
78
82
  }
79
83
  function initRetry(chunkId) {
80
84
  var _config$domain$, _config$domain3;
@@ -83,32 +87,32 @@ function initRetry(chunkId) {
83
87
  var existRetryTimes = 1;
84
88
  var nextDomain = (_config$domain$ = (_config$domain3 = config.domain) === null || _config$domain3 === void 0 ? void 0 : _config$domain3[0]) !== null && _config$domain$ !== void 0 ? _config$domain$ : window.origin;
85
89
  return {
86
- existRetryTimes: existRetryTimes,
87
90
  nextDomain: nextDomain,
88
91
  nextRetryUrl: getNextRetryUrl(existRetryTimes, nextDomain, originalSrcUrl),
89
92
  originalScriptFilename: originalScriptFilename,
90
93
  originalSrcUrl: originalSrcUrl
91
94
  };
92
95
  }
93
- function nextRetry(chunkId) {
94
- var currRetry = getCurrentRetry(chunkId);
96
+ function nextRetry(chunkId, existRetryTimes) {
97
+ var currRetry = getCurrentRetry(chunkId, existRetryTimes);
95
98
  var nextRetry;
96
- if (!currRetry) {
99
+ var nextExistRetryTimes = existRetryTimes + 1;
100
+ if (existRetryTimes === 0 || currRetry === undefined) {
97
101
  nextRetry = initRetry(chunkId);
102
+ retryCollector[chunkId] = [];
98
103
  } else {
99
104
  var originalScriptFilename = currRetry.originalScriptFilename,
100
105
  originalSrcUrl = currRetry.originalSrcUrl;
101
- var existRetryTimes = currRetry.existRetryTimes + 1;
102
106
  var nextDomain = findNextDomain(currRetry.nextDomain);
103
107
  nextRetry = {
104
- existRetryTimes: existRetryTimes,
105
108
  nextDomain: nextDomain,
106
- nextRetryUrl: getNextRetryUrl(existRetryTimes, nextDomain, originalSrcUrl),
109
+ nextRetryUrl: getNextRetryUrl(nextExistRetryTimes, nextDomain, originalSrcUrl),
107
110
  originalScriptFilename: originalScriptFilename,
108
111
  originalSrcUrl: originalSrcUrl
109
112
  };
110
113
  }
111
- retryCollector[chunkId] = nextRetry;
114
+ retryCollector[chunkId][nextExistRetryTimes] = nextRetry;
115
+ globalCurrRetrying[chunkId] = nextRetry;
112
116
  return nextRetry;
113
117
  }
114
118
 
@@ -122,6 +126,9 @@ var originalLoadScript = __RUNTIME_GLOBALS_LOAD_SCRIPT__;
122
126
 
123
127
  // if users want to support es5, add Promise polyfill first https://github.com/webpack/webpack/issues/12877
124
128
  function ensureChunk(chunkId) {
129
+ var callingCounter = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
130
+ count: 0
131
+ };
125
132
  var result = originalEnsureChunk(chunkId);
126
133
  var originalScriptFilename = originalGetChunkScriptFilename(chunkId);
127
134
  var originalCssFilename = originalGetCssFilename(chunkId);
@@ -135,17 +142,20 @@ function ensureChunk(chunkId) {
135
142
  window.__RB_ASYNC_CHUNKS__[originalCssFilename] = true;
136
143
  }
137
144
  }
145
+ callingCounter.count += 1;
138
146
  return result.catch(function (error) {
139
147
  var _error$message;
140
- var _nextRetry = nextRetry(chunkId),
141
- existRetryTimes = _nextRetry.existRetryTimes,
148
+ // the first calling is not retry
149
+ // if the failed request is 4 in network panel, callingCounter.count === 4, the first one is the normal request, and existRetryTimes is 3, retried 3 times
150
+ var existRetryTimes = callingCounter.count - 1;
151
+ var _nextRetry = nextRetry(chunkId, existRetryTimes),
142
152
  originalSrcUrl = _nextRetry.originalSrcUrl,
143
153
  nextRetryUrl = _nextRetry.nextRetryUrl,
144
154
  nextDomain = _nextRetry.nextDomain;
145
155
 
146
- // At present, we don't consider the switching domain and addQuery of async css chunk
147
- // 1. Async js chunk will be requested first. It is rare for async css chunk to fail alone.
148
- // 2. the code of loading css in webpack runtime is complex and it may be modified by cssExtractPlugin, increase the complexity of this plugin.
156
+ // At present, we don't consider the switching domain and addQuery of async CSS chunk
157
+ // 1. Async js chunk will be requested first. It is rare for async CSS chunk to fail alone.
158
+ // 2. the code of loading CSS in webpack runtime is complex and it may be modified by cssExtractPlugin, increase the complexity of this plugin.
149
159
  var isCssAsyncChunkLoadFailed = Boolean(error === null || error === void 0 || (_error$message = error.message) === null || _error$message === void 0 ? void 0 : _error$message.includes('CSS chunk'));
150
160
  var createContext = function createContext(times) {
151
161
  return {
@@ -156,9 +166,10 @@ function ensureChunk(chunkId) {
156
166
  isAsyncChunk: true
157
167
  };
158
168
  };
159
- var context = createContext(existRetryTimes - 1);
160
- if (existRetryTimes > maxRetries) {
161
- error.message = "Loading chunk ".concat(chunkId, " from ").concat(originalSrcUrl, " failed after ").concat(maxRetries, " retries: \"").concat(error.message, "\"");
169
+ var context = createContext(existRetryTimes);
170
+ if (existRetryTimes >= maxRetries) {
171
+ var _error$message2;
172
+ error.message = (_error$message2 = error.message) !== null && _error$message2 !== void 0 && _error$message2.includes('retries:') ? error.message : "Loading chunk ".concat(chunkId, " from ").concat(originalSrcUrl, " failed after ").concat(maxRetries, " retries: \"").concat(error.message, "\"");
162
173
  if (typeof config.onFail === 'function') {
163
174
  config.onFail(context);
164
175
  }
@@ -186,22 +197,22 @@ function ensureChunk(chunkId) {
186
197
  if (typeof config.onRetry === 'function') {
187
198
  config.onRetry(context);
188
199
  }
189
- return ensureChunk(chunkId).then(function (result) {
190
- if (typeof config.onSuccess === 'function') {
191
- var _getCurrentRetry;
192
- var _context = createContext(existRetryTimes);
193
- var _ref2 = (_getCurrentRetry = getCurrentRetry(chunkId)) !== null && _getCurrentRetry !== void 0 ? _getCurrentRetry : {},
194
- currRetryTimes = _ref2.existRetryTimes;
195
- if (currRetryTimes === existRetryTimes) {
196
- config.onSuccess(_context);
197
- }
200
+ var nextPromise = ensureChunk(chunkId, callingCounter);
201
+ return nextPromise.then(function (result) {
202
+ // when after retrying the third time
203
+ // ensureChunk(chunkId, { count: 3 }), at that time, existRetryTimes === 2
204
+ // after all, callingCounter.count is 4
205
+ var isLastSuccessRetry = callingCounter.count === existRetryTimes + 2;
206
+ if (typeof config.onSuccess === 'function' && isLastSuccessRetry) {
207
+ var _context = createContext(existRetryTimes + 1);
208
+ config.onSuccess(_context);
198
209
  }
199
210
  return result;
200
211
  });
201
212
  });
202
213
  }
203
214
  function loadScript(originalUrl, done, key, chunkId) {
204
- var retry = getCurrentRetry(chunkId);
215
+ var retry = globalCurrRetrying[chunkId];
205
216
  return originalLoadScript(retry ? retry.nextRetryUrl : originalUrl, done, key, chunkId);
206
217
  }
207
218
  function registerAsyncChunkRetry() {
@@ -1 +1 @@
1
- "use strict";var _ref,_RUNTIME_GLOBALS_GET,config=__RETRY_OPTIONS__,maxRetries=config.max||3,retryCollector={};function findCurrentDomain(n){for(var r,e=null!==(r=config.domain)&&void 0!==r?r:[],i="",t=0;t<e.length;t++)if(-1!==n.indexOf(e[t])){i=e[t];break}return i||window.origin}function findNextDomain(n){var r,e=null!==(r=config.domain)&&void 0!==r?r:[],i=findCurrentDomain(n),t=e.indexOf(i);return e[(t+1)%e.length]||n}var postfixRE=/[?#].*$/;function cleanUrl(n){return n.replace(postfixRE,"")}function getQueryFromUrl(n){var r=n.split("?")[1];return r?"?".concat(r.split("#")[0]):""}function getUrlRetryQuery(n,r){return!0===config.addQuery?""!==r?"".concat(r,"&retry=").concat(n):"?retry=".concat(n):"function"==typeof config.addQuery?config.addQuery({times:n,originalQuery:r}):""}function removeDomainFromUrl(n){var r=n.indexOf("//");if(-1===r&&n.startsWith("/"))return n;var e=r+2,i=n.indexOf("/",e);return n.slice(i)}function getAbsolutePathFromUrl(n){return cleanUrl(removeDomainFromUrl(n))}function getNextRetryUrl(n,r,e){return r+getAbsolutePathFromUrl(e)+getUrlRetryQuery(n,getQueryFromUrl(e))}function getCurrentRetry(n){return retryCollector[n]}function initRetry(n){var r,e,i=originalGetChunkScriptFilename(n),t=__RUNTIME_GLOBALS_PUBLIC_PATH__+i,o=null!==(r=null===(e=config.domain)||void 0===e?void 0:e[0])&&void 0!==r?r:window.origin;return{existRetryTimes:1,nextDomain:o,nextRetryUrl:getNextRetryUrl(1,o,t),originalScriptFilename:i,originalSrcUrl:t}}function nextRetry(n){var r,e=getCurrentRetry(n);if(e){var i=e.originalScriptFilename,t=e.originalSrcUrl,o=e.existRetryTimes+1,_=findNextDomain(e.nextDomain);r={existRetryTimes:o,nextDomain:_,nextRetryUrl:getNextRetryUrl(o,_,t),originalScriptFilename:i,originalSrcUrl:t}}else r=initRetry(n);return retryCollector[n]=r,r}var originalEnsureChunk=__RUNTIME_GLOBALS_ENSURE_CHUNK__,originalGetChunkScriptFilename=__RUNTIME_GLOBALS_GET_CHUNK_SCRIPT_FILENAME__,originalGetCssFilename=null!==(_ref=null!==(_RUNTIME_GLOBALS_GET=__RUNTIME_GLOBALS_GET_MINI_CSS_EXTRACT_FILENAME__)&&void 0!==_RUNTIME_GLOBALS_GET?_RUNTIME_GLOBALS_GET:__RUNTIME_GLOBALS_GET_CSS_FILENAME__)&&void 0!==_ref?_ref:function(){return null},originalLoadScript=__RUNTIME_GLOBALS_LOAD_SCRIPT__;function ensureChunk(n){var r=originalEnsureChunk(n),e=originalGetChunkScriptFilename(n),i=originalGetCssFilename(n);return"undefined"!=typeof window&&(e&&(window.__RB_ASYNC_CHUNKS__[e]=!0),i&&(window.__RB_ASYNC_CHUNKS__[i]=!0)),r.catch((function(r){var e,i=nextRetry(n),t=i.existRetryTimes,o=i.originalSrcUrl,_=i.nextRetryUrl,a=i.nextDomain,u=Boolean(null==r||null===(e=r.message)||void 0===e?void 0:e.includes("CSS chunk")),c=function(n){return{times:n,domain:a,url:_,tagName:u?"link":"script",isAsyncChunk:!0}},l=c(t-1);if(t>maxRetries)throw r.message="Loading chunk ".concat(n," from ").concat(o," failed after ").concat(maxRetries,' retries: "').concat(r.message,'"'),"function"==typeof config.onFail&&config.onFail(l),r;var f=config.test;if(f){if("string"==typeof f){var s=new RegExp(f);f=function(n){return s.test(n)}}if("function"!=typeof f||!f(_))throw r}if(config.domain&&config.domain.length>0&&-1===config.domain.indexOf(a))throw r;return"function"==typeof config.onRetry&&config.onRetry(l),ensureChunk(n).then((function(r){if("function"==typeof config.onSuccess){var e,i=c(t);(null!==(e=getCurrentRetry(n))&&void 0!==e?e:{}).existRetryTimes===t&&config.onSuccess(i)}return r}))}))}function loadScript(n,r,e,i){var t=getCurrentRetry(i);return originalLoadScript(t?t.nextRetryUrl:n,r,e,i)}function registerAsyncChunkRetry(){if("undefined"==typeof window||window.__RB_ASYNC_CHUNKS__||(window.__RB_ASYNC_CHUNKS__={}),"undefined"!=typeof __RUNTIME_GLOBALS_REQUIRE__)try{__RUNTIME_GLOBALS_ENSURE_CHUNK__=ensureChunk,__RUNTIME_GLOBALS_LOAD_SCRIPT__=loadScript}catch(n){console.error("[@rsbuild/plugin-assets-retry] Register async chunk retry runtime failed",n)}}registerAsyncChunkRetry();
1
+ "use strict";var _ref,_RUNTIME_GLOBALS_GET,config=__RETRY_OPTIONS__,maxRetries=config.max||3,retryCollector={};function findCurrentDomain(n){for(var r,e=null!==(r=config.domain)&&void 0!==r?r:[],i="",t=0;t<e.length;t++)if(-1!==n.indexOf(e[t])){i=e[t];break}return i||window.origin}function findNextDomain(n){var r,e=null!==(r=config.domain)&&void 0!==r?r:[],i=findCurrentDomain(n),t=e.indexOf(i);return e[(t+1)%e.length]||n}var postfixRE=/[?#].*$/;function cleanUrl(n){return n.replace(postfixRE,"")}function getQueryFromUrl(n){var r=n.split("?")[1];return r?"?".concat(r.split("#")[0]):""}function getUrlRetryQuery(n,r){return!0===config.addQuery?""!==r?"".concat(r,"&retry=").concat(n):"?retry=".concat(n):"function"==typeof config.addQuery?config.addQuery({times:n,originalQuery:r}):""}function removeDomainFromUrl(n){var r=n.indexOf("//");if(-1===r&&n.startsWith("/"))return n;var e=r+2,i=n.indexOf("/",e);return n.slice(i)}function getAbsolutePathFromUrl(n){return cleanUrl(removeDomainFromUrl(n))}function getNextRetryUrl(n,r,e){return r+getAbsolutePathFromUrl(e)+getUrlRetryQuery(n,getQueryFromUrl(e))}var globalCurrRetrying={};function getCurrentRetry(n,r){var e;return null===(e=retryCollector[n])||void 0===e?void 0:e[r]}function initRetry(n){var r,e,i=originalGetChunkScriptFilename(n),t=__RUNTIME_GLOBALS_PUBLIC_PATH__+i,o=null!==(r=null===(e=config.domain)||void 0===e?void 0:e[0])&&void 0!==r?r:window.origin;return{nextDomain:o,nextRetryUrl:getNextRetryUrl(1,o,t),originalScriptFilename:i,originalSrcUrl:t}}function nextRetry(n,r){var e,i=getCurrentRetry(n,r),t=r+1;if(0===r||void 0===i)e=initRetry(n),retryCollector[n]=[];else{var o=i.originalScriptFilename,_=i.originalSrcUrl,a=findNextDomain(i.nextDomain);e={nextDomain:a,nextRetryUrl:getNextRetryUrl(t,a,_),originalScriptFilename:o,originalSrcUrl:_}}return retryCollector[n][t]=e,globalCurrRetrying[n]=e,e}var originalEnsureChunk=__RUNTIME_GLOBALS_ENSURE_CHUNK__,originalGetChunkScriptFilename=__RUNTIME_GLOBALS_GET_CHUNK_SCRIPT_FILENAME__,originalGetCssFilename=null!==(_ref=null!==(_RUNTIME_GLOBALS_GET=__RUNTIME_GLOBALS_GET_MINI_CSS_EXTRACT_FILENAME__)&&void 0!==_RUNTIME_GLOBALS_GET?_RUNTIME_GLOBALS_GET:__RUNTIME_GLOBALS_GET_CSS_FILENAME__)&&void 0!==_ref?_ref:function(){return null},originalLoadScript=__RUNTIME_GLOBALS_LOAD_SCRIPT__;function ensureChunk(n){var r=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{count:0},e=originalEnsureChunk(n),i=originalGetChunkScriptFilename(n),t=originalGetCssFilename(n);return"undefined"!=typeof window&&(i&&(window.__RB_ASYNC_CHUNKS__[i]=!0),t&&(window.__RB_ASYNC_CHUNKS__[t]=!0)),r.count+=1,e.catch((function(e){var i,t,o=r.count-1,_=nextRetry(n,o),a=_.originalSrcUrl,l=_.nextRetryUrl,u=_.nextDomain,c=Boolean(null==e||null===(i=e.message)||void 0===i?void 0:i.includes("CSS chunk")),f=function(n){return{times:n,domain:u,url:l,tagName:c?"link":"script",isAsyncChunk:!0}},g=f(o);if(o>=maxRetries)throw e.message=null!==(t=e.message)&&void 0!==t&&t.includes("retries:")?e.message:"Loading chunk ".concat(n," from ").concat(a," failed after ").concat(maxRetries,' retries: "').concat(e.message,'"'),"function"==typeof config.onFail&&config.onFail(g),e;var s=config.test;if(s){if("string"==typeof s){var d=new RegExp(s);s=function(n){return d.test(n)}}if("function"!=typeof s||!s(l))throw e}if(config.domain&&config.domain.length>0&&-1===config.domain.indexOf(u))throw e;return"function"==typeof config.onRetry&&config.onRetry(g),ensureChunk(n,r).then((function(n){var e=r.count===o+2;if("function"==typeof config.onSuccess&&e){var i=f(o+1);config.onSuccess(i)}return n}))}))}function loadScript(n,r,e,i){var t=globalCurrRetrying[i];return originalLoadScript(t?t.nextRetryUrl:n,r,e,i)}function registerAsyncChunkRetry(){if("undefined"==typeof window||window.__RB_ASYNC_CHUNKS__||(window.__RB_ASYNC_CHUNKS__={}),"undefined"!=typeof __RUNTIME_GLOBALS_REQUIRE__)try{__RUNTIME_GLOBALS_ENSURE_CHUNK__=ensureChunk,__RUNTIME_GLOBALS_LOAD_SCRIPT__=loadScript}catch(n){console.error("[@rsbuild/plugin-assets-retry] Register async chunk retry runtime failed",n)}}registerAsyncChunkRetry();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@rsbuild/plugin-assets-retry",
3
- "version": "1.0.3",
3
+ "version": "1.0.4",
4
4
  "description": "Assets retry plugin for Rsbuild",
5
5
  "homepage": "https://rsbuild.dev",
6
6
  "repository": {
@@ -23,17 +23,17 @@
23
23
  "dist"
24
24
  ],
25
25
  "devDependencies": {
26
- "@babel/core": "^7.25.8",
27
- "@babel/preset-env": "^7.25.8",
28
- "@babel/preset-typescript": "^7.25.7",
26
+ "@babel/core": "^7.26.0",
27
+ "@babel/preset-env": "^7.26.0",
28
+ "@babel/preset-typescript": "^7.26.0",
29
29
  "@types/serialize-javascript": "^5.0.4",
30
30
  "serialize-javascript": "^6.0.2",
31
- "terser": "5.35.0",
31
+ "terser": "5.36.0",
32
32
  "typescript": "^5.6.3",
33
- "@rsbuild/core": "1.0.15"
33
+ "@rsbuild/core": "1.0.19"
34
34
  },
35
35
  "peerDependencies": {
36
- "@rsbuild/core": "1.x || ^1.0.1-rc.0"
36
+ "@rsbuild/core": "1.x"
37
37
  },
38
38
  "publishConfig": {
39
39
  "access": "public",