on master help sign in
Merge pull request #59 from replit/am-globe

Better global support

commit2c6459fbabe6db1df9f795665082f1c8bf5dc8b3 authorAmjad Masad <amjad.masad@gmail.com> dateFri 11 Sep 2020, 19:18 (6 years ago) parent4692e8d0797e31
4 files changed+42−16
languages/nodejs/repl.js+19−15 test_files/global_bug.js+12 tests/nodejs/eval_code.exp+1−1 tests/nodejs/global_bug.exp+10
languages/nodejs/repl.js+19−15
@@ -1,4 +1,4 @@
1−const util = require('util');
1+const util = require("util");
22const repl = require("repl");
33const path = require("path");
44const fs = require("fs");
@@ -134,31 +134,35 @@ if (process.env.PRYBAR_CODE) {
134134
135135 process.mainModule = module;
136136 const sandbox = {
137+ console,
137138 module,
138139 require: module.require.bind(module),
139140 __dirname: path.dirname(mainPath),
140141 __filename: mainPath,
141−
142− // These are deprecated properties and accessing them will trigger a warning.
143− // We add them manually for backward compat.
144− GLOBAL: global,
145− root: global,
146142 };
147143
148− // These properties will show a warning. We can avoid them.
149− for (const prop of Object.getOwnPropertyNames(global)) {
150− if (sandbox.hasOwnProperty(prop)) {
151− continue;
152− }
153−
154− sandbox[prop] = global[prop];
155− }
156−
157144 console.log(
158145 "\u001b[0m\u001b[90mHint: hit control+c anytime to enter REPL.\u001b[0m"
159146 );
160147 const context = vm.createContext(sandbox);
161148
149+ // Adapted from https://bit.ly/2Fc4WjM
150+ const globalBuiltins = new Set(
151+ vm.runInContext("Object.getOwnPropertyNames(globalThis)", context)
152+ );
153+
154+ for (const name of Object.getOwnPropertyNames(global)) {
155+ // Only set properties that do not already exist as a global builtin.
156+ if (!globalBuiltins.has(name)) {
157+ Object.defineProperty(
158+ context,
159+ name,
160+ Object.getOwnPropertyDescriptor(global, name)
161+ );
162+ }
163+ }
164+ context.global = context;
165+
162166 let script;
163167 try {
164168 script = vm.createScript(main, {
test_files/global_bug.jsnew file+12
@@ -0,0 +1,12 @@
1+console.log([] instanceof global.Array);
2+console.assert(process);
3+console.assert(URL);
4+console.assert(URLSearchParams);
5+console.assert(clearImmediate);
6+console.assert(clearInterval);
7+console.assert(clearTimeout);
8+console.assert(setImmediate);
9+console.assert(setInterval);
10+console.assert(setTimeout);
11+console.assert(Buffer);
12+console.assert(globalThis === global);
tests/nodejs/eval_code.exp+1−1
@@ -1,4 +1,4 @@
1−#!/usr/bin/expect -d
1+#!/usr/bin/expect -f
22
33set timeout -1
44spawn ./prybar-nodejs -q -e 1+1
tests/nodejs/global_bug.expnew file+10
@@ -0,0 +1,10 @@
1+#!/usr/bin/expect -f
2+
3+set timeout -1
4+spawn ./prybar-nodejs ./test_files/global_bug.js
5+match_max 100000
6+expect -exact "Node v12.18.3 on linux\r
7+\u001b\[0m\u001b\[90mHint: hit control+c anytime to enter REPL.\[0m\r
8+\u001b\[33mtrue\u001b\[39m\r
9+"
10+expect eof