@rsbuild/plugin-assets-retry 1.0.2 → 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.
@@ -1,5 +1,5 @@
1
1
  import { type Rspack } from '@rsbuild/core';
2
- import type { PluginAssetsRetryOptions, RuntimeRetryOptions } from './types';
2
+ import type { PluginAssetsRetryOptions, RuntimeRetryOptions } from './types.js';
3
3
  declare class AsyncChunkRetryPlugin implements Rspack.RspackPluginInstance {
4
4
  readonly name = "ASYNC_CHUNK_RETRY_PLUGIN";
5
5
  readonly options: PluginAssetsRetryOptions & {
package/dist/index.cjs CHANGED
@@ -1,234 +1,399 @@
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 __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
9
- var __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
- var __copyProps = (to, from, except, desc) => {
17
- if (from && typeof from === "object" || typeof from === "function") {
18
- for (let key of __getOwnPropNames(from))
19
- if (!__hasOwnProp.call(to, key) && key !== except)
20
- __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
21
- }
22
- return to;
23
- };
24
- var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
25
- // If the importer is in node compatibility mode or this is not an ESM
26
- // file that has been converted to a CommonJS file using a Babel-
27
- // compatible transform (i.e. "__esModule" has not been set), then set
28
- // "default" to the CommonJS "module.exports" for node compatibility.
29
- isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
30
- mod
31
- ));
32
- var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
33
- var __publicField = (obj, key, value) => {
34
- __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
35
- return value;
36
- };
37
-
38
- // src/AsyncChunkRetryPlugin.ts
39
- var AsyncChunkRetryPlugin_exports = {};
40
- __export(AsyncChunkRetryPlugin_exports, {
41
- AsyncChunkRetryPlugin: () => AsyncChunkRetryPlugin
42
- });
43
- function appendWebpackScript(module2, appendSource) {
44
- try {
45
- const originSource = module2.getGeneratedCode();
46
- module2.getGeneratedCode = () => `${originSource}
47
- ${appendSource}`;
48
- } catch (err) {
49
- console.error("Failed to modify Webpack RuntimeModule");
50
- throw err;
51
- }
52
- }
53
- function appendRspackScript(module2, appendSource) {
54
- try {
55
- const source = module2.source.source.toString();
56
- module2.source.source = Buffer.from(`${source}
57
- ${appendSource}`, "utf-8");
58
- } catch (err) {
59
- console.error("Failed to modify Rspack RuntimeModule");
60
- throw err;
61
- }
62
- }
63
- function pick(obj, keys) {
64
- return keys.reduce(
65
- (ret, key) => {
66
- if (obj[key] !== void 0) {
67
- ret[key] = obj[key];
68
- }
69
- return ret;
1
+ var __webpack_modules__ = {
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;
70
4
  },
71
- {}
72
- );
73
- }
74
- var import_node_fs, import_node_path, import_core, import_serialize_javascript, AsyncChunkRetryPlugin;
75
- var init_AsyncChunkRetryPlugin = __esm({
76
- "src/AsyncChunkRetryPlugin.ts"() {
77
- "use strict";
78
- import_node_fs = __toESM(require("fs"));
79
- import_node_path = __toESM(require("path"));
80
- import_core = require("@rsbuild/core");
81
- import_serialize_javascript = __toESM(require("serialize-javascript"));
82
- AsyncChunkRetryPlugin = class {
83
- constructor(options) {
84
- __publicField(this, "name", "ASYNC_CHUNK_RETRY_PLUGIN");
85
- __publicField(this, "options");
86
- __publicField(this, "runtimeOptions");
87
- this.options = options;
88
- this.runtimeOptions = pick(options, [
89
- "domain",
90
- "max",
91
- "onRetry",
92
- "onSuccess",
93
- "onFail",
94
- "addQuery",
95
- "test"
96
- ]);
97
- }
98
- getRawRuntimeRetryCode() {
99
- const { RuntimeGlobals } = import_core.rspack;
100
- const filename = "asyncChunkRetry";
101
- const runtimeFilePath = import_node_path.default.join(
102
- __dirname,
103
- "runtime",
104
- this.options.minify ? `${filename}.min.js` : `${filename}.js`
105
- );
106
- const rawText = import_node_fs.default.readFileSync(runtimeFilePath, "utf-8");
107
- return rawText.replaceAll("__RUNTIME_GLOBALS_REQUIRE__", RuntimeGlobals.require).replaceAll(
108
- "__RUNTIME_GLOBALS_ENSURE_CHUNK__",
109
- RuntimeGlobals.ensureChunk
110
- ).replaceAll(
111
- "__RUNTIME_GLOBALS_GET_CHUNK_SCRIPT_FILENAME__",
112
- RuntimeGlobals.getChunkScriptFilename
113
- ).replaceAll(
114
- "__RUNTIME_GLOBALS_GET_CSS_FILENAME__",
115
- RuntimeGlobals.getChunkCssFilename
116
- ).replaceAll(
117
- "__RUNTIME_GLOBALS_GET_MINI_CSS_EXTRACT_FILENAME__",
118
- "__webpack_require__.miniCssF"
119
- ).replaceAll("__RUNTIME_GLOBALS_PUBLIC_PATH__", RuntimeGlobals.publicPath).replaceAll("__RUNTIME_GLOBALS_LOAD_SCRIPT__", RuntimeGlobals.loadScript).replaceAll("__RETRY_OPTIONS__", (0, import_serialize_javascript.default)(this.runtimeOptions));
120
- }
121
- apply(compiler) {
122
- compiler.hooks.thisCompilation.tap(this.name, (compilation) => {
123
- compilation.hooks.runtimeModule.tap(this.name, (module2) => {
124
- const { isRspack } = this.options;
125
- const constructorName = isRspack ? module2.constructorName : module2.constructor?.name;
126
- const isPublicPathModule = module2.name === "publicPath" || constructorName === "PublicPathRuntimeModule" || constructorName === "AutoPublicPathRuntimeModule";
127
- if (!isPublicPathModule) {
128
- return;
5
+ "../../node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js": function(module1, __unused_webpack_exports, __webpack_require__) {
6
+ "use strict";
7
+ /*
8
+ Copyright (c) 2014, Yahoo! Inc. All rights reserved.
9
+ Copyrights licensed under the New BSD License.
10
+ See the accompanying LICENSE file for terms.
11
+ */ var randomBytes = __webpack_require__("../../node_modules/.pnpm/randombytes@2.1.0/node_modules/randombytes/index.js");
12
+ // Generate an internal UID to make the regexp pattern harder to guess.
13
+ var UID_LENGTH = 16;
14
+ var UID = generateUID();
15
+ var PLACE_HOLDER_REGEXP = new RegExp('(\\\\)?"@__(F|R|D|M|S|A|U|I|B|L)-' + UID + '-(\\d+)__@"', 'g');
16
+ var IS_NATIVE_CODE_REGEXP = /\{\s*\[native code\]\s*\}/g;
17
+ var IS_PURE_FUNCTION = /function.*?\(/;
18
+ var IS_ARROW_FUNCTION = /.*?=>.*?/;
19
+ var UNSAFE_CHARS_REGEXP = /[<>\/\u2028\u2029]/g;
20
+ var RESERVED_SYMBOLS = [
21
+ '*',
22
+ 'async'
23
+ ];
24
+ // Mapping of unsafe HTML and invalid JavaScript line terminator chars to their
25
+ // Unicode char counterparts which are safe to use in JavaScript strings.
26
+ var ESCAPED_CHARS = {
27
+ '<': '\\u003C',
28
+ '>': '\\u003E',
29
+ '/': '\\u002F',
30
+ '\u2028': '\\u2028',
31
+ '\u2029': '\\u2029'
32
+ };
33
+ function escapeUnsafeChars(unsafeChar) {
34
+ return ESCAPED_CHARS[unsafeChar];
35
+ }
36
+ function generateUID() {
37
+ var bytes = randomBytes(UID_LENGTH);
38
+ var result = '';
39
+ for(var i = 0; i < UID_LENGTH; ++i)result += bytes[i].toString(16);
40
+ return result;
41
+ }
42
+ function deleteFunctions(obj) {
43
+ var functionKeys = [];
44
+ for(var key in obj)if ("function" == typeof obj[key]) functionKeys.push(key);
45
+ for(var i = 0; i < functionKeys.length; i++)delete obj[functionKeys[i]];
46
+ }
47
+ module1.exports = function serialize(obj, options) {
48
+ options || (options = {});
49
+ // Backwards-compatibility for `space` as the second argument.
50
+ if ('number' == typeof options || 'string' == typeof options) options = {
51
+ space: options
52
+ };
53
+ var functions = [];
54
+ var regexps = [];
55
+ var dates = [];
56
+ var maps = [];
57
+ var sets = [];
58
+ var arrays = [];
59
+ var undefs = [];
60
+ var infinities = [];
61
+ var bigInts = [];
62
+ var urls = [];
63
+ // Returns placeholders for functions and regexps (identified by index)
64
+ // which are later replaced by their string representation.
65
+ function replacer(key, value) {
66
+ // For nested function
67
+ if (options.ignoreFunction) deleteFunctions(value);
68
+ if (!value && void 0 !== value && value !== BigInt(0)) return value;
69
+ // If the value is an object w/ a toJSON method, toJSON is called before
70
+ // the replacer runs, so we use this[key] to get the non-toJSONed value.
71
+ var origValue = this[key];
72
+ var type = typeof origValue;
73
+ if ('object' === type) {
74
+ if (origValue instanceof RegExp) return '@__R-' + UID + '-' + (regexps.push(origValue) - 1) + '__@';
75
+ if (origValue instanceof Date) return '@__D-' + UID + '-' + (dates.push(origValue) - 1) + '__@';
76
+ if (origValue instanceof Map) return '@__M-' + UID + '-' + (maps.push(origValue) - 1) + '__@';
77
+ if (origValue instanceof Set) return '@__S-' + UID + '-' + (sets.push(origValue) - 1) + '__@';
78
+ if (origValue instanceof Array) {
79
+ var isSparse = origValue.filter(function() {
80
+ return true;
81
+ }).length !== origValue.length;
82
+ if (isSparse) return '@__A-' + UID + '-' + (arrays.push(origValue) - 1) + '__@';
83
+ }
84
+ if (origValue instanceof URL) return '@__L-' + UID + '-' + (urls.push(origValue) - 1) + '__@';
85
+ }
86
+ if ('function' === type) return '@__F-' + UID + '-' + (functions.push(origValue) - 1) + '__@';
87
+ if ('undefined' === type) return '@__U-' + UID + '-' + (undefs.push(origValue) - 1) + '__@';
88
+ if ('number' === type && !isNaN(origValue) && !isFinite(origValue)) return '@__I-' + UID + '-' + (infinities.push(origValue) - 1) + '__@';
89
+ if ('bigint' === type) return '@__B-' + UID + '-' + (bigInts.push(origValue) - 1) + '__@';
90
+ return value;
129
91
  }
130
- const runtimeCode = this.getRawRuntimeRetryCode();
131
- if (isRspack) {
132
- appendRspackScript(module2, runtimeCode);
133
- } else {
134
- appendWebpackScript(module2, runtimeCode);
92
+ function serializeFunc(fn) {
93
+ var serializedFn = fn.toString();
94
+ if (IS_NATIVE_CODE_REGEXP.test(serializedFn)) throw new TypeError('Serializing native function: ' + fn.name);
95
+ // pure functions, example: {key: function() {}}
96
+ if (IS_PURE_FUNCTION.test(serializedFn)) return serializedFn;
97
+ // arrow functions, example: arg1 => arg1+5
98
+ if (IS_ARROW_FUNCTION.test(serializedFn)) return serializedFn;
99
+ var argsStartsAt = serializedFn.indexOf('(');
100
+ var def = serializedFn.substr(0, argsStartsAt).trim().split(' ').filter(function(val) {
101
+ return val.length > 0;
102
+ });
103
+ var nonReservedSymbols = def.filter(function(val) {
104
+ return -1 === RESERVED_SYMBOLS.indexOf(val);
105
+ });
106
+ // enhanced literal objects, example: {key() {}}
107
+ if (nonReservedSymbols.length > 0) return (def.indexOf('async') > -1 ? 'async ' : '') + 'function' + (def.join('').indexOf('*') > -1 ? '*' : '') + serializedFn.substr(argsStartsAt);
108
+ // arrow functions
109
+ return serializedFn;
135
110
  }
136
- });
137
- });
138
- }
111
+ // Check if the parameter is function
112
+ if (options.ignoreFunction && "function" == typeof obj) obj = void 0;
113
+ // Protects against `JSON.stringify()` returning `undefined`, by serializing
114
+ // to the literal string: "undefined".
115
+ if (void 0 === obj) return String(obj);
116
+ var str;
117
+ // Creates a JSON string representation of the value.
118
+ // NOTE: Node 0.12 goes into slow mode with extra JSON.stringify() args.
119
+ str = options.isJSON && !options.space ? JSON.stringify(obj) : JSON.stringify(obj, options.isJSON ? null : replacer, options.space);
120
+ // Protects against `JSON.stringify()` returning `undefined`, by serializing
121
+ // to the literal string: "undefined".
122
+ if ('string' != typeof str) return String(str);
123
+ // Replace unsafe HTML and invalid JavaScript line terminator chars with
124
+ // their safe Unicode char counterpart. This _must_ happen before the
125
+ // regexps and functions are serialized and added back to the string.
126
+ if (true !== options.unsafe) str = str.replace(UNSAFE_CHARS_REGEXP, escapeUnsafeChars);
127
+ if (0 === functions.length && 0 === regexps.length && 0 === dates.length && 0 === maps.length && 0 === sets.length && 0 === arrays.length && 0 === undefs.length && 0 === infinities.length && 0 === bigInts.length && 0 === urls.length) return str;
128
+ // Replaces all occurrences of function, regexp, date, map and set placeholders in the
129
+ // JSON string with their string representations. If the original value can
130
+ // not be found, then `undefined` is used.
131
+ return str.replace(PLACE_HOLDER_REGEXP, function(match, backSlash, type, valueIndex) {
132
+ // The placeholder may not be preceded by a backslash. This is to prevent
133
+ // replacing things like `"a\"@__R-<UID>-0__@"` and thus outputting
134
+ // invalid JS.
135
+ if (backSlash) return match;
136
+ if ('D' === type) return "new Date(\"" + dates[valueIndex].toISOString() + "\")";
137
+ if ('R' === type) return "new RegExp(" + serialize(regexps[valueIndex].source) + ", \"" + regexps[valueIndex].flags + "\")";
138
+ if ('M' === type) return "new Map(" + serialize(Array.from(maps[valueIndex].entries()), options) + ")";
139
+ if ('S' === type) return "new Set(" + serialize(Array.from(sets[valueIndex].values()), options) + ")";
140
+ if ('A' === type) return "Array.prototype.slice.call(" + serialize(Object.assign({
141
+ length: arrays[valueIndex].length
142
+ }, arrays[valueIndex]), options) + ")";
143
+ if ('U' === type) return 'undefined';
144
+ if ('I' === type) return infinities[valueIndex];
145
+ if ('B' === type) return "BigInt(\"" + bigInts[valueIndex] + "\")";
146
+ if ('L' === type) return "new URL(" + serialize(urls[valueIndex].toString(), options) + ")";
147
+ var fn = functions[valueIndex];
148
+ return serializeFunc(fn);
149
+ });
150
+ };
151
+ },
152
+ crypto: function(module1) {
153
+ "use strict";
154
+ module1.exports = require("crypto");
155
+ }
156
+ };
157
+ /************************************************************************/ // The module cache
158
+ var __webpack_module_cache__ = {};
159
+ // The require function
160
+ function __webpack_require__(moduleId) {
161
+ // Check if module is in cache
162
+ var cachedModule = __webpack_module_cache__[moduleId];
163
+ if (void 0 !== cachedModule) return cachedModule.exports;
164
+ // Create a new module (and put it into the cache)
165
+ var module1 = __webpack_module_cache__[moduleId] = {
166
+ exports: {}
139
167
  };
140
- }
141
- });
142
-
143
- // src/index.ts
144
- var src_exports = {};
145
- __export(src_exports, {
146
- PLUGIN_ASSETS_RETRY_NAME: () => PLUGIN_ASSETS_RETRY_NAME,
147
- pluginAssetsRetry: () => pluginAssetsRetry
148
- });
149
- module.exports = __toCommonJS(src_exports);
150
- var import_node_fs2 = __toESM(require("fs"));
151
- var import_node_path2 = __toESM(require("path"));
152
- var import_core2 = require("@rsbuild/core");
153
- var PLUGIN_ASSETS_RETRY_NAME = "rsbuild:assets-retry";
154
- async function getRetryCode(options) {
155
- const { default: serialize2 } = await import("serialize-javascript");
156
- const filename = "initialChunkRetry";
157
- const { minify, inlineScript: _, ...restOptions } = options;
158
- const runtimeFilePath = import_node_path2.default.join(
159
- __dirname,
160
- "runtime",
161
- minify ? `${filename}.min.js` : `${filename}.js`
162
- );
163
- const runtimeCode = await import_node_fs2.default.promises.readFile(runtimeFilePath, "utf-8");
164
- return `(function(){${runtimeCode};init(${serialize2(restOptions)});})()`;
168
+ // Execute the module function
169
+ __webpack_modules__[moduleId](module1, module1.exports, __webpack_require__);
170
+ // Return the exports of the module
171
+ return module1.exports;
165
172
  }
166
- var pluginAssetsRetry = (userOptions = {}) => ({
167
- name: PLUGIN_ASSETS_RETRY_NAME,
168
- setup(api) {
169
- const { inlineScript = true } = userOptions;
170
- const getScriptPath = (environment) => {
171
- const distDir = environment.config.output.distPath.js;
172
- return import_node_path2.default.posix.join(distDir, `assets-retry.${"1.0.14"}.js`);
173
+ /************************************************************************/ // webpack/runtime/compat_get_default_export
174
+ (()=>{
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
+ } : function() {
180
+ return module1;
181
+ };
182
+ __webpack_require__.d(getter, {
183
+ a: getter
184
+ });
185
+ return getter;
173
186
  };
174
- const formatOptions = (config) => {
175
- const options = { ...userOptions };
176
- if (options.crossOrigin === void 0) {
177
- options.crossOrigin = config.html.crossorigin;
178
- }
179
- if (options.minify === void 0) {
180
- const minify = typeof config.output.minify === "boolean" ? config.output.minify : config.output.minify?.js;
181
- options.minify = minify && config.mode === "production";
182
- }
183
- return options;
187
+ })();
188
+ // webpack/runtime/define_property_getters
189
+ (()=>{
190
+ __webpack_require__.d = function(exports1, definition) {
191
+ for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
192
+ enumerable: true,
193
+ get: definition[key]
194
+ });
184
195
  };
185
- if (inlineScript) {
186
- api.modifyHTMLTags(async ({ headTags, bodyTags }, { environment }) => {
187
- const code = await getRetryCode(formatOptions(environment.config));
188
- headTags.unshift({
189
- tag: "script",
190
- attrs: {},
191
- children: code
196
+ })();
197
+ // webpack/runtime/has_own_property
198
+ (()=>{
199
+ __webpack_require__.o = function(obj, prop) {
200
+ return Object.prototype.hasOwnProperty.call(obj, prop);
201
+ };
202
+ })();
203
+ // webpack/runtime/make_namespace_object
204
+ (()=>{
205
+ // define __esModule on exports
206
+ __webpack_require__.r = function(exports1) {
207
+ if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
208
+ value: 'Module'
192
209
  });
193
- return { headTags, bodyTags };
194
- });
195
- } else {
196
- api.modifyHTMLTags(
197
- async ({ headTags, bodyTags }, { assetPrefix, environment }) => {
198
- const scriptPath = getScriptPath(environment);
199
- const url = (0, import_core2.ensureAssetPrefix)(scriptPath, assetPrefix);
200
- headTags.unshift({
201
- tag: "script",
202
- attrs: {
203
- src: url
204
- }
205
- });
206
- return { headTags, bodyTags };
210
+ Object.defineProperty(exports1, '__esModule', {
211
+ value: true
212
+ });
213
+ };
214
+ })();
215
+ /************************************************************************/ var __webpack_exports__ = {};
216
+ // This entry need to be wrapped in an IIFE because it need to be in strict mode.
217
+ (()=>{
218
+ "use strict";
219
+ // ESM COMPAT FLAG
220
+ __webpack_require__.r(__webpack_exports__);
221
+ // EXPORTS
222
+ __webpack_require__.d(__webpack_exports__, {
223
+ PLUGIN_ASSETS_RETRY_NAME: ()=>/* binding */ PLUGIN_ASSETS_RETRY_NAME,
224
+ pluginAssetsRetry: ()=>/* binding */ pluginAssetsRetry
225
+ });
226
+ const external_node_fs_namespaceObject = require("node:fs");
227
+ var external_node_fs_default = /*#__PURE__*/ __webpack_require__.n(external_node_fs_namespaceObject);
228
+ const external_node_path_namespaceObject = require("node:path");
229
+ var external_node_path_default = /*#__PURE__*/ __webpack_require__.n(external_node_path_namespaceObject);
230
+ const external_node_url_namespaceObject = require("node:url");
231
+ const core_namespaceObject = require("@rsbuild/core");
232
+ // EXTERNAL MODULE: ../../node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js
233
+ var serialize_javascript = __webpack_require__("../../node_modules/.pnpm/serialize-javascript@6.0.2/node_modules/serialize-javascript/index.js");
234
+ var serialize_javascript_default = /*#__PURE__*/ __webpack_require__.n(serialize_javascript);
235
+ function _define_property(obj, key, value) {
236
+ if (key in obj) Object.defineProperty(obj, key, {
237
+ value: value,
238
+ enumerable: true,
239
+ configurable: true,
240
+ writable: true
241
+ });
242
+ else obj[key] = value;
243
+ return obj;
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
+ }()));
248
+ // https://github.com/web-infra-dev/rspack/pull/5370
249
+ function appendWebpackScript(module1, appendSource) {
250
+ try {
251
+ const originSource = module1.getGeneratedCode();
252
+ module1.getGeneratedCode = ()=>`${originSource}\n${appendSource}`;
253
+ } catch (err) {
254
+ console.error('Failed to modify Webpack RuntimeModule');
255
+ throw err;
207
256
  }
208
- );
209
- api.processAssets(
210
- { stage: "additional" },
211
- async ({ sources, compilation, environment }) => {
212
- const scriptPath = getScriptPath(environment);
213
- const code = await getRetryCode(formatOptions(environment.config));
214
- compilation.emitAsset(scriptPath, new sources.RawSource(code));
257
+ }
258
+ function appendRspackScript(module1, appendSource) {
259
+ try {
260
+ const source = module1.source.source.toString();
261
+ module1.source.source = Buffer.from(`${source}\n${appendSource}`, 'utf-8');
262
+ } catch (err) {
263
+ console.error('Failed to modify Rspack RuntimeModule');
264
+ throw err;
215
265
  }
216
- );
217
266
  }
218
- api.modifyBundlerChain(async (chain, { environment }) => {
219
- const { config, htmlPaths } = environment;
220
- if (!userOptions || Object.keys(htmlPaths).length === 0) {
221
- return;
222
- }
223
- const { AsyncChunkRetryPlugin: AsyncChunkRetryPlugin2 } = await Promise.resolve().then(() => (init_AsyncChunkRetryPlugin(), AsyncChunkRetryPlugin_exports));
224
- const options = formatOptions(config);
225
- const isRspack = api.context.bundlerType === "rspack";
226
- chain.plugin("async-chunk-retry").use(AsyncChunkRetryPlugin2, [{ ...options, isRspack }]);
227
- });
228
- }
229
- });
230
- // Annotate the CommonJS export names for ESM import in node:
231
- 0 && (module.exports = {
232
- PLUGIN_ASSETS_RETRY_NAME,
233
- pluginAssetsRetry
267
+ function pick(obj, keys) {
268
+ return keys.reduce((ret, key)=>{
269
+ if (void 0 !== obj[key]) ret[key] = obj[key];
270
+ return ret;
271
+ }, {});
272
+ }
273
+ class AsyncChunkRetryPlugin {
274
+ getRawRuntimeRetryCode() {
275
+ const { RuntimeGlobals } = core_namespaceObject.rspack;
276
+ const filename = 'asyncChunkRetry';
277
+ const runtimeFilePath = external_node_path_default().join(AsyncChunkRetryPlugin_dirname, 'runtime', this.options.minify ? `${filename}.min.js` : `${filename}.js`);
278
+ const rawText = external_node_fs_default().readFileSync(runtimeFilePath, 'utf-8');
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));
280
+ }
281
+ apply(compiler) {
282
+ compiler.hooks.thisCompilation.tap(this.name, (compilation)=>{
283
+ compilation.hooks.runtimeModule.tap(this.name, (module1)=>{
284
+ var _module_constructor;
285
+ const { isRspack } = this.options;
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;
288
+ if (!isPublicPathModule) return;
289
+ const runtimeCode = this.getRawRuntimeRetryCode();
290
+ // Rspack currently does not have module.addRuntimeModule on the js side,
291
+ // so we insert our runtime code after PublicPathRuntimeModule or AutoPublicPathRuntimeModule.
292
+ if (isRspack) appendRspackScript(module1, runtimeCode);
293
+ else appendWebpackScript(module1, runtimeCode);
294
+ });
295
+ });
296
+ }
297
+ constructor(options){
298
+ _define_property(this, "name", 'ASYNC_CHUNK_RETRY_PLUGIN');
299
+ _define_property(this, "options", void 0);
300
+ _define_property(this, "runtimeOptions", void 0);
301
+ this.options = options;
302
+ this.runtimeOptions = pick(options, [
303
+ 'domain',
304
+ 'max',
305
+ 'onRetry',
306
+ 'onSuccess',
307
+ 'onFail',
308
+ 'addQuery',
309
+ 'test'
310
+ ]);
311
+ }
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
+ }()));
316
+ const PLUGIN_ASSETS_RETRY_NAME = 'rsbuild:assets-retry';
317
+ async function getRetryCode(options) {
318
+ const filename = 'initialChunkRetry';
319
+ const { minify, inlineScript: _, ...restOptions } = options;
320
+ const runtimeFilePath = external_node_path_default().join(src_dirname, 'runtime', minify ? `${filename}.min.js` : `${filename}.js`);
321
+ const runtimeCode = await external_node_fs_default().promises.readFile(runtimeFilePath, 'utf-8');
322
+ return `(function(){${runtimeCode};init(${serialize_javascript_default()(restOptions)});})()`;
323
+ }
324
+ const pluginAssetsRetry = (userOptions = {})=>({
325
+ name: PLUGIN_ASSETS_RETRY_NAME,
326
+ setup (api) {
327
+ const { inlineScript = true } = userOptions;
328
+ const getScriptPath = (environment)=>{
329
+ const distDir = environment.config.output.distPath.js;
330
+ return external_node_path_default().posix.join(distDir, "assets-retry.1-0-4.js");
331
+ };
332
+ const formatOptions = (config)=>{
333
+ const options = {
334
+ ...userOptions
335
+ };
336
+ // options.crossOrigin should be same as html.crossorigin by default
337
+ if (void 0 === options.crossOrigin) options.crossOrigin = config.html.crossorigin;
338
+ if (void 0 === options.minify) {
339
+ var _config_output_minify;
340
+ const minify = 'boolean' == typeof config.output.minify ? config.output.minify : null === (_config_output_minify = config.output.minify) || void 0 === _config_output_minify ? void 0 : _config_output_minify.js;
341
+ options.minify = minify && 'production' === config.mode;
342
+ }
343
+ return options;
344
+ };
345
+ if (inlineScript) api.modifyHTMLTags(async ({ headTags, bodyTags }, { environment })=>{
346
+ const code = await getRetryCode(formatOptions(environment.config));
347
+ headTags.unshift({
348
+ tag: 'script',
349
+ attrs: {},
350
+ children: code
351
+ });
352
+ return {
353
+ headTags,
354
+ bodyTags
355
+ };
356
+ });
357
+ else {
358
+ api.modifyHTMLTags(async ({ headTags, bodyTags }, { assetPrefix, environment })=>{
359
+ const scriptPath = getScriptPath(environment);
360
+ const url = (0, core_namespaceObject.ensureAssetPrefix)(scriptPath, assetPrefix);
361
+ headTags.unshift({
362
+ tag: 'script',
363
+ attrs: {
364
+ src: url
365
+ }
366
+ });
367
+ return {
368
+ headTags,
369
+ bodyTags
370
+ };
371
+ });
372
+ api.processAssets({
373
+ stage: 'additional'
374
+ }, async ({ sources, compilation, environment })=>{
375
+ const scriptPath = getScriptPath(environment);
376
+ const code = await getRetryCode(formatOptions(environment.config));
377
+ compilation.emitAsset(scriptPath, new sources.RawSource(code));
378
+ });
379
+ }
380
+ api.modifyBundlerChain(async (chain, { environment })=>{
381
+ const { config, htmlPaths } = environment;
382
+ if (!userOptions || 0 === Object.keys(htmlPaths).length) return;
383
+ const options = formatOptions(config);
384
+ const isRspack = 'rspack' === api.context.bundlerType;
385
+ chain.plugin('async-chunk-retry').use(AsyncChunkRetryPlugin, [
386
+ {
387
+ ...options,
388
+ isRspack
389
+ }
390
+ ]);
391
+ });
392
+ }
393
+ });
394
+ })();
395
+ var __webpack_export_target__ = exports;
396
+ for(var i in __webpack_exports__)__webpack_export_target__[i] = __webpack_exports__[i];
397
+ if (__webpack_exports__.__esModule) Object.defineProperty(__webpack_export_target__, '__esModule', {
398
+ value: true
234
399
  });
@@ -1,5 +1,5 @@
1
1
  import type { RsbuildPlugin } from '@rsbuild/core';
2
- import type { PluginAssetsRetryOptions } from './types';
2
+ import type { PluginAssetsRetryOptions } from './types.js';
3
3
  export type { PluginAssetsRetryOptions };
4
4
  export declare const PLUGIN_ASSETS_RETRY_NAME = "rsbuild:assets-retry";
5
5
  export declare const pluginAssetsRetry: (userOptions?: PluginAssetsRetryOptions) => RsbuildPlugin;