-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathrefreshUtils.js
More file actions
284 lines (250 loc) · 8.44 KB
/
refreshUtils.js
File metadata and controls
284 lines (250 loc) · 8.44 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
/* global __webpack_require__ */
import {
getFamilyByType,
isLikelyComponentType,
performReactRefresh,
register,
} from 'react-refresh/runtime';
/**
* Extracts exports from a Rspack module object.
* @param {string} moduleId An Rspack module ID.
* @returns {*} An exports object from the module.
*/
function getModuleExports(moduleId) {
if (typeof moduleId === 'undefined') {
// `moduleId` is unavailable, which indicates that this module is not in the cache,
// which means we won't be able to capture any exports,
// and thus they cannot be refreshed safely.
// These are likely runtime or dynamically generated modules.
return {};
}
const maybeModule = __webpack_require__.c[moduleId];
if (typeof maybeModule === 'undefined') {
// `moduleId` is available but the module in cache is unavailable,
// which indicates the module is somehow corrupted (e.g. broken Webpacak `module` globals).
// We will warn the user (as this is likely a mistake) and assume they cannot be refreshed.
console.warn(
`[React Refresh] Failed to get exports for module: ${moduleId}.`,
);
return {};
}
const exportsOrPromise = maybeModule.exports;
if (typeof Promise !== 'undefined' && exportsOrPromise instanceof Promise) {
return exportsOrPromise.then((moduleExports) => moduleExports);
}
return exportsOrPromise;
}
/**
* Calculates the signature of a React refresh boundary.
* If this signature changes, it's unsafe to accept the boundary.
*
* This implementation is based on the one in [Metro](https://github.com/facebook/metro/blob/907d6af22ac6ebe58572be418e9253a90665ecbd/packages/metro/src/lib/polyfills/require.js#L795-L816).
* @param {*} moduleExports An Rspack module exports object.
* @returns {string[]} A React refresh boundary signature array.
*/
function getReactRefreshBoundarySignature(moduleExports) {
const signature = [getFamilyByType(moduleExports)];
if (moduleExports == null || typeof moduleExports !== 'object') {
// Exit if we can't iterate over exports.
return signature;
}
for (const key in moduleExports) {
if (key === '__esModule') {
continue;
}
signature.push(key);
signature.push(getFamilyByType(moduleExports[key]));
}
return signature;
}
/**
* Creates a helper that performs a delayed React refresh.
* @returns {function(function(): void): void} A debounced React refresh function.
*/
function createDebounceUpdate() {
/**
* A cached setTimeout handler.
* @type {number | undefined}
*/
let refreshTimeout;
/**
* Performs react refresh on a delay.
* @param {function(): void} [callback]
* @returns {void}
*/
const enqueueUpdate = (callback) => {
if (typeof refreshTimeout !== 'undefined') {
return;
}
refreshTimeout = setTimeout(() => {
refreshTimeout = undefined;
performReactRefresh();
if (callback) {
callback();
}
}, 30);
};
return enqueueUpdate;
}
/**
* Checks if all exports are likely a React component.
*
* This implementation is based on the one in [Metro](https://github.com/facebook/metro/blob/febdba2383113c88296c61e28e4ef6a7f4939fda/packages/metro/src/lib/polyfills/require.js#L748-L774).
* @param {*} moduleExports An Rspack module exports object.
* @returns {boolean} Whether the exports are React component like.
*/
function isReactRefreshBoundary(moduleExports) {
if (isLikelyComponentType(moduleExports)) {
return true;
}
if (
moduleExports === undefined ||
moduleExports === null ||
typeof moduleExports !== 'object'
) {
// Exit if we can't iterate over exports.
return false;
}
let hasExports = false;
let areAllExportsComponents = true;
for (const key in moduleExports) {
hasExports = true;
// This is the ES Module indicator flag
if (key === '__esModule') {
continue;
}
// We can (and have to) safely execute getters here,
// as Rspack/webpack manually assigns ESM exports to getters,
// without any side-effects attached.
// Ref: https://github.com/webpack/webpack/blob/b93048643fe74de2a6931755911da1212df55897/lib/MainTemplate.js#L281
const exportValue = moduleExports[key];
if (!isLikelyComponentType(exportValue)) {
areAllExportsComponents = false;
}
}
return hasExports && areAllExportsComponents;
}
/**
* Checks if exports are likely a React component and registers them.
*
* This implementation is based on the one in [Metro](https://github.com/facebook/metro/blob/febdba2383113c88296c61e28e4ef6a7f4939fda/packages/metro/src/lib/polyfills/require.js#L818-L835).
* @param {*} moduleExports An Rspack module exports object.
* @param {string} moduleId An Rspack module ID.
* @returns {void}
*/
function registerExportsForReactRefresh(moduleExports, moduleId) {
if (isLikelyComponentType(moduleExports)) {
// Register module.exports if it is likely a component
register(moduleExports, `${moduleId} %exports%`);
}
if (
moduleExports === undefined ||
moduleExports === null ||
typeof moduleExports !== 'object'
) {
// Exit if we can't iterate over the exports.
return;
}
for (const key in moduleExports) {
// Skip registering the ES Module indicator
if (key === '__esModule') {
continue;
}
const exportValue = moduleExports[key];
if (isLikelyComponentType(exportValue)) {
const typeID = `${moduleId} %exports% ${key}`;
register(exportValue, typeID);
}
}
}
/**
* Compares previous and next module objects to check for mutated boundaries.
*
* This implementation is based on the one in [Metro](https://github.com/facebook/metro/blob/907d6af22ac6ebe58572be418e9253a90665ecbd/packages/metro/src/lib/polyfills/require.js#L776-L792).
* @param {*} prevExports The current Rspack module exports object.
* @param {*} nextExports The next Rspack module exports object.
* @returns {boolean} Whether the React refresh boundary should be invalidated.
*/
function shouldInvalidateReactRefreshBoundary(prevExports, nextExports) {
const prevSignature = getReactRefreshBoundarySignature(prevExports);
const nextSignature = getReactRefreshBoundarySignature(nextExports);
return (
prevSignature.length !== nextSignature.length ||
nextSignature.some(
(signatureItem, index) => prevSignature[index] !== signatureItem,
)
);
}
const enqueueUpdate = createDebounceUpdate();
function executeRuntime(moduleExports, moduleId, hot, isTest) {
registerExportsForReactRefresh(moduleExports, moduleId);
if (hot) {
const isHotUpdate = Boolean(hot.data);
let prevExports;
if (isHotUpdate) {
prevExports = hot.data.prevExports;
}
if (isReactRefreshBoundary(moduleExports)) {
/**
* A callback to performs a full refresh if React has unrecoverable errors,
* and also caches the to-be-disposed module.
* @param {*} data A hot module data object from Rspack HMR.
* @returns {void}
*/
const hotDisposeCallback = (data) => {
// We have to mutate the data object to get data registered and cached
data.prevExports = moduleExports;
};
/**
* An error handler to allow self-recovering behaviors.
* @param {Error} error An error occurred during evaluation of a module.
* @returns {void}
*/
const hotErrorHandler = (error) => {
console.error(error);
if (
__reload_on_runtime_errors__ &&
isUnrecoverableRuntimeError(error)
) {
location.reload();
return;
}
if (
typeof isTest !== 'undefined' &&
isTest &&
window.onHotAcceptError
) {
window.onHotAcceptError(error.message);
}
__webpack_require__.c[moduleId].hot.accept(hotErrorHandler);
};
hot.dispose(hotDisposeCallback);
hot.accept(hotErrorHandler);
if (isHotUpdate) {
if (
isReactRefreshBoundary(prevExports) &&
shouldInvalidateReactRefreshBoundary(prevExports, moduleExports)
) {
hot.invalidate();
} else {
enqueueUpdate();
}
}
} else {
if (isHotUpdate && typeof prevExports !== 'undefined') {
hot.invalidate();
}
}
}
}
function isUnrecoverableRuntimeError(error) {
return error.message.startsWith('RuntimeError: factory is undefined');
}
export {
enqueueUpdate,
executeRuntime,
getModuleExports,
isReactRefreshBoundary,
registerExportsForReactRefresh,
shouldInvalidateReactRefreshBoundary,
};