本文整理汇总了TypeScript中vm.runInNewContext函数的典型用法代码示例。如果您正苦于以下问题:TypeScript runInNewContext函数的具体用法?TypeScript runInNewContext怎么用?TypeScript runInNewContext使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了runInNewContext函数的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。
示例1:
(function () {
var sandbox = { expTypeScript: null };
var typescriptmodulefile = require.resolve("typescript");
var location = path.dirname(typescriptmodulefile);
var tmp = module.exports._libdPath = require.resolve(location + '/lib.d.ts');
var contents = [
"(function() {",
fs.readFileSync(typescriptmodulefile, "utf8"),
"expTypeScript = TypeScript;",
"}).call({});"
].join("");
vm.runInNewContext(contents, sandbox, 'ts.vm');
var TypeScript = module.exports.TypeScript = sandbox.expTypeScript;
TypeScript.moduleGenTarget = TypeScript.ModuleGenTarget.Synchronous;
})();
示例2: Error
b.bundle((err, src) => {
if (err) {
throw new Error("failed to bundle!");
}
vm.runInNewContext(src.toString(), {
test: t.test.bind(t),
Buffer,
Int8Array,
Int16Array,
Int32Array,
Float32Array,
Float64Array,
Uint8Array,
Uint16Array,
Uint32Array,
Uint8ClampedArray,
console: { log: console.log.bind(console) }
});
t.end();
});
示例3: test
test('bundleNextModule should bundle a virtual empty module per external falsy configuration', t => {
const modules: any[] = [];
const plugins = {};
const globals = {
global: false,
process: false,
buffer: false
};
const host = new HostMock({});
enqueueModule('fs');
bundleNextModule(modules, { config: { externals: { fs: false } } as any, host }, globals, plugins);
const sandbox = {
module: {
exports: {
}
}
};
runInNewContext(generate(modules[0]) + '_0(module, module.exports);', sandbox);
t.deepEqual(sandbox.module.exports, {});
});
示例4:
const sandbox = {
animal: 'cat',
count: 2
};
const context = vm.createContext(sandbox);
console.log(vm.isContext(context));
const script = new vm.Script('count += 1; name = "kitty"');
for (let i = 0; i < 10; ++i) {
script.runInContext(context);
}
console.log(util.inspect(sandbox));
vm.runInNewContext('count += 1; name = "kitty"', sandbox);
console.log(util.inspect(sandbox));
}
{
const sandboxes = [{}, {}, {}];
const script = new vm.Script('globalVar = "set"');
sandboxes.forEach((sandbox) => {
script.runInNewContext(sandbox);
script.runInThisContext();
});
console.log(util.inspect(sandboxes));
示例5: beforeEach
beforeEach(() => {
mockContext = vm.createContext();
mockGlobals = vm.runInNewContext('this', mockContext);
moduleMocker = new ModuleMocker(mockGlobals);
});
示例6: visitDQSTRING
visitDQSTRING(dqstring: DescentParserNode, streams: Stream[], callback: executionCallback): void {
const value = vm.runInNewContext(dqstring.token.text);
callback(value);
}
示例7: it
it('should be able to encode Arrays across stack frames', function() {
assert.equal(
vm.runInNewContext("RLP.encode(['dog', 'god', 'cat']).toString('hex')", { RLP }),
'cc83646f6783676f6483636174',
)
})
示例8: field
export const evaluate = (connection: SendableConnection, message: NewEvalMessage, onDispose: () => void, fork?: ForkProvider): ActiveEvaluation | void => {
/**
* Send the response and call onDispose.
*/
// tslint:disable-next-line no-any
const sendResp = (resp: any): void => {
logger.trace(() => [
"resolve",
field("id", message.getId()),
field("response", stringify(resp)),
]);
const evalDone = new EvalDoneMessage();
evalDone.setId(message.getId());
evalDone.setResponse(stringify(resp));
const serverMsg = new ServerMessage();
serverMsg.setEvalDone(evalDone);
connection.send(serverMsg.serializeBinary());
onDispose();
};
/**
* Send an exception and call onDispose.
*/
const sendException = (error: Error): void => {
logger.trace(() => [
"reject",
field("id", message.getId()),
field("response", stringify(error, true)),
]);
const evalFailed = new EvalFailedMessage();
evalFailed.setId(message.getId());
evalFailed.setResponse(stringify(error, true));
const serverMsg = new ServerMessage();
serverMsg.setEvalFailed(evalFailed);
connection.send(serverMsg.serializeBinary());
onDispose();
};
let eventEmitter = message.getActive() ? new EventEmitter(): undefined;
const sandbox = {
helper: eventEmitter ? new ServerActiveEvalHelper({
removeAllListeners: (event?: string): void => {
eventEmitter!.removeAllListeners(event);
},
// tslint:disable no-any
on: (event: string, cb: (...args: any[]) => void): void => {
eventEmitter!.on(event, (...args: any[]) => {
logger.trace(() => [
`${event}`,
field("id", message.getId()),
field("args", args.map((a) => stringify(a))),
]);
cb(...args);
});
},
emit: (event: string, ...args: any[]): void => {
logger.trace(() => [
`emit ${event}`,
field("id", message.getId()),
field("args", args.map((a) => stringify(a))),
]);
const eventMsg = new EvalEventMessage();
eventMsg.setEvent(event);
eventMsg.setArgsList(args.map((a) => stringify(a)));
eventMsg.setId(message.getId());
const serverMsg = new ServerMessage();
serverMsg.setEvalEvent(eventMsg);
connection.send(serverMsg.serializeBinary());
},
// tslint:enable no-any
}, fork || cpFork) : new EvalHelper(),
_Buffer: Buffer,
// When the client is ran from Webpack, it will replace
// __non_webpack_require__ with require, which we then need to provide to
// the sandbox. Since the server might also be using Webpack, we need to set
// it to the non-Webpack version when that's the case. Then we need to also
// provide __non_webpack_require__ for when the client doesn't run through
// Webpack meaning it doesn't get replaced with require (Jest for example).
require: typeof __non_webpack_require__ !== "undefined" ? __non_webpack_require__ : require,
__non_webpack_require__: typeof __non_webpack_require__ !== "undefined" ? __non_webpack_require__ : require,
setTimeout,
setInterval,
clearTimeout,
process: {
env: process.env,
},
args: message.getArgsList().map(parse),
};
let value: any; // tslint:disable-line no-any
try {
const code = `(${message.getFunction()})(helper, ...args);`;
value = vm.runInNewContext(code, sandbox, {
// If the code takes longer than this to return, it is killed and throws.
//.........这里部分代码省略.........
示例9: initializeTests
public initializeTests() {
switch (this.testType) {
case UnittestTestType.Compiler:
this.tests = this.enumerateFiles('tests/cases/unittests/compiler');
break;
case UnittestTestType.LanguageService:
this.tests = this.enumerateFiles('tests/cases/unittests/ls');
break;
case UnittestTestType.Services:
this.tests = this.enumerateFiles('tests/cases/unittests/services');
break;
case UnittestTestType.Harness:
this.tests = this.enumerateFiles('tests/cases/unittests/harness');
break;
case UnittestTestType.Samples:
this.tests = this.enumerateFiles('tests/cases/unittests/samples');
break;
default:
if (this.tests.length === 0) {
throw new Error('Unsupported test cases: ' + this.testType);
}
break;
}
var outfile = new Harness.Compiler.WriterAggregator()
var outerr = new Harness.Compiler.WriterAggregator();
var harnessCompiler = Harness.Compiler.getCompiler(Harness.Compiler.CompilerInstance.DesignTime);
var toBeAdded = this.tests.map(test => {
return { unitName: test, content: TypeScript.IO.readFile(test, /*codepage:*/ null).contents }
});
harnessCompiler.addInputFiles(toBeAdded);
harnessCompiler.compile({ noResolve: true });
var stdout = new Harness.Compiler.EmitterIOHost();
var emitDiagnostics = harnessCompiler.emitAll(stdout);
var results = stdout.toArray();
var lines: string[] = [];
results.forEach(v => lines = lines.concat(v.file.lines));
var code = lines.join("\n")
describe("Setup compiler for compiler unittests", () => {
Harness.Compiler.recreate(Harness.Compiler.CompilerInstance.RunTime, { useMinimalDefaultLib: this.testType !== UnittestTestType.Samples, noImplicitAny: false });
});
if (typeof require !== "undefined") {
var vm = require('vm');
vm.runInNewContext(code,
{
require: require,
TypeScript: TypeScript,
process: process,
describe: describe,
it: it,
assert: Harness.Assert,
Harness: Harness,
IO: TypeScript.IO,
Exec: Exec,
Services: TypeScript.Services,
// Formatting: Formatting,
Diff: Diff,
FourSlash: FourSlash
},
"generated_test_code.js"
);
} else {
eval(code);
}
// make sure the next unittestrunner doesn't include the previous one's stuff
Harness.Compiler.recreate(Harness.Compiler.CompilerInstance.DesignTime);
}
示例10: executeFixComments
function executeFixComments(input: string, files: any = {}, settings: any = {}): any {
const processed = fixComments(input, files);
const result = {};
runInNewContext(processed, result);
return result;
}