-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
75 lines (63 loc) · 1.84 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// @flow
'use strict';
const path = require('path');
const child = require('child_process');
const CHILD_SCRIPT = path.join(__dirname, 'child.js');
/*::
type Serializeable =
| null
| number
| boolean
| string
| Array<Serializeable>
| { [key: string]: Serializeable };
type Projector =
& ((script: string, args?: Array<Serializeable>) => Promise<Serializeable>)
& ((script: string, exportName?: string, args?: Array<Serializeable>) => Promise<Serializeable>);
*/
function projector(script, exportName, args) {
if (arguments.length === 1) {
exportName = 'default';
args = [];
} else if (arguments.length === 2) {
if (typeof exportName === 'object') {
args = exportName;
exportName = 'default';
} else {
args = [];
}
} else if (typeof exportName === 'undefined') {
exportName = 'default';
}
if (typeof script !== 'string') {
throw new Error('Projector script must be a string');
}
if (typeof exportName !== 'string') {
throw new Error('Projector export name must be a string');
}
if (!Array.isArray(args)) {
throw new Error('Projector `args` must be an array');
}
return new Promise((resolve, reject) => {
let proc = child.fork(CHILD_SCRIPT, {
silent: false
});
proc.on('message', ({ status, payload }) => {
if (status === 'ready') {
proc.send({ script, exportName, args });
} else if (status === 'complete') {
resolve(payload);
} else if (status === 'error') {
let err = new Error(payload.message);
err.stack = payload.stack;
reject(err);
} else {
reject(new Error('Recieved unknown message from child process.'));
}
});
proc.on('close', () => {
reject(new Error('Never recieved a response from child process.'));
});
});
}
module.exports = (projector /*: Projector */);