Skip to content
This repository was archived by the owner on May 5, 2023. It is now read-only.

Commit 9d25bb6

Browse files
committed
Fix filename option
1 parent ccc3445 commit 9d25bb6

File tree

2 files changed

+26
-7
lines changed

2 files changed

+26
-7
lines changed

src/index.ts

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import { generate } from 'escodegen';
33
import { parseScript } from 'esprima';
44
import { visit, namedTypes as n, builders as b } from 'ast-types';
55
import { Context, RunningScriptOptions } from 'vm';
6-
import { VM } from 'vm2';
6+
import { VM, VMScript } from 'vm2';
77

88
/**
99
* Compiles sync JavaScript code into JavaScript with async Functions.
@@ -138,7 +138,10 @@ namespace degenerator {
138138
): (...args: A) => Promise<R> {
139139
const compiled = degenerator(code, names);
140140
const vm = new VM(options);
141-
const fn = vm.run(`${compiled};${returnName}`);
141+
const script = new VMScript(`${compiled};${returnName}`, {
142+
filename: options.filename,
143+
});
144+
const fn = vm.run(script);
142145
if (typeof fn !== 'function') {
143146
throw new Error(
144147
`Expected a "function" to be returned for \`${returnName}\`, but got "${typeof fn}"`

test/test.ts

Lines changed: 21 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -159,26 +159,42 @@ describe('degenerator()', () => {
159159
assert.equal(val, 'foo');
160160
});
161161
});
162-
it('should prevent privilege escalation of untrusted code', async() => {
162+
it('should prevent privilege escalation of untrusted code', async () => {
163163
let err;
164164
try {
165165
const fn = compile<typeof process>(
166166
`const f = this.constructor.constructor('return process');`,
167167
'f',
168-
[],
168+
[]
169169
);
170170
await fn();
171-
} catch(_err) {
171+
} catch (_err) {
172172
err = _err;
173173
}
174-
assert.equal(err.message,'process is not defined')
174+
assert.equal(err.message, 'process is not defined');
175175
});
176176
it('should allow to return synchronous undefined', () => {
177177
function u() {}
178178
const fn = compile(`${u}`, 'u', ['']);
179-
return fn().then(val => {
179+
return fn().then((val) => {
180180
assert.strictEqual(val, undefined);
181181
});
182182
});
183+
it('should support "filename" option', async () => {
184+
function u() {
185+
throw new Error('fail');
186+
}
187+
let err;
188+
const fn = compile(`${u}`, 'u', [''], {
189+
filename: '/foo/bar/baz.js',
190+
});
191+
try {
192+
await fn();
193+
} catch (_err) {
194+
err = _err;
195+
}
196+
assert.strictEqual(err.message, 'fail');
197+
assert(err.stack.includes('at u (/foo/bar/baz.js:'));
198+
});
183199
});
184200
});

0 commit comments

Comments
 (0)