|
| 1 | +#include <node.h> |
| 2 | +#include <assert.h> |
| 3 | + |
| 4 | +namespace { |
| 5 | + |
| 6 | +using v8::Context; |
| 7 | +using v8::Function; |
| 8 | +using v8::FunctionTemplate; |
| 9 | +using v8::Isolate; |
| 10 | +using v8::Local; |
| 11 | +using v8::MaybeLocal; |
| 12 | +using v8::NewStringType; |
| 13 | +using v8::Object; |
| 14 | +using v8::Script; |
| 15 | +using v8::String; |
| 16 | +using v8::Value; |
| 17 | + |
| 18 | +inline void RunInNewContext( |
| 19 | + const v8::FunctionCallbackInfo<v8::Value>& args) { |
| 20 | + Isolate* isolate = args.GetIsolate(); |
| 21 | + Local<Context> context = Context::New(isolate); |
| 22 | + Context::Scope context_scope(context); |
| 23 | + |
| 24 | + context->Global()->Set( |
| 25 | + context, |
| 26 | + String::NewFromUtf8(isolate, "data", NewStringType::kNormal) |
| 27 | + .ToLocalChecked(), |
| 28 | + args[1]).FromJust(); |
| 29 | + |
| 30 | + assert(args[0]->IsString()); // source code |
| 31 | + Local<Script> script; |
| 32 | + Local<Value> ret; |
| 33 | + if (!Script::Compile(context, args[0].As<String>()).ToLocal(&script) || |
| 34 | + !script->Run(context).ToLocal(&ret)) { |
| 35 | + return; |
| 36 | + } |
| 37 | + |
| 38 | + args.GetReturnValue().Set(ret); |
| 39 | +} |
| 40 | + |
| 41 | +inline void Initialize(Local<Object> exports, |
| 42 | + Local<Value> module, |
| 43 | + Local<Context> context) { |
| 44 | + Isolate* isolate = context->GetIsolate(); |
| 45 | + Local<String> key = String::NewFromUtf8( |
| 46 | + isolate, "runInNewContext", NewStringType::kNormal).ToLocalChecked(); |
| 47 | + Local<Function> value = FunctionTemplate::New(isolate, RunInNewContext) |
| 48 | + ->GetFunction(context) |
| 49 | + .ToLocalChecked(); |
| 50 | + assert(exports->Set(context, key, value).IsJust()); |
| 51 | +} |
| 52 | + |
| 53 | +} // anonymous namespace |
| 54 | + |
| 55 | +NODE_MODULE_CONTEXT_AWARE(NODE_GYP_MODULE_NAME, Initialize) |
0 commit comments