Files
flipper/desktop/app/src/HMRClient.js
dependabot[bot] 35a433d1a3 Bump metro from 0.60.0 to 0.63.0 in /desktop (#1606)
Summary:
Bumps [metro](https://github.com/facebook/metro) from 0.60.0 to 0.63.0.
<details>
<summary>Release notes</summary>
<p><em>Sourced from <a href="https://github.com/facebook/metro/releases">metro's releases</a>.</em></p>
<blockquote>
<h2>Release v0.63.0</h2>
<ul>
<li>[fix] Change initialisation logo and text from RN to Metro</li>
</ul>
<h2>Release v0.62.0</h2>
<ul>
<li>[feature] Add onBundleBuilt to ServerOptions</li>
</ul>
<h2>Release v0.61.0</h2>
<p>Contains all changes since 0.60.0:</p>
<ul>
<li>[Feature]: Add support for blockList and array of regexs</li>
<li>[Fix]: Change order of imports to be the same as in source files</li>
<li>[Feature]: Add new secureServerOptions option to runServer</li>
<li>[Feature]: Add inline-requires option</li>
<li>[PetPeeve]: Metro server =&gt; Metro</li>
</ul>
<p>See <a href="https://github.com/facebook/metro/compare/0.60.0...0.61.0">0.59.0...0.60.0</a> for a full list of changes.</p>
</blockquote>
</details>
<details>
<summary>Commits</summary>
<ul>
<li><a href="b9bacd51d0"><code>b9bacd5</code></a> Metro release v0.63.0</li>
<li><a href="c106b6540e"><code>c106b65</code></a> Change initialisation logo and text</li>
<li><a href="be719b29c0"><code>be719b2</code></a> remove redundant deprecated-utility setting from flow configs</li>
<li><a href="9236feba99"><code>9236feb</code></a> Turn off template literal and shorthand properties transform for hermes-canary</li>
<li><a href="6b82e8443c"><code>6b82e84</code></a> Create a <code>metro-runtime</code> module</li>
<li><a href="18883f6caa"><code>18883f6</code></a> Fix up package.json files.</li>
<li><a href="921b73e4d0"><code>921b73e</code></a> Remove autogenerated table of contents (deprecated in docusaurus v2)</li>
<li><a href="eb9b02572b"><code>eb9b025</code></a> Update configuration page with examples</li>
<li><a href="00a5a6d8d6"><code>00a5a6d</code></a> Fix troubleshooting and help pages</li>
<li><a href="c73eaf88f8"><code>c73eaf8</code></a> Update docusaurus version</li>
<li>Additional commits viewable in <a href="https://github.com/facebook/metro/compare/v0.60.0...v0.63.0">compare view</a></li>
</ul>
</details>
<br />

[![Dependabot compatibility score](https://dependabot-badges.githubapp.com/badges/compatibility_score?dependency-name=metro&package-manager=npm_and_yarn&previous-version=0.60.0&new-version=0.63.0)](https://docs.github.com/en/github/managing-security-vulnerabilities/configuring-github-dependabot-security-updates)

Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting `dependabot rebase`.

[//]: # (dependabot-automerge-start)
[//]: # (dependabot-automerge-end)

 ---

<details>
<summary>Dependabot commands and options</summary>
<br />

You can trigger Dependabot actions by commenting on this PR:
- `dependabot rebase` will rebase this PR
- `dependabot recreate` will recreate this PR, overwriting any edits that have been made to it
- `dependabot merge` will merge this PR after your CI passes on it
- `dependabot squash and merge` will squash and merge this PR after your CI passes on it
- `dependabot cancel merge` will cancel a previously requested merge and block automerging
- `dependabot reopen` will reopen this PR if it is closed
- `dependabot close` will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
- `dependabot ignore this major version` will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
- `dependabot ignore this minor version` will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
- `dependabot ignore this dependency` will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)

</details>

Pull Request resolved: https://github.com/facebook/flipper/pull/1606

Reviewed By: passy

Differential Revision: D24392103

Pulled By: nikoant

fbshipit-source-id: 6d816629f55e04852d6737f9960fa61d7e83cee8
2020-10-20 08:54:17 -07:00

295 lines
9.0 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
/**
* * * * * * * ** * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * * * * * ** * * * * * * * * *
* This implementation of HMR Client is based on React Native implementation with some code commented out: *
* https://github.com/facebook/react-native/blob/master/Libraries/Utilities/HMRClient.js *
* * * * * * * ** * * * * * * * * * * * * * * * * * ** * * * * * * * * * * * * * * * * * ** * * * * * * * * *
*/
// // const DevSettings = require('./DevSettings');
import invariant from 'invariant';
import {default as MetroHMRClient} from 'metro-runtime/src/modules/HMRClient';
// // const Platform = require('./Platform');
import prettyFormat from 'pretty-format';
const pendingEntryPoints = [];
let hmrClient = null;
let hmrUnavailableReason = null;
let currentCompileErrorMessage = null;
let didConnect = false;
const pendingLogs = [];
/**
* HMR Client that receives from the server HMR updates and propagates them
* runtime to reflects those changes.
*/
const HMRClient = {
enable() {
if (hmrUnavailableReason !== null) {
// If HMR became unavailable while you weren't using it,
// explain why when you try to turn it on.
// This is an error (and not a warning) because it is shown
// in response to a direct user action.
throw new Error(hmrUnavailableReason);
}
invariant(hmrClient, 'Expected HMRClient.setup() call at startup.');
//// const LoadingView = require('./LoadingView');
// We use this for internal logging only.
// It doesn't affect the logic.
hmrClient.send(JSON.stringify({type: 'log-opt-in'}));
// When toggling Fast Refresh on, we might already have some stashed updates.
// Since they'll get applied now, we'll show a banner.
const hasUpdates = hmrClient.hasPendingUpdates();
if (hasUpdates) {
//// LoadingView.showMessage('Refreshing...', 'refresh');
console.log('Loading start: Refreshing...');
}
try {
hmrClient.enable();
} finally {
if (hasUpdates) {
//// LoadingView.hide();
console.log('Loading end');
}
}
// There could be a compile error while Fast Refresh was off,
// but we ignored it at the time. Show it now.
showCompileError();
},
disable() {
invariant(hmrClient, 'Expected HMRClient.setup() call at startup.');
hmrClient.disable();
},
registerBundle(requestUrl) {
invariant(hmrClient, 'Expected HMRClient.setup() call at startup.');
pendingEntryPoints.push(requestUrl);
registerBundleEntryPoints(hmrClient);
},
log(level, data) {
if (!hmrClient) {
// Catch a reasonable number of early logs
// in case hmrClient gets initialized later.
pendingLogs.push([level, data]);
if (pendingLogs.length > 100) {
pendingLogs.shift();
}
return;
}
try {
hmrClient.send(
JSON.stringify({
type: 'log',
level,
data: data.map((item) =>
typeof item === 'string'
? item
: prettyFormat(item, {
escapeString: true,
highlight: true,
maxDepth: 3,
min: true,
plugins: [prettyFormat.plugins.ReactElement],
}),
),
}),
);
} catch (error) {
// If sending logs causes any failures we want to silently ignore them
// to ensure we do not cause infinite-logging loops.
}
},
// Called once by the bridge on startup, even if Fast Refresh is off.
// It creates the HMR client but doesn't actually set up the socket yet.
setup(platform, bundleEntry, host, port, isEnabled) {
invariant(platform, 'Missing required parameter `platform`');
invariant(bundleEntry, 'Missing required parameter `bundleEntry`');
invariant(host, 'Missing required parameter `host`');
invariant(!hmrClient, 'Cannot initialize hmrClient twice');
//// const LoadingView = require('./LoadingView');
const wsHost = port !== null && port !== '' ? `${host}:${port}` : host;
const client = new MetroHMRClient(`ws://${wsHost}/hot`);
hmrClient = client;
pendingEntryPoints.push(
`ws://${wsHost}/hot?bundleEntry=${bundleEntry}&platform=${platform}`,
);
client.on('connection-error', (e) => {
let error = `Cannot connect to the Metro server.
Try the following to fix the issue:
- Ensure that the Metro server is running and available on the same network`;
error += `
- Ensure that your device/emulator is connected to your machine and has USB debugging enabled - run 'adb devices' to see a list of connected devices
- If you're on a physical device connected to the same machine, run 'adb reverse tcp:8081 tcp:8081' to forward requests from your device
- If your device is on the same Wi-Fi network, set 'Debug server host & port for device' in 'Dev settings' to your machine's IP address and the port of the local dev server - e.g. 10.0.1.1:8081`;
error += `
URL: ${host}:${port}
Error: ${e.message}`;
setHMRUnavailableReason(error);
});
client.on('update-start', ({isInitialUpdate}) => {
currentCompileErrorMessage = null;
didConnect = true;
if (client.isEnabled() && !isInitialUpdate) {
//// LoadingView.showMessage('Refreshing...', 'refresh');
console.log('Loading start: Refreshing...');
}
});
client.on('update', ({isInitialUpdate}) => {
if (client.isEnabled() && !isInitialUpdate) {
dismissRedbox();
//// LogBoxData.clear();
}
});
client.on('update-done', () => {
//// LoadingView.hide();
console.log('Loading end');
});
client.on('error', (data) => {
//// LoadingView.hide();
console.log('Loading end');
if (data.type === 'GraphNotFoundError') {
client.close();
setHMRUnavailableReason(
'The Metro server has restarted since the last edit. Reload to reconnect.',
);
} else if (data.type === 'RevisionNotFoundError') {
client.close();
setHMRUnavailableReason(
'The Metro server and the client are out of sync. Reload to reconnect.',
);
} else {
currentCompileErrorMessage = `${data.type} ${data.message}`;
if (client.isEnabled()) {
showCompileError();
}
}
});
client.on('close', (data) => {
//// LoadingView.hide();
console.log('Loading end');
setHMRUnavailableReason('Disconnected from the Metro server.');
});
if (isEnabled) {
HMRClient.enable();
} else {
HMRClient.disable();
}
registerBundleEntryPoints(hmrClient);
flushEarlyLogs(hmrClient);
},
};
function setHMRUnavailableReason(reason) {
invariant(hmrClient, 'Expected HMRClient.setup() call at startup.');
if (hmrUnavailableReason !== null) {
// Don't show more than one warning.
return;
}
hmrUnavailableReason = reason;
// We only want to show a warning if Fast Refresh is on *and* if we ever
// previously managed to connect successfully. We don't want to show
// the warning to native engineers who use cached bundles without Metro.
if (hmrClient.isEnabled() && didConnect) {
console.warn(reason);
// (Not using the `warning` module to prevent a Buck cycle.)
}
}
function registerBundleEntryPoints(client) {
if (hmrUnavailableReason) {
// // DevSettings.reload('Bundle Splitting Metro disconnected');
console.log('Bundle Spliiting - Metro disconnected');
return;
}
if (pendingEntryPoints.length > 0) {
client.send(
JSON.stringify({
type: 'register-entrypoints',
entryPoints: pendingEntryPoints,
}),
);
pendingEntryPoints.length = 0;
}
}
function flushEarlyLogs(client) {
try {
pendingLogs.forEach(([level, data]) => {
HMRClient.log(level, data);
});
} finally {
pendingLogs.length = 0;
}
}
function dismissRedbox() {
// // if (
// // Platform.OS === 'ios' &&
// // NativeRedBox != null &&
// // NativeRedBox.dismiss != null
// // ) {
// // NativeRedBox.dismiss();
// // } else {
// // const NativeExceptionsManager = require('../Core/NativeExceptionsManager')
// // .default;
// // NativeExceptionsManager &&
// // NativeExceptionsManager.dismissRedbox &&
// // NativeExceptionsManager.dismissRedbox();
// // }
}
function showCompileError() {
if (currentCompileErrorMessage === null) {
return;
}
// Even if there is already a redbox, syntax errors are more important.
// Otherwise you risk seeing a stale runtime error while a syntax error is more recent.
dismissRedbox();
const message = currentCompileErrorMessage;
currentCompileErrorMessage = null;
const error = new Error(message);
// Symbolicating compile errors is wasted effort
// because the stack trace is meaningless:
error.preventSymbolication = true;
throw error;
}
export default HMRClient;