Roll src/third_party/WebKit 395ff9e:18c0088 (svn 192995:192997)
[chromium-blink-merge.git] / extensions / renderer / module_system.cc
blob6194b8ed4c4be059a5f298055d91df3b00bc4cab
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "extensions/renderer/module_system.h"
7 #include "base/bind.h"
8 #include "base/command_line.h"
9 #include "base/stl_util.h"
10 #include "base/strings/string_util.h"
11 #include "base/strings/stringprintf.h"
12 #include "base/trace_event/trace_event.h"
13 #include "content/public/renderer/render_frame.h"
14 #include "content/public/renderer/render_view.h"
15 #include "extensions/common/extension.h"
16 #include "extensions/common/extensions_client.h"
17 #include "extensions/renderer/console.h"
18 #include "extensions/renderer/safe_builtins.h"
19 #include "extensions/renderer/script_context.h"
20 #include "gin/modules/module_registry.h"
21 #include "third_party/WebKit/public/web/WebFrame.h"
22 #include "third_party/WebKit/public/web/WebScopedMicrotaskSuppression.h"
24 namespace extensions {
26 namespace {
28 const char* kModuleSystem = "module_system";
29 const char* kModuleName = "module_name";
30 const char* kModuleField = "module_field";
31 const char* kModulesField = "modules";
33 // Logs a fatal error for the calling context, with some added metadata about
34 // the context:
35 // - Its type (blessed, unblessed, etc).
36 // - Whether it's valid.
37 // - The extension ID, if one exists.
39 // This will only actual be fatal in in dev/canary, since in too many cases
40 // we're at the mercy of the extension or web page's environment. They can mess
41 // up our JS in unexpected ways. Hopefully dev/canary channel will pick up such
42 // problems, but given the wider variety on stable/beta it's impossible to know.
43 void Fatal(ScriptContext* context, const std::string& message) {
44 // Prepend some context metadata.
45 std::string full_message = "(";
46 if (!context->is_valid())
47 full_message += "Invalid ";
48 full_message += context->GetContextTypeDescription();
49 full_message += " context";
50 if (context->extension()) {
51 full_message += " for ";
52 full_message += context->extension()->id();
54 full_message += ") ";
55 full_message += message;
57 if (ExtensionsClient::Get()->ShouldSuppressFatalErrors())
58 console::Error(context->isolate()->GetCallingContext(), full_message);
59 else
60 console::Fatal(context->isolate()->GetCallingContext(), full_message);
63 void Warn(v8::Isolate* isolate, const std::string& message) {
64 console::Warn(isolate->GetCallingContext(), message);
67 // Default exception handler which logs the exception.
68 class DefaultExceptionHandler : public ModuleSystem::ExceptionHandler {
69 public:
70 explicit DefaultExceptionHandler(ScriptContext* context)
71 : context_(context) {}
73 // Fatally dumps the debug info from |try_catch| to the console.
74 // Make sure this is never used for exceptions that originate in external
75 // code!
76 void HandleUncaughtException(const v8::TryCatch& try_catch) override {
77 v8::HandleScope handle_scope(context_->isolate());
78 std::string stack_trace = "<stack trace unavailable>";
79 if (!try_catch.StackTrace().IsEmpty()) {
80 v8::String::Utf8Value stack_value(try_catch.StackTrace());
81 if (*stack_value)
82 stack_trace.assign(*stack_value, stack_value.length());
83 else
84 stack_trace = "<could not convert stack trace to string>";
86 Fatal(context_, CreateExceptionString(try_catch) + "{" + stack_trace + "}");
89 private:
90 ScriptContext* context_;
93 } // namespace
95 std::string ModuleSystem::ExceptionHandler::CreateExceptionString(
96 const v8::TryCatch& try_catch) {
97 v8::Handle<v8::Message> message(try_catch.Message());
98 if (message.IsEmpty()) {
99 return "try_catch has no message";
102 std::string resource_name = "<unknown resource>";
103 if (!message->GetScriptOrigin().ResourceName().IsEmpty()) {
104 v8::String::Utf8Value resource_name_v8(
105 message->GetScriptOrigin().ResourceName());
106 resource_name.assign(*resource_name_v8, resource_name_v8.length());
109 std::string error_message = "<no error message>";
110 if (!message->Get().IsEmpty()) {
111 v8::String::Utf8Value error_message_v8(message->Get());
112 error_message.assign(*error_message_v8, error_message_v8.length());
115 return base::StringPrintf("%s:%d: %s",
116 resource_name.c_str(),
117 message->GetLineNumber(),
118 error_message.c_str());
121 ModuleSystem::ModuleSystem(ScriptContext* context, SourceMap* source_map)
122 : ObjectBackedNativeHandler(context),
123 context_(context),
124 source_map_(source_map),
125 natives_enabled_(0),
126 exception_handler_(new DefaultExceptionHandler(context)),
127 weak_factory_(this) {
128 RouteFunction(
129 "require",
130 base::Bind(&ModuleSystem::RequireForJs, base::Unretained(this)));
131 RouteFunction(
132 "requireNative",
133 base::Bind(&ModuleSystem::RequireNative, base::Unretained(this)));
134 RouteFunction(
135 "requireAsync",
136 base::Bind(&ModuleSystem::RequireAsync, base::Unretained(this)));
137 RouteFunction("privates",
138 base::Bind(&ModuleSystem::Private, base::Unretained(this)));
140 v8::Handle<v8::Object> global(context->v8_context()->Global());
141 v8::Isolate* isolate = context->isolate();
142 global->SetHiddenValue(v8::String::NewFromUtf8(isolate, kModulesField),
143 v8::Object::New(isolate));
144 global->SetHiddenValue(v8::String::NewFromUtf8(isolate, kModuleSystem),
145 v8::External::New(isolate, this));
147 gin::ModuleRegistry::From(context->v8_context())->AddObserver(this);
148 if (context_->GetRenderFrame()) {
149 context_->GetRenderFrame()->EnsureMojoBuiltinsAreAvailable(
150 context->isolate(), context->v8_context());
154 ModuleSystem::~ModuleSystem() { Invalidate(); }
156 void ModuleSystem::Invalidate() {
157 if (!is_valid())
158 return;
160 // Clear the module system properties from the global context. It's polite,
161 // and we use this as a signal in lazy handlers that we no longer exist.
163 v8::HandleScope scope(GetIsolate());
164 v8::Handle<v8::Object> global = context()->v8_context()->Global();
165 global->DeleteHiddenValue(
166 v8::String::NewFromUtf8(GetIsolate(), kModulesField));
167 global->DeleteHiddenValue(
168 v8::String::NewFromUtf8(GetIsolate(), kModuleSystem));
171 // Invalidate all of the successfully required handlers we own.
172 for (NativeHandlerMap::iterator it = native_handler_map_.begin();
173 it != native_handler_map_.end();
174 ++it) {
175 it->second->Invalidate();
178 ObjectBackedNativeHandler::Invalidate();
181 ModuleSystem::NativesEnabledScope::NativesEnabledScope(
182 ModuleSystem* module_system)
183 : module_system_(module_system) {
184 module_system_->natives_enabled_++;
187 ModuleSystem::NativesEnabledScope::~NativesEnabledScope() {
188 module_system_->natives_enabled_--;
189 CHECK_GE(module_system_->natives_enabled_, 0);
192 void ModuleSystem::HandleException(const v8::TryCatch& try_catch) {
193 exception_handler_->HandleUncaughtException(try_catch);
196 v8::Handle<v8::Value> ModuleSystem::Require(const std::string& module_name) {
197 v8::EscapableHandleScope handle_scope(GetIsolate());
198 return handle_scope.Escape(RequireForJsInner(
199 v8::String::NewFromUtf8(GetIsolate(), module_name.c_str())));
202 void ModuleSystem::RequireForJs(
203 const v8::FunctionCallbackInfo<v8::Value>& args) {
204 v8::Handle<v8::String> module_name = args[0]->ToString(args.GetIsolate());
205 args.GetReturnValue().Set(RequireForJsInner(module_name));
208 v8::Local<v8::Value> ModuleSystem::RequireForJsInner(
209 v8::Handle<v8::String> module_name) {
210 v8::EscapableHandleScope handle_scope(GetIsolate());
211 v8::Context::Scope context_scope(context()->v8_context());
213 v8::Handle<v8::Object> global(context()->v8_context()->Global());
215 // The module system might have been deleted. This can happen if a different
216 // context keeps a reference to us, but our frame is destroyed (e.g.
217 // background page keeps reference to chrome object in a closed popup).
218 v8::Handle<v8::Value> modules_value = global->GetHiddenValue(
219 v8::String::NewFromUtf8(GetIsolate(), kModulesField));
220 if (modules_value.IsEmpty() || modules_value->IsUndefined()) {
221 Warn(GetIsolate(), "Extension view no longer exists");
222 return v8::Undefined(GetIsolate());
225 v8::Handle<v8::Object> modules(v8::Handle<v8::Object>::Cast(modules_value));
226 v8::Local<v8::Value> exports(modules->Get(module_name));
227 if (!exports->IsUndefined())
228 return handle_scope.Escape(exports);
230 exports = LoadModule(*v8::String::Utf8Value(module_name));
231 modules->Set(module_name, exports);
232 return handle_scope.Escape(exports);
235 v8::Local<v8::Value> ModuleSystem::CallModuleMethod(
236 const std::string& module_name,
237 const std::string& method_name) {
238 v8::EscapableHandleScope handle_scope(GetIsolate());
239 v8::Handle<v8::Value> no_args;
240 return handle_scope.Escape(
241 CallModuleMethod(module_name, method_name, 0, &no_args));
244 v8::Local<v8::Value> ModuleSystem::CallModuleMethod(
245 const std::string& module_name,
246 const std::string& method_name,
247 std::vector<v8::Handle<v8::Value> >* args) {
248 return CallModuleMethod(
249 module_name, method_name, args->size(), vector_as_array(args));
252 v8::Local<v8::Value> ModuleSystem::CallModuleMethod(
253 const std::string& module_name,
254 const std::string& method_name,
255 int argc,
256 v8::Handle<v8::Value> argv[]) {
257 TRACE_EVENT2("v8",
258 "v8.callModuleMethod",
259 "module_name",
260 module_name,
261 "method_name",
262 method_name);
264 v8::EscapableHandleScope handle_scope(GetIsolate());
265 v8::Context::Scope context_scope(context()->v8_context());
267 v8::Local<v8::Value> module;
269 NativesEnabledScope natives_enabled(this);
270 module = RequireForJsInner(
271 v8::String::NewFromUtf8(GetIsolate(), module_name.c_str()));
274 if (module.IsEmpty() || !module->IsObject()) {
275 Fatal(context_,
276 "Failed to get module " + module_name + " to call " + method_name);
277 return handle_scope.Escape(
278 v8::Local<v8::Primitive>(v8::Undefined(GetIsolate())));
281 v8::Local<v8::Value> value = v8::Handle<v8::Object>::Cast(module)->Get(
282 v8::String::NewFromUtf8(GetIsolate(), method_name.c_str()));
283 if (value.IsEmpty() || !value->IsFunction()) {
284 Fatal(context_, module_name + "." + method_name + " is not a function");
285 return handle_scope.Escape(
286 v8::Local<v8::Primitive>(v8::Undefined(GetIsolate())));
289 v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(value);
290 v8::Local<v8::Value> result;
292 v8::TryCatch try_catch;
293 try_catch.SetCaptureMessage(true);
294 result = context_->CallFunction(func, argc, argv);
295 if (try_catch.HasCaught())
296 HandleException(try_catch);
298 return handle_scope.Escape(result);
301 void ModuleSystem::RegisterNativeHandler(
302 const std::string& name,
303 scoped_ptr<NativeHandler> native_handler) {
304 native_handler_map_[name] =
305 linked_ptr<NativeHandler>(native_handler.release());
308 void ModuleSystem::OverrideNativeHandlerForTest(const std::string& name) {
309 overridden_native_handlers_.insert(name);
312 void ModuleSystem::RunString(const std::string& code, const std::string& name) {
313 v8::HandleScope handle_scope(GetIsolate());
314 RunString(v8::String::NewFromUtf8(GetIsolate(), code.c_str()),
315 v8::String::NewFromUtf8(GetIsolate(), name.c_str()));
318 // static
319 void ModuleSystem::NativeLazyFieldGetter(
320 v8::Local<v8::String> property,
321 const v8::PropertyCallbackInfo<v8::Value>& info) {
322 LazyFieldGetterInner(property, info, &ModuleSystem::RequireNativeFromString);
325 // static
326 void ModuleSystem::LazyFieldGetter(
327 v8::Local<v8::String> property,
328 const v8::PropertyCallbackInfo<v8::Value>& info) {
329 LazyFieldGetterInner(property, info, &ModuleSystem::Require);
332 // static
333 void ModuleSystem::LazyFieldGetterInner(
334 v8::Local<v8::String> property,
335 const v8::PropertyCallbackInfo<v8::Value>& info,
336 RequireFunction require_function) {
337 CHECK(!info.Data().IsEmpty());
338 CHECK(info.Data()->IsObject());
339 v8::HandleScope handle_scope(info.GetIsolate());
340 v8::Handle<v8::Object> parameters = v8::Handle<v8::Object>::Cast(info.Data());
341 // This context should be the same as context()->v8_context().
342 v8::Handle<v8::Context> context = parameters->CreationContext();
343 v8::Handle<v8::Object> global(context->Global());
344 v8::Handle<v8::Value> module_system_value = global->GetHiddenValue(
345 v8::String::NewFromUtf8(info.GetIsolate(), kModuleSystem));
346 if (module_system_value.IsEmpty() || !module_system_value->IsExternal()) {
347 // ModuleSystem has been deleted.
348 // TODO(kalman): See comment in header file.
349 Warn(info.GetIsolate(),
350 "Module system has been deleted, does extension view exist?");
351 return;
354 ModuleSystem* module_system = static_cast<ModuleSystem*>(
355 v8::Handle<v8::External>::Cast(module_system_value)->Value());
357 std::string name = *v8::String::Utf8Value(parameters->Get(
358 v8::String::NewFromUtf8(info.GetIsolate(), kModuleName)));
360 // Switch to our v8 context because we need functions created while running
361 // the require()d module to belong to our context, not the current one.
362 v8::Context::Scope context_scope(context);
363 NativesEnabledScope natives_enabled_scope(module_system);
365 v8::TryCatch try_catch;
366 v8::Handle<v8::Value> module_value = (module_system->*require_function)(name);
367 if (try_catch.HasCaught()) {
368 module_system->HandleException(try_catch);
369 return;
371 if (module_value.IsEmpty() || !module_value->IsObject()) {
372 // require_function will have already logged this, we don't need to.
373 return;
376 v8::Handle<v8::Object> module = v8::Handle<v8::Object>::Cast(module_value);
377 v8::Handle<v8::String> field =
378 parameters->Get(v8::String::NewFromUtf8(info.GetIsolate(), kModuleField))
379 ->ToString(info.GetIsolate());
381 if (!module->Has(field)) {
382 std::string field_str = *v8::String::Utf8Value(field);
383 Fatal(module_system->context_,
384 "Lazy require of " + name + "." + field_str + " did not set the " +
385 field_str + " field");
386 return;
389 v8::Local<v8::Value> new_field = module->Get(field);
390 if (try_catch.HasCaught()) {
391 module_system->HandleException(try_catch);
392 return;
395 // Ok for it to be undefined, among other things it's how bindings signify
396 // that the extension doesn't have permission to use them.
397 CHECK(!new_field.IsEmpty());
399 // Delete the getter and set this field to |new_field| so the same object is
400 // returned every time a certain API is accessed.
401 v8::Handle<v8::Value> val = info.This();
402 if (val->IsObject()) {
403 v8::Handle<v8::Object> object = v8::Handle<v8::Object>::Cast(val);
404 object->Delete(property);
405 object->Set(property, new_field);
406 } else {
407 NOTREACHED();
409 info.GetReturnValue().Set(new_field);
412 void ModuleSystem::SetLazyField(v8::Handle<v8::Object> object,
413 const std::string& field,
414 const std::string& module_name,
415 const std::string& module_field) {
416 SetLazyField(
417 object, field, module_name, module_field, &ModuleSystem::LazyFieldGetter);
420 void ModuleSystem::SetLazyField(v8::Handle<v8::Object> object,
421 const std::string& field,
422 const std::string& module_name,
423 const std::string& module_field,
424 v8::AccessorGetterCallback getter) {
425 v8::HandleScope handle_scope(GetIsolate());
426 v8::Handle<v8::Object> parameters = v8::Object::New(GetIsolate());
427 parameters->Set(v8::String::NewFromUtf8(GetIsolate(), kModuleName),
428 v8::String::NewFromUtf8(GetIsolate(), module_name.c_str()));
429 parameters->Set(v8::String::NewFromUtf8(GetIsolate(), kModuleField),
430 v8::String::NewFromUtf8(GetIsolate(), module_field.c_str()));
431 object->SetAccessor(v8::String::NewFromUtf8(GetIsolate(), field.c_str()),
432 getter,
433 NULL,
434 parameters);
437 void ModuleSystem::SetNativeLazyField(v8::Handle<v8::Object> object,
438 const std::string& field,
439 const std::string& module_name,
440 const std::string& module_field) {
441 SetLazyField(object,
442 field,
443 module_name,
444 module_field,
445 &ModuleSystem::NativeLazyFieldGetter);
448 v8::Handle<v8::Value> ModuleSystem::RunString(v8::Handle<v8::String> code,
449 v8::Handle<v8::String> name) {
450 v8::EscapableHandleScope handle_scope(GetIsolate());
451 v8::Context::Scope context_scope(context()->v8_context());
453 // Prepend extensions:: to |name| so that internal code can be differentiated
454 // from external code in stack traces. This has no effect on behaviour.
455 std::string internal_name =
456 base::StringPrintf("extensions::%s", *v8::String::Utf8Value(name));
458 blink::WebScopedMicrotaskSuppression suppression;
459 v8::TryCatch try_catch;
460 try_catch.SetCaptureMessage(true);
461 v8::Handle<v8::Script> script(
462 v8::Script::Compile(code,
463 v8::String::NewFromUtf8(GetIsolate(),
464 internal_name.c_str(),
465 v8::String::kNormalString,
466 internal_name.size())));
467 if (try_catch.HasCaught()) {
468 HandleException(try_catch);
469 return v8::Undefined(GetIsolate());
472 v8::Local<v8::Value> result = script->Run();
473 if (try_catch.HasCaught()) {
474 HandleException(try_catch);
475 return v8::Undefined(GetIsolate());
478 return handle_scope.Escape(result);
481 v8::Handle<v8::Value> ModuleSystem::GetSource(const std::string& module_name) {
482 v8::EscapableHandleScope handle_scope(GetIsolate());
483 if (!source_map_->Contains(module_name))
484 return v8::Undefined(GetIsolate());
485 return handle_scope.Escape(
486 v8::Local<v8::Value>(source_map_->GetSource(GetIsolate(), module_name)));
489 void ModuleSystem::RequireNative(
490 const v8::FunctionCallbackInfo<v8::Value>& args) {
491 CHECK_EQ(1, args.Length());
492 std::string native_name = *v8::String::Utf8Value(args[0]);
493 args.GetReturnValue().Set(RequireNativeFromString(native_name));
496 v8::Handle<v8::Value> ModuleSystem::RequireNativeFromString(
497 const std::string& native_name) {
498 if (natives_enabled_ == 0) {
499 // HACK: if in test throw exception so that we can test the natives-disabled
500 // logic; however, under normal circumstances, this is programmer error so
501 // we could crash.
502 if (exception_handler_) {
503 return GetIsolate()->ThrowException(
504 v8::String::NewFromUtf8(GetIsolate(), "Natives disabled"));
506 Fatal(context_, "Natives disabled for requireNative(" + native_name + ")");
507 return v8::Undefined(GetIsolate());
510 if (overridden_native_handlers_.count(native_name) > 0u) {
511 return RequireForJsInner(
512 v8::String::NewFromUtf8(GetIsolate(), native_name.c_str()));
515 NativeHandlerMap::iterator i = native_handler_map_.find(native_name);
516 if (i == native_handler_map_.end()) {
517 Fatal(context_,
518 "Couldn't find native for requireNative(" + native_name + ")");
519 return v8::Undefined(GetIsolate());
521 return i->second->NewInstance();
524 void ModuleSystem::RequireAsync(
525 const v8::FunctionCallbackInfo<v8::Value>& args) {
526 CHECK_EQ(1, args.Length());
527 std::string module_name = *v8::String::Utf8Value(args[0]);
528 v8::Handle<v8::Promise::Resolver> resolver(
529 v8::Promise::Resolver::New(GetIsolate()));
530 args.GetReturnValue().Set(resolver->GetPromise());
531 scoped_ptr<v8::Global<v8::Promise::Resolver>> global_resolver(
532 new v8::Global<v8::Promise::Resolver>(GetIsolate(), resolver));
533 gin::ModuleRegistry* module_registry =
534 gin::ModuleRegistry::From(context_->v8_context());
535 if (!module_registry) {
536 Warn(GetIsolate(), "Extension view no longer exists");
537 resolver->Reject(v8::Exception::Error(v8::String::NewFromUtf8(
538 GetIsolate(), "Extension view no longer exists")));
539 return;
541 module_registry->LoadModule(
542 GetIsolate(), module_name,
543 base::Bind(&ModuleSystem::OnModuleLoaded, weak_factory_.GetWeakPtr(),
544 base::Passed(&global_resolver)));
545 if (module_registry->available_modules().count(module_name) == 0)
546 LoadModule(module_name);
549 v8::Handle<v8::String> ModuleSystem::WrapSource(v8::Handle<v8::String> source) {
550 v8::EscapableHandleScope handle_scope(GetIsolate());
551 // Keep in order with the arguments in RequireForJsInner.
552 v8::Handle<v8::String> left = v8::String::NewFromUtf8(
553 GetIsolate(),
554 "(function(define, require, requireNative, requireAsync, exports, "
555 "console, privates,"
556 "$Array, $Function, $JSON, $Object, $RegExp, $String, $Error) {"
557 "'use strict';");
558 v8::Handle<v8::String> right = v8::String::NewFromUtf8(GetIsolate(), "\n})");
559 return handle_scope.Escape(v8::Local<v8::String>(
560 v8::String::Concat(left, v8::String::Concat(source, right))));
563 void ModuleSystem::Private(const v8::FunctionCallbackInfo<v8::Value>& args) {
564 CHECK_EQ(1, args.Length());
565 if (!args[0]->IsObject() || args[0]->IsNull()) {
566 GetIsolate()->ThrowException(
567 v8::Exception::TypeError(v8::String::NewFromUtf8(GetIsolate(),
568 args[0]->IsUndefined()
569 ? "Method called without a valid receiver (this). "
570 "Did you forget to call .bind()?"
571 : "Invalid invocation: receiver is not an object!")));
572 return;
574 v8::Local<v8::Object> obj = args[0].As<v8::Object>();
575 v8::Local<v8::String> privates_key =
576 v8::String::NewFromUtf8(GetIsolate(), "privates");
577 v8::Local<v8::Value> privates = obj->GetHiddenValue(privates_key);
578 if (privates.IsEmpty()) {
579 privates = v8::Object::New(args.GetIsolate());
580 if (privates.IsEmpty()) {
581 GetIsolate()->ThrowException(
582 v8::String::NewFromUtf8(GetIsolate(), "Failed to create privates"));
583 return;
585 obj->SetHiddenValue(privates_key, privates);
587 args.GetReturnValue().Set(privates);
590 v8::Handle<v8::Value> ModuleSystem::LoadModule(const std::string& module_name) {
591 v8::EscapableHandleScope handle_scope(GetIsolate());
592 v8::Context::Scope context_scope(context()->v8_context());
594 v8::Handle<v8::Value> source(GetSource(module_name));
595 if (source.IsEmpty() || source->IsUndefined()) {
596 Fatal(context_, "No source for require(" + module_name + ")");
597 return v8::Undefined(GetIsolate());
599 v8::Handle<v8::String> wrapped_source(
600 WrapSource(v8::Handle<v8::String>::Cast(source)));
601 // Modules are wrapped in (function(){...}) so they always return functions.
602 v8::Handle<v8::Value> func_as_value =
603 RunString(wrapped_source,
604 v8::String::NewFromUtf8(GetIsolate(), module_name.c_str()));
605 if (func_as_value.IsEmpty() || func_as_value->IsUndefined()) {
606 Fatal(context_, "Bad source for require(" + module_name + ")");
607 return v8::Undefined(GetIsolate());
610 v8::Handle<v8::Function> func = v8::Handle<v8::Function>::Cast(func_as_value);
612 v8::Handle<v8::Object> define_object = v8::Object::New(GetIsolate());
613 gin::ModuleRegistry::InstallGlobals(GetIsolate(), define_object);
615 v8::Local<v8::Value> exports = v8::Object::New(GetIsolate());
616 v8::Handle<v8::Object> natives(NewInstance());
617 CHECK(!natives.IsEmpty()); // this can happen if v8 has issues
619 // These must match the argument order in WrapSource.
620 v8::Handle<v8::Value> args[] = {
621 // AMD.
622 define_object->Get(v8::String::NewFromUtf8(GetIsolate(), "define")),
623 // CommonJS.
624 natives->Get(v8::String::NewFromUtf8(
625 GetIsolate(), "require", v8::String::kInternalizedString)),
626 natives->Get(v8::String::NewFromUtf8(
627 GetIsolate(), "requireNative", v8::String::kInternalizedString)),
628 natives->Get(v8::String::NewFromUtf8(
629 GetIsolate(), "requireAsync", v8::String::kInternalizedString)),
630 exports,
631 // Libraries that we magically expose to every module.
632 console::AsV8Object(GetIsolate()),
633 natives->Get(v8::String::NewFromUtf8(
634 GetIsolate(), "privates", v8::String::kInternalizedString)),
635 // Each safe builtin. Keep in order with the arguments in WrapSource.
636 context_->safe_builtins()->GetArray(),
637 context_->safe_builtins()->GetFunction(),
638 context_->safe_builtins()->GetJSON(),
639 context_->safe_builtins()->GetObjekt(),
640 context_->safe_builtins()->GetRegExp(),
641 context_->safe_builtins()->GetString(),
642 context_->safe_builtins()->GetError(),
645 v8::TryCatch try_catch;
646 try_catch.SetCaptureMessage(true);
647 context_->CallFunction(func, arraysize(args), args);
648 if (try_catch.HasCaught()) {
649 HandleException(try_catch);
650 return v8::Undefined(GetIsolate());
653 return handle_scope.Escape(exports);
656 void ModuleSystem::OnDidAddPendingModule(
657 const std::string& id,
658 const std::vector<std::string>& dependencies) {
659 bool module_system_managed = source_map_->Contains(id);
661 gin::ModuleRegistry* registry =
662 gin::ModuleRegistry::From(context_->v8_context());
663 DCHECK(registry);
664 for (const auto& dependency : dependencies) {
665 // If a dependency is not available, and either the module or this
666 // dependency is managed by ModuleSystem, attempt to load it. Other
667 // gin::ModuleRegistry users (WebUI and users of the mojoPrivate API) are
668 // responsible for loading their module dependencies when required.
669 if (registry->available_modules().count(dependency) == 0 &&
670 (module_system_managed || source_map_->Contains(dependency))) {
671 LoadModule(dependency);
674 registry->AttemptToLoadMoreModules(GetIsolate());
677 void ModuleSystem::OnModuleLoaded(
678 scoped_ptr<v8::Global<v8::Promise::Resolver>> resolver,
679 v8::Handle<v8::Value> value) {
680 if (!is_valid())
681 return;
682 v8::HandleScope handle_scope(GetIsolate());
683 v8::Handle<v8::Promise::Resolver> resolver_local(
684 v8::Local<v8::Promise::Resolver>::New(GetIsolate(), *resolver));
685 resolver_local->Resolve(value);
688 } // namespace extensions