diff --git a/src/contextify.cc b/src/contextify.cc new file mode 100644 index 00000000000000..0a2439f4be0808 --- /dev/null +++ b/src/contextify.cc @@ -0,0 +1,54 @@ +#include "contextify.h" +#include + +void ContextifyContext::Initialize(v8::Local target) { + v8::Local t = Nan::New(Nan::New([](const v8::FunctionCallbackInfo& args) { + if (args.IsConstructCall()) { + ContextifyContext* context = new ContextifyContext(); + context->Wrap(args.This()); + Nan::SetPrototypeMethod(args.Callee(), "createContext", createContext); + Nan::SetPrototypeMethod(args.Callee(), "definePropertyOnContext", definePropertyOnContext); + } + })); + + v8::Local proto = Nan::New([](const v8::FunctionCallbackInfo& args) { + if (args.IsConstructCall()) { + ContextifyContext* context = new ContextifyContext(); + context->Wrap(args.This()); + Nan::SetPrototypeMethod(args.Callee(), "createContext", createContext); + Nan::SetPrototypeMethod(args.Callee(), "definePropertyOnContext", definePropertyOnContext); + } + }); + + Nan::Set(target, Nan::New("ContextifyContext").ToLocalChecked(), t->GetFunction()); +} + +v8::Local ContextifyContext::CreateContext(v8::Local sandbox) { + v8::Local context = v8::Context::New(Nan::GetCurrentContext()->GetIsolate()); + v8::Local global = context->Global(); + + // Copy properties from sandbox to context + v8::Local props = sandbox->GetPropertyNames(); + for (uint32_t i = 0; i < props->Length(); i++) { + v8::Local prop = props->Get(i); + v8::Local value = sandbox->Get(prop); + context->Global()->Set(context, prop, value); + } + + return context; +} + +void ContextifyContext::PropertyDefinerCallback(v8::Local property, const v8::PropertyCallbackInfo& info) { + v8::Isolate* isolate = info.GetIsolate(); + v8::Local context = isolate->GetCurrentContext(); + v8::Local global = context->Global(); + + // Check if property exists in global + if (global->Has(context, property).FromJust()) { + v8::Local value = global->Get(context, property).ToLocalChecked(); + info.GetReturnValue().Set(value); + } else { + // Intercept the request and return undefined + info.GetReturnValue().SetUndefined(); + } +} \ No newline at end of file diff --git a/src/contextify.h b/src/contextify.h new file mode 100644 index 00000000000000..f44cd2c05d7c01 --- /dev/null +++ b/src/contextify.h @@ -0,0 +1,14 @@ +#ifndef CONTEXTIFY_H +#define CONTEXTIFY_H + +#include +#include + +class ContextifyContext { +public: + static void Initialize(v8::Local target); + static v8::Local CreateContext(v8::Local sandbox); + static void PropertyDefinerCallback(v8::Local property, const v8::PropertyCallbackInfo& info); +}; + +#endif // CONTEXTIFY_H \ No newline at end of file