UNPKG

2.46 kBJavaScriptView Raw
1'use strict';
2
3var osHomedir = require('os-homedir'),
4 path = require('path'),
5 replHistory = require('repl.history');
6
7// used as the special var to assign the result of REPL expressions
8var specialVar = process.env.SPECIAL_VAR || '$';
9
10// store method reference in case it is overwritten later
11var getDescriptor = Object.getOwnPropertyDescriptor,
12 setDescriptor = Object.defineProperty;
13
14// create REPL server instance
15var repl = require('repl'),
16 server = repl.start({
17 prompt: 'n_ > ',
18 // allow strict mode via environment variable
19 replMode: (process.env.NODE_REPL_MODE === 'strict' || process.argv.indexOf('--use_strict') !== -1) ? repl.REPL_MODE_STRICT : repl.REPL_MODE_MAGIC
20 });
21
22// save repl history
23replHistory(server, path.join(osHomedir(), '.n_repl_history'));
24
25// create new pristine `lodash` instance
26var _ = require(process.env.N_LODASH_REQUIRE_PATH || 'lodash').runInContext(server.context);
27
28var lodashToInject = process.argv.indexOf('--fp') === -1 ? _ : require('lodash/fp').runInContext(server.context);
29
30// state vars
31var prevVal = lodashToInject,
32 currVal = lodashToInject;
33
34// inject lodash into the context
35setDescriptor(server.context, '_', {
36 'configurable': true,
37 'enumerable': false,
38 'get': function () {
39 return currVal;
40 },
41 'set': function (val) {
42 prevVal = currVal;
43 currVal = val;
44 }
45});
46
47var useRedirect = parseInt(process.version.split('.')[0].split('v')[1]) < 6; // node < 6.x
48function redirect(context) {
49 /* istanbul ignore next */ // we do cover this - see .travis.yml
50 if (useRedirect) {
51 context[specialVar] = context._;
52 }
53}
54
55// in node < 6.x redirect REPL changes of `_` to the new special variable
56_.each(repl._builtinLibs, function (name) {
57 var context = server.context,
58 descriptor = getDescriptor(context, name);
59
60 setDescriptor(context, name, _.assign(descriptor, {
61 'get': _.wrap(descriptor.get, function (get) {
62 var context = server.context,
63 result = get();
64
65 redirect(context);
66 currVal = prevVal;
67 return result;
68 })
69 }));
70});
71
72var events = server.rli._events;
73events.line = _.wrap(events.line, function (line, cmd) {
74 var context = server.context;
75 line[0](cmd); // actual command execution
76 line[1](cmd); // history persistance
77 redirect(context);
78 currVal = prevVal;
79});
80
81module.exports = server;