This commit is contained in:
Yamozha
2021-04-02 02:24:13 +03:00
parent c23950b545
commit 7256d79e2c
31493 changed files with 3036630 additions and 0 deletions

View File

@ -0,0 +1,22 @@
/**
* 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
*/
/// <reference types="node" />
import ws from 'ws';
import { Server as HttpServer } from 'http';
import { Server as HttpsServer } from 'https';
declare type Server = HttpServer | HttpsServer;
declare function attachToServer(server: Server, path: string): {
server: ws.Server;
isDebuggerConnected(): boolean;
};
declare const _default: {
attachToServer: typeof attachToServer;
};
export default _default;
//# sourceMappingURL=debuggerProxyServer.d.ts.map

View File

@ -0,0 +1,135 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _ws() {
const data = _interopRequireDefault(require("ws"));
_ws = function () {
return data;
};
return data;
}
function _cliTools() {
const data = require("@react-native-community/cli-tools");
_cliTools = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* 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
*/
function attachToServer(server, path) {
const WebSocketServer = _ws().default.Server;
const wss = new WebSocketServer({
server,
path
});
let debuggerSocket;
let clientSocket;
function send(dest, message) {
if (!dest) {
return;
}
try {
dest.send(message);
} catch (e) {
_cliTools().logger.warn(e); // Sometimes this call throws 'not opened'
}
}
const debuggerSocketCloseHandler = () => {
debuggerSocket = null;
if (clientSocket) {
clientSocket.close(1011, 'Debugger was disconnected');
}
};
const clientSocketCloseHandler = () => {
clientSocket = null;
send(debuggerSocket, JSON.stringify({
method: '$disconnected'
}));
};
wss.on('connection', connection => {
// @ts-ignore current definition of ws does not have upgradeReq type
const {
url
} = connection.upgradeReq;
if (url.indexOf('role=debugger') > -1) {
if (debuggerSocket) {
connection.close(1011, 'Another debugger is already connected');
return;
}
debuggerSocket = connection;
if (debuggerSocket) {
debuggerSocket.onerror = debuggerSocketCloseHandler;
debuggerSocket.onclose = debuggerSocketCloseHandler;
debuggerSocket.onmessage = ({
data
}) => send(clientSocket, data);
}
} else if (url.indexOf('role=client') > -1) {
if (clientSocket) {
// @ts-ignore not nullable with current type definition of ws
clientSocket.onerror = null; // @ts-ignore not nullable with current type definition of ws
clientSocket.onclose = null; // @ts-ignore not nullable with current type definition of ws
clientSocket.onmessage = null;
clientSocket.close(1011, 'Another client connected');
}
clientSocket = connection;
clientSocket.onerror = clientSocketCloseHandler;
clientSocket.onclose = clientSocketCloseHandler;
clientSocket.onmessage = ({
data
}) => send(debuggerSocket, data);
} else {
connection.close(1011, 'Missing role param');
}
});
return {
server: wss,
isDebuggerConnected() {
return !!debuggerSocket;
}
};
}
var _default = {
attachToServer
};
exports.default = _default;
//# sourceMappingURL=debuggerProxyServer.js.map

View File

@ -0,0 +1,36 @@
/// <reference types="node" />
import { Server as HttpServer } from 'http';
import { Server as HttpsServer } from 'https';
import messageSocketModule from './messageSocketServer';
/**
* The eventsSocket websocket listens at the 'events/` for websocket
* connections, on which all Metro reports will be emitted.
*
* This is mostly useful for developer tools (clients) that wants to monitor Metro,
* and the apps connected to Metro.
*
* The eventsSocket provides the following features:
* - it reports any Metro event (that is reported through a reporter) to all clients
* - it reports any console.log's (and friends) from the connected app to all clients
* (as client_log event)
* - it allows connected clients to send commands through Metro to the connected app.
* This reuses the generic command mechanism.
* Two useful commands are 'reload' and 'devmenu'.
*/
declare type Server = HttpServer | HttpsServer;
declare type MessageSocket = ReturnType<typeof messageSocketModule.attachToServer>;
/**
* Starts the eventsSocket at the given path
*
* @param server
* @param path typically: 'events/'
* @param messageSocket: webSocket to which all connected RN apps are listening
*/
declare function attachToServer(server: Server, path: string, messageSocket: MessageSocket): {
reportEvent: (event: any) => void;
};
declare const _default: {
attachToServer: typeof attachToServer;
};
export default _default;
//# sourceMappingURL=eventsSocketServer.d.ts.map

View File

@ -0,0 +1,208 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _ws() {
const data = require("ws");
_ws = function () {
return data;
};
return data;
}
function _cliTools() {
const data = require("@react-native-community/cli-tools");
_cliTools = function () {
return data;
};
return data;
}
function _prettyFormat() {
const data = _interopRequireDefault(require("pretty-format"));
_prettyFormat = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* This number is used to version the communication protocol between
* Dev tooling like Flipper and Metro, so that in the future we can recognize
* messages coming from old clients, so that it will be simpler to implement
* backward compatibility.
*
* We start at 2 as the protocol is currently the same as used internally at FB,
* which happens to be at version 2 as well.
*/
const PROTOCOL_VERSION = 2;
function parseMessage(data) {
try {
const message = JSON.parse(data);
if (message.version === PROTOCOL_VERSION) {
return message;
}
_cliTools().logger.error('Received message had wrong protocol version: ' + message.version);
} catch (_unused) {
_cliTools().logger.error('Failed to parse the message as JSON:\n' + data);
}
return undefined;
}
/**
* Two types of messages will arrive in this function,
* 1) messages generated by Metro itself (through the reporter abstraction)
* those are yet to be serialized, and can contain any kind of data structure
* 2) a specific event generated by Metro is `client_log`, which describes
* console.* calls in the app.
* The arguments send to the console are pretty printed so that they can be
* displayed in a nicer way in dev tools
*
* @param message
*/
function serializeMessage(message) {
// We do want to send Metro report messages, but their contents is not guaranteed to be serializable.
// For some known types we will pretty print otherwise not serializable parts first:
let toSerialize = message;
if (message && message.error && message.error instanceof Error) {
toSerialize = { ...message,
error: (0, _prettyFormat().default)(message.error, {
escapeString: true,
highlight: true,
maxDepth: 3,
min: true
})
};
} else if (message && message.type === 'client_log') {
toSerialize = { ...message,
data: message.data.map(item => typeof item === 'string' ? item : (0, _prettyFormat().default)(item, {
escapeString: true,
highlight: true,
maxDepth: 3,
min: true,
plugins: [_prettyFormat().default.plugins.ReactElement]
}))
};
}
try {
return JSON.stringify(toSerialize);
} catch (e) {
_cliTools().logger.error('Failed to serialize: ' + e);
return null;
}
}
/**
* Starts the eventsSocket at the given path
*
* @param server
* @param path typically: 'events/'
* @param messageSocket: webSocket to which all connected RN apps are listening
*/
function attachToServer(server, path, messageSocket) {
const wss = new (_ws().Server)({
server: server,
path: path,
verifyClient({
origin
}) {
// This exposes the full JS logs and enables issuing commands like reload
// so let's make sure only locally running stuff can connect to it
return origin.startsWith('http://localhost:') || origin.startsWith('file:');
}
});
const clients = new Map();
let nextClientId = 0;
/**
* broadCastEvent is called by reportEvent (below), which is called by the
* default reporter of this server, to make sure that all Metro events are
* broadcasted to all connected clients
* (that is, all devtools such as Flipper, _not_: connected apps)
*
* @param message
*/
function broadCastEvent(message) {
if (!clients.size) {
return;
}
const serialized = serializeMessage(message);
if (!serialized) {
return;
}
for (const ws of clients.values()) {
try {
ws.send(serialized);
} catch (e) {
_cliTools().logger.error(`Failed to send broadcast to client due to:\n ${e.toString()}`);
}
}
}
wss.on('connection', function (clientWs) {
const clientId = `client#${nextClientId++}`;
clients.set(clientId, clientWs);
clientWs.onclose = clientWs.onerror = () => {
clients.delete(clientId);
};
clientWs.onmessage = event => {
const message = parseMessage(event.data.toString());
if (message == null) {
return;
}
if (message.type === 'command') {
try {
/**
* messageSocket.broadcast (not to be confused with our own broadcast above)
* forwards a command to all connected React Native applications.
*/
messageSocket.broadcast(message.command, message.params);
} catch (e) {
_cliTools().logger.error('Failed to forward message to clients: ', e);
}
} else {
_cliTools().logger.error('Unknown message type: ', message.type);
}
};
});
return {
reportEvent: event => {
broadCastEvent(event);
}
};
}
var _default = {
attachToServer
};
exports.default = _default;
//# sourceMappingURL=eventsSocketServer.js.map

View File

@ -0,0 +1,20 @@
/**
* 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.
*/
/// <reference types="node" />
import { Server as HttpServer } from 'http';
import { Server as HttpsServer } from 'https';
declare function parseMessage(data: string, binary: any): any;
declare type Server = HttpServer | HttpsServer;
declare function attachToServer(server: Server, path: string): {
broadcast: (method: string, params?: Record<string, any> | undefined) => void;
};
declare const _default: {
attachToServer: typeof attachToServer;
parseMessage: typeof parseMessage;
};
export default _default;
//# sourceMappingURL=messageSocketServer.d.ts.map

View File

@ -0,0 +1,258 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
function _url() {
const data = _interopRequireDefault(require("url"));
_url = function () {
return data;
};
return data;
}
function _ws() {
const data = require("ws");
_ws = function () {
return data;
};
return data;
}
function _cliTools() {
const data = require("@react-native-community/cli-tools");
_cliTools = function () {
return data;
};
return data;
}
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
/**
* 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.
*/
const PROTOCOL_VERSION = 2;
function parseMessage(data, binary) {
if (binary) {
_cliTools().logger.error('Expected text message, got binary!');
return undefined;
}
try {
const message = JSON.parse(data);
if (message.version === PROTOCOL_VERSION) {
return message;
}
_cliTools().logger.error(`Received message had wrong protocol version: ${message.version}`);
} catch (e) {
_cliTools().logger.error(`Failed to parse the message as JSON:\n${data}`);
}
return undefined;
}
function isBroadcast(message) {
return typeof message.method === 'string' && message.id === undefined && message.target === undefined;
}
function isRequest(message) {
return typeof message.method === 'string' && typeof message.target === 'string';
}
function isResponse(message) {
return typeof message.id === 'object' && typeof message.id.requestId !== 'undefined' && typeof message.id.clientId === 'string' && (message.result !== undefined || message.error !== undefined);
}
function attachToServer(server, path) {
const wss = new (_ws().Server)({
server,
path
});
const clients = new Map();
let nextClientId = 0;
function getClientWs(clientId) {
const clientWs = clients.get(clientId);
if (clientWs === undefined) {
throw new Error(`could not find id "${clientId}" while forwarding request`);
}
return clientWs;
}
function handleSendBroadcast(broadcasterId, message) {
const forwarded = {
version: PROTOCOL_VERSION,
method: message.method,
params: message.params
};
if (clients.size === 0) {
_cliTools().logger.warn(`No apps connected. Sending "${message.method}" to all React Native apps failed. Make sure your app is running in the simulator or on a phone connected via USB.`);
}
for (const [otherId, otherWs] of clients) {
if (otherId !== broadcasterId) {
try {
otherWs.send(JSON.stringify(forwarded));
} catch (e) {
_cliTools().logger.error(`Failed to send broadcast to client: '${otherId}' ` + `due to:\n ${e.toString()}`);
}
}
}
}
wss.on('connection', clientWs => {
const clientId = `client#${nextClientId++}`;
function handleCaughtError(message, error) {
const errorMessage = {
id: message.id,
method: message.method,
target: message.target,
error: message.error === undefined ? 'undefined' : 'defined',
params: message.params === undefined ? 'undefined' : 'defined',
result: message.result === undefined ? 'undefined' : 'defined'
};
if (message.id === undefined) {
_cliTools().logger.error(`Handling message from ${clientId} failed with:\n${error}\n` + `message:\n${JSON.stringify(errorMessage)}`);
} else {
try {
clientWs.send(JSON.stringify({
version: PROTOCOL_VERSION,
error,
id: message.id
}));
} catch (e) {
_cliTools().logger.error(`Failed to reply to ${clientId} with error:\n${error}` + `\nmessage:\n${JSON.stringify(errorMessage)}` + `\ndue to error: ${e.toString()}`);
}
}
}
function handleServerRequest(message) {
let result = null;
switch (message.method) {
case 'getid':
result = clientId;
break;
case 'getpeers':
result = {};
clients.forEach((otherWs, otherId) => {
if (clientId !== otherId) {
result[otherId] = _url().default.parse(otherWs.upgradeReq.url, true).query;
}
});
break;
default:
throw new Error(`unknown method: ${message.method}`);
}
clientWs.send(JSON.stringify({
version: PROTOCOL_VERSION,
result,
id: message.id
}));
}
function forwardRequest(message) {
getClientWs(message.target).send(JSON.stringify({
version: PROTOCOL_VERSION,
method: message.method,
params: message.params,
id: message.id === undefined ? undefined : {
requestId: message.id,
clientId
}
}));
}
function forwardResponse(message) {
if (!message.id) {
return;
}
getClientWs(message.id.clientId).send(JSON.stringify({
version: PROTOCOL_VERSION,
result: message.result,
error: message.error,
id: message.id.requestId
}));
}
clients.set(clientId, clientWs);
const onCloseHandler = () => {
// @ts-ignore
clientWs.onmessage = null;
clients.delete(clientId);
};
clientWs.onclose = onCloseHandler;
clientWs.onerror = onCloseHandler;
clientWs.onmessage = event => {
const message = parseMessage(event.data, event.binary);
if (message === undefined) {
_cliTools().logger.error('Received message not matching protocol');
return;
}
try {
if (isBroadcast(message)) {
handleSendBroadcast(clientId, message);
} else if (isRequest(message)) {
if (message.target === 'server') {
handleServerRequest(message);
} else {
forwardRequest(message);
}
} else if (isResponse(message)) {
forwardResponse(message);
} else {
throw new Error('Invalid message, did not match the protocol');
}
} catch (e) {
handleCaughtError(message, e.toString());
}
};
});
return {
broadcast: (method, params) => {
handleSendBroadcast(null, {
method,
params
});
}
};
}
var _default = {
attachToServer,
parseMessage
};
exports.default = _default;
//# sourceMappingURL=messageSocketServer.js.map