-
Notifications
You must be signed in to change notification settings - Fork 51.1k
Expand file tree
/
Copy pathbackendManager.js
More file actions
218 lines (189 loc) · 6.68 KB
/
backendManager.js
File metadata and controls
218 lines (189 loc) · 6.68 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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {
DevToolsHook,
ReactRenderer,
} from 'react-devtools-shared/src/backend/types';
import {hasAssignedBackend} from 'react-devtools-shared/src/backend/utils';
import {COMPACT_VERSION_NAME} from 'react-devtools-extensions/src/utils';
import {getIsReloadAndProfileSupported} from 'react-devtools-shared/src/utils';
import {
getIfReloadedAndProfiling,
onReloadAndProfile,
onReloadAndProfileFlagsReset,
} from 'react-devtools-shared/src/utils';
let welcomeHasInitialized = false;
const requiredBackends = new Set<string>();
function welcome(event: $FlowFixMe) {
if (
event.source !== window ||
event.data.source !== 'react-devtools-content-script'
) {
return;
}
// In some circumstances, this method is called more than once for a single welcome message.
// The exact circumstances of this are unclear, though it seems related to 3rd party event batching code.
//
// Regardless, call this method multiple times can cause DevTools to add duplicate elements to the Store
// (and throw an error) or worse yet, choke up entirely and freeze the browser.
//
// The simplest solution is to ignore the duplicate events.
// To be clear, this SHOULD NOT BE NECESSARY, since we remove the event handler below.
//
// See https://github.com/facebook/react/issues/24162
if (welcomeHasInitialized) {
console.warn(
'React DevTools detected duplicate welcome "message" events from the content script.',
);
return;
}
welcomeHasInitialized = true;
window.removeEventListener('message', welcome);
setup(window.__REACT_DEVTOOLS_GLOBAL_HOOK__);
}
function setup(hook: ?DevToolsHook) {
// this should not happen, but Chrome can be weird sometimes
if (hook == null) {
return;
}
// register renderers that have already injected themselves.
hook.renderers.forEach(renderer => {
registerRenderer(renderer, hook);
});
// Activate and remove from required all present backends, registered within the hook
hook.backends.forEach((_, backendVersion) => {
requiredBackends.delete(backendVersion);
activateBackend(backendVersion, hook);
});
updateRequiredBackends();
// register renderers that inject themselves later.
const unsubscribeRendererListener = hook.sub('renderer', ({renderer}) => {
registerRenderer(renderer, hook);
updateRequiredBackends();
});
// listen for backend installations.
const unsubscribeBackendInstallationListener = hook.sub(
'devtools-backend-installed',
version => {
activateBackend(version, hook);
updateRequiredBackends();
},
);
const unsubscribeShutdownListener: () => void = hook.sub('shutdown', () => {
unsubscribeRendererListener();
unsubscribeBackendInstallationListener();
unsubscribeShutdownListener();
});
}
function registerRenderer(renderer: ReactRenderer, hook: DevToolsHook) {
let version = renderer.reconcilerVersion || renderer.version;
if (!hasAssignedBackend(version)) {
version = COMPACT_VERSION_NAME;
}
// Check if required backend is already activated, no need to require again
if (!hook.backends.has(version)) {
requiredBackends.add(version);
}
}
function activateBackend(version: string, hook: DevToolsHook) {
const backend = hook.backends.get(version);
if (!backend) {
throw new Error(`Could not find backend for version "${version}"`);
}
const {Agent, Bridge, initBackend, setupNativeStyleEditor} = backend;
const bridge = new Bridge({
listen(fn) {
const listener = (event: $FlowFixMe) => {
if (
event.source !== window ||
!event.data ||
event.data.source !== 'react-devtools-content-script' ||
!event.data.payload
) {
return;
}
fn(event.data.payload);
};
window.addEventListener('message', listener);
return () => {
window.removeEventListener('message', listener);
};
},
send(event: string, payload: any, transferable?: Array<any>) {
window.postMessage(
{
source: 'react-devtools-bridge',
payload: {event, payload},
},
'*',
transferable,
);
},
});
const agent = new Agent(
bridge,
getIfReloadedAndProfiling(),
onReloadAndProfile,
);
// Agent read flags successfully, we can count it as successful launch
// Clean up flags, so that next reload won't start profiling
onReloadAndProfileFlagsReset();
agent.addListener('shutdown', () => {
// If we received 'shutdown' from `agent`, we assume the `bridge` is already shutting down,
// and that caused the 'shutdown' event on the `agent`, so we don't need to call `bridge.shutdown()` here.
hook.emit('shutdown');
delete window.__REACT_DEVTOOLS_BACKEND_MANAGER_INJECTED__;
});
initBackend(hook, agent, window, getIsReloadAndProfileSupported());
// Setup React Native style editor if a renderer like react-native-web has injected it.
if (typeof setupNativeStyleEditor === 'function' && hook.resolveRNStyle) {
setupNativeStyleEditor(
bridge,
agent,
hook.resolveRNStyle,
hook.nativeStyleEditorValidAttributes,
);
}
// Let the frontend know that the backend has attached listeners and is ready for messages.
// This covers the case of syncing saved values after reloading/navigating while DevTools remain open.
bridge.send('extensionBackendInitialized');
// this backend is activated
requiredBackends.delete(version);
}
// tell the service worker which versions of backends are needed for the current page
function updateRequiredBackends() {
if (requiredBackends.size === 0) {
return;
}
window.postMessage(
{
source: 'react-devtools-backend-manager',
payload: {
type: 'require-backends',
versions: Array.from(requiredBackends),
},
},
'*',
);
}
/*
* Make sure this is executed only once in case Frontend is reloaded multiple times while Backend is initializing
* We can't use `reactDevToolsAgent` field on a global Hook object, because it only cleaned up after both Frontend and Backend initialized
*/
if (!window.__REACT_DEVTOOLS_BACKEND_MANAGER_INJECTED__) {
window.__REACT_DEVTOOLS_BACKEND_MANAGER_INJECTED__ = true;
window.addEventListener('message', welcome);
// Signal to the content script that the backend manager has been injected.
// This allows the content script to connect immediately without polling.
window.document.documentElement.setAttribute(
'data-react-devtools-ready',
'true',
);
window.dispatchEvent(new CustomEvent('react-devtools-ready'));
}