Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(503)

Unified Diff: third_party/WebKit/Source/core/dom/ScriptLoader.cpp

Issue 2781713003: Enable module scripts in ScriptLoader (Closed)
Patch Set: Rebase Created 3 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View side-by-side diff with in-line comments
Download patch
Index: third_party/WebKit/Source/core/dom/ScriptLoader.cpp
diff --git a/third_party/WebKit/Source/core/dom/ScriptLoader.cpp b/third_party/WebKit/Source/core/dom/ScriptLoader.cpp
index 77cc040f3400f0f5af8bc9f49e42ae0b41fe73e9..00410e997593f30420d1c6e72f03fee8a8695671 100644
--- a/third_party/WebKit/Source/core/dom/ScriptLoader.cpp
+++ b/third_party/WebKit/Source/core/dom/ScriptLoader.cpp
@@ -26,6 +26,7 @@
#include "bindings/core/v8/ScriptController.h"
#include "bindings/core/v8/ScriptSourceCode.h"
+#include "bindings/core/v8/V8Binding.h"
#include "core/HTMLNames.h"
#include "core/SVGNames.h"
#include "core/dom/ClassicPendingScript.h"
@@ -33,6 +34,8 @@
#include "core/dom/Document.h"
#include "core/dom/DocumentParserTiming.h"
#include "core/dom/IgnoreDestructiveWriteCountIncrementer.h"
+#include "core/dom/Modulator.h"
+#include "core/dom/ModulePendingScript.h"
#include "core/dom/Script.h"
#include "core/dom/ScriptElementBase.h"
#include "core/dom/ScriptRunner.h"
@@ -45,6 +48,8 @@
#include "core/html/CrossOriginAttribute.h"
#include "core/html/imports/HTMLImport.h"
#include "core/html/parser/HTMLParserIdioms.h"
+#include "core/loader/modulescript/ModuleScriptFetchRequest.h"
+#include "core/loader/resource/ScriptResource.h"
#include "platform/WebFrameScheduler.h"
#include "platform/loader/fetch/AccessControlStatus.h"
#include "platform/loader/fetch/FetchParameters.h"
@@ -106,6 +111,7 @@ DEFINE_TRACE(ScriptLoader) {
visitor->Trace(element_);
visitor->Trace(resource_);
visitor->Trace(pending_script_);
+ visitor->Trace(module_tree_client_);
PendingScriptClient::Trace(visitor);
}
@@ -235,6 +241,14 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
if (!IsScriptTypeSupported(support_legacy_types))
return false;
+ // TODO(hiroshige): Make the determination of script type spec-comformant.
+ if (RuntimeEnabledFeatures::moduleScriptsEnabled() &&
+ element_->TypeAttributeValue() == "module") {
+ script_type_ = ScriptType::kModule;
+ } else {
+ script_type_ = ScriptType::kClassic;
+ }
+
// 7. "If was-parser-inserted is true,
// then flag the element as "parser-inserted" again,
// and set the element's "non-blocking" flag to false."
@@ -295,6 +309,14 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
return false;
}
+ // Inline module script is not yet supported.
+ if (GetScriptType() == ScriptType::kModule && !module_tree_client_) {
+ fprintf(stderr,
+ "Inline module script is not yet supported (Document URL: %s)\n",
+ element_document.Url().GetString().Utf8().Data());
+ CHECK(false);
+ }
+
// 22. "If the element does not have a src content attribute,
// run these substeps:"
@@ -321,8 +343,9 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// Since the asynchronous, low priority fetch for doc.written blocked
// script is not for execution, return early from here. Watch for its
// completion to be able to remove it from the memory cache.
- if (document_write_intervention_ ==
- DocumentWriteIntervention::kFetchDocWrittenScriptDeferIdle) {
+ if (GetScriptType() == ScriptType::kClassic &&
+ document_write_intervention_ ==
+ DocumentWriteIntervention::kFetchDocWrittenScriptDeferIdle) {
pending_script_ = CreatePendingScript();
pending_script_->WatchForLoad(this);
return true;
@@ -343,9 +366,14 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// the element has a src attribute, and the element has a defer attribute,
// and the element has been flagged as "parser-inserted",
// and the element does not have an async attribute"
- // TODO(hiroshige): Check the script's type and implement "module" case.
- if (element_->HasSourceAttribute() && element_->DeferAttributeValue() &&
- parser_inserted_ && !element_->AsyncAttributeValue()) {
+ // - "If the script's type is "module",
+ // and the element has been flagged as "parser-inserted",
+ // and the element does not have an async attribute"
+ if ((GetScriptType() == ScriptType::kClassic &&
+ element_->HasSourceAttribute() && element_->DeferAttributeValue() &&
+ parser_inserted_ && !element_->AsyncAttributeValue()) ||
+ (GetScriptType() == ScriptType::kModule && parser_inserted_ &&
+ !element_->AsyncAttributeValue())) {
// This clause is implemented by the caller-side of prepareScript():
// - HTMLParserScriptRunner::requestDeferredScript(), and
// - TODO(hiroshige): Investigate XMLDocumentParser::endElementNs()
@@ -361,7 +389,8 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// and the element has been flagged as "parser-inserted",
// and the element does not have an async attribute"
// TODO(hiroshige): Check the script's type.
- if (element_->HasSourceAttribute() && parser_inserted_ &&
+ if (GetScriptType() == ScriptType::kClassic &&
+ element_->HasSourceAttribute() && parser_inserted_ &&
!element_->AsyncAttributeValue()) {
// This clause is implemented by the caller-side of prepareScript():
// - HTMLParserScriptRunner::requestParsingBlockingScript()
@@ -385,7 +414,11 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// Part of the condition check is done in
// HTMLParserScriptRunner::processScriptElementInternal().
// TODO(hiroshige): Clean up the split condition check.
- if (!element_->HasSourceAttribute() && parser_inserted_ &&
+ // We check that the type is "classic" here, because according to the spec
+ // a "module" script doesn't reach the 5th Clause because the 4th Clause
+ // catches all "module" scripts.
+ if (GetScriptType() == ScriptType::kClassic &&
+ !element_->HasSourceAttribute() && parser_inserted_ &&
!element_document.IsScriptExecutionReady()) {
// The former part of this clause is
// implemented by the caller-side of prepareScript():
@@ -403,16 +436,22 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// and the element has a src attribute,
// and the element does not have an async attribute,
// and the element does not have the "non-blocking" flag set"
+ // - "If the script's type is "module",
+ // and the element does not have an async attribute,
+ // and the element does not have the "non-blocking" flag set"
// TODO(hiroshige): Check the script's type and implement "module" case.
- if (element_->HasSourceAttribute() && !element_->AsyncAttributeValue() &&
- !non_blocking_) {
+ if ((GetScriptType() == ScriptType::kClassic &&
+ element_->HasSourceAttribute() && !element_->AsyncAttributeValue() &&
+ !non_blocking_) ||
+ (GetScriptType() == ScriptType::kModule &&
+ !element_->AsyncAttributeValue() && !non_blocking_)) {
// "Add the element to the end of the list of scripts that will execute
// in order as soon as possible associated with the node document of the
// script element at the time the prepare a script algorithm started."
pending_script_ = CreatePendingScript();
async_exec_type_ = ScriptRunner::kInOrder;
// TODO(hiroshige): Here |contextDocument| is used as "node document"
- // while Step 14 uses |elementDocument| as "node document". Fix this.
+ // while Step 14 uses |element_document| as "node document". Fix this.
context_document->GetScriptRunner()->QueueScriptForExecution(
this, async_exec_type_);
// Note that watchForLoad can immediately call pendingScriptFinished.
@@ -426,8 +465,10 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// 4th Clause:
// - "If the script's type is "classic", and the element has a src attribute"
- // TODO(hiroshige): Check the script's type and implement "module" case.
- if (element_->HasSourceAttribute()) {
+ // - "If the script's type is "module""
+ if ((GetScriptType() == ScriptType::kClassic &&
+ element_->HasSourceAttribute()) ||
+ GetScriptType() == ScriptType::kModule) {
// "The element must be added to the set of scripts that will execute
// as soon as possible of the node document of the script element at the
// time the prepare a script algorithm started."
@@ -435,8 +476,9 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
async_exec_type_ = ScriptRunner::kAsync;
pending_script_->StartStreamingIfPossible(&element_->GetDocument(),
ScriptStreamer::kAsync);
+
// TODO(hiroshige): Here |contextDocument| is used as "node document"
- // while Step 14 uses |elementDocument| as "node document". Fix this.
+ // while Step 14 uses |element_document| as "node document". Fix this.
context_document->GetScriptRunner()->QueueScriptForExecution(
this, async_exec_type_);
// Note that watchForLoad can immediately call pendingScriptFinished.
@@ -458,6 +500,8 @@ bool ScriptLoader::PrepareScript(const TextPosition& script_start_position,
// This clause is executed only if the script's type is "classic"
// and the element doesn't have a src attribute.
+ DCHECK_EQ(GetScriptType(), ScriptType::kClassic);
+ DCHECK(!is_external_script_);
// Reset line numbering for nested writes.
TextPosition position = element_document.IsInDocumentWrite()
@@ -485,76 +529,117 @@ bool ScriptLoader::FetchScript(const String& source_url,
return false;
DCHECK(!resource_);
+ DCHECK(!module_tree_client_);
+
// 21. "If the element has a src content attribute, run these substeps:"
if (!StripLeadingAndTrailingHTMLSpaces(source_url).IsEmpty()) {
// 21.4. "Parse src relative to the element's node document."
- ResourceRequest resource_request(element_document->CompleteURL(source_url));
-
- // [Intervention]
- if (document_write_intervention_ ==
- DocumentWriteIntervention::kFetchDocWrittenScriptDeferIdle) {
- resource_request.SetHTTPHeaderField(
- "Intervention",
- "<https://www.chromestatus.com/feature/5718547946799104>");
- }
-
- FetchParameters params(resource_request, element_->InitiatorName());
+ KURL url = element_document->CompleteURL(source_url);
// 15. "Let CORS setting be the current state of the element's
// crossorigin content attribute."
CrossOriginAttributeValue cross_origin =
GetCrossOriginAttributeValue(element_->CrossOriginAttributeValue());
- // 16. "Let module script credentials mode be determined by switching
- // on CORS setting:"
- // TODO(hiroshige): Implement this step for "module".
-
- // 21.6, "classic": "Fetch a classic script given ... CORS setting
- // ... and encoding."
- if (cross_origin != kCrossOriginAttributeNotSet) {
- params.SetCrossOriginAccessControl(element_document->GetSecurityOrigin(),
- cross_origin);
- }
-
- params.SetCharset(encoding);
-
// 17. "If the script element has a nonce attribute,
// then let cryptographic nonce be that attribute's value.
// Otherwise, let cryptographic nonce be the empty string."
+ String nonce;
if (element_->IsNonceableElement())
- params.SetContentSecurityPolicyNonce(element_->nonce());
+ nonce = element_->nonce();
// 19. "Let parser state be "parser-inserted"
// if the script element has been flagged as "parser-inserted",
// and "not parser-inserted" otherwise."
- params.SetParserDisposition(IsParserInserted() ? kParserInserted
- : kNotParserInserted);
-
- params.SetDefer(defer);
-
- // 18. "If the script element has an integrity attribute,
- // then let integrity metadata be that attribute's value.
- // Otherwise, let integrity metadata be the empty string."
- String integrity_attr = element_->IntegrityAttributeValue();
- if (!integrity_attr.IsEmpty()) {
- IntegrityMetadataSet metadata_set;
- SubresourceIntegrity::ParseIntegrityAttribute(
- integrity_attr, metadata_set, element_document);
- params.SetIntegrityMetadata(metadata_set);
- }
+ ParserDisposition parser_state =
+ IsParserInserted() ? kParserInserted : kNotParserInserted;
// 21.6. "Switch on the script's type:"
-
- // - "classic":
- // "Fetch a classic script given url, settings, cryptographic nonce,
- // integrity metadata, parser state, CORS setting, and encoding."
- resource_ = ScriptResource::Fetch(params, element_document->Fetcher());
-
- // - "module":
- // "Fetch a module script graph given url, settings, "script",
- // cryptographic nonce, parser state, and
- // module script credentials mode."
- // TODO(kouhei, hiroshige): Implement this.
+ if (RuntimeEnabledFeatures::moduleScriptsEnabled() &&
+ GetScriptType() == ScriptType::kModule) {
+ // - "module":
+
+ // 16. "Let module script credentials mode be determined by switching
+ // on CORS setting:"
+ // FOXME
+ WebURLRequest::FetchCredentialsMode credentials_mode =
+ WebURLRequest::kFetchCredentialsModeOmit;
+ switch (cross_origin) {
+ case kCrossOriginAttributeNotSet:
+ credentials_mode = WebURLRequest::kFetchCredentialsModeOmit;
+ break;
+ case kCrossOriginAttributeAnonymous:
+ credentials_mode = WebURLRequest::kFetchCredentialsModeSameOrigin;
+ break;
+ case kCrossOriginAttributeUseCredentials:
+ credentials_mode = WebURLRequest::kFetchCredentialsModeInclude;
+ break;
+ }
+
+ // Step 18 is skipped because "integrity metadata" is not used
+ // for module scripts.
+
+ // TODO(hiroshige): (How) should we reflect |defer|?
+
+ // "Fetch a module script graph given url, settings, "script",
+ // cryptographic nonce, parser state, and
+ // module script credentials mode."
+ ModuleScriptFetchRequest module_request(url, nonce, parser_state,
+ credentials_mode);
+ module_tree_client_ = ModulePendingScriptTreeClient::Create();
+ Modulator::From(ToScriptStateForMainWorld(element_document->GetFrame()))
+ ->FetchTree(module_request, module_tree_client_);
+ } else {
+ // - "classic":
+
+ // Step 16 is skipped because "module script credentials" is not used
+ // for classic scripts.
+
+ // 18. "If the script element has an integrity attribute,
+ // then let integrity metadata be that attribute's value.
+ // Otherwise, let integrity metadata be the empty string."
+ String integrity_attr = element_->IntegrityAttributeValue();
+
+ // "Fetch a classic script given url, settings, ..."
+ ResourceRequest resource_request(url);
+
+ // [Intervention]
+ if (document_write_intervention_ ==
+ DocumentWriteIntervention::kFetchDocWrittenScriptDeferIdle) {
+ resource_request.SetHTTPHeaderField(
+ "Intervention",
+ "<https://www.chromestatus.com/feature/5718547946799104>");
+ }
+
+ FetchParameters params(resource_request, element_->InitiatorName());
+
+ // "... cryptographic nonce, ..."
+ params.SetContentSecurityPolicyNonce(nonce);
+
+ // "... integrity metadata, ..."
+ if (!integrity_attr.IsEmpty()) {
+ IntegrityMetadataSet metadata_set;
+ SubresourceIntegrity::ParseIntegrityAttribute(
+ integrity_attr, metadata_set, element_document);
+ params.SetIntegrityMetadata(metadata_set);
+ }
+
+ // "... parser state, ..."
+ params.SetParserDisposition(parser_state);
+
+ // "... CORS setting, ..."
+ if (cross_origin != kCrossOriginAttributeNotSet) {
+ params.SetCrossOriginAccessControl(
+ element_document->GetSecurityOrigin(), cross_origin);
+ }
+
+ // "... and encoding."
+ params.SetCharset(encoding);
+
+ params.SetDefer(defer);
+
+ resource_ = ScriptResource::Fetch(params, element_document->Fetcher());
+ }
// "When the chosen algorithm asynchronously completes, set
// the script's script to the result. At that time, the script is ready."
@@ -569,7 +654,7 @@ bool ScriptLoader::FetchScript(const String& source_url,
is_external_script_ = true;
}
- if (!resource_) {
+ if (GetScriptType() == ScriptType::kClassic && !resource_) {
// 21.2. "If src is the empty string, queue a task to
// fire an event named error at the element, and abort these steps."
// 21.5. "If the previous step failed, queue a task to
@@ -580,7 +665,8 @@ bool ScriptLoader::FetchScript(const String& source_url,
}
// [Intervention]
- if (created_during_document_write_ &&
+ if (GetScriptType() == ScriptType::kClassic &&
+ created_during_document_write_ &&
resource_->GetResourceRequest().GetCachePolicy() ==
WebCachePolicy::kReturnCacheDataDontLoad) {
document_write_intervention_ =
@@ -591,8 +677,16 @@ bool ScriptLoader::FetchScript(const String& source_url,
}
PendingScript* ScriptLoader::CreatePendingScript() {
- CHECK(resource_);
- return ClassicPendingScript::Create(element_, resource_);
+ switch (GetScriptType()) {
+ case ScriptType::kClassic:
+ CHECK(resource_);
+ return ClassicPendingScript::Create(element_, resource_);
+ case ScriptType::kModule:
+ CHECK(module_tree_client_);
+ return ModulePendingScript::Create(element_, module_tree_client_);
+ }
+ NOTREACHED();
+ return nullptr;
}
bool ScriptLoader::ExecuteScript(const Script* script) {
@@ -619,6 +713,7 @@ bool ScriptLoader::ExecuteScript(const Script* script) {
// TODO(hiroshige): Move event dispatching code to doExecuteScript().
bool ScriptLoader::DoExecuteScript(const Script* script) {
DCHECK(already_started_);
+ CHECK_EQ(script->GetScriptType(), GetScriptType());
if (script->IsEmpty())
return true;
@@ -654,6 +749,8 @@ bool ScriptLoader::DoExecuteScript(const Script* script) {
context_document, element_->GetDocument().GetSecurityOrigin()))
return false;
}
+ // FOXME: In module cases, AccessControlStatus is not set or used here.
+ // Instead, it is used when module script is fetched (and compiled).
const bool is_imported_script = context_document != element_document;
@@ -664,7 +761,11 @@ bool ScriptLoader::DoExecuteScript(const Script* script) {
// TODO(hiroshige): Implement "module" case.
IgnoreDestructiveWriteCountIncrementer
ignore_destructive_write_count_incrementer(
- is_external_script_ || is_imported_script ? context_document : 0);
+ is_external_script_ ||
+ script->GetScriptType() == ScriptType::kModule ||
+ is_imported_script
+ ? context_document
+ : 0);
// 4. "Let old script element be the value to which the script element's
// node document's currentScript object was most recently set."
@@ -675,18 +776,24 @@ bool ScriptLoader::DoExecuteScript(const Script* script) {
// 1. "If the script element's root is not a shadow root,
// then set the script element's node document's currentScript
// attribute to the script element. Otherwise, set it to null."
- context_document->PushCurrentScript(element_.Get());
+ // - "module":
+ // 1. "Set the script element's node document's currentScript attribute
+ // to null."
+ ScriptElementBase* current_script = nullptr;
+ if (script->GetScriptType() == ScriptType::kClassic)
+ current_script = element_;
+ context_document->PushCurrentScript(current_script);
+ // - "classic":
// 2. "Run the classic script given by the script's script."
// Note: This is where the script is compiled and actually executed.
- script->RunScript(frame, element_->GetDocument().GetSecurityOrigin());
-
// - "module":
- // TODO(hiroshige): Implement this.
+ // 2. "Run the module script given by the script's script."
+ script->RunScript(frame, element_->GetDocument().GetSecurityOrigin());
// 6. "Set the script element's node document's currentScript attribute
// to old script element."
- context_document->PopCurrentScript(element_.Get());
+ context_document->PopCurrentScript(current_script);
return true;
@@ -701,22 +808,24 @@ void ScriptLoader::Execute() {
DCHECK(pending_script_->IsExternal());
bool error_occurred = false;
Script* script = pending_script_->GetSource(KURL(), error_occurred);
- const bool wasCanceled = pending_script_->WasCanceled();
+ const bool was_canceled = pending_script_->WasCanceled();
DetachPendingScript();
if (error_occurred) {
DispatchErrorEvent();
- } else if (!wasCanceled) {
+ } else if (!was_canceled) {
if (ExecuteScript(script))
DispatchLoadEvent();
else
DispatchErrorEvent();
}
resource_ = nullptr;
+ module_tree_client_ = nullptr;
}
void ScriptLoader::PendingScriptFinished(PendingScript* pending_script) {
DCHECK(!will_be_parser_executed_);
DCHECK_EQ(pending_script_, pending_script);
+ DCHECK_EQ(pending_script_->GetScriptType(), GetScriptType());
// We do not need this script in the memory cache. The primary goals of
// sending this fetch request are to let the third party server know

Powered by Google App Engine
This is Rietveld 408576698