Skip to content
This repository has been archived by the owner on Jan 18, 2024. It is now read-only.

Commit

Permalink
refactor: add @expo/dev-server
Browse files Browse the repository at this point in the history
  • Loading branch information
fson committed Apr 9, 2020
1 parent 60acc59 commit bddf261
Show file tree
Hide file tree
Showing 12 changed files with 1,261 additions and 10 deletions.
2 changes: 2 additions & 0 deletions packages/dev-server/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
node_modules
build
22 changes: 22 additions & 0 deletions packages/dev-server/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
The MIT License (MIT)

Copyright (c) 2015-present 650 Industries, Inc. (aka Expo)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

1 change: 1 addition & 0 deletions packages/dev-server/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
# dev-server
11 changes: 11 additions & 0 deletions packages/dev-server/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module.exports = function(api) {
api.cache(true);
return {
// Only use this when running tests
env: {
test: {
presets: ['@expo/babel-preset-cli'],
},
},
};
};
58 changes: 58 additions & 0 deletions packages/dev-server/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
{
"name": "@expo/dev-server",
"version": "0.0.0",
"description": "Development servers for starting React Native projects",
"main": "build/MetroDevServer.js",
"scripts": {
"watch": "tsc --watch",
"build": "tsc",
"prepare": "yarn run clean && yarn build",
"clean": "rm -rf build ./tsconfig.tsbuildinfo",
"lint": "eslint .",
"test": "jest"
},
"jest": {
"testEnvironment": "node",
"roots": [
"src"
]
},
"repository": {
"type": "git",
"url": "https://github.com/expo/expo-cli.git",
"directory": "packages/dev-server"
},
"keywords": [
"json",
"react-native",
"expo",
"react",
"metro",
"dev-server",
"bundler"
],
"license": "MIT",
"bugs": {
"url": "https://github.com/expo/expo-cli/issues"
},
"homepage": "https://github.com/expo/expo-cli/tree/master/packages/dev-server#readme",
"files": [
"build",
"external"
],
"dependencies": {
"@expo/config": "^2.5.0",
"@expo/metro-config": "0.0.3",
"metro": "^0.58.0"
},
"devDependencies": {
"@expo/babel-preset-cli": "^0.2.1",
"@expo/bunyan": "^3.0.2",
"body-parser": "^1.19.0",
"jest": "^25.3.0",
"node-fetch": "^2.6.0"
},
"publishConfig": {
"access": "public"
}
}
40 changes: 40 additions & 0 deletions packages/dev-server/src/MetroDevServer.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import Metro from 'metro';
import { createDevServerMiddleware } from '@react-native-community/dev-server-api';
import * as ExpoMetroConfig from '@expo/metro-config';

export async function runMetroDevServerAsync(
projectRoot: string,
options: ExpoMetroConfig.LoadOptions
) {
let reportEvent: ((event: any) => void) | undefined;
// TODO(ville): implement a reporter
const reporter = {
update(event: any) {
const { type, ...data } = event;
console.log(`[${event.type}]`, data);
if (reportEvent) {
reportEvent(event);
}
},
};

const metroConfig = await ExpoMetroConfig.loadAsync(projectRoot, { reporter, ...options });

const { middleware, attachToServer } = createDevServerMiddleware({
port: metroConfig.server.port,
watchFolders: metroConfig.watchFolders,
});

const customEnhanceMiddleware = metroConfig.server.enhanceMiddleware;
metroConfig.server.enhanceMiddleware = (metroMiddleware: any, server: unknown) => {
if (customEnhanceMiddleware) {
metroMiddleware = customEnhanceMiddleware(metroMiddleware, server);
}
return middleware.use(metroMiddleware);
};

const serverInstance = await Metro.runServer(metroConfig, { hmrEnabled: true });

const { eventsSocket } = attachToServer(serverInstance);
reportEvent = eventsSocket.reportEvent;
}
85 changes: 85 additions & 0 deletions packages/dev-server/src/metro/middleware/clientLogsMiddleware.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import http from 'http';

import { Logger, ProjectUtils } from '@expo/xdl';
import { createMiddlewareWithURL } from '../utils';
import { RawRequest } from '../index.types';

export default (projectRoot: string) =>
createMiddlewareWithURL(
// @ts-ignore
async (req: RawRequest, res: http.ServerResponse, next: (err?: any) => void) => {
try {
let deviceId = req.headers['Device-Id'] as string;
let deviceName = req.headers['Device-Name'] as string;
// @ts-ignore
const rawBody = req.rawBody;
if (deviceId && deviceName && rawBody) {
_handleDeviceLogs(projectRoot, deviceId, deviceName, rawBody);
}
} catch (e) {
ProjectUtils.logError(projectRoot, 'expo', `Error getting device logs: ${e} ${e.stack}`);
}
res.end('Success');
},
['/logs']
);

function _isIgnorableBugReportingExtraData(body: any[]) {
return body.length === 2 && body[0] === 'BugReporting extraData:';
}

function _isAppRegistryStartupMessage(body: any[]) {
return (
body.length === 1 &&
(/^Running application "main" with appParams:/.test(body[0]) ||
/^Running "main" with \{/.test(body[0]))
);
}

function _handleDeviceLogs(projectRoot: string, deviceId: string, deviceName: string, logs: any) {
for (let i = 0; i < logs.length; i++) {
let log = logs[i];
let body = typeof log.body === 'string' ? [log.body] : log.body;
let { level } = log;

if (_isIgnorableBugReportingExtraData(body)) {
level = Logger.DEBUG;
}
if (_isAppRegistryStartupMessage(body)) {
body = [`Running application on ${deviceName}.`];
}

let string = body
.map((obj: any) => {
if (typeof obj === 'undefined') {
return 'undefined';
}
if (obj === 'null') {
return 'null';
}
if (typeof obj === 'string' || typeof obj === 'number' || typeof obj === 'boolean') {
return obj;
}
try {
return JSON.stringify(obj);
} catch (e) {
return obj.toString();
}
})
.join(' ');

ProjectUtils.logWithLevel(
projectRoot,
level,
{
tag: 'device',
deviceId,
deviceName,
groupDepth: log.groupDepth,
shouldHide: log.shouldHide,
includesStack: log.includesStack,
},
string
);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`logs messages from the device 1`] = `
Array [
"iPhone: [info] Hello world!",
"iPhone: [error] Something went wrong...",
]
`;
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import http from 'http';

import bodyParser from 'body-parser';
import bunyan from '@expo/bunyan';
import connect from 'connect';
import fetch from 'node-fetch';

import clientLogsMiddleware from '../clientLogsMiddleware';

const headers = {
'content-type': 'application/json',
'device-id': '11111111-CAFE-0000-0000-111111111111',
'session-id': '22222222-C0DE-0000-0000-222222222222',
'device-name': 'iPhone',
};

it('logs messages from the device', async () => {
const { server, url, logStream } = await createServerAsync();
try {
const response = await fetch(`${url}/logs`, {
method: 'POST',
headers,
body: JSON.stringify([
{
count: 1,
level: 'info',
body: ['Hello world!'],
includesStack: false,
groupDepth: 0,
},
{
count: 2,
level: 'error',
body: [
{
message: 'Something went wrong...',
stack: 'App.js:3:12 in <global>',
},
],
includesStack: true,
groupDepth: 0,
},
{
// We want this to be filtered out.
count: 3,
level: 'info',
body: [
'BugReporting extraData:',
'Object {\n' +
' "AppRegistry.runApplication1": "Running \\"main\\" with yada yada yada",\n' +
'}',
],
includesStack: false,
groupDepth: 0,
},
]),
});
expect(response.ok).toBe(true);
expect(logStream.output).toMatchSnapshot();
} finally {
server.close();
}
});

class TestLogStream {
output: string[] = [];

write(record: any) {
const message = record.includesStack ? JSON.parse(record.msg).message : record.msg;
const deviceName = record.deviceName ?? '';
if (record.level < bunyan.INFO) {
this.output.push(`${deviceName}: [debug] ${message}`);
} else if (record.level < bunyan.WARN) {
this.output.push(`${deviceName}: [info] ${message}`);
} else if (record.level < bunyan.ERROR) {
this.output.push(`${deviceName}: [warn] ${message}`);
} else {
this.output.push(`${deviceName}: [error] ${message}`);
}
}
}

async function createServerAsync() {
const logStream = new TestLogStream();
const logger = bunyan.createLogger({
name: 'expo-test',
streams: [
{
type: 'raw',
stream: logStream,
level: 'info',
},
],
});
const app = connect()
.use(bodyParser.json())
.use(clientLogsMiddleware(logger));

const server = http.createServer(app);
await new Promise((resolve, reject) =>
server.listen((error: any) => {
if (error) reject(error);
else resolve();
})
);

return {
server,
url: `http://localhost:${server.address().port}`,
logStream,
};
}
Loading

0 comments on commit bddf261

Please sign in to comment.