react-refresh-runtime.development.js 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658
  1. /**
  2. * @license React
  3. * react-refresh-runtime.development.js
  4. *
  5. * Copyright (c) Facebook, Inc. and its affiliates.
  6. *
  7. * This source code is licensed under the MIT license found in the
  8. * LICENSE file in the root directory of this source tree.
  9. */
  10. 'use strict';
  11. if (process.env.NODE_ENV !== "production") {
  12. (function() {
  13. 'use strict';
  14. // ATTENTION
  15. var REACT_FORWARD_REF_TYPE = Symbol.for('react.forward_ref');
  16. var REACT_MEMO_TYPE = Symbol.for('react.memo');
  17. var PossiblyWeakMap = typeof WeakMap === 'function' ? WeakMap : Map; // We never remove these associations.
  18. // It's OK to reference families, but use WeakMap/Set for types.
  19. var allFamiliesByID = new Map();
  20. var allFamiliesByType = new PossiblyWeakMap();
  21. var allSignaturesByType = new PossiblyWeakMap(); // This WeakMap is read by React, so we only put families
  22. // that have actually been edited here. This keeps checks fast.
  23. // $FlowIssue
  24. var updatedFamiliesByType = new PossiblyWeakMap(); // This is cleared on every performReactRefresh() call.
  25. // It is an array of [Family, NextType] tuples.
  26. var pendingUpdates = []; // This is injected by the renderer via DevTools global hook.
  27. var helpersByRendererID = new Map();
  28. var helpersByRoot = new Map(); // We keep track of mounted roots so we can schedule updates.
  29. var mountedRoots = new Set(); // If a root captures an error, we remember it so we can retry on edit.
  30. var failedRoots = new Set(); // In environments that support WeakMap, we also remember the last element for every root.
  31. // It needs to be weak because we do this even for roots that failed to mount.
  32. // If there is no WeakMap, we won't attempt to do retrying.
  33. // $FlowIssue
  34. var rootElements = // $FlowIssue
  35. typeof WeakMap === 'function' ? new WeakMap() : null;
  36. var isPerformingRefresh = false;
  37. function computeFullKey(signature) {
  38. if (signature.fullKey !== null) {
  39. return signature.fullKey;
  40. }
  41. var fullKey = signature.ownKey;
  42. var hooks;
  43. try {
  44. hooks = signature.getCustomHooks();
  45. } catch (err) {
  46. // This can happen in an edge case, e.g. if expression like Foo.useSomething
  47. // depends on Foo which is lazily initialized during rendering.
  48. // In that case just assume we'll have to remount.
  49. signature.forceReset = true;
  50. signature.fullKey = fullKey;
  51. return fullKey;
  52. }
  53. for (var i = 0; i < hooks.length; i++) {
  54. var hook = hooks[i];
  55. if (typeof hook !== 'function') {
  56. // Something's wrong. Assume we need to remount.
  57. signature.forceReset = true;
  58. signature.fullKey = fullKey;
  59. return fullKey;
  60. }
  61. var nestedHookSignature = allSignaturesByType.get(hook);
  62. if (nestedHookSignature === undefined) {
  63. // No signature means Hook wasn't in the source code, e.g. in a library.
  64. // We'll skip it because we can assume it won't change during this session.
  65. continue;
  66. }
  67. var nestedHookKey = computeFullKey(nestedHookSignature);
  68. if (nestedHookSignature.forceReset) {
  69. signature.forceReset = true;
  70. }
  71. fullKey += '\n---\n' + nestedHookKey;
  72. }
  73. signature.fullKey = fullKey;
  74. return fullKey;
  75. }
  76. function haveEqualSignatures(prevType, nextType) {
  77. var prevSignature = allSignaturesByType.get(prevType);
  78. var nextSignature = allSignaturesByType.get(nextType);
  79. if (prevSignature === undefined && nextSignature === undefined) {
  80. return true;
  81. }
  82. if (prevSignature === undefined || nextSignature === undefined) {
  83. return false;
  84. }
  85. if (computeFullKey(prevSignature) !== computeFullKey(nextSignature)) {
  86. return false;
  87. }
  88. if (nextSignature.forceReset) {
  89. return false;
  90. }
  91. return true;
  92. }
  93. function isReactClass(type) {
  94. return type.prototype && type.prototype.isReactComponent;
  95. }
  96. function canPreserveStateBetween(prevType, nextType) {
  97. if (isReactClass(prevType) || isReactClass(nextType)) {
  98. return false;
  99. }
  100. if (haveEqualSignatures(prevType, nextType)) {
  101. return true;
  102. }
  103. return false;
  104. }
  105. function resolveFamily(type) {
  106. // Only check updated types to keep lookups fast.
  107. return updatedFamiliesByType.get(type);
  108. } // If we didn't care about IE11, we could use new Map/Set(iterable).
  109. function cloneMap(map) {
  110. var clone = new Map();
  111. map.forEach(function (value, key) {
  112. clone.set(key, value);
  113. });
  114. return clone;
  115. }
  116. function cloneSet(set) {
  117. var clone = new Set();
  118. set.forEach(function (value) {
  119. clone.add(value);
  120. });
  121. return clone;
  122. } // This is a safety mechanism to protect against rogue getters and Proxies.
  123. function getProperty(object, property) {
  124. try {
  125. return object[property];
  126. } catch (err) {
  127. // Intentionally ignore.
  128. return undefined;
  129. }
  130. }
  131. function performReactRefresh() {
  132. if (pendingUpdates.length === 0) {
  133. return null;
  134. }
  135. if (isPerformingRefresh) {
  136. return null;
  137. }
  138. isPerformingRefresh = true;
  139. try {
  140. var staleFamilies = new Set();
  141. var updatedFamilies = new Set();
  142. var updates = pendingUpdates;
  143. pendingUpdates = [];
  144. updates.forEach(function (_ref) {
  145. var family = _ref[0],
  146. nextType = _ref[1];
  147. // Now that we got a real edit, we can create associations
  148. // that will be read by the React reconciler.
  149. var prevType = family.current;
  150. updatedFamiliesByType.set(prevType, family);
  151. updatedFamiliesByType.set(nextType, family);
  152. family.current = nextType; // Determine whether this should be a re-render or a re-mount.
  153. if (canPreserveStateBetween(prevType, nextType)) {
  154. updatedFamilies.add(family);
  155. } else {
  156. staleFamilies.add(family);
  157. }
  158. }); // TODO: rename these fields to something more meaningful.
  159. var update = {
  160. updatedFamilies: updatedFamilies,
  161. // Families that will re-render preserving state
  162. staleFamilies: staleFamilies // Families that will be remounted
  163. };
  164. helpersByRendererID.forEach(function (helpers) {
  165. // Even if there are no roots, set the handler on first update.
  166. // This ensures that if *new* roots are mounted, they'll use the resolve handler.
  167. helpers.setRefreshHandler(resolveFamily);
  168. });
  169. var didError = false;
  170. var firstError = null; // We snapshot maps and sets that are mutated during commits.
  171. // If we don't do this, there is a risk they will be mutated while
  172. // we iterate over them. For example, trying to recover a failed root
  173. // may cause another root to be added to the failed list -- an infinite loop.
  174. var failedRootsSnapshot = cloneSet(failedRoots);
  175. var mountedRootsSnapshot = cloneSet(mountedRoots);
  176. var helpersByRootSnapshot = cloneMap(helpersByRoot);
  177. failedRootsSnapshot.forEach(function (root) {
  178. var helpers = helpersByRootSnapshot.get(root);
  179. if (helpers === undefined) {
  180. throw new Error('Could not find helpers for a root. This is a bug in React Refresh.');
  181. }
  182. if (!failedRoots.has(root)) {// No longer failed.
  183. }
  184. if (rootElements === null) {
  185. return;
  186. }
  187. if (!rootElements.has(root)) {
  188. return;
  189. }
  190. var element = rootElements.get(root);
  191. try {
  192. helpers.scheduleRoot(root, element);
  193. } catch (err) {
  194. if (!didError) {
  195. didError = true;
  196. firstError = err;
  197. } // Keep trying other roots.
  198. }
  199. });
  200. mountedRootsSnapshot.forEach(function (root) {
  201. var helpers = helpersByRootSnapshot.get(root);
  202. if (helpers === undefined) {
  203. throw new Error('Could not find helpers for a root. This is a bug in React Refresh.');
  204. }
  205. if (!mountedRoots.has(root)) {// No longer mounted.
  206. }
  207. try {
  208. helpers.scheduleRefresh(root, update);
  209. } catch (err) {
  210. if (!didError) {
  211. didError = true;
  212. firstError = err;
  213. } // Keep trying other roots.
  214. }
  215. });
  216. if (didError) {
  217. throw firstError;
  218. }
  219. return update;
  220. } finally {
  221. isPerformingRefresh = false;
  222. }
  223. }
  224. function register(type, id) {
  225. {
  226. if (type === null) {
  227. return;
  228. }
  229. if (typeof type !== 'function' && typeof type !== 'object') {
  230. return;
  231. } // This can happen in an edge case, e.g. if we register
  232. // return value of a HOC but it returns a cached component.
  233. // Ignore anything but the first registration for each type.
  234. if (allFamiliesByType.has(type)) {
  235. return;
  236. } // Create family or remember to update it.
  237. // None of this bookkeeping affects reconciliation
  238. // until the first performReactRefresh() call above.
  239. var family = allFamiliesByID.get(id);
  240. if (family === undefined) {
  241. family = {
  242. current: type
  243. };
  244. allFamiliesByID.set(id, family);
  245. } else {
  246. pendingUpdates.push([family, type]);
  247. }
  248. allFamiliesByType.set(type, family); // Visit inner types because we might not have registered them.
  249. if (typeof type === 'object' && type !== null) {
  250. switch (getProperty(type, '$$typeof')) {
  251. case REACT_FORWARD_REF_TYPE:
  252. register(type.render, id + '$render');
  253. break;
  254. case REACT_MEMO_TYPE:
  255. register(type.type, id + '$type');
  256. break;
  257. }
  258. }
  259. }
  260. }
  261. function setSignature(type, key) {
  262. var forceReset = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false;
  263. var getCustomHooks = arguments.length > 3 ? arguments[3] : undefined;
  264. {
  265. if (!allSignaturesByType.has(type)) {
  266. allSignaturesByType.set(type, {
  267. forceReset: forceReset,
  268. ownKey: key,
  269. fullKey: null,
  270. getCustomHooks: getCustomHooks || function () {
  271. return [];
  272. }
  273. });
  274. } // Visit inner types because we might not have signed them.
  275. if (typeof type === 'object' && type !== null) {
  276. switch (getProperty(type, '$$typeof')) {
  277. case REACT_FORWARD_REF_TYPE:
  278. setSignature(type.render, key, forceReset, getCustomHooks);
  279. break;
  280. case REACT_MEMO_TYPE:
  281. setSignature(type.type, key, forceReset, getCustomHooks);
  282. break;
  283. }
  284. }
  285. }
  286. } // This is lazily called during first render for a type.
  287. // It captures Hook list at that time so inline requires don't break comparisons.
  288. function collectCustomHooksForSignature(type) {
  289. {
  290. var signature = allSignaturesByType.get(type);
  291. if (signature !== undefined) {
  292. computeFullKey(signature);
  293. }
  294. }
  295. }
  296. function getFamilyByID(id) {
  297. {
  298. return allFamiliesByID.get(id);
  299. }
  300. }
  301. function getFamilyByType(type) {
  302. {
  303. return allFamiliesByType.get(type);
  304. }
  305. }
  306. function findAffectedHostInstances(families) {
  307. {
  308. var affectedInstances = new Set();
  309. mountedRoots.forEach(function (root) {
  310. var helpers = helpersByRoot.get(root);
  311. if (helpers === undefined) {
  312. throw new Error('Could not find helpers for a root. This is a bug in React Refresh.');
  313. }
  314. var instancesForRoot = helpers.findHostInstancesForRefresh(root, families);
  315. instancesForRoot.forEach(function (inst) {
  316. affectedInstances.add(inst);
  317. });
  318. });
  319. return affectedInstances;
  320. }
  321. }
  322. function injectIntoGlobalHook(globalObject) {
  323. {
  324. // For React Native, the global hook will be set up by require('react-devtools-core').
  325. // That code will run before us. So we need to monkeypatch functions on existing hook.
  326. // For React Web, the global hook will be set up by the extension.
  327. // This will also run before us.
  328. var hook = globalObject.__REACT_DEVTOOLS_GLOBAL_HOOK__;
  329. if (hook === undefined) {
  330. // However, if there is no DevTools extension, we'll need to set up the global hook ourselves.
  331. // Note that in this case it's important that renderer code runs *after* this method call.
  332. // Otherwise, the renderer will think that there is no global hook, and won't do the injection.
  333. var nextID = 0;
  334. globalObject.__REACT_DEVTOOLS_GLOBAL_HOOK__ = hook = {
  335. renderers: new Map(),
  336. supportsFiber: true,
  337. inject: function (injected) {
  338. return nextID++;
  339. },
  340. onScheduleFiberRoot: function (id, root, children) {},
  341. onCommitFiberRoot: function (id, root, maybePriorityLevel, didError) {},
  342. onCommitFiberUnmount: function () {}
  343. };
  344. }
  345. if (hook.isDisabled) {
  346. // This isn't a real property on the hook, but it can be set to opt out
  347. // of DevTools integration and associated warnings and logs.
  348. // Using console['warn'] to evade Babel and ESLint
  349. console['warn']('Something has shimmed the React DevTools global hook (__REACT_DEVTOOLS_GLOBAL_HOOK__). ' + 'Fast Refresh is not compatible with this shim and will be disabled.');
  350. return;
  351. } // Here, we just want to get a reference to scheduleRefresh.
  352. var oldInject = hook.inject;
  353. hook.inject = function (injected) {
  354. var id = oldInject.apply(this, arguments);
  355. if (typeof injected.scheduleRefresh === 'function' && typeof injected.setRefreshHandler === 'function') {
  356. // This version supports React Refresh.
  357. helpersByRendererID.set(id, injected);
  358. }
  359. return id;
  360. }; // Do the same for any already injected roots.
  361. // This is useful if ReactDOM has already been initialized.
  362. // https://github.com/facebook/react/issues/17626
  363. hook.renderers.forEach(function (injected, id) {
  364. if (typeof injected.scheduleRefresh === 'function' && typeof injected.setRefreshHandler === 'function') {
  365. // This version supports React Refresh.
  366. helpersByRendererID.set(id, injected);
  367. }
  368. }); // We also want to track currently mounted roots.
  369. var oldOnCommitFiberRoot = hook.onCommitFiberRoot;
  370. var oldOnScheduleFiberRoot = hook.onScheduleFiberRoot || function () {};
  371. hook.onScheduleFiberRoot = function (id, root, children) {
  372. if (!isPerformingRefresh) {
  373. // If it was intentionally scheduled, don't attempt to restore.
  374. // This includes intentionally scheduled unmounts.
  375. failedRoots.delete(root);
  376. if (rootElements !== null) {
  377. rootElements.set(root, children);
  378. }
  379. }
  380. return oldOnScheduleFiberRoot.apply(this, arguments);
  381. };
  382. hook.onCommitFiberRoot = function (id, root, maybePriorityLevel, didError) {
  383. var helpers = helpersByRendererID.get(id);
  384. if (helpers !== undefined) {
  385. helpersByRoot.set(root, helpers);
  386. var current = root.current;
  387. var alternate = current.alternate; // We need to determine whether this root has just (un)mounted.
  388. // This logic is copy-pasted from similar logic in the DevTools backend.
  389. // If this breaks with some refactoring, you'll want to update DevTools too.
  390. if (alternate !== null) {
  391. var wasMounted = alternate.memoizedState != null && alternate.memoizedState.element != null && mountedRoots.has(root);
  392. var isMounted = current.memoizedState != null && current.memoizedState.element != null;
  393. if (!wasMounted && isMounted) {
  394. // Mount a new root.
  395. mountedRoots.add(root);
  396. failedRoots.delete(root);
  397. } else if (wasMounted && isMounted) ; else if (wasMounted && !isMounted) {
  398. // Unmount an existing root.
  399. mountedRoots.delete(root);
  400. if (didError) {
  401. // We'll remount it on future edits.
  402. failedRoots.add(root);
  403. } else {
  404. helpersByRoot.delete(root);
  405. }
  406. } else if (!wasMounted && !isMounted) {
  407. if (didError) {
  408. // We'll remount it on future edits.
  409. failedRoots.add(root);
  410. }
  411. }
  412. } else {
  413. // Mount a new root.
  414. mountedRoots.add(root);
  415. }
  416. } // Always call the decorated DevTools hook.
  417. return oldOnCommitFiberRoot.apply(this, arguments);
  418. };
  419. }
  420. }
  421. function hasUnrecoverableErrors() {
  422. // TODO: delete this after removing dependency in RN.
  423. return false;
  424. } // Exposed for testing.
  425. function _getMountedRootCount() {
  426. {
  427. return mountedRoots.size;
  428. }
  429. } // This is a wrapper over more primitive functions for setting signature.
  430. // Signatures let us decide whether the Hook order has changed on refresh.
  431. //
  432. // This function is intended to be used as a transform target, e.g.:
  433. // var _s = createSignatureFunctionForTransform()
  434. //
  435. // function Hello() {
  436. // const [foo, setFoo] = useState(0);
  437. // const value = useCustomHook();
  438. // _s(); /* Call without arguments triggers collecting the custom Hook list.
  439. // * This doesn't happen during the module evaluation because we
  440. // * don't want to change the module order with inline requires.
  441. // * Next calls are noops. */
  442. // return <h1>Hi</h1>;
  443. // }
  444. //
  445. // /* Call with arguments attaches the signature to the type: */
  446. // _s(
  447. // Hello,
  448. // 'useState{[foo, setFoo]}(0)',
  449. // () => [useCustomHook], /* Lazy to avoid triggering inline requires */
  450. // );
  451. function createSignatureFunctionForTransform() {
  452. {
  453. var savedType;
  454. var hasCustomHooks;
  455. var didCollectHooks = false;
  456. return function (type, key, forceReset, getCustomHooks) {
  457. if (typeof key === 'string') {
  458. // We're in the initial phase that associates signatures
  459. // with the functions. Note this may be called multiple times
  460. // in HOC chains like _s(hoc1(_s(hoc2(_s(actualFunction))))).
  461. if (!savedType) {
  462. // We're in the innermost call, so this is the actual type.
  463. savedType = type;
  464. hasCustomHooks = typeof getCustomHooks === 'function';
  465. } // Set the signature for all types (even wrappers!) in case
  466. // they have no signatures of their own. This is to prevent
  467. // problems like https://github.com/facebook/react/issues/20417.
  468. if (type != null && (typeof type === 'function' || typeof type === 'object')) {
  469. setSignature(type, key, forceReset, getCustomHooks);
  470. }
  471. return type;
  472. } else {
  473. // We're in the _s() call without arguments, which means
  474. // this is the time to collect custom Hook signatures.
  475. // Only do this once. This path is hot and runs *inside* every render!
  476. if (!didCollectHooks && hasCustomHooks) {
  477. didCollectHooks = true;
  478. collectCustomHooksForSignature(savedType);
  479. }
  480. }
  481. };
  482. }
  483. }
  484. function isLikelyComponentType(type) {
  485. {
  486. switch (typeof type) {
  487. case 'function':
  488. {
  489. // First, deal with classes.
  490. if (type.prototype != null) {
  491. if (type.prototype.isReactComponent) {
  492. // React class.
  493. return true;
  494. }
  495. var ownNames = Object.getOwnPropertyNames(type.prototype);
  496. if (ownNames.length > 1 || ownNames[0] !== 'constructor') {
  497. // This looks like a class.
  498. return false;
  499. } // eslint-disable-next-line no-proto
  500. if (type.prototype.__proto__ !== Object.prototype) {
  501. // It has a superclass.
  502. return false;
  503. } // Pass through.
  504. // This looks like a regular function with empty prototype.
  505. } // For plain functions and arrows, use name as a heuristic.
  506. var name = type.name || type.displayName;
  507. return typeof name === 'string' && /^[A-Z]/.test(name);
  508. }
  509. case 'object':
  510. {
  511. if (type != null) {
  512. switch (getProperty(type, '$$typeof')) {
  513. case REACT_FORWARD_REF_TYPE:
  514. case REACT_MEMO_TYPE:
  515. // Definitely React components.
  516. return true;
  517. default:
  518. return false;
  519. }
  520. }
  521. return false;
  522. }
  523. default:
  524. {
  525. return false;
  526. }
  527. }
  528. }
  529. }
  530. exports._getMountedRootCount = _getMountedRootCount;
  531. exports.collectCustomHooksForSignature = collectCustomHooksForSignature;
  532. exports.createSignatureFunctionForTransform = createSignatureFunctionForTransform;
  533. exports.findAffectedHostInstances = findAffectedHostInstances;
  534. exports.getFamilyByID = getFamilyByID;
  535. exports.getFamilyByType = getFamilyByType;
  536. exports.hasUnrecoverableErrors = hasUnrecoverableErrors;
  537. exports.injectIntoGlobalHook = injectIntoGlobalHook;
  538. exports.isLikelyComponentType = isLikelyComponentType;
  539. exports.performReactRefresh = performReactRefresh;
  540. exports.register = register;
  541. exports.setSignature = setSignature;
  542. })();
  543. }