Add prettier to metro-bundler

Reviewed By: mjesun

Differential Revision: D6187278

fbshipit-source-id: 05b0881743b69c4a1eb491a6f8c57581081a85e4
This commit is contained in:
Rafael Oleza 2017-10-31 03:44:59 -07:00 committed by Facebook Github Bot
parent bada7f8684
commit 2850627a66
54 changed files with 1229 additions and 847 deletions

29
flow-typed/Promise.js vendored
View File

@ -8,6 +8,7 @@
*
* @flow
* @nolint
* @format
*/
/* eslint-disable */
@ -16,23 +17,25 @@
// tweaked so that then() and catch() accept `null` arguments, that they
// rightfully do. This should probably be changed in the core lib eventually.
declare class Promise<+R> {
constructor(callback: (
resolve: (result?: Promise<R> | R) => void,
reject: (error?: any) => void
) => mixed): void;
constructor(
callback: (
resolve: (result?: Promise<R> | R) => void,
reject: (error?: any) => void,
) => mixed,
): void,
then<U>(
onFulfill?: ?(value: R) => Promise<U> | ?U,
onReject?: ?(error: any) => Promise<U> | ?U
): Promise<U>;
onReject?: ?(error: any) => Promise<U> | ?U,
): Promise<U>,
catch<U>(
onReject?: (error: any) => ?Promise<U> | U
): Promise<U>;
catch<U>(onReject?: (error: any) => ?Promise<U> | U): Promise<U>,
static resolve<T>(object?: Promise<T> | T): Promise<T>;
static reject<T>(error?: mixed): Promise<T>;
static resolve<T>(object?: Promise<T> | T): Promise<T>,
static reject<T>(error?: mixed): Promise<T>,
static all<T: Iterable<mixed>>(promises: T): Promise<$TupleMap<T, typeof $await>>;
static race<T>(promises: Array<Promise<T>>): Promise<T>;
static all<T: Iterable<mixed>>(
promises: T,
): Promise<$TupleMap<T, typeof $await>>,
static race<T>(promises: Array<Promise<T>>): Promise<T>,
}

31
flow-typed/console.js vendored
View File

@ -6,29 +6,30 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
declare module "console" {
declare module 'console' {
declare export class Console {
constructor(stdout: mixed, stderr: mixed): void;
assert(value: mixed, message?: string, ...messageParts: Array<mixed>): void;
dir(data: mixed, options?: Object): void;
constructor(stdout: mixed, stderr: mixed): void,
assert(value: mixed, message?: string, ...messageParts: Array<mixed>): void,
dir(data: mixed, options?: Object): void,
error(msg: string, ...msgParts: Array<mixed>): void;
error(data: mixed): void;
error(msg: string, ...msgParts: Array<mixed>): void,
error(data: mixed): void,
info(msg: string, ...msgParts: Array<mixed>): void;
info(data: mixed): void;
info(msg: string, ...msgParts: Array<mixed>): void,
info(data: mixed): void,
log(msg: string, ...msgParts: Array<mixed>): void;
log(data: mixed): void;
log(msg: string, ...msgParts: Array<mixed>): void,
log(data: mixed): void,
time(label: string): void;
timeEnd(label: string): void;
trace(msg: string, ...msgParts: Array<mixed>): void;
time(label: string): void,
timeEnd(label: string): void,
trace(msg: string, ...msgParts: Array<mixed>): void,
warn(msg: string, ...msgParts: Array<mixed>): void;
warn(data: mixed): void;
warn(msg: string, ...msgParts: Array<mixed>): void,
warn(data: mixed): void,
}
}

View File

@ -6,161 +6,314 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
declare module "graceful-fs" {
declare module 'graceful-fs' {
declare class Stats {
dev: number;
ino: number;
mode: number;
nlink: number;
uid: number;
gid: number;
rdev: number;
size: number;
blksize: number;
blocks: number;
atime: Date;
mtime: Date;
ctime: Date;
dev: number,
ino: number,
mode: number,
nlink: number,
uid: number,
gid: number,
rdev: number,
size: number,
blksize: number,
blocks: number,
atime: Date,
mtime: Date,
ctime: Date,
isFile(): boolean;
isDirectory(): boolean;
isBlockDevice(): boolean;
isCharacterDevice(): boolean;
isSymbolicLink(): boolean;
isFIFO(): boolean;
isSocket(): boolean;
isFile(): boolean,
isDirectory(): boolean,
isBlockDevice(): boolean,
isCharacterDevice(): boolean,
isSymbolicLink(): boolean,
isFIFO(): boolean,
isSocket(): boolean,
}
declare class FSWatcher extends events$EventEmitter {
close(): void
close(): void,
}
declare class ReadStream extends stream$Readable {
close(): void
close(): void,
}
declare class WriteStream extends stream$Writable {
close(): void
close(): void,
}
declare function gracefulify(fs: Object): void;
declare function rename(oldPath: string, newPath: string, callback?: (err: ?Error) => void): void;
declare function rename(
oldPath: string,
newPath: string,
callback?: (err: ?Error) => void,
): void;
declare function renameSync(oldPath: string, newPath: string): void;
declare function ftruncate(fd: number, len: number, callback?: (err: ?Error) => void): void;
declare function ftruncate(
fd: number,
len: number,
callback?: (err: ?Error) => void,
): void;
declare function ftruncateSync(fd: number, len: number): void;
declare function truncate(path: string, len: number, callback?: (err: ?Error) => void): void;
declare function truncate(
path: string,
len: number,
callback?: (err: ?Error) => void,
): void;
declare function truncateSync(path: string, len: number): void;
declare function chown(path: string, uid: number, gid: number, callback?: (err: ?Error) => void): void;
declare function chown(
path: string,
uid: number,
gid: number,
callback?: (err: ?Error) => void,
): void;
declare function chownSync(path: string, uid: number, gid: number): void;
declare function fchown(fd: number, uid: number, gid: number, callback?: (err: ?Error) => void): void;
declare function fchown(
fd: number,
uid: number,
gid: number,
callback?: (err: ?Error) => void,
): void;
declare function fchownSync(fd: number, uid: number, gid: number): void;
declare function lchown(path: string, uid: number, gid: number, callback?: (err: ?Error) => void): void;
declare function lchown(
path: string,
uid: number,
gid: number,
callback?: (err: ?Error) => void,
): void;
declare function lchownSync(path: string, uid: number, gid: number): void;
declare function chmod(path: string, mode: number | string, callback?: (err: ?Error) => void): void;
declare function chmod(
path: string,
mode: number | string,
callback?: (err: ?Error) => void,
): void;
declare function chmodSync(path: string, mode: number | string): void;
declare function fchmod(fd: number, mode: number | string, callback?: (err: ?Error) => void): void;
declare function fchmod(
fd: number,
mode: number | string,
callback?: (err: ?Error) => void,
): void;
declare function fchmodSync(fd: number, mode: number | string): void;
declare function lchmod(path: string, mode: number | string, callback?: (err: ?Error) => void): void;
declare function lchmod(
path: string,
mode: number | string,
callback?: (err: ?Error) => void,
): void;
declare function lchmodSync(path: string, mode: number | string): void;
declare function stat(path: string, callback?: (err: ?Error, stats: Stats) => any): void;
declare function stat(
path: string,
callback?: (err: ?Error, stats: Stats) => any,
): void;
declare function statSync(path: string): Stats;
declare function fstat(fd: number, callback?: (err: ?Error, stats: Stats) => any): void;
declare function fstat(
fd: number,
callback?: (err: ?Error, stats: Stats) => any,
): void;
declare function fstatSync(fd: number): Stats;
declare function lstat(path: string, callback?: (err: ?Error, stats: Stats) => any): void;
declare function lstat(
path: string,
callback?: (err: ?Error, stats: Stats) => any,
): void;
declare function lstatSync(path: string): Stats;
declare function link(srcpath: string, dstpath: string, callback?: (err: ?Error) => void): void;
declare function link(
srcpath: string,
dstpath: string,
callback?: (err: ?Error) => void,
): void;
declare function linkSync(srcpath: string, dstpath: string): void;
declare function symlink(srcpath: string, dtspath: string, type?: string, callback?: (err: ?Error) => void): void;
declare function symlinkSync(srcpath: string, dstpath: string, type: string): void;
declare function readlink(path: string, callback: (err: ?Error, linkString: string) => void): void;
declare function symlink(
srcpath: string,
dtspath: string,
type?: string,
callback?: (err: ?Error) => void,
): void;
declare function symlinkSync(
srcpath: string,
dstpath: string,
type: string,
): void;
declare function readlink(
path: string,
callback: (err: ?Error, linkString: string) => void,
): void;
declare function readlinkSync(path: string): string;
declare function realpath(path: string, cache?: Object, callback?: (err: ?Error, resolvedPath: string) => void): void;
declare function realpath(
path: string,
cache?: Object,
callback?: (err: ?Error, resolvedPath: string) => void,
): void;
declare function realpathSync(path: string, cache?: Object): string;
declare function unlink(path: string, callback?: (err: ?Error) => void): void;
declare function unlinkSync(path: string): void;
declare function rmdir(path: string, callback?: (err: ?Error) => void): void;
declare function rmdirSync(path: string): void;
declare function mkdir(path: string, mode?: number, callback?: (err: ?Error) => void): void;
declare function mkdir(
path: string,
mode?: number,
callback?: (err: ?Error) => void,
): void;
declare function mkdirSync(path: string, mode?: number): void;
declare function readdir(path: string, callback?: (err: ?Error, files: Array<string>) => void): void;
declare function readdir(
path: string,
callback?: (err: ?Error, files: Array<string>) => void,
): void;
declare function readdirSync(path: string): Array<string>;
declare function close(fd: number, callback?: (err: ?Error) => void): void;
declare function closeSync(fd: number): void;
declare function open(path: string, flags: string, mode?: number, callback?: (err: ?Error, fd: number) => void): void;
declare function open(
path: string,
flags: string,
mode?: number,
callback?: (err: ?Error, fd: number) => void,
): void;
declare function openSync(path: string, flags: string, mode?: number): number;
declare function utimes(path: string, atime: number, mtime: number, callback?: (err: ?Error) => void): void;
declare function utimes(
path: string,
atime: number,
mtime: number,
callback?: (err: ?Error) => void,
): void;
declare function utimesSync(path: string, atime: number, mtime: number): void;
declare function futimes(fd: number, atime: number, mtime: number, callback?: (err: ?Error) => void): void;
declare function futimes(
fd: number,
atime: number,
mtime: number,
callback?: (err: ?Error) => void,
): void;
declare function futimesSync(fd: number, atime: number, mtime: number): void;
declare function fsync(fd: number, callback?: (err: ?Error) => void): void;
declare function fsyncSync(fd: number): void;
declare var write: (fd: number, buffer: Buffer, offset: number, length: number, position?: mixed, callback?: (err: ?Error, write: number, str: string) => void) => void
| (fd: number, data: mixed, position?: mixed, encoding?: string, callback?: (err: ?Error, write: number, str: string) => void) => void;
declare var writeSync: (fd: number, buffer: Buffer, offset: number, length: number, position?: number) => number
| (fd: number, data: mixed, position?: mixed, encoding?: string) => number;
declare var write: (
fd: number,
buffer: Buffer,
offset: number,
length: number,
position?: mixed,
callback?: (err: ?Error, write: number, str: string) => void,
) =>
| void
| ((
fd: number,
data: mixed,
position?: mixed,
encoding?: string,
callback?: (err: ?Error, write: number, str: string) => void,
) => void);
declare var writeSync: (
fd: number,
buffer: Buffer,
offset: number,
length: number,
position?: number,
) =>
| number
| ((
fd: number,
data: mixed,
position?: mixed,
encoding?: string,
) => number);
declare function read(
fd: number,
buffer: Buffer,
offset: number,
length: number,
position: ?number,
callback?: (err: ?Error, bytesRead: number, buffer: Buffer) => void
callback?: (err: ?Error, bytesRead: number, buffer: Buffer) => void,
): void;
declare function readSync(
fd: number,
buffer: Buffer,
offset: number,
length: number,
position: number
position: number,
): number;
declare function readFile(
filename: string,
callback: (err: ?Error, data: Buffer) => void
callback: (err: ?Error, data: Buffer) => void,
): void;
declare function readFile(
filename: string,
encoding: string,
callback: (err: ?Error, data: string) => void
callback: (err: ?Error, data: string) => void,
): void;
declare function readFile(
filename: string,
options: { encoding: string; flag?: string },
callback: (err: ?Error, data: string) => void
options: {encoding: string, flag?: string},
callback: (err: ?Error, data: string) => void,
): void;
declare function readFile(
filename: string,
options: { flag?: string },
callback: (err: ?Error, data: Buffer) => void
options: {flag?: string},
callback: (err: ?Error, data: Buffer) => void,
): void;
declare function readFileSync(filename: string, _: void): Buffer;
declare function readFileSync(filename: string, encoding: string): string;
declare function readFileSync(filename: string, options: { encoding: string, flag?: string }): string;
declare function readFileSync(filename: string, options: { encoding?: void, flag?: string }): Buffer;
declare function readFileSync(
filename: string,
options: {encoding: string, flag?: string},
): string;
declare function readFileSync(
filename: string,
options: {encoding?: void, flag?: string},
): Buffer;
declare function writeFile(
filename: string,
data: Buffer | string,
options?: Object | string,
callback?: (err: ?Error) => void
callback?: (err: ?Error) => void,
): void;
declare function writeFileSync(
filename: string,
data: Buffer | string,
options?: Object | string
options?: Object | string,
): void;
declare function appendFile(
filename: string,
data: string | Buffer,
options?: Object,
callback?: (err: ?Error) => void,
): void;
declare function appendFileSync(
filename: string,
data: string | Buffer,
options?: Object,
): void;
declare function watchFile(
filename: string,
options?: Object,
listener?: (curr: Stats, prev: Stats) => void,
): void;
declare function unwatchFile(
filename: string,
listener?: (curr: Stats, prev: Stats) => void,
): void;
declare function watch(
filename: string,
options?: Object,
listener?: (event: string, filename: string) => void,
): FSWatcher;
declare function exists(
path: string,
callback?: (exists: boolean) => void,
): void;
declare function appendFile(filename: string, data: string | Buffer, options?: Object, callback?: (err: ?Error) => void): void;
declare function appendFileSync(filename: string, data: string | Buffer, options?: Object): void;
declare function watchFile(filename: string, options?: Object, listener?: (curr: Stats, prev: Stats) => void): void;
declare function unwatchFile(filename: string, listener?: (curr: Stats, prev: Stats) => void): void;
declare function watch(filename: string, options?: Object, listener?: (event: string, filename: string) => void): FSWatcher;
declare function exists(path: string, callback?: (exists: boolean) => void): void;
declare function existsSync(path: string): boolean;
declare function access(path: string, mode?: any, callback?: (err: ?Error) => void): void;
declare function access(
path: string,
mode?: any,
callback?: (err: ?Error) => void,
): void;
declare function accessSync(path: string, mode?: any): void;
declare function createReadStream(path: string, options?: Object): ReadStream;
declare function createWriteStream(path: string, options?: Object): WriteStream;
declare function createWriteStream(
path: string,
options?: Object,
): WriteStream;
declare var F_OK: number;
declare var R_OK: number;

56
flow-typed/uglify.js vendored
View File

@ -5,6 +5,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
'use strict';
@ -14,25 +16,28 @@ type _Input =
| Array<string> // array of file names
| {[filename: string]: string}; // file names and corresponding code
type _Options = {
// https://github.com/mishoo/UglifyJS2/tree/harmony#compress-options
compress?: false | Object,
ie8?: boolean,
mangle?: boolean | {
eval?: boolean,
keep_fnames?: boolean,
properties?: boolean | {
builtins?: boolean,
debug?: boolean,
keep_quoted?: boolean,
regex?: RegExp,
reserved?: Array<string>,
},
reserved?: Array<string>,
safari10?: boolean,
toplevel?: boolean,
},
mangle?:
| boolean
| {
eval?: boolean,
keep_fnames?: boolean,
properties?:
| boolean
| {
builtins?: boolean,
debug?: boolean,
keep_quoted?: boolean,
regex?: RegExp,
reserved?: Array<string>,
},
reserved?: Array<string>,
safari10?: boolean,
toplevel?: boolean,
},
output?: {
ascii_only?: boolean,
beautify?: boolean,
@ -73,22 +78,21 @@ type _SourceMap = {
version: number,
};
type _SourceMapOptions = true | {
filename?: string,
content?: ?string | _SourceMap,
includeSources?: boolean,
root?: string,
url?: string,
};
type _SourceMapOptions =
| true
| {
filename?: string,
content?: ?string | _SourceMap,
includeSources?: boolean,
root?: string,
url?: string,
};
type _Error = {|error: Error|};
type _Result = {|code: string, warnings?: Array<string>|};
declare module 'uglify-es' {
declare function minify(
code: _Input,
options?: _Options,
): _Error | _Result;
declare function minify(code: _Input, options?: _Options): _Error | _Result;
declare function minify(
code: _Input,
options: {..._Options, sourceMap: _SourceMapOptions},

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*
*/
'use strict';

View File

@ -5,12 +5,16 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
'use strict';
const mockColor = () => {
return {
bold: () => { return { }; },
bold: () => {
return {};
},
};
};
@ -23,7 +27,7 @@ mockColor.bgRed = function() {
};
module.exports = {
dim: s => s,
dim: s => s,
magenta: mockColor,
white: mockColor,
blue: mockColor,

View File

@ -8,6 +8,8 @@
*
* eslint-disable no-console
*
*
* @format
*/
'use strict';
@ -50,7 +52,9 @@ describe('Logger', () => {
});
it('creates action end log entries', () => {
const actionEndLogEntry = createActionEndEntry(createActionStartEntry('Test'));
const actionEndLogEntry = createActionEndEntry(
createActionStartEntry('Test'),
);
expect(actionEndLogEntry).toEqual({
action_name: 'Test',
action_phase: 'end',

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -17,11 +18,7 @@ const {EventEmitter} = require('events');
const VERSION = require('../../package.json').version;
import type {
ActionLogEntryData,
ActionStartLogEntry,
LogEntry,
} from './Types';
import type {ActionLogEntryData, ActionStartLogEntry, LogEntry} from './Types';
const log_session = `${os.hostname()}-${Date.now()}`;
const eventEmitter = new EventEmitter();
@ -54,11 +51,7 @@ function createActionStartEntry(data: ActionLogEntryData | string): LogEntry {
}
function createActionEndEntry(logEntry: ActionStartLogEntry): LogEntry {
const {
action_name,
action_phase,
start_timestamp,
} = logEntry;
const {action_name, action_phase, start_timestamp} = logEntry;
if (action_phase !== 'start' || !Array.isArray(start_timestamp)) {
throw new Error('Action has not started or has already ended');

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -26,11 +27,8 @@ const NO_OPTIONS = {};
exports.create = function create(resolve: ResolveFn, load: LoadFn): GraphFn {
async function Graph(entryPoints, platform, options) {
const {
log = (console: any),
optimize = false,
skip,
} = options || NO_OPTIONS;
const {log = (console: any), optimize = false, skip} =
options || NO_OPTIONS;
if (typeof platform !== 'string') {
log.error('`Graph`, called without a platform');
@ -40,8 +38,21 @@ exports.create = function create(resolve: ResolveFn, load: LoadFn): GraphFn {
const loadOptions = {log, optimize};
const memoizingLoad = memoizeLoad(load);
const queue: Queue<{id: string, parent: ?string, parentDependencyIndex: number, skip: ?Set<string>}, LoadResult, Map<?string, Module>> = new Queue(
({id, parent}) => memoizingLoad(resolve(id, parent, platform, options || NO_OPTIONS), loadOptions),
const queue: Queue<
{
id: string,
parent: ?string,
parentDependencyIndex: number,
skip: ?Set<string>,
},
LoadResult,
Map<?string, Module>,
> = new Queue(
({id, parent}) =>
memoizingLoad(
resolve(id, parent, platform, options || NO_OPTIONS),
loadOptions,
),
onFileLoaded,
new Map([[null, emptyModule()]]),
);
@ -55,10 +66,11 @@ exports.create = function create(resolve: ResolveFn, load: LoadFn): GraphFn {
if (tasks.length === 0) {
log.error('`Graph` called without any entry points');
return Promise.reject(new Error('At least one entry point has to be passed.'));
return Promise.reject(
new Error('At least one entry point has to be passed.'),
);
}
queue.enqueue(...tasks);
return collect(await queue.result);
}
@ -77,7 +89,11 @@ class Queue<T, R, A> {
_running: boolean;
result: Promise<A>;
constructor(runTask: T => R | Promise<R>, accumulate: (Queue<T, R, A>, A, R, T) => A, initial: A) {
constructor(
runTask: T => R | Promise<R>,
accumulate: (Queue<T, R, A>, A, R, T) => A,
initial: A,
) {
this._runTask = runTask;
this._accumulate = accumulate;
this._result = initial;
@ -117,7 +133,10 @@ class Queue<T, R, A> {
const result = runTask(task);
if (isPromise(result)) {
this._pending.add(task);
result.then(result => this._onAsyncTaskDone(result, task), this._reject);
result.then(
result => this._onAsyncTaskDone(result, task),
this._reject,
);
} else {
this._onTaskDone(result, task);
}
@ -130,7 +149,12 @@ class Queue<T, R, A> {
}
}
function onFileLoaded(queue, modules, {file, dependencies}, {id, parent, parentDependencyIndex, skip}) {
function onFileLoaded(
queue,
modules,
{file, dependencies},
{id, parent, parentDependencyIndex, skip},
) {
const {path} = file;
const parentModule = modules.get(parent);
@ -139,12 +163,14 @@ function onFileLoaded(queue, modules, {file, dependencies}, {id, parent, parentD
if ((!skip || !skip.has(path)) && !modules.has(path)) {
modules.set(path, {file, dependencies: Array(dependencies.length)});
queue.enqueue(...dependencies.map((id, i) => ({
id,
parent: path,
parentDependencyIndex: i,
skip,
})));
queue.enqueue(
...dependencies.map((id, i) => ({
id,
parent: path,
parentDependencyIndex: i,
skip,
})),
);
}
return modules;
@ -163,8 +189,9 @@ function collect(
const {dependencies} = module;
if (path === null) {
serialized.entryModules =
dependencies.map(dep => nullthrows(modules.get(dep.path)));
serialized.entryModules = dependencies.map(dep =>
nullthrows(modules.get(dep.path)),
);
} else {
serialized.modules.push(module);
seen.add(path);

View File

@ -7,17 +7,17 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
import type {Module} from './types.flow';
exports.empty = (): Module => virtual('');
// creates a virtual module (i.e. not corresponding to a file on disk)
// with the given source code.
const virtual = exports.virtual = (code: string): Module => ({
const virtual = (exports.virtual = (code: string): Module => ({
dependencies: [],
file: {
code,
@ -25,4 +25,4 @@ const virtual = exports.virtual = (code: string): Module => ({
path: '',
type: 'script',
},
});
}));

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -51,9 +52,7 @@ module.exports = class HasteFS {
}
matchFiles() {
throw new Error(
'HasteFS.matchFiles is not implemented yet.'
);
throw new Error('HasteFS.matchFiles is not implemented yet.');
}
matches(directory: string, pattern: RegExp) {

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -59,7 +60,7 @@ module.exports = class ModuleCache {
getPackageData(path: string): PackageData {
const pkg = this.getTransformedFile(path).package;
if (!pkg) {
throw new Error(`"${path}" does not exist`);
throw new Error(`"${path}" does not exist`);
}
return pkg;
}

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -39,7 +40,8 @@ module.exports = class Package {
let main = getMain(this.data);
if (replacements && typeof replacements === 'object') {
main = replacements[main] ||
main =
replacements[main] ||
replacements[main + '.js'] ||
replacements[main + '.json'] ||
replacements[main.replace(/(\.js|\.json)$/, '')] ||
@ -68,9 +70,7 @@ module.exports = class Package {
if (!path.isAbsolute(name)) {
const replacement = replacements[name];
// support exclude with "someDependency": false
return replacement === false
? false
: replacement || name;
return replacement === false ? false : replacement || name;
}
let relPath = './' + path.relative(this.root, name);
@ -94,10 +94,7 @@ module.exports = class Package {
}
if (redirect) {
return path.join(
this.root,
redirect
);
return path.join(this.root, redirect);
}
return name;

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -44,7 +45,7 @@ export type ModuleCache = {
getModule(path: Path): Module,
getPackage(path: Path): Package,
getPackageOf(path: Path): ?Package,
}
};
export type FastFS = {
dirExists(path: Path): boolean,

View File

@ -5,6 +5,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
'use strict';

View File

@ -5,6 +5,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
'use strict';

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -18,7 +19,9 @@ import type {OptimizationOptions} from './worker/optimize-module';
import type {TransformOptions} from './worker/transform-module';
import type {WorkerFnWithIO} from './worker/wrap-worker-fn';
exports.optimizeModule =
(wrapWorkerFn(optimizeModule): WorkerFnWithIO<OptimizationOptions>);
exports.transformModule =
(wrapWorkerFn(transformModule): WorkerFnWithIO<TransformOptions<{+retainLines?: boolean}>>);
exports.optimizeModule = (wrapWorkerFn(optimizeModule): WorkerFnWithIO<
OptimizationOptions,
>);
exports.transformModule = (wrapWorkerFn(transformModule): WorkerFnWithIO<
TransformOptions<{+retainLines?: boolean}>,
>);

View File

@ -5,6 +5,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
'use strict';
@ -29,7 +31,9 @@ class MultipartResponse {
res.writeHead(200, {
'Content-Type': `multipart/mixed; boundary="${BOUNDARY}"`,
});
res.write('If you are seeing this, your client does not support multipart response');
res.write(
'If you are seeing this, your client does not support multipart response',
);
}
writeChunk(headers, data, isLast = false) {

View File

@ -5,6 +5,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
'use strict';
@ -36,29 +38,31 @@ describe('MultipartResponse', () => {
res.setHeader('Result-Header-2', 2);
res.end('Hello, world!');
expect(nres.toString()).toEqual([
'HTTP/1.1 200',
'Content-Type: multipart/mixed; boundary="3beqjf3apnqeu3h5jqorms4i"',
'',
'If you are seeing this, your client does not support multipart response',
'--3beqjf3apnqeu3h5jqorms4i',
'foo: bar',
'',
'first chunk',
'--3beqjf3apnqeu3h5jqorms4i',
'test: 2',
'',
'second chunk',
'--3beqjf3apnqeu3h5jqorms4i',
'empty headers third chunk',
'--3beqjf3apnqeu3h5jqorms4i',
'Result-Header-1: 1',
'Result-Header-2: 2',
'',
'Hello, world!',
'--3beqjf3apnqeu3h5jqorms4i--',
'',
].join('\r\n'));
expect(nres.toString()).toEqual(
[
'HTTP/1.1 200',
'Content-Type: multipart/mixed; boundary="3beqjf3apnqeu3h5jqorms4i"',
'',
'If you are seeing this, your client does not support multipart response',
'--3beqjf3apnqeu3h5jqorms4i',
'foo: bar',
'',
'first chunk',
'--3beqjf3apnqeu3h5jqorms4i',
'test: 2',
'',
'second chunk',
'--3beqjf3apnqeu3h5jqorms4i',
'empty headers third chunk',
'--3beqjf3apnqeu3h5jqorms4i',
'Result-Header-1: 1',
'Result-Header-2: 2',
'',
'Hello, world!',
'--3beqjf3apnqeu3h5jqorms4i--',
'',
].join('\r\n'),
);
});
it('sends status code as last chunk header', () => {
@ -72,23 +76,25 @@ describe('MultipartResponse', () => {
});
res.end('{}');
expect(nres.toString()).toEqual([
'HTTP/1.1 200',
'Content-Type: multipart/mixed; boundary="3beqjf3apnqeu3h5jqorms4i"',
'',
'If you are seeing this, your client does not support multipart response',
'--3beqjf3apnqeu3h5jqorms4i',
'foo: bar',
'',
'first chunk',
'--3beqjf3apnqeu3h5jqorms4i',
'X-Http-Status: 500',
'Content-Type: application/json; boundary="3beqjf3apnqeu3h5jqorms4i"',
'',
'{}',
'--3beqjf3apnqeu3h5jqorms4i--',
'',
].join('\r\n'));
expect(nres.toString()).toEqual(
[
'HTTP/1.1 200',
'Content-Type: multipart/mixed; boundary="3beqjf3apnqeu3h5jqorms4i"',
'',
'If you are seeing this, your client does not support multipart response',
'--3beqjf3apnqeu3h5jqorms4i',
'foo: bar',
'',
'first chunk',
'--3beqjf3apnqeu3h5jqorms4i',
'X-Http-Status: 500',
'Content-Type: application/json; boundary="3beqjf3apnqeu3h5jqorms4i"',
'',
'{}',
'--3beqjf3apnqeu3h5jqorms4i--',
'',
].join('\r\n'),
);
});
it('supports empty responses', () => {
@ -101,19 +107,21 @@ describe('MultipartResponse', () => {
});
res.end();
expect(nres.toString()).toEqual([
'HTTP/1.1 200',
'Content-Type: multipart/mixed; boundary="3beqjf3apnqeu3h5jqorms4i"',
'',
'If you are seeing this, your client does not support multipart response',
'--3beqjf3apnqeu3h5jqorms4i',
'X-Http-Status: 304',
'Content-Type: application/json; boundary="3beqjf3apnqeu3h5jqorms4i"',
'',
'',
'--3beqjf3apnqeu3h5jqorms4i--',
'',
].join('\r\n'));
expect(nres.toString()).toEqual(
[
'HTTP/1.1 200',
'Content-Type: multipart/mixed; boundary="3beqjf3apnqeu3h5jqorms4i"',
'',
'If you are seeing this, your client does not support multipart response',
'--3beqjf3apnqeu3h5jqorms4i',
'X-Http-Status: 304',
'Content-Type: application/json; boundary="3beqjf3apnqeu3h5jqorms4i"',
'',
'',
'--3beqjf3apnqeu3h5jqorms4i--',
'',
].join('\r\n'),
);
});
});
@ -130,9 +138,15 @@ function mockNodeResponse() {
status = st;
headers = {...headers, ...hdrs};
}),
setHeader: jest.fn((key, val) => { headers[key] = val; }),
write: jest.fn(data => { body += data; }),
end: jest.fn(data => { body += (data || ''); }),
setHeader: jest.fn((key, val) => {
headers[key] = val;
}),
write: jest.fn(data => {
body += data;
}),
end: jest.fn(data => {
body += data || '';
}),
// For testing only
toString() {

View File

@ -5,11 +5,12 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
'use strict';
jest.mock('child_process')
.mock('net');
jest.mock('child_process').mock('net');
const EventEmitter = require('events');
const {Readable} = require('stream');
@ -38,18 +39,17 @@ beforeEach(() => {
it('sends a socket path to the child process', () => {
socketResponse = '{}';
return worker([], fakeSourceMaps())
.then(() => expect(childProcess.send).toBeCalledWith(expect.any(String)));
return worker([], fakeSourceMaps()).then(() =>
expect(childProcess.send).toBeCalledWith(expect.any(String)),
);
});
it('fails if the child process emits an error', () => {
const error = new Error('Expected error');
childProcess.send.mockImplementation(() =>
childProcess.emit('error', error));
childProcess.send.mockImplementation(() => childProcess.emit('error', error));
expect.assertions(1);
return worker([], fakeSourceMaps())
.catch(e => expect(e).toBe(error));
return worker([], fakeSourceMaps()).catch(e => expect(e).toBe(error));
});
it('fails if the socket connection emits an error', () => {
@ -57,46 +57,51 @@ it('fails if the socket connection emits an error', () => {
socket._read = () => socket.emit('error', error);
expect.assertions(1);
return worker([], fakeSourceMaps())
.catch(e => expect(e).toBe(error));
return worker([], fakeSourceMaps()).catch(e => expect(e).toBe(error));
});
it('sends the passed in stack and maps over the socket', () => {
socketResponse = '{}';
const stack = ['the', 'stack'];
return worker(stack, fakeSourceMaps())
.then(() =>
expect(socket.end).toBeCalledWith(JSON.stringify({
return worker(stack, fakeSourceMaps()).then(() =>
expect(socket.end).toBeCalledWith(
JSON.stringify({
maps: Array.from(fakeSourceMaps()),
stack,
})));
}),
),
);
});
it('resolves to the `result` property of the message returned over the socket', () => {
socketResponse = '{"result": {"the": "result"}}';
return worker([], fakeSourceMaps())
.then(response => expect(response).toEqual({the: 'result'}));
return worker([], fakeSourceMaps()).then(response =>
expect(response).toEqual({the: 'result'}),
);
});
it('rejects with the `error` property of the message returned over the socket', () => {
socketResponse = '{"error": "the error message"}';
expect.assertions(1);
return worker([], fakeSourceMaps())
.catch(error => expect(error).toEqual(new Error('the error message')));
return worker([], fakeSourceMaps()).catch(error =>
expect(error).toEqual(new Error('the error message')),
);
});
it('rejects if the socket response cannot be parsed as JSON', () => {
socketResponse = '{';
expect.assertions(1);
return worker([], fakeSourceMaps())
.catch(error => expect(error).toBeInstanceOf(SyntaxError));
return worker([], fakeSourceMaps()).catch(error =>
expect(error).toBeInstanceOf(SyntaxError),
);
});
function setupCommunication() {
childProcess.send.mockImplementation(() =>
process.nextTick(() => childProcess.emit('message')));
process.nextTick(() => childProcess.emit('message')),
);
}
function* fakeSourceMaps() {

View File

@ -5,6 +5,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
'use strict';
@ -39,8 +41,7 @@ describe('Lazy Promise', () => {
describe('value and error propagation', () => {
it('resolves to the value provided by the factory', () => {
expect.assertions(1);
return new LazyPromise(factory)
.then(v => expect(v).toBe(value));
return new LazyPromise(factory).then(v => expect(v).toBe(value));
});
it('passes through errors if not handled', () => {
@ -48,9 +49,7 @@ describe('Lazy Promise', () => {
factory.mockReturnValue(Promise.reject(error));
expect.assertions(1);
return new LazyPromise(factory)
.then()
.catch(e => expect(e).toBe(error));
return new LazyPromise(factory).then().catch(e => expect(e).toBe(error));
});
it('uses rejection handlers passed to `then()`', () => {
@ -58,8 +57,10 @@ describe('Lazy Promise', () => {
factory.mockReturnValue(Promise.reject(error));
expect.assertions(1);
return new LazyPromise(factory)
.then(() => {}, e => expect(e).toBe(error));
return new LazyPromise(factory).then(
() => {},
e => expect(e).toBe(error),
);
});
it('uses rejection handlers passed to `catch()`', () => {
@ -67,8 +68,7 @@ describe('Lazy Promise', () => {
factory.mockReturnValue(Promise.reject(error));
expect.assertions(1);
return new LazyPromise(factory)
.catch(e => expect(e).toBe(error));
return new LazyPromise(factory).catch(e => expect(e).toBe(error));
});
});
});
@ -78,8 +78,9 @@ describe('Locking Promise', () => {
const value = {};
expect.assertions(1);
return new LockingPromise(Promise.resolve(value))
.then(v => expect(v).toBe(value));
return new LockingPromise(Promise.resolve(value)).then(v =>
expect(v).toBe(value),
);
});
it('passes through rejections', () => {
@ -95,16 +96,19 @@ describe('Locking Promise', () => {
const error = new Error('Must be handled');
expect.assertions(1);
return new LockingPromise(Promise.reject(error))
.then(x => x, e => expect(e).toBe(error));
return new LockingPromise(Promise.reject(error)).then(
x => x,
e => expect(e).toBe(error),
);
});
it('uses rejection handlers passed to `catch()`', () => {
const error = new Error('Must be handled');
expect.assertions(1);
return new LockingPromise(Promise.reject(error))
.catch(e => expect(e).toBe(error));
return new LockingPromise(Promise.reject(error)).catch(e =>
expect(e).toBe(error),
);
});
describe('locking', () => {
@ -114,7 +118,6 @@ describe('Locking Promise', () => {
locking = new LockingPromise(Promise.resolve(value));
});
it('only allows one handler to access the promise value', () => {
const deferred = defer();
const secondHandler = jest.fn();
@ -137,19 +140,19 @@ describe('Locking Promise', () => {
deferred.resolve();
return Promise.all([x, y, z])
.then(([first, second, third]) => {
expect(first).toEqual([1, value]);
expect(second).toEqual([2, value]);
expect(third).toEqual([3, value]);
});
return Promise.all([x, y, z]).then(([first, second, third]) => {
expect(first).toEqual([1, value]);
expect(second).toEqual([2, value]);
expect(third).toEqual([3, value]);
});
});
});
});
function defer() {
let resolve;
const promise = new Promise(res => { resolve = res; });
const promise = new Promise(res => {
resolve = res;
});
return {promise, resolve};
}

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -19,12 +20,14 @@ const xpipe = require('xpipe');
const {LazyPromise, LockingPromise} = require('./util');
const {fork} = require('child_process');
export type {SourceMap as SourceMap};
export type {SourceMap};
import type {SourceMap} from '../../lib/SourceMap';
export type Stack = Array<{file: string, lineNumber: number, column: number}>;
export type Symbolicate =
(Stack, Iterable<[string, SourceMap]>) => Promise<Stack>;
export type Symbolicate = (
Stack,
Iterable<[string, SourceMap]>,
) => Promise<Stack>;
const affixes = {prefix: 'metro-bundler-symbolicate', suffix: '.sock'};
const childPath = require.resolve('./worker');
@ -32,31 +35,29 @@ const childPath = require.resolve('./worker');
exports.createWorker = (): Symbolicate => {
// There are issues with named sockets on windows that cause the connection to
// close too early so run the symbolicate server on a random localhost port.
const socket = process.platform === 'win32'
? 34712
: xpipe.eq(temp.path(affixes));
const socket =
process.platform === 'win32' ? 34712 : xpipe.eq(temp.path(affixes));
const child = new LockingPromise(new LazyPromise(() => startupChild(socket)));
return (stack, sourceMaps) =>
child
.then(() => connectAndSendJob(socket, message(stack, sourceMaps)))
.then(JSON.parse)
.then(response =>
'error' in response
? Promise.reject(new Error(response.error))
: response.result
.then(
response =>
'error' in response
? Promise.reject(new Error(response.error))
: response.result,
);
};
function startupChild(socket) {
const child = fork(childPath);
return new Promise((resolve, reject) => {
child
.once('error', reject)
.once('message', () => {
child.removeAllListeners();
resolve(child);
});
child.once('error', reject).once('message', () => {
child.removeAllListeners();
resolve(child);
});
// $FlowFixMe ChildProcess.send should accept any type.
child.send(socket);
});

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -14,7 +15,7 @@
type PromiseLike<R> = {
catch<U>(onReject?: (error: any) => ?Promise<U> | U): Promise<U>,
then<U>(
fulfilled?: R => Promise<U> | U,
fulfilled?: (R) => Promise<U> | U,
rejected?: (error: any) => Promise<U> | U,
): Promise<U>,
};
@ -38,14 +39,12 @@ exports.LazyPromise = class LazyPromise<T> {
then<U>(
fulfilled?: (value: T) => Promise<U> | U,
rejected?: (error: any) => Promise<U> | U
rejected?: (error: any) => Promise<U> | U,
): Promise<U> {
return this._promise.then(fulfilled, rejected);
}
catch<U>(
rejected?: (error: any) => ?Promise<U> | U
): Promise<U> {
catch<U>(rejected?: (error: any) => ?Promise<U> | U): Promise<U> {
return this._promise.catch(rejected);
}
};
@ -56,8 +55,8 @@ exports.LazyPromise = class LazyPromise<T> {
* asynchronous work.
*/
exports.LockingPromise = class LockingPromise<T> {
_gate: PromiseLike<any>
_promise: PromiseLike<T>
_gate: PromiseLike<any>;
_promise: PromiseLike<T>;
constructor(promise: PromiseLike<T>) {
this._gate = this._promise = promise;
@ -65,7 +64,7 @@ exports.LockingPromise = class LockingPromise<T> {
then<U>(
fulfilled?: (value: T) => Promise<U> | U,
rejected?: (error: any) => Promise<U> | U
rejected?: (error: any) => Promise<U> | U,
): Promise<U> {
const whenUnlocked = () => {
const promise = this._promise.then(fulfilled, rejected);
@ -76,9 +75,7 @@ exports.LockingPromise = class LockingPromise<T> {
return this._gate.then(whenUnlocked, whenUnlocked);
}
catch<U>(
rejected?: (error: any) => ?Promise<U> | U
): Promise<U> {
catch<U>(rejected?: (error: any) => ?Promise<U> | U): Promise<U> {
return this._promise.catch(rejected);
}
};

View File

@ -5,6 +5,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
'use strict';
@ -17,13 +19,16 @@ const concat = require('concat-stream');
const net = require('net');
process.once('message', socket => {
net.createServer({allowHalfOpen: true}, connection => {
connection.setEncoding('utf8');
connection.pipe(concat(data =>
symbolicate(connection, data)
.catch(console.error) // log the error as a last resort
));
}).listen(socket, () => process.send(null));
net
.createServer({allowHalfOpen: true}, connection => {
connection.setEncoding('utf8');
connection.pipe(
concat(
data => symbolicate(connection, data).catch(console.error), // log the error as a last resort
),
);
})
.listen(socket, () => process.send(null));
});
function symbolicate(connection, data) {
@ -64,7 +69,7 @@ function mapFrame(frame, consumers) {
function makeErrorMessage(error) {
return JSON.stringify({
error: String(error && error.message || error),
error: String((error && error.message) || error),
});
}

View File

@ -5,6 +5,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
'use strict';

View File

@ -5,6 +5,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
'use strict';
@ -21,7 +23,7 @@ const PLUGINS = [
if (/^v[0-7]\./.test(process.version)) {
PLUGINS.push(
'transform-async-to-generator',
'syntax-trailing-function-commas'
'syntax-trailing-function-commas',
);
}

View File

@ -1,6 +1,8 @@
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* @format
*/
'use strict';

View File

@ -5,4 +5,6 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -37,7 +38,8 @@ function createCodeWithMap(
const map = bundle.getSourceMap({dev});
const sourceMap = relativizeSourceMap(
typeof map === 'string' ? (JSON.parse(map): SourceMap) : map,
sourceMapSourcesRoot);
sourceMapSourcesRoot,
);
return {
code: bundle.getSource({dev}),
map: sourceMap,
@ -48,7 +50,7 @@ function saveBundleAndMap(
bundle: Bundle,
options: OutputOptions,
log: (...args: Array<string>) => {},
/* $FlowFixMe(>=0.54.0 site=react_native_fb) This comment suppresses an error
/* $FlowFixMe(>=0.54.0 site=react_native_fb) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
): Promise<> {
@ -61,7 +63,11 @@ function saveBundleAndMap(
} = options;
log('start');
const origCodeWithMap = createCodeWithMap(bundle, !!dev, sourcemapSourcesRoot);
const origCodeWithMap = createCodeWithMap(
bundle,
!!dev,
sourcemapSourcesRoot,
);
const codeWithMap = bundle.postProcessBundleSourcemap({
...origCodeWithMap,
outFileName: bundleOutput,
@ -75,15 +81,18 @@ function saveBundleAndMap(
const writeMetadata = writeFile(
bundleOutput + '.meta',
meta(code, encoding),
'binary');
Promise.all([writeBundle, writeMetadata])
.then(() => log('Done writing bundle output'));
'binary',
);
Promise.all([writeBundle, writeMetadata]).then(() =>
log('Done writing bundle output'),
);
if (sourcemapOutput) {
log('Writing sourcemap output to:', sourcemapOutput);
const map = typeof codeWithMap.map !== 'string'
? JSON.stringify(codeWithMap.map)
: codeWithMap.map;
const map =
typeof codeWithMap.map !== 'string'
? JSON.stringify(codeWithMap.map)
: codeWithMap.map;
const writeMap = writeFile(sourcemapOutput, map, null);
writeMap.then(() => log('Done writing sourcemap output'));
return Promise.all([writeBundle, writeMetadata, writeMap]);

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -17,9 +18,11 @@ const crypto = require('crypto');
const isUTF8 = encoding => /^utf-?8$/i.test(encoding);
const constantFor = encoding =>
/^ascii$/i.test(encoding) ? 1 :
isUTF8(encoding) ? 2 :
/^(?:utf-?16(?:le)?|ucs-?2)$/.test(encoding) ? 3 : 0;
/^ascii$/i.test(encoding)
? 1
: isUTF8(encoding)
? 2
: /^(?:utf-?16(?:le)?|ucs-?2)$/.test(encoding) ? 3 : 0;
module.exports = function(
code: Buffer | string,
@ -29,18 +32,25 @@ module.exports = function(
const hash = crypto.createHash('sha1');
hash.update(buffer);
const digest = hash.digest();
const signature = Buffer.alloc ? Buffer.alloc(digest.length + 1) : new Buffer(digest.length + 1);
const signature = Buffer.alloc
? Buffer.alloc(digest.length + 1)
: new Buffer(digest.length + 1);
digest.copy(signature);
signature.writeUInt8(
constantFor(tryAsciiPromotion(buffer, encoding)),
signature.length - 1);
signature.length - 1,
);
return signature;
};
function tryAsciiPromotion(buffer, encoding) {
if (!isUTF8(encoding)) { return encoding; }
if (!isUTF8(encoding)) {
return encoding;
}
for (let i = 0, n = buffer.length; i < n; i++) {
if (buffer[i] > 0x7f) { return encoding; }
if (buffer[i] > 0x7f) {
return encoding;
}
}
return 'ascii';
}

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -54,37 +55,38 @@ function saveAsAssets(
log('Writing bundle output to:', bundleOutput);
const modulesDir = path.join(path.dirname(bundleOutput), MODULES_DIR);
const writeUnbundle =
createDir(modulesDir).then( // create the modules directory first
() => Promise.all([
const writeUnbundle = createDir(modulesDir).then(
// create the modules directory first
() =>
Promise.all([
writeModules(lazyModules, modulesDir, encoding),
writeFile(bundleOutput, startupCode, encoding),
writeMagicFlagFile(modulesDir),
])
);
]),
);
writeUnbundle.then(() => log('Done writing unbundle output'));
const sourceMap =
relativizeSourceMap(
buildSourceMapWithMetaData({
fixWrapperOffset: true,
lazyModules: lazyModules.concat(),
moduleGroups: null,
startupModules: startupModules.concat(),
}),
sourcemapSourcesRoot
);
const sourceMap = relativizeSourceMap(
buildSourceMapWithMetaData({
fixWrapperOffset: true,
lazyModules: lazyModules.concat(),
moduleGroups: null,
startupModules: startupModules.concat(),
}),
sourcemapSourcesRoot,
);
return Promise.all([
writeUnbundle,
sourcemapOutput && writeSourceMap(sourcemapOutput, JSON.stringify(sourceMap), log),
sourcemapOutput &&
writeSourceMap(sourcemapOutput, JSON.stringify(sourceMap), log),
]);
}
function createDir(dirName) {
return new Promise((resolve, reject) =>
mkdirp(dirName, error => error ? reject(error) : resolve()));
mkdirp(dirName, error => (error ? reject(error) : resolve())),
);
}
function writeModuleFile(module, modulesDir, encoding) {
@ -93,8 +95,9 @@ function writeModuleFile(module, modulesDir, encoding) {
}
function writeModules(modules, modulesDir, encoding) {
const writeFiles =
modules.map(module => writeModuleFile(module, modulesDir, encoding));
const writeFiles = modules.map(module =>
writeModuleFile(module, modulesDir, encoding),
);
return Promise.all(writeFiles);
}

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -20,7 +21,11 @@ const writeSourceMap = require('./write-sourcemap');
const {joinModules} = require('./util');
import type Bundle from '../../../Bundler/Bundle';
import type {ModuleGroups, ModuleTransportLike, OutputOptions} from '../../types.flow';
import type {
ModuleGroups,
ModuleTransportLike,
OutputOptions,
} from '../../types.flow';
const SIZEOF_UINT32 = 4;
@ -35,7 +40,7 @@ function saveAsIndexedFile(
bundle: Bundle,
options: OutputOptions,
log: (...args: Array<string>) => void,
/* $FlowFixMe(>=0.54.0 site=react_native_fb) This comment suppresses an error
/* $FlowFixMe(>=0.54.0 site=react_native_fb) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
): Promise<> {
@ -56,23 +61,23 @@ function saveAsIndexedFile(
log('Writing unbundle output to:', bundleOutput);
const writeUnbundle = writeBuffers(
fs.createWriteStream(bundleOutput),
buildTableAndContents(startupCode, lazyModules, moduleGroups, encoding)
buildTableAndContents(startupCode, lazyModules, moduleGroups, encoding),
).then(() => log('Done writing unbundle output'));
const sourceMap =
relativizeSourceMap(
buildSourceMapWithMetaData({
startupModules: startupModules.concat(),
lazyModules: lazyModules.concat(),
moduleGroups,
fixWrapperOffset: true,
}),
sourcemapSourcesRoot
);
const sourceMap = relativizeSourceMap(
buildSourceMapWithMetaData({
startupModules: startupModules.concat(),
lazyModules: lazyModules.concat(),
moduleGroups,
fixWrapperOffset: true,
}),
sourcemapSourcesRoot,
);
return Promise.all([
writeUnbundle,
sourcemapOutput && writeSourceMap(sourcemapOutput, JSON.stringify(sourceMap), log),
sourcemapOutput &&
writeSourceMap(sourcemapOutput, JSON.stringify(sourceMap), log),
]);
}
@ -163,15 +168,13 @@ function groupCode(rootCode, moduleGroup, modulesById) {
function buildModuleBuffers(modules, moduleGroups, encoding) {
return modules
.filter(m => !moduleGroups.modulesInGroups.has(m.id))
.map(({id, code}) => moduleToBuffer(
id,
groupCode(
code,
moduleGroups.groups.get(id),
moduleGroups.modulesById,
.map(({id, code}) =>
moduleToBuffer(
id,
groupCode(code, moduleGroups.groups.get(id), moduleGroups.modulesById),
encoding,
),
encoding
));
);
}
function buildTableAndContents(
@ -188,13 +191,15 @@ function buildTableAndContents(
const startupCodeBuffer = nullTerminatedBuffer(startupCode, encoding);
const moduleBuffers = buildModuleBuffers(modules, moduleGroups, encoding);
const table = buildModuleTable(startupCodeBuffer, moduleBuffers, moduleGroups);
return [
fileHeader,
table,
const table = buildModuleTable(
startupCodeBuffer,
].concat(moduleBuffers.map(({buffer}) => buffer));
moduleBuffers,
moduleGroups,
);
return [fileHeader, table, startupCodeBuffer].concat(
moduleBuffers.map(({buffer}) => buffer),
);
}
function createModuleGroups(
@ -208,9 +213,9 @@ function createModuleGroups(
};
}
function * concat(iterators) {
function* concat(iterators) {
for (const it of iterators) {
yield * it;
yield* it;
}
}

View File

@ -7,10 +7,15 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
const {combineSourceMaps, combineSourceMapsAddingOffsets, joinModules} = require('./util');
const {
combineSourceMaps,
combineSourceMapsAddingOffsets,
joinModules,
} = require('./util');
import type {ModuleGroups, ModuleTransportLike} from '../../types.flow';
@ -21,11 +26,16 @@ type Params = {|
startupModules: $ReadOnlyArray<ModuleTransportLike>,
|};
module.exports = ({fixWrapperOffset, lazyModules, moduleGroups, startupModules}: Params) => {
module.exports = ({
fixWrapperOffset,
lazyModules,
moduleGroups,
startupModules,
}: Params) => {
const options = fixWrapperOffset ? {fixWrapperOffset: true} : undefined;
const startupModule: ModuleTransportLike = {
code: joinModules(startupModules),
id: Number.MIN_SAFE_INTEGER,
id: Number.MIN_SAFE_INTEGER,
map: combineSourceMaps(startupModules, undefined, options),
sourcePath: '',
};

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -36,12 +37,12 @@ function saveUnbundle(
// we fork here depending on the platform:
// while android is pretty good at loading individual assets, ios has a large
// overhead when reading hundreds pf assets from disk
return options.platform === 'android' && !options.indexedUnbundle ?
asAssets(bundle, options, log) :
/* $FlowFixMe(>=0.54.0 site=react_native_fb) This comment suppresses an
return options.platform === 'android' && !options.indexedUnbundle
? asAssets(bundle, options, log)
: /* $FlowFixMe(>=0.54.0 site=react_native_fb) This comment suppresses an
* error found when Flow v0.54 was deployed. To see the error delete this
* comment and run Flow. */
asIndexedFile(bundle, options, log);
asIndexedFile(bundle, options, log);
}
exports.build = buildBundle;

View File

@ -7,7 +7,8 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
module.exports = 0xFB0BD1E5;
module.exports = 0xfb0bd1e5;

View File

@ -7,20 +7,28 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
const invariant = require('fbjs/lib/invariant');
import type {FBIndexMap, IndexMap, MappingsMap, SourceMap} from '../../../lib/SourceMap';
import type {
FBIndexMap,
IndexMap,
MappingsMap,
SourceMap,
} from '../../../lib/SourceMap';
import type {ModuleGroups, ModuleTransportLike} from '../../types.flow';
const newline = /\r\n?|\n|\u2028|\u2029/g;
// fastest implementation
const countLines = (string: string) => (string.match(newline) || []).length + 1;
function lineToLineSourceMap(source: string, filename: string = ''): MappingsMap {
function lineToLineSourceMap(
source: string,
filename: string = '',
): MappingsMap {
// The first line mapping in our package is the base64vlq code for zeros (A).
const firstLine = 'AAAA;';
@ -39,9 +47,10 @@ function lineToLineSourceMap(source: string, filename: string = ''): MappingsMap
const wrapperEnd = wrappedCode => wrappedCode.indexOf('{') + 1;
const Section =
(line: number, column: number, map: SourceMap) =>
({map, offset: {line, column}});
const Section = (line: number, column: number, map: SourceMap) => ({
map,
offset: {line, column},
});
type CombineOptions = {fixWrapperOffset: boolean};
@ -60,7 +69,12 @@ function combineSourceMapsAddingOffsets(
options?: ?CombineOptions,
): FBIndexMap {
const x_facebook_offsets = [];
const sections = combineMaps(modules, x_facebook_offsets, moduleGroups, options);
const sections = combineMaps(
modules,
x_facebook_offsets,
moduleGroups,
options,
);
return {sections, version: 3, x_facebook_offsets};
}
@ -80,15 +94,15 @@ function combineMaps(modules, offsets: ?Array<number>, moduleGroups, options) {
return;
}
if (offsets != null) {
group = moduleGroups && moduleGroups.groups.get(id);
if (group && moduleGroups) {
const {modulesById} = moduleGroups;
const otherModules: $ReadOnlyArray<ModuleTransportLike> =
Array.from(group || [])
.map(moduleId => modulesById.get(moduleId))
.filter(Boolean); // needed to appease flow
const otherModules: $ReadOnlyArray<ModuleTransportLike> = Array.from(
group || [],
)
.map(moduleId => modulesById.get(moduleId))
.filter(Boolean); // needed to appease flow
otherModules.forEach(m => {
groupLines += countLines(m.code);
});
@ -102,7 +116,9 @@ function combineMaps(modules, offsets: ?Array<number>, moduleGroups, options) {
!Array.isArray(map),
'Random Access Bundle source maps cannot be built from raw mappings',
);
sections.push(Section(line, column, map || lineToLineSourceMap(code, name)));
sections.push(
Section(line, column, map || lineToLineSourceMap(code, name)),
);
if (offsets != null && id != null) {
offsets[id] = line;
for (const moduleId of group || []) {
@ -115,9 +131,8 @@ function combineMaps(modules, offsets: ?Array<number>, moduleGroups, options) {
return sections;
}
const joinModules =
(modules: $ReadOnlyArray<{+code: string}>): string =>
modules.map(m => m.code).join('\n');
const joinModules = (modules: $ReadOnlyArray<{+code: string}>): string =>
modules.map(m => m.code).join('\n');
module.exports = {
combineSourceMaps,

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -16,7 +17,7 @@ function writeSourcemap(
fileName: string,
contents: string,
log: (...args: Array<string>) => void,
/* $FlowFixMe(>=0.54.0 site=react_native_fb) This comment suppresses an error
/* $FlowFixMe(>=0.54.0 site=react_native_fb) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
): Promise<> {

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
@ -14,8 +15,11 @@ const denodeify = require('denodeify');
const fs = require('fs');
const throat = require('throat');
type WriteFn =
(file: string, data: string | Buffer, encoding?: ?string) => Promise<mixed>;
type WriteFn = (
file: string,
data: string | Buffer,
encoding?: ?string,
) => Promise<mixed>;
const writeFile: WriteFn = throat(128, denodeify(fs.writeFile));
module.exports = writeFile;

View File

@ -7,6 +7,7 @@
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
* @format
*/
'use strict';
import type {SourceMapOrMappings} from '../lib/ModuleTransport';

View File

@ -5,6 +5,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
'use strict';

View File

@ -5,9 +5,11 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
/* eslint-disable */
module.exports = function (inp, callback) {
callback(null, inp + ' BAR (' + process.pid + ')')
}
module.exports = function(inp, callback) {
callback(null, inp + ' BAR (' + process.pid + ')');
};

View File

@ -5,17 +5,18 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
/* eslint-disable */
var workerFarm = require('../../')
, workers = workerFarm(require.resolve('./child'))
, ret = 0
var workerFarm = require('../../'),
workers = workerFarm(require.resolve('./child')),
ret = 0;
for (var i = 0; i < 10; i++) {
workers('#' + i + ' FOO', function (err, outp) {
console.log(outp)
if (++ret == 10)
workerFarm.end(workers)
})
workers('#' + i + ' FOO', function(err, outp) {
console.log(outp);
if (++ret == 10) workerFarm.end(workers);
});
}

View File

@ -5,6 +5,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
/* eslint-disable */
@ -18,13 +20,12 @@
* increase accuracy.
*/
module.exports = function (points, callback) {
var inside = 0
, i = points
module.exports = function(points, callback) {
var inside = 0,
i = points;
while (i--)
if (Math.pow(Math.random(), 2) + Math.pow(Math.random(), 2) <= 1)
inside++
if (Math.pow(Math.random(), 2) + Math.pow(Math.random(), 2) <= 1) inside++;
callback(null, (inside / points) * 4)
}
callback(null, inside / points * 4);
};

View File

@ -5,45 +5,51 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
/* eslint-disable */
const CHILDREN = 500
, POINTS_PER_CHILD = 1000000
, FARM_OPTIONS = {
maxConcurrentWorkers : require('os').cpus().length
, maxCallsPerWorker : Infinity
, maxConcurrentCallsPerWorker : 1
}
const CHILDREN = 500,
POINTS_PER_CHILD = 1000000,
FARM_OPTIONS = {
maxConcurrentWorkers: require('os').cpus().length,
maxCallsPerWorker: Infinity,
maxConcurrentCallsPerWorker: 1,
};
var workerFarm = require('../../')
, calcDirect = require('./calc')
, calcWorker = workerFarm(FARM_OPTIONS, require.resolve('./calc'))
, ret
, start
, tally = function (finish, err, avg) {
ret.push(avg)
if (ret.length == CHILDREN) {
var pi = ret.reduce(function (a, b) { return a + b }) / ret.length
, end = +new Date()
console.log('PI ~=', pi, '\t(' + Math.abs(pi - Math.PI), 'away from actual!)')
console.log('took', end - start, 'milliseconds')
if (finish)
finish()
}
var workerFarm = require('../../'),
calcDirect = require('./calc'),
calcWorker = workerFarm(FARM_OPTIONS, require.resolve('./calc')),
ret,
start,
tally = function(finish, err, avg) {
ret.push(avg);
if (ret.length == CHILDREN) {
var pi =
ret.reduce(function(a, b) {
return a + b;
}) / ret.length,
end = +new Date();
console.log(
'PI ~=',
pi,
'\t(' + Math.abs(pi - Math.PI),
'away from actual!)',
);
console.log('took', end - start, 'milliseconds');
if (finish) finish();
}
},
calc = function(method, callback) {
ret = [];
start = +new Date();
for (var i = 0; i < CHILDREN; i++)
method(POINTS_PER_CHILD, tally.bind(null, callback));
};
, calc = function (method, callback) {
ret = []
start = +new Date()
for (var i = 0; i < CHILDREN; i++)
method(POINTS_PER_CHILD, tally.bind(null, callback))
}
console.log('Doing it the slow (single-process) way...')
calc(calcDirect, function () {
console.log('Doing it the fast (multi-process) way...')
calc(calcWorker, process.exit)
})
console.log('Doing it the slow (single-process) way...');
calc(calcDirect, function() {
console.log('Doing it the fast (multi-process) way...');
calc(calcWorker, process.exit);
});

View File

@ -5,75 +5,74 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
/* eslint-disable */
var fs = require('fs')
var fs = require('fs');
module.exports = function (timeout, callback) {
callback = callback.bind(null, null, process.pid, Math.random(), timeout)
if (timeout)
return setTimeout(callback, timeout)
callback()
}
module.exports = function(timeout, callback) {
callback = callback.bind(null, null, process.pid, Math.random(), timeout);
if (timeout) return setTimeout(callback, timeout);
callback();
};
module.exports.run0 = function (callback) {
module.exports(0, callback)
}
module.exports.run0 = function(callback) {
module.exports(0, callback);
};
module.exports.killable = function (id, callback) {
if (Math.random() < 0.5)
return process.exit(-1)
callback(null, id, process.pid)
}
module.exports.killable = function(id, callback) {
if (Math.random() < 0.5) return process.exit(-1);
callback(null, id, process.pid);
};
module.exports.err = function (type, message, data, callback) {
module.exports.err = function(type, message, data, callback) {
if (typeof data == 'function') {
callback = data
data = null
callback = data;
data = null;
} else {
var err = new Error(message)
var err = new Error(message);
Object.keys(data).forEach(function(key) {
err[key] = data[key]
})
callback(err)
return
err[key] = data[key];
});
callback(err);
return;
}
if (type == 'TypeError')
return callback(new TypeError(message))
callback(new Error(message))
}
if (type == 'TypeError') return callback(new TypeError(message));
callback(new Error(message));
};
module.exports.block = function () {
module.exports.block = function() {
while (true);
}
};
// use provided file path to save retries count among terminated workers
module.exports.stubborn = function (path, callback) {
module.exports.stubborn = function(path, callback) {
function isOutdated(path) {
return ((new Date).getTime() - fs.statSync(path).mtime.getTime()) > 2000
return new Date().getTime() - fs.statSync(path).mtime.getTime() > 2000;
}
// file may not be properly deleted, check if modified no earler than two seconds ago
if (!fs.existsSync(path) || isOutdated(path)) {
fs.writeFileSync(path, '1')
process.exit(-1)
fs.writeFileSync(path, '1');
process.exit(-1);
}
var retry = parseInt(fs.readFileSync(path, 'utf8'))
var retry = parseInt(fs.readFileSync(path, 'utf8'));
if (Number.isNaN(retry))
return callback(new Error('file contents is not a number'))
return callback(new Error('file contents is not a number'));
if (retry > 4) {
callback(null, 12)
callback(null, 12);
} else {
fs.writeFileSync(path, String(retry + 1))
process.exit(-1)
fs.writeFileSync(path, String(retry + 1));
process.exit(-1);
}
}
};
var started = Date.now()
var started = Date.now();
module.exports.uptime = function(callback) {
callback(null, Date.now() - started)
}
callback(null, Date.now() - started);
};

View File

@ -5,462 +5,524 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
/* eslint-disable */
var tape = require('tape')
, workerFarm = require('../')
, childPath = require.resolve('./child')
, fs = require('fs')
, uniq = function (ar) {
var a = [], i, j
o: for (i = 0; i < ar.length; ++i) {
for (j = 0; j < a.length; ++j) if (a[j] == ar[i]) continue o
a[a.length] = ar[i]
}
return a
var tape = require('tape'),
workerFarm = require('../'),
childPath = require.resolve('./child'),
fs = require('fs'),
uniq = function(ar) {
var a = [],
i,
j;
o: for (i = 0; i < ar.length; ++i) {
for (j = 0; j < a.length; ++j) if (a[j] == ar[i]) continue o;
a[a.length] = ar[i];
}
return a;
};
// a child where module.exports = function ...
tape('simple, exports=function test', function (t) {
t.plan(4)
tape('simple, exports=function test', function(t) {
t.plan(4);
var child = workerFarm(childPath)
child(0, function (err, pid, rnd) {
t.ok(pid > process.pid, 'pid makes sense')
t.ok(pid < process.pid + 500, 'pid makes sense')
t.ok(rnd >= 0 && rnd < 1, 'rnd result makes sense')
})
var child = workerFarm(childPath);
child(0, function(err, pid, rnd) {
t.ok(pid > process.pid, 'pid makes sense');
t.ok(pid < process.pid + 500, 'pid makes sense');
t.ok(rnd >= 0 && rnd < 1, 'rnd result makes sense');
});
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
})
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
});
// a child where we have module.exports.fn = function ...
tape('simple, exports.fn test', function (t) {
t.plan(4)
tape('simple, exports.fn test', function(t) {
t.plan(4);
var child = workerFarm(childPath, [ 'run0' ])
child.run0(function (err, pid, rnd) {
t.ok(pid > process.pid, 'pid makes sense')
t.ok(pid < process.pid + 500, 'pid makes sense')
t.ok(rnd >= 0 && rnd < 1, 'rnd result makes sense')
})
var child = workerFarm(childPath, ['run0']);
child.run0(function(err, pid, rnd) {
t.ok(pid > process.pid, 'pid makes sense');
t.ok(pid < process.pid + 500, 'pid makes sense');
t.ok(rnd >= 0 && rnd < 1, 'rnd result makes sense');
});
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
})
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
});
// use the returned pids to check that we're using a single child process
// when maxConcurrentWorkers = 1
tape('single worker', function (t) {
t.plan(2)
tape('single worker', function(t) {
t.plan(2);
var child = workerFarm({ maxConcurrentWorkers: 1 }, childPath)
, pids = []
, i = 10
var child = workerFarm({maxConcurrentWorkers: 1}, childPath),
pids = [],
i = 10;
while (i--) {
child(0, function (err, pid) {
pids.push(pid)
child(0, function(err, pid) {
pids.push(pid);
if (pids.length == 10) {
t.equal(1, uniq(pids).length, 'only a single process (by pid)')
} else if (pids.length > 10)
t.fail('too many callbacks!')
})
t.equal(1, uniq(pids).length, 'only a single process (by pid)');
} else if (pids.length > 10) t.fail('too many callbacks!');
});
}
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
})
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
});
// use the returned pids to check that we're using two child processes
// when maxConcurrentWorkers = 2
tape('two workers', function (t) {
t.plan(2)
tape('two workers', function(t) {
t.plan(2);
var child = workerFarm({ maxConcurrentWorkers: 2 }, childPath)
, pids = []
, i = 10
var child = workerFarm({maxConcurrentWorkers: 2}, childPath),
pids = [],
i = 10;
while (i--) {
child(0, function (err, pid) {
pids.push(pid)
child(0, function(err, pid) {
pids.push(pid);
if (pids.length == 10) {
t.equal(2, uniq(pids).length, 'only two child processes (by pid)')
} else if (pids.length > 10)
t.fail('too many callbacks!')
})
t.equal(2, uniq(pids).length, 'only two child processes (by pid)');
} else if (pids.length > 10) t.fail('too many callbacks!');
});
}
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
})
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
});
// use the returned pids to check that we're using a child process per
// call when maxConcurrentWorkers = 10
tape('many workers', function (t) {
t.plan(2)
tape('many workers', function(t) {
t.plan(2);
var child = workerFarm({ maxConcurrentWorkers: 10 }, childPath)
, pids = []
, i = 10
var child = workerFarm({maxConcurrentWorkers: 10}, childPath),
pids = [],
i = 10;
while (i--) {
child(1, function (err, pid) {
pids.push(pid)
child(1, function(err, pid) {
pids.push(pid);
if (pids.length == 10) {
t.equal(10, uniq(pids).length, 'pids are all the same (by pid)')
} else if (pids.length > 10)
t.fail('too many callbacks!')
})
t.equal(10, uniq(pids).length, 'pids are all the same (by pid)');
} else if (pids.length > 10) t.fail('too many callbacks!');
});
}
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
})
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
});
tape('auto start workers', function (t) {
t.plan(4)
tape('auto start workers', function(t) {
t.plan(4);
var child = workerFarm({ maxConcurrentWorkers: 3, autoStart: true }, childPath, ['uptime'])
, pids = []
, i = 3
, delay = 150
var child = workerFarm(
{maxConcurrentWorkers: 3, autoStart: true},
childPath,
['uptime'],
),
pids = [],
i = 3,
delay = 150;
setTimeout(function() {
while (i--)
child.uptime(function (err, uptime) {
t.ok(uptime > 10, 'child has been up before the request')
})
child.uptime(function(err, uptime) {
t.ok(uptime > 10, 'child has been up before the request');
});
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
}, delay)
})
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
}, delay);
});
// use the returned pids to check that we're using a child process per
// call when we set maxCallsPerWorker = 1 even when we have maxConcurrentWorkers = 1
tape('single call per worker', function (t) {
t.plan(2)
tape('single call per worker', function(t) {
t.plan(2);
var child = workerFarm({ maxConcurrentWorkers: 1, maxCallsPerWorker: 1 }, childPath)
, pids = []
, i = 10
var child = workerFarm(
{maxConcurrentWorkers: 1, maxCallsPerWorker: 1},
childPath,
),
pids = [],
i = 10;
while (i--) {
child(0, function (err, pid) {
pids.push(pid)
child(0, function(err, pid) {
pids.push(pid);
if (pids.length == 10) {
t.equal(10, uniq(pids).length, 'one process for each call (by pid)')
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
} else if (pids.length > 10)
t.fail('too many callbacks!')
})
t.equal(10, uniq(pids).length, 'one process for each call (by pid)');
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
} else if (pids.length > 10) t.fail('too many callbacks!');
});
}
})
});
// use the returned pids to check that we're using a child process per
// two-calls when we set maxCallsPerWorker = 2 even when we have maxConcurrentWorkers = 1
tape('two calls per worker', function (t) {
t.plan(2)
tape('two calls per worker', function(t) {
t.plan(2);
var child = workerFarm({ maxConcurrentWorkers: 1, maxCallsPerWorker: 2 }, childPath)
, pids = []
, i = 10
var child = workerFarm(
{maxConcurrentWorkers: 1, maxCallsPerWorker: 2},
childPath,
),
pids = [],
i = 10;
while (i--) {
child(0, function (err, pid) {
pids.push(pid)
child(0, function(err, pid) {
pids.push(pid);
if (pids.length == 10) {
t.equal(5, uniq(pids).length, 'one process for each call (by pid)')
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
} else if (pids.length > 10)
t.fail('too many callbacks!')
})
t.equal(5, uniq(pids).length, 'one process for each call (by pid)');
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
} else if (pids.length > 10) t.fail('too many callbacks!');
});
}
})
});
// use timing to confirm that one worker will process calls sequentially
tape('many concurrent calls', function (t) {
t.plan(2)
tape('many concurrent calls', function(t) {
t.plan(2);
var child = workerFarm({ maxConcurrentWorkers: 1 }, childPath)
, i = 10
, cbc = 0
, start = Date.now()
var child = workerFarm({maxConcurrentWorkers: 1}, childPath),
i = 10,
cbc = 0,
start = Date.now();
while (i--) {
child(100, function () {
child(100, function() {
if (++cbc == 10) {
var time = Date.now() - start
t.ok(time > 100 && time < 200, 'processed tasks concurrently (' + time + 'ms)')
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
} else if (cbc > 10)
t.fail('too many callbacks!')
})
var time = Date.now() - start;
t.ok(
time > 100 && time < 200,
'processed tasks concurrently (' + time + 'ms)',
);
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
} else if (cbc > 10) t.fail('too many callbacks!');
});
}
})
});
// use timing to confirm that one child processes calls sequentially with
// maxConcurrentCallsPerWorker = 1
tape('single concurrent call', function (t) {
t.plan(2)
tape('single concurrent call', function(t) {
t.plan(2);
var child = workerFarm(
{ maxConcurrentWorkers: 1, maxConcurrentCallsPerWorker: 1 }
, childPath
)
, i = 10
, cbc = 0
, start = Date.now()
{maxConcurrentWorkers: 1, maxConcurrentCallsPerWorker: 1},
childPath,
),
i = 10,
cbc = 0,
start = Date.now();
while (i--) {
child(10, function () {
child(10, function() {
if (++cbc == 10) {
var time = Date.now() - start
t.ok(time > 100 && time < 190, 'processed tasks sequentially (' + time + 'ms)')
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
} else if (cbc > 10)
t.fail('too many callbacks!')
})
var time = Date.now() - start;
t.ok(
time > 100 && time < 190,
'processed tasks sequentially (' + time + 'ms)',
);
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
} else if (cbc > 10) t.fail('too many callbacks!');
});
}
})
});
// use timing to confirm that one child processes *only* 5 calls concurrently
tape('multiple concurrent calls', function (t) {
t.plan(2)
tape('multiple concurrent calls', function(t) {
t.plan(2);
var child = workerFarm({ maxConcurrentWorkers: 1, maxConcurrentCallsPerWorker: 5 }, childPath)
, i = 10
, cbc = 0
, start = Date.now()
var child = workerFarm(
{maxConcurrentWorkers: 1, maxConcurrentCallsPerWorker: 5},
childPath,
),
i = 10,
cbc = 0,
start = Date.now();
while (i--) {
child(50, function () {
child(50, function() {
if (++cbc == 10) {
var time = Date.now() - start
t.ok(time > 100 && time < 200, 'processed tasks concurrently (' + time + 'ms)')
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
} else if (cbc > 10)
t.fail('too many callbacks!')
})
var time = Date.now() - start;
t.ok(
time > 100 && time < 200,
'processed tasks concurrently (' + time + 'ms)',
);
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
} else if (cbc > 10) t.fail('too many callbacks!');
});
}
})
});
// call a method that will die with a probability of 0.5 but expect that
// we'll get results for each of our calls anyway
tape('durability', function (t) {
t.plan(3)
tape('durability', function(t) {
t.plan(3);
var child = workerFarm({ maxConcurrentWorkers: 2 }, childPath, [ 'killable' ])
, ids = []
, pids = []
, i = 10
var child = workerFarm({maxConcurrentWorkers: 2}, childPath, ['killable']),
ids = [],
pids = [],
i = 10;
while (i--) {
child.killable(i, function (err, id, pid) {
ids.push(id)
pids.push(pid)
child.killable(i, function(err, id, pid) {
ids.push(id);
pids.push(pid);
if (ids.length == 10) {
t.ok(uniq(pids).length > 2, 'processed by many (' + uniq(pids).length + ') workers, but got there in the end!')
t.ok(uniq(ids).length == 10, 'received a single result for each unique call')
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
} else if (ids.length > 10)
t.fail('too many callbacks!')
})
t.ok(
uniq(pids).length > 2,
'processed by many (' +
uniq(pids).length +
') workers, but got there in the end!',
);
t.ok(
uniq(ids).length == 10,
'received a single result for each unique call',
);
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
} else if (ids.length > 10) t.fail('too many callbacks!');
});
}
})
});
// a callback provided to .end() can and will be called (uses "simple, exports=function test" to create a child)
tape('simple, end callback', function (t) {
t.plan(4)
tape('simple, end callback', function(t) {
t.plan(4);
var child = workerFarm(childPath)
child(0, function (err, pid, rnd) {
t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid)
t.ok(pid < process.pid + 500, 'pid makes sense ' + pid + ' vs ' + process.pid)
t.ok(rnd >= 0 && rnd < 1, 'rnd result makes sense')
})
var child = workerFarm(childPath);
child(0, function(err, pid, rnd) {
t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid);
t.ok(
pid < process.pid + 500,
'pid makes sense ' + pid + ' vs ' + process.pid,
);
t.ok(rnd >= 0 && rnd < 1, 'rnd result makes sense');
});
workerFarm.end(child, function() {
t.pass('an .end() callback was successfully called')
})
})
t.pass('an .end() callback was successfully called');
});
});
tape('call timeout test', function (t) {
t.plan(3 + 3 + 4 + 4 + 4 + 3 + 1)
tape('call timeout test', function(t) {
t.plan(3 + 3 + 4 + 4 + 4 + 3 + 1);
var child = workerFarm({ maxCallTime: 250, maxConcurrentWorkers: 1 }, childPath)
var child = workerFarm(
{maxCallTime: 250, maxConcurrentWorkers: 1},
childPath,
);
// should come back ok
child(50, function (err, pid, rnd) {
t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid)
t.ok(pid < process.pid + 500, 'pid makes sense ' + pid + ' vs ' + process.pid)
t.ok(rnd > 0 && rnd < 1, 'rnd result makes sense ' + rnd)
})
child(50, function(err, pid, rnd) {
t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid);
t.ok(
pid < process.pid + 500,
'pid makes sense ' + pid + ' vs ' + process.pid,
);
t.ok(rnd > 0 && rnd < 1, 'rnd result makes sense ' + rnd);
});
// should come back ok
child(50, function (err, pid, rnd) {
t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid)
t.ok(pid < process.pid + 500, 'pid makes sense ' + pid + ' vs ' + process.pid)
t.ok(rnd > 0 && rnd < 1, 'rnd result makes sense ' + rnd)
})
child(50, function(err, pid, rnd) {
t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid);
t.ok(
pid < process.pid + 500,
'pid makes sense ' + pid + ' vs ' + process.pid,
);
t.ok(rnd > 0 && rnd < 1, 'rnd result makes sense ' + rnd);
});
// should die
child(500, function (err, pid, rnd) {
t.ok(err, 'got an error')
t.equal(err.type, 'TimeoutError', 'correct error type')
t.ok(pid === undefined, 'no pid')
t.ok(rnd === undefined, 'no rnd')
})
child(500, function(err, pid, rnd) {
t.ok(err, 'got an error');
t.equal(err.type, 'TimeoutError', 'correct error type');
t.ok(pid === undefined, 'no pid');
t.ok(rnd === undefined, 'no rnd');
});
// should die
child(1000, function (err, pid, rnd) {
t.ok(err, 'got an error')
t.equal(err.type, 'TimeoutError', 'correct error type')
t.ok(pid === undefined, 'no pid')
t.ok(rnd === undefined, 'no rnd')
})
child(1000, function(err, pid, rnd) {
t.ok(err, 'got an error');
t.equal(err.type, 'TimeoutError', 'correct error type');
t.ok(pid === undefined, 'no pid');
t.ok(rnd === undefined, 'no rnd');
});
// should die even though it is only a 100ms task, it'll get caught up
// in a dying worker
setTimeout(function () {
child(100, function (err, pid, rnd) {
t.ok(err, 'got an error')
t.equal(err.type, 'TimeoutError', 'correct error type')
t.ok(pid === undefined, 'no pid')
t.ok(rnd === undefined, 'no rnd')
})
}, 200)
setTimeout(function() {
child(100, function(err, pid, rnd) {
t.ok(err, 'got an error');
t.equal(err.type, 'TimeoutError', 'correct error type');
t.ok(pid === undefined, 'no pid');
t.ok(rnd === undefined, 'no rnd');
});
}, 200);
// should be ok, new worker
setTimeout(function () {
child(50, function (err, pid, rnd) {
t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid)
t.ok(pid < process.pid + 500, 'pid makes sense ' + pid + ' vs ' + process.pid)
t.ok(rnd > 0 && rnd < 1, 'rnd result makes sense ' + rnd)
})
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
}, 400)
})
setTimeout(function() {
child(50, function(err, pid, rnd) {
t.ok(pid > process.pid, 'pid makes sense ' + pid + ' vs ' + process.pid);
t.ok(
pid < process.pid + 500,
'pid makes sense ' + pid + ' vs ' + process.pid,
);
t.ok(rnd > 0 && rnd < 1, 'rnd result makes sense ' + rnd);
});
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
}, 400);
});
tape('test error passing', function (t) {
t.plan(10)
tape('test error passing', function(t) {
t.plan(10);
var child = workerFarm(childPath, [ 'err' ])
child.err('Error', 'this is an Error', function (err) {
t.ok(err instanceof Error, 'is an Error object')
t.equal('Error', err.type, 'correct type')
t.equal('this is an Error', err.message, 'correct message')
})
child.err('TypeError', 'this is a TypeError', function (err) {
t.ok(err instanceof Error, 'is a TypeError object')
t.equal('TypeError', err.type, 'correct type')
t.equal('this is a TypeError', err.message, 'correct message')
})
child.err('Error', 'this is an Error with custom props', {foo: 'bar', 'baz': 1}, function (err) {
t.ok(err instanceof Error, 'is an Error object')
t.equal(err.foo, 'bar', 'passes data')
t.equal(err.baz, 1, 'passes data')
})
var child = workerFarm(childPath, ['err']);
child.err('Error', 'this is an Error', function(err) {
t.ok(err instanceof Error, 'is an Error object');
t.equal('Error', err.type, 'correct type');
t.equal('this is an Error', err.message, 'correct message');
});
child.err('TypeError', 'this is a TypeError', function(err) {
t.ok(err instanceof Error, 'is a TypeError object');
t.equal('TypeError', err.type, 'correct type');
t.equal('this is a TypeError', err.message, 'correct message');
});
child.err(
'Error',
'this is an Error with custom props',
{foo: 'bar', baz: 1},
function(err) {
t.ok(err instanceof Error, 'is an Error object');
t.equal(err.foo, 'bar', 'passes data');
t.equal(err.baz, 1, 'passes data');
},
);
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
})
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
});
tape('test maxConcurrentCalls', function(t) {
t.plan(10);
tape('test maxConcurrentCalls', function (t) {
t.plan(10)
var child = workerFarm({maxConcurrentCalls: 5}, childPath);
var child = workerFarm({ maxConcurrentCalls: 5 }, childPath)
child(50, function(err) {
t.notOk(err, 'no error');
});
child(50, function(err) {
t.notOk(err, 'no error');
});
child(50, function(err) {
t.notOk(err, 'no error');
});
child(50, function(err) {
t.notOk(err, 'no error');
});
child(50, function(err) {
t.notOk(err, 'no error');
});
child(50, function(err) {
t.ok(err);
t.equal(err.type, 'MaxConcurrentCallsError', 'correct error type');
});
child(50, function(err) {
t.ok(err);
t.equal(err.type, 'MaxConcurrentCallsError', 'correct error type');
});
child(50, function (err) { t.notOk(err, 'no error') })
child(50, function (err) { t.notOk(err, 'no error') })
child(50, function (err) { t.notOk(err, 'no error') })
child(50, function (err) { t.notOk(err, 'no error') })
child(50, function (err) { t.notOk(err, 'no error') })
child(50, function (err) {
t.ok(err)
t.equal(err.type, 'MaxConcurrentCallsError', 'correct error type')
})
child(50, function (err) {
t.ok(err)
t.equal(err.type, 'MaxConcurrentCallsError', 'correct error type')
})
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
})
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
});
// this test should not keep the process running! if the test process
// doesn't die then the problem is here
tape('test timeout kill', function (t) {
t.plan(3)
tape('test timeout kill', function(t) {
t.plan(3);
var child = workerFarm({ maxCallTime: 250, maxConcurrentWorkers: 1 }, childPath, [ 'block' ])
child.block(function (err) {
t.ok(err, 'got an error')
t.equal(err.type, 'TimeoutError', 'correct error type')
})
var child = workerFarm(
{maxCallTime: 250, maxConcurrentWorkers: 1},
childPath,
['block'],
);
child.block(function(err) {
t.ok(err, 'got an error');
t.equal(err.type, 'TimeoutError', 'correct error type');
});
workerFarm.end(child, function () {
t.ok(true, 'workerFarm ended')
})
})
workerFarm.end(child, function() {
t.ok(true, 'workerFarm ended');
});
});
tape('test max retries after process terminate', function (t) {
t.plan(7)
tape('test max retries after process terminate', function(t) {
t.plan(7);
// temporary file is used to store the number of retries among terminating workers
var filepath1 = '.retries1'
var child1 = workerFarm({ maxConcurrentWorkers: 1, maxRetries: 5}, childPath, [ 'stubborn' ])
child1.stubborn(filepath1, function (err, result) {
t.notOk(err, 'no error')
t.equal(result, 12, 'correct result')
})
var filepath1 = '.retries1';
var child1 = workerFarm({maxConcurrentWorkers: 1, maxRetries: 5}, childPath, [
'stubborn',
]);
child1.stubborn(filepath1, function(err, result) {
t.notOk(err, 'no error');
t.equal(result, 12, 'correct result');
});
workerFarm.end(child1, function () {
fs.unlinkSync(filepath1)
t.ok(true, 'workerFarm ended')
})
workerFarm.end(child1, function() {
fs.unlinkSync(filepath1);
t.ok(true, 'workerFarm ended');
});
var filepath2 = '.retries2'
var child2 = workerFarm({ maxConcurrentWorkers: 1, maxRetries: 3}, childPath, [ 'stubborn' ])
child2.stubborn(filepath2, function (err, result) {
t.ok(err, 'got an error')
t.equal(err.type, 'ProcessTerminatedError', 'correct error type')
t.equal(err.message, 'cancel after 3 retries!', 'correct message and number of retries')
})
var filepath2 = '.retries2';
var child2 = workerFarm({maxConcurrentWorkers: 1, maxRetries: 3}, childPath, [
'stubborn',
]);
child2.stubborn(filepath2, function(err, result) {
t.ok(err, 'got an error');
t.equal(err.type, 'ProcessTerminatedError', 'correct error type');
t.equal(
err.message,
'cancel after 3 retries!',
'correct message and number of retries',
);
});
workerFarm.end(child2, function () {
fs.unlinkSync(filepath2)
t.ok(true, 'workerFarm ended')
})
})
workerFarm.end(child2, function() {
fs.unlinkSync(filepath2);
t.ok(true, 'workerFarm ended');
});
});

View File

@ -4,6 +4,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
const fs = require('fs');

View File

@ -4,6 +4,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
const spawn = require('child_process').spawnSync;
@ -14,9 +16,8 @@ module.exports = function runCommand(cmd, args, cwd) {
cwd = __dirname;
}
const displayArgs = args.length > 25
? args.slice(0, 25) + '...'
: args.join(' ');
const displayArgs =
args.length > 25 ? args.slice(0, 25) + '...' : args.join(' ');
console.log(chalk.dim('$ cd ' + cwd + `\n$ ${cmd} ${displayArgs}\n`));
const result = spawn(cmd, args, {
cwd,

View File

@ -4,6 +4,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
/**
@ -38,14 +40,14 @@ const IGNORE_PATTERN = '**/__tests__/**';
const PACKAGES_DIR = path.resolve(__dirname, '../packages');
const babelNodeOptions = JSON.parse(
fs.readFileSync(path.resolve(__dirname, '..', '.babelrc'), 'utf8')
fs.readFileSync(path.resolve(__dirname, '..', '.babelrc'), 'utf8'),
);
babelNodeOptions.babelrc = false;
const babelEs5Options = Object.assign(
{},
babelNodeOptions,
{presets: 'env'},
{plugins: [].concat(babelNodeOptions.plugins, 'transform-runtime')}
{plugins: [].concat(babelNodeOptions.plugins, 'transform-runtime')},
);
const fixedWidth = str => {
@ -55,7 +57,10 @@ const fixedWidth = str => {
if (lastString.length < WIDTH) {
lastString += Array(WIDTH - lastString.length).join(chalk.dim('.'));
}
return strs.slice(0, -1).concat(lastString).join('\n');
return strs
.slice(0, -1)
.concat(lastString)
.join('\n');
};
function getPackageName(file) {
@ -87,13 +92,13 @@ function buildFile(file, silent) {
const pkgJsonPath = path.resolve(
PACKAGES_DIR,
getPackageName(file),
'package.json'
'package.json',
);
const browser = require(pkgJsonPath).browser;
if (browser) {
if (browser.indexOf(BUILD_ES5_DIR) !== 0) {
throw new Error(
`browser field for ${pkgJsonPath} should start with "${BUILD_ES5_DIR}"`
`browser field for ${pkgJsonPath} should start with "${BUILD_ES5_DIR}"`,
);
}
buildFileFor(file, silent, 'es5');
@ -111,7 +116,7 @@ function buildFileFor(file, silent, env) {
process.stdout.write(
chalk.dim(' \u2022 ') +
path.relative(PACKAGES_DIR, file) +
' (ignore)\n'
' (ignore)\n',
);
} else if (!micromatch.isMatch(file, JS_FILES_PATTERN)) {
fs.createReadStream(file).pipe(fs.createWriteStream(destPath));
@ -122,7 +127,7 @@ function buildFileFor(file, silent, env) {
chalk.red(' \u21D2 ') +
path.relative(PACKAGES_DIR, destPath) +
' (copy)' +
'\n'
'\n',
);
} else {
const transformed = babel.transformFileSync(file, babelOptions).code;
@ -136,7 +141,7 @@ function buildFileFor(file, silent, env) {
path.relative(PACKAGES_DIR, file) +
chalk.green(' \u21D2 ') +
path.relative(PACKAGES_DIR, destPath) +
'\n'
'\n',
);
}
}

View File

@ -4,6 +4,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
/**
@ -36,13 +38,13 @@ const reporter = createReporter();
const mapFileCoverage = fileCoverage => {
fileCoverage.path = fileCoverage.path.replace(
/(.*packages\/.*\/)(build)(\/.*)/,
'$1src$3'
'$1src$3',
);
return fileCoverage;
};
Object.keys(coverage).forEach(filename =>
map.addFileCoverage(mapFileCoverage(coverage[filename]))
map.addFileCoverage(mapFileCoverage(coverage[filename])),
);
reporter.addAll(['json', 'lcov', 'text']);

View File

@ -4,6 +4,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
const path = require('path');

View File

@ -5,6 +5,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
'use strict';

View File

@ -4,6 +4,8 @@
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @format
*/
/**
@ -46,7 +48,7 @@ getPackages().forEach(p => {
chalk.red(' \u2022 ') +
path.relative(path.resolve(srcDir, '..', '..'), buildFile) +
' (deleted)' +
'\n'
'\n',
);
} catch (e) {}
}