Source/JavaScriptCore/ChangeLog

 12021-02-11 Yusuke Suzuki <ysuzuki@apple.com>
 2
 3 JS Modules in Workers
 4 https://bugs.webkit.org/show_bug.cgi?id=164860
 5
 6 Reviewed by NOBODY (OOPS!).
 7
 8 * runtime/AggregateError.cpp:
 9 (JSC::AggregateError::AggregateError):
 10 * runtime/Error.cpp:
 11 (JSC::createError):
 12 (JSC::createEvalError):
 13 (JSC::createRangeError):
 14 (JSC::createReferenceError):
 15 (JSC::createSyntaxError):
 16 (JSC::createTypeError):
 17 (JSC::createURIError):
 18 (JSC::createGetterTypeError):
 19 * runtime/ErrorConstructor.cpp:
 20 (JSC::JSC_DEFINE_HOST_FUNCTION):
 21 * runtime/ErrorInstance.cpp:
 22 (JSC::ErrorInstance::ErrorInstance):
 23 (JSC::ErrorInstance::create):
 24 (JSC::ErrorInstance::sanitizedMessageString):
 25 (JSC::ErrorInstance::sanitizedNameString):
 26 (JSC::ErrorInstance::sanitizedToString):
 27 * runtime/ErrorInstance.h:
 28 (JSC::ErrorInstance::create):
 29 (JSC::ErrorInstance::errorType const):
 30 * runtime/JSGlobalObjectFunctions.cpp:
 31 (JSC::JSC_DEFINE_HOST_FUNCTION):
 32 * runtime/NativeErrorConstructor.cpp:
 33 (JSC::NativeErrorConstructor<errorType>::constructImpl):
 34 (JSC::NativeErrorConstructor<errorType>::callImpl):
 35 * runtime/NullSetterFunction.cpp:
 36 (JSC::NullSetterFunctionInternal::JSC_DEFINE_HOST_FUNCTION):
 37 * wasm/js/JSWebAssemblyCompileError.cpp:
 38 (JSC::JSWebAssemblyCompileError::JSWebAssemblyCompileError):
 39 * wasm/js/JSWebAssemblyLinkError.cpp:
 40 (JSC::JSWebAssemblyLinkError::JSWebAssemblyLinkError):
 41 * wasm/js/JSWebAssemblyRuntimeError.cpp:
 42 (JSC::JSWebAssemblyRuntimeError::JSWebAssemblyRuntimeError):
 43 * wasm/js/WebAssemblyCompileErrorConstructor.cpp:
 44 (JSC::JSC_DEFINE_HOST_FUNCTION):
 45 * wasm/js/WebAssemblyLinkErrorConstructor.cpp:
 46 (JSC::JSC_DEFINE_HOST_FUNCTION):
 47 * wasm/js/WebAssemblyRuntimeErrorConstructor.cpp:
 48 (JSC::JSC_DEFINE_HOST_FUNCTION):
 49
1502021-02-10 Saam Barati <sbarati@apple.com>
251
352 Don't crash when reparsing an arrow function and the parsing invariant is broken

Source/WebCore/ChangeLog

 12021-02-11 Yusuke Suzuki <ysuzuki@apple.com>
 2
 3 JS Modules in Workers
 4 https://bugs.webkit.org/show_bug.cgi?id=164860
 5
 6 Reviewed by NOBODY (OOPS!).
 7
 8 * Headers.cmake:
 9 * Sources.txt:
 10 * WebCore.xcodeproj/project.pbxproj:
 11 * bindings/js/CachedModuleScriptLoader.cpp:
 12 (WebCore::CachedModuleScriptLoader::create):
 13 (WebCore::CachedModuleScriptLoader::CachedModuleScriptLoader):
 14 (WebCore::CachedModuleScriptLoader::load):
 15 (WebCore::CachedModuleScriptLoader::notifyFinished):
 16 * bindings/js/CachedModuleScriptLoader.h:
 17 * bindings/js/CachedScriptFetcher.cpp:
 18 (WebCore::CachedScriptFetcher::requestScriptWithCache const):
 19 * bindings/js/JSDOMExceptionHandling.cpp:
 20 (WebCore::retrieveErrorMessageWithoutName):
 21 * bindings/js/JSDOMExceptionHandling.h:
 22 * bindings/js/JSDOMGlobalObject.cpp:
 23 (WebCore::scriptModuleLoader):
 24 (WebCore::JSDOMGlobalObject::moduleLoaderResolve):
 25 (WebCore::JSDOMGlobalObject::moduleLoaderFetch):
 26 (WebCore::JSDOMGlobalObject::moduleLoaderEvaluate):
 27 (WebCore::JSDOMGlobalObject::moduleLoaderImportModule):
 28 (WebCore::JSDOMGlobalObject::moduleLoaderCreateImportMetaProperties):
 29 * bindings/js/JSDOMGlobalObject.h:
 30 * bindings/js/JSDOMWindowBase.cpp:
 31 (WebCore::JSDOMWindowBase::moduleLoaderResolve): Deleted.
 32 (WebCore::JSDOMWindowBase::moduleLoaderFetch): Deleted.
 33 (WebCore::JSDOMWindowBase::moduleLoaderEvaluate): Deleted.
 34 (WebCore::JSDOMWindowBase::moduleLoaderImportModule): Deleted.
 35 (WebCore::JSDOMWindowBase::moduleLoaderCreateImportMetaProperties): Deleted.
 36 * bindings/js/JSDOMWindowBase.h:
 37 * bindings/js/JSExecState.h:
 38 (WebCore::JSExecState::loadAndEvaluateModule):
 39 * bindings/js/JSWorkerGlobalScopeBase.cpp:
 40 * bindings/js/JSWorkletGlobalScopeBase.cpp:
 41 * bindings/js/ModuleScriptLoader.h: Copied from Source/WebCore/workers/WorkerType.h.
 42 (WebCore::ModuleScriptLoader::clearClient):
 43 (WebCore::ModuleScriptLoader::scriptFetcher):
 44 (WebCore::ModuleScriptLoader::parameters):
 45 (WebCore::ModuleScriptLoader::ModuleScriptLoader):
 46 * bindings/js/ModuleScriptLoaderClient.h: Renamed from Source/WebCore/bindings/js/CachedModuleScriptLoaderClient.h.
 47 * bindings/js/ScriptModuleLoader.cpp:
 48 (WebCore::ScriptModuleLoader::ScriptModuleLoader):
 49 (WebCore::resolveModuleSpecifier):
 50 (WebCore::ScriptModuleLoader::resolve):
 51 (WebCore::ScriptModuleLoader::fetch):
 52 (WebCore::ScriptModuleLoader::moduleURL):
 53 (WebCore::ScriptModuleLoader::responseURLFromRequestURL):
 54 (WebCore::ScriptModuleLoader::evaluate):
 55 (WebCore::ScriptModuleLoader::importModule):
 56 (WebCore::ScriptModuleLoader::notifyFinished):
 57 * bindings/js/ScriptModuleLoader.h:
 58 * bindings/js/ScriptSourceCode.h:
 59 (WebCore::ScriptSourceCode::ScriptSourceCode):
 60 * bindings/js/WorkerModuleScriptLoader.cpp: Added.
 61 (WebCore::WorkerModuleScriptLoader::create):
 62 (WebCore::WorkerModuleScriptLoader::WorkerModuleScriptLoader):
 63 (WebCore::WorkerModuleScriptLoader::~WorkerModuleScriptLoader):
 64 (WebCore::WorkerModuleScriptLoader::load):
 65 (WebCore::WorkerModuleScriptLoader::notifyFinished):
 66 * bindings/js/WorkerModuleScriptLoader.h: Copied from Source/WebCore/workers/WorkerType.h.
 67 * bindings/js/WorkerScriptFetcher.h: Added.
 68 * dom/Document.cpp:
 69 * dom/LoadableModuleScript.cpp:
 70 (WebCore::LoadableModuleScript::load): Deleted.
 71 * dom/LoadableModuleScript.h:
 72 * dom/ScriptElement.cpp:
 73 (WebCore::ScriptElement::requestModuleScript):
 74 * loader/ThreadableLoader.cpp:
 75 (WebCore::ThreadableLoader::create):
 76 * loader/ThreadableLoader.h:
 77 (WebCore::ThreadableLoader::create):
 78 * workers/Worker.cpp:
 79 (WebCore::Worker::Worker):
 80 (WebCore::Worker::create):
 81 (WebCore::Worker::notifyFinished):
 82 * workers/Worker.h:
 83 * workers/Worker.idl:
 84 * workers/WorkerGlobalScope.cpp:
 85 (WebCore::WorkerGlobalScope::WorkerGlobalScope):
 86 (WebCore::WorkerGlobalScope::importScripts):
 87 * workers/WorkerGlobalScope.h:
 88 (WebCore::WorkerGlobalScope::credentials const):
 89 * workers/WorkerGlobalScopeProxy.h:
 90 * workers/WorkerMessagingProxy.cpp:
 91 (WebCore::WorkerMessagingProxy::startWorkerGlobalScope):
 92 * workers/WorkerMessagingProxy.h:
 93 * workers/WorkerOrWorkletGlobalScope.cpp:
 94 (WebCore::WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope):
 95 * workers/WorkerOrWorkletGlobalScope.h:
 96 (WebCore::WorkerOrWorkletGlobalScope::moduleLoader):
 97 * workers/WorkerOrWorkletScriptController.cpp:
 98 (WebCore::jsValueToModuleKey):
 99 (WebCore::WorkerOrWorkletScriptController::evaluateModule):
 100 (WebCore::WorkerOrWorkletScriptController::loadModuleSynchronously):
 101 (WebCore::WorkerOrWorkletScriptController::linkAndEvaluateModule):
 102 (WebCore::WorkerOrWorkletScriptController::loadAndEvaluateModule):
 103 * workers/WorkerOrWorkletScriptController.h:
 104 * workers/WorkerScriptLoader.cpp:
 105 (WebCore::WorkerScriptLoader::loadAsynchronously):
 106 (WebCore::WorkerScriptLoader::didReceiveResponse):
 107 * workers/WorkerScriptLoader.h:
 108 (WebCore::WorkerScriptLoader::responseSource const):
 109 (WebCore::WorkerScriptLoader::isRedirected const):
 110 * workers/WorkerThread.cpp:
 111 (WebCore::WorkerParameters::isolatedCopy const):
 112 (WebCore::WorkerThread::evaluateScriptIfNecessary):
 113 * workers/WorkerThread.h:
 114 * workers/WorkerType.h:
 115 * workers/service/ServiceWorkerContainer.h:
 116 * workers/service/ServiceWorkerJob.cpp:
 117 (WebCore::ServiceWorkerJob::fetchScriptWithContext):
 118 * workers/service/ServiceWorkerRegistrationOptions.h:
 119 * workers/service/context/ServiceWorkerThread.cpp:
 120 (WebCore::ServiceWorkerThread::ServiceWorkerThread):
 121 * workers/service/server/SWServerWorker.h:
 122 * worklets/WorkletGlobalScope.cpp:
 123 (WebCore::WorkletGlobalScope::fetchAndInvokeScript):
 124 (WebCore::WorkletGlobalScope::processNextScriptFetchJobIfNeeded): Deleted.
 125 (WebCore::WorkletGlobalScope::didReceiveResponse): Deleted.
 126 (WebCore::WorkletGlobalScope::notifyFinished): Deleted.
 127 (WebCore::WorkletGlobalScope::didCompleteScriptFetchJob): Deleted.
 128 * worklets/WorkletGlobalScope.h:
 129
11302021-02-10 Alexey Proskuryakov <ap@apple.com>
2131
3132 Do not differentiate between Release and Production via ENABLE_DEVELOPER_MODE

Source/JavaScriptCore/runtime/AggregateError.cpp

@@namespace JSC {
3636const ClassInfo AggregateError::s_info = { "AggregateError", &Base::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(AggregateError) };
3737
3838AggregateError::AggregateError(VM& vm, Structure* structure)
39  : Base(vm, structure)
 39 : Base(vm, structure, ErrorType::AggregateError)
4040{
4141}
4242

Source/JavaScriptCore/runtime/Error.cpp

@@namespace JSC {
3535JSObject* createError(JSGlobalObject* globalObject, const String& message, ErrorInstance::SourceAppender appender)
3636{
3737 ASSERT(!message.isEmpty());
38  return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(), message, appender, TypeNothing, true);
 38 return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(), message, appender, TypeNothing, ErrorType::Error, true);
3939}
4040
4141JSObject* createEvalError(JSGlobalObject* globalObject, const String& message, ErrorInstance::SourceAppender appender)
4242{
4343 ASSERT(!message.isEmpty());
44  return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::EvalError), message, appender, TypeNothing, true);
 44 return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::EvalError), message, appender, TypeNothing, ErrorType::EvalError, true);
4545}
4646
4747JSObject* createRangeError(JSGlobalObject* globalObject, const String& message, ErrorInstance::SourceAppender appender)
4848{
4949 ASSERT(!message.isEmpty());
50  return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::RangeError), message, appender, TypeNothing, true);
 50 return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::RangeError), message, appender, TypeNothing, ErrorType::RangeError, true);
5151}
5252
5353JSObject* createReferenceError(JSGlobalObject* globalObject, const String& message, ErrorInstance::SourceAppender appender)
5454{
5555 ASSERT(!message.isEmpty());
56  return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::ReferenceError), message, appender, TypeNothing, true);
 56 return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::ReferenceError), message, appender, TypeNothing, ErrorType::ReferenceError, true);
5757}
5858
5959JSObject* createSyntaxError(JSGlobalObject* globalObject, const String& message, ErrorInstance::SourceAppender appender)
6060{
6161 ASSERT(!message.isEmpty());
62  return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::SyntaxError), message, appender, TypeNothing, true);
 62 return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::SyntaxError), message, appender, TypeNothing, ErrorType::SyntaxError, true);
6363}
6464
6565JSObject* createTypeError(JSGlobalObject* globalObject, const String& message, ErrorInstance::SourceAppender appender, RuntimeType type)
6666{
6767 ASSERT(!message.isEmpty());
68  return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::TypeError), message, appender, type, true);
 68 return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::TypeError), message, appender, type, ErrorType::TypeError, true);
6969}
7070
7171JSObject* createNotEnoughArgumentsError(JSGlobalObject* globalObject, ErrorInstance::SourceAppender appender)

@@JSObject* createNotEnoughArgumentsError(JSGlobalObject* globalObject, ErrorInsta
7676JSObject* createURIError(JSGlobalObject* globalObject, const String& message, ErrorInstance::SourceAppender appender)
7777{
7878 ASSERT(!message.isEmpty());
79  return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::URIError), message, appender, TypeNothing, true);
 79 return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::URIError), message, appender, TypeNothing, ErrorType::URIError, true);
8080}
8181
8282JSObject* createError(JSGlobalObject* globalObject, ErrorType errorType, const String& message)

@@JSObject* createError(JSGlobalObject* globalObject, ErrorTypeWithExtension error
113113JSObject* createGetterTypeError(JSGlobalObject* globalObject, const String& message)
114114{
115115 ASSERT(!message.isEmpty());
116  auto* error = ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::TypeError), message);
 116 auto* error = ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::TypeError), message, nullptr, TypeNothing, ErrorType::TypeError);
117117 error->setNativeGetterTypeError();
118118 return error;
119119}

Source/JavaScriptCore/runtime/ErrorConstructor.cpp

@@JSC_DEFINE_HOST_FUNCTION(constructErrorConstructor, (JSGlobalObject* globalObjec
6060 : InternalFunction::createSubclassStructure(globalObject, newTarget, getFunctionRealm(vm, newTarget)->errorStructure());
6161 RETURN_IF_EXCEPTION(scope, { });
6262
63  RELEASE_AND_RETURN(scope, JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false)));
 63 RELEASE_AND_RETURN(scope, JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, ErrorType::Error, false)));
6464}
6565
6666JSC_DEFINE_HOST_FUNCTION(callErrorConstructor, (JSGlobalObject* globalObject, CallFrame* callFrame))
6767{
6868 JSValue message = callFrame->argument(0);
6969 Structure* errorStructure = globalObject->errorStructure();
70  return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false));
 70 return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, ErrorType::Error, false));
7171}
7272
7373bool ErrorConstructor::put(JSCell* cell, JSGlobalObject* globalObject, PropertyName propertyName, JSValue value, PutPropertySlot& slot)

Source/JavaScriptCore/runtime/ErrorInstance.cpp

@@namespace JSC {
3434
3535const ClassInfo ErrorInstance::s_info = { "Error", &JSNonFinalObject::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(ErrorInstance) };
3636
37 ErrorInstance::ErrorInstance(VM& vm, Structure* structure)
 37ErrorInstance::ErrorInstance(VM& vm, Structure* structure, ErrorType errorType)
3838 : Base(vm, structure)
 39 , m_errorType(errorType)
 40 , m_stackOverflowError(false)
 41 , m_outOfMemoryError(false)
 42 , m_errorInfoMaterialized(false)
 43 , m_nativeGetterTypeError(false)
3944{
4045}
4146
42 ErrorInstance* ErrorInstance::create(JSGlobalObject* globalObject, Structure* structure, JSValue message, SourceAppender appender, RuntimeType type, bool useCurrentFrame)
 47ErrorInstance* ErrorInstance::create(JSGlobalObject* globalObject, Structure* structure, JSValue message, SourceAppender appender, RuntimeType type, ErrorType errorType, bool useCurrentFrame)
4348{
4449 VM& vm = globalObject->vm();
4550 auto scope = DECLARE_THROW_SCOPE(vm);
4651 String messageString = message.isUndefined() ? String() : message.toWTFString(globalObject);
4752 RETURN_IF_EXCEPTION(scope, nullptr);
48  return create(globalObject, vm, structure, messageString, appender, type, useCurrentFrame);
 53 return create(globalObject, vm, structure, messageString, appender, type, errorType, useCurrentFrame);
4954}
5055
5156static String appendSourceToErrorMessage(CallFrame* callFrame, ErrorInstance* exception, BytecodeIndex bytecodeIndex, const String& message)

@@void ErrorInstance::finishCreation(VM& vm, JSGlobalObject* globalObject, const S
131136// Based on ErrorPrototype's errorProtoFuncToString(), but is modified to
132137// have no observable side effects to the user (i.e. does not call proxies,
133138// and getters).
134 String ErrorInstance::sanitizedToString(JSGlobalObject* globalObject)
 139String ErrorInstance::sanitizedMessageString(JSGlobalObject* globalObject)
 140{
 141 VM& vm = globalObject->vm();
 142 auto scope = DECLARE_THROW_SCOPE(vm);
 143 Integrity::auditStructureID(vm, structureID());
 144
 145 JSValue messageValue;
 146 auto messagePropertName = vm.propertyNames->message;
 147 PropertySlot messageSlot(this, PropertySlot::InternalMethodType::VMInquiry, &vm);
 148 if (JSObject::getOwnPropertySlot(this, globalObject, messagePropertName, messageSlot) && messageSlot.isValue())
 149 messageValue = messageSlot.getValue(globalObject, messagePropertName);
 150 scope.assertNoException();
 151
 152 if (!messageValue)
 153 return String();
 154 RELEASE_AND_RETURN(scope, messageValue.toWTFString(globalObject));
 155}
 156
 157String ErrorInstance::sanitizedNameString(JSGlobalObject* globalObject)
135158{
136159 VM& vm = globalObject->vm();
137160 auto scope = DECLARE_THROW_SCOPE(vm);

@@String ErrorInstance::sanitizedToString(JSGlobalObject* globalObject)
157180 }
158181 scope.assertNoException();
159182
160  String nameString;
161183 if (!nameValue)
162  nameString = "Error"_s;
163  else {
164  nameString = nameValue.toWTFString(globalObject);
165  RETURN_IF_EXCEPTION(scope, String());
166  }
 184 return "Error"_s;
 185 RELEASE_AND_RETURN(scope, nameValue.toWTFString(globalObject));
 186}
167187
168  JSValue messageValue;
169  auto messagePropertName = vm.propertyNames->message;
170  PropertySlot messageSlot(this, PropertySlot::InternalMethodType::VMInquiry, &vm);
171  if (JSObject::getOwnPropertySlot(this, globalObject, messagePropertName, messageSlot) && messageSlot.isValue())
172  messageValue = messageSlot.getValue(globalObject, messagePropertName);
173  scope.assertNoException();
 188String ErrorInstance::sanitizedToString(JSGlobalObject* globalObject)
 189{
 190 VM& vm = globalObject->vm();
 191 auto scope = DECLARE_THROW_SCOPE(vm);
 192 Integrity::auditStructureID(vm, structureID());
174193
175  String messageString;
176  if (!messageValue)
177  messageString = String();
178  else {
179  messageString = messageValue.toWTFString(globalObject);
180  RETURN_IF_EXCEPTION(scope, String());
181  }
 194 String nameString = sanitizedNameString(globalObject);
 195 RETURN_IF_EXCEPTION(scope, String());
 196
 197 String messageString = sanitizedMessageString(globalObject);
 198 RETURN_IF_EXCEPTION(scope, String());
182199
183200 if (!nameString.length())
184201 return messageString;

Source/JavaScriptCore/runtime/ErrorInstance.h

2020
2121#pragma once
2222
 23#include "ErrorType.h"
2324#include "JSObject.h"
2425#include "RuntimeType.h"
2526#include "StackFrame.h"

@@class ErrorInstance : public JSNonFinalObject {
5354 return Structure::create(vm, globalObject, prototype, TypeInfo(ErrorInstanceType, StructureFlags), info());
5455 }
5556
56  static ErrorInstance* create(JSGlobalObject* globalObject, VM& vm, Structure* structure, const String& message, SourceAppender appender = nullptr, RuntimeType type = TypeNothing, bool useCurrentFrame = true)
 57 static ErrorInstance* create(JSGlobalObject* globalObject, VM& vm, Structure* structure, const String& message, SourceAppender appender = nullptr, RuntimeType type = TypeNothing, ErrorType errorType = ErrorType::Error, bool useCurrentFrame = true)
5758 {
58  ErrorInstance* instance = new (NotNull, allocateCell<ErrorInstance>(vm.heap)) ErrorInstance(vm, structure);
 59 ErrorInstance* instance = new (NotNull, allocateCell<ErrorInstance>(vm.heap)) ErrorInstance(vm, structure, errorType);
5960 instance->finishCreation(vm, globalObject, message, appender, type, useCurrentFrame);
6061 return instance;
6162 }
6263
63  static ErrorInstance* create(JSGlobalObject*, Structure*, JSValue message, SourceAppender = nullptr, RuntimeType = TypeNothing, bool useCurrentFrame = true);
 64 static ErrorInstance* create(JSGlobalObject*, Structure*, JSValue message, SourceAppender = nullptr, RuntimeType = TypeNothing, ErrorType = ErrorType::Error, bool useCurrentFrame = true);
6465
6566 bool hasSourceAppender() const { return !!m_sourceAppender; }
6667 SourceAppender sourceAppender() const { return m_sourceAppender; }

@@class ErrorInstance : public JSNonFinalObject {
7071 RuntimeType runtimeTypeForCause() const { return m_runtimeTypeForCause; }
7172 void clearRuntimeTypeForCause() { m_runtimeTypeForCause = TypeNothing; }
7273
 74 ErrorType errorType() const { return m_errorType; }
7375 void setStackOverflowError() { m_stackOverflowError = true; }
7476 bool isStackOverflowError() const { return m_stackOverflowError; }
7577 void setOutOfMemoryError() { m_outOfMemoryError = true; }

@@class ErrorInstance : public JSNonFinalObject {
7981 bool isNativeGetterTypeError() const { return m_nativeGetterTypeError; }
8082
8183 JS_EXPORT_PRIVATE String sanitizedToString(JSGlobalObject*);
 84 JS_EXPORT_PRIVATE String sanitizedMessageString(JSGlobalObject*);
 85 JS_EXPORT_PRIVATE String sanitizedNameString(JSGlobalObject*);
8286
8387 Vector<StackFrame>* stackTrace() { return m_stackTrace.get(); }
8488

@@class ErrorInstance : public JSNonFinalObject {
8892 void finalizeUnconditionally(VM&);
8993
9094protected:
91  explicit ErrorInstance(VM&, Structure*);
 95 explicit ErrorInstance(VM&, Structure*, ErrorType);
9296
9397 void finishCreation(VM&, JSGlobalObject*, const String&, SourceAppender = nullptr, RuntimeType = TypeNothing, bool useCurrentFrame = true);
9498

@@class ErrorInstance : public JSNonFinalObject {
108112 String m_sourceURL;
109113 String m_stackString;
110114 RuntimeType m_runtimeTypeForCause { TypeNothing };
111  bool m_stackOverflowError { false };
112  bool m_outOfMemoryError { false };
113  bool m_errorInfoMaterialized { false };
114  bool m_nativeGetterTypeError { false };
 115 ErrorType m_errorType { ErrorType::Error };
 116 bool m_stackOverflowError : 1;
 117 bool m_outOfMemoryError : 1;
 118 bool m_errorInfoMaterialized : 1;
 119 bool m_nativeGetterTypeError : 1;
115120};
116121
117122} // namespace JSC

Source/JavaScriptCore/runtime/JSGlobalObjectFunctions.cpp

@@JSC_DEFINE_HOST_FUNCTION(globalFuncThrowTypeErrorArgumentsCalleeAndCaller, (JSGl
694694JSC_DEFINE_HOST_FUNCTION(globalFuncMakeTypeError, (JSGlobalObject* globalObject, CallFrame* callFrame))
695695{
696696 Structure* errorStructure = globalObject->errorStructure(ErrorType::TypeError);
697  return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, callFrame->argument(0), nullptr, TypeNothing, false));
 697 return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, callFrame->argument(0), nullptr, TypeNothing, ErrorType::TypeError, false));
698698}
699699
700700JSC_DEFINE_HOST_FUNCTION(globalFuncProtoGetter, (JSGlobalObject* globalObject, CallFrame* callFrame))

Source/JavaScriptCore/runtime/NativeErrorConstructor.cpp

@@inline EncodedJSValue NativeErrorConstructor<errorType>::constructImpl(JSGlobalO
5858 RETURN_IF_EXCEPTION(scope, { });
5959 ASSERT(errorStructure);
6060
61  RELEASE_AND_RETURN(scope, JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false)));
 61 RELEASE_AND_RETURN(scope, JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, errorType, false)));
6262}
6363
6464template<ErrorType errorType>

@@inline EncodedJSValue NativeErrorConstructor<errorType>::callImpl(JSGlobalObject
6666{
6767 JSValue message = callFrame->argument(0);
6868 Structure* errorStructure = globalObject->errorStructure(errorType);
69  return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false));
 69 return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, errorType, false));
7070}
7171
7272JSC_DEFINE_HOST_FUNCTION(callEvalError, (JSGlobalObject* globalObject, CallFrame* callFrame))

Source/JavaScriptCore/runtime/NullSetterFunction.cpp

@@JSC_DEFINE_HOST_FUNCTION(callThrowError, (JSGlobalObject* globalObject, CallFram
9494 auto scope = DECLARE_THROW_SCOPE(vm);
9595 // This function is only called from IC. And we do not want to include this frame in Error's stack.
9696 constexpr bool useCurrentFrame = false;
97  throwException(globalObject, scope, ErrorInstance::create(globalObject, vm, globalObject->errorStructure(ErrorType::TypeError), ReadonlyPropertyWriteError, nullptr, TypeNothing, useCurrentFrame));
 97 throwException(globalObject, scope, ErrorInstance::create(globalObject, vm, globalObject->errorStructure(ErrorType::TypeError), ReadonlyPropertyWriteError, nullptr, TypeNothing, ErrorType::TypeError, useCurrentFrame));
9898 return { };
9999}
100100

Source/JavaScriptCore/wasm/js/JSWebAssemblyCompileError.cpp

@@JSWebAssemblyCompileError* JSWebAssemblyCompileError::create(JSGlobalObject* glo
4141}
4242
4343JSWebAssemblyCompileError::JSWebAssemblyCompileError(VM& vm, Structure* structure)
44  : Base(vm, structure)
 44 : Base(vm, structure, ErrorType::Error)
4545{
4646}
4747

Source/JavaScriptCore/wasm/js/JSWebAssemblyLinkError.cpp

@@JSWebAssemblyLinkError* JSWebAssemblyLinkError::create(JSGlobalObject* globalObj
4141}
4242
4343JSWebAssemblyLinkError::JSWebAssemblyLinkError(VM& vm, Structure* structure)
44  : Base(vm, structure)
 44 : Base(vm, structure, ErrorType::Error)
4545{
4646}
4747

Source/JavaScriptCore/wasm/js/JSWebAssemblyRuntimeError.cpp

@@JSWebAssemblyRuntimeError* JSWebAssemblyRuntimeError::create(JSGlobalObject* glo
4141}
4242
4343JSWebAssemblyRuntimeError::JSWebAssemblyRuntimeError(VM& vm, Structure* structure)
44  : Base(vm, structure)
 44 : Base(vm, structure, ErrorType::Error)
4545{
4646}
4747

Source/JavaScriptCore/wasm/js/WebAssemblyCompileErrorConstructor.cpp

@@JSC_DEFINE_HOST_FUNCTION(callJSWebAssemblyCompileError, (JSGlobalObject* globalO
6565{
6666 JSValue message = callFrame->argument(0);
6767 Structure* errorStructure = globalObject->webAssemblyCompileErrorStructure();
68  return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false));
 68 return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, ErrorType::Error, false));
6969}
7070
7171WebAssemblyCompileErrorConstructor* WebAssemblyCompileErrorConstructor::create(VM& vm, Structure* structure, WebAssemblyCompileErrorPrototype* thisPrototype)

Source/JavaScriptCore/wasm/js/WebAssemblyLinkErrorConstructor.cpp

@@JSC_DEFINE_HOST_FUNCTION(callJSWebAssemblyLinkError, (JSGlobalObject* globalObje
6565{
6666 JSValue message = callFrame->argument(0);
6767 Structure* errorStructure = globalObject->webAssemblyLinkErrorStructure();
68  return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false));
 68 return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, ErrorType::Error, false));
6969}
7070
7171WebAssemblyLinkErrorConstructor* WebAssemblyLinkErrorConstructor::create(VM& vm, Structure* structure, WebAssemblyLinkErrorPrototype* thisPrototype)

Source/JavaScriptCore/wasm/js/WebAssemblyRuntimeErrorConstructor.cpp

@@JSC_DEFINE_HOST_FUNCTION(callJSWebAssemblyRuntimeError, (JSGlobalObject* globalO
6767{
6868 JSValue message = callFrame->argument(0);
6969 Structure* errorStructure = globalObject->webAssemblyRuntimeErrorStructure();
70  return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false));
 70 return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, ErrorType::Error, false));
7171}
7272
7373WebAssemblyRuntimeErrorConstructor* WebAssemblyRuntimeErrorConstructor::create(VM& vm, Structure* structure, WebAssemblyRuntimeErrorPrototype* thisPrototype)

Source/WebCore/Headers.cmake

@@set(WebCore_PRIVATE_FRAMEWORK_HEADERS
3030
3131 Modules/fetch/FetchBodyConsumer.h
3232 Modules/fetch/FetchBodySource.h
 33 Modules/fetch/FetchRequestCredentials.h
3334 Modules/fetch/FetchHeaders.h
3435 Modules/fetch/FetchIdentifier.h
3536 Modules/fetch/FetchLoader.h

@@set(WebCore_PRIVATE_FRAMEWORK_HEADERS
287288 bindings/js/WebCoreJITOperations.h
288289 bindings/js/WebCoreTypedArrayController.h
289290 bindings/js/WindowProxy.h
 291 bindings/js/WorkerScriptFetcher.h
290292
291293 bridge/Bridge.h
292294 bridge/IdentifierRep.h

Source/WebCore/Sources.txt

@@bindings/js/StructuredClone.cpp
639639bindings/js/WebCoreJITOperations.cpp
640640bindings/js/WebCoreJSClientData.cpp
641641bindings/js/WebCoreTypedArrayController.cpp
 642bindings/js/WorkerModuleScriptLoader.cpp
642643bindings/js/WindowProxy.cpp
643644bindings/js/WritableStream.cpp
644645bridge/IdentifierRep.cpp

Source/WebCore/WebCore.xcodeproj/project.pbxproj

50715071 E30592641E27A3AD00D57C98 /* InlineClassicScript.h in Headers */ = {isa = PBXBuildFile; fileRef = E30592621E27A38C00D57C98 /* InlineClassicScript.h */; settings = {ATTRIBUTES = (Private, ); }; };
50725072 E30592681E27A3D100D57C98 /* CachedScriptFetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = E30592661E27A3C600D57C98 /* CachedScriptFetcher.h */; settings = {ATTRIBUTES = (Private, ); }; };
50735073 E307DED01D81E4C700141CAF /* CachedModuleScriptLoader.h in Headers */ = {isa = PBXBuildFile; fileRef = E307DEC71D81E44800141CAF /* CachedModuleScriptLoader.h */; settings = {ATTRIBUTES = (Private, ); }; };
5074  E307DED11D81E4CB00141CAF /* CachedModuleScriptLoaderClient.h in Headers */ = {isa = PBXBuildFile; fileRef = E307DEC81D81E44800141CAF /* CachedModuleScriptLoaderClient.h */; settings = {ATTRIBUTES = (Private, ); }; };
50755074 E307DED51D81E4F200141CAF /* LoadableModuleScript.h in Headers */ = {isa = PBXBuildFile; fileRef = E307DED31D81E4ED00141CAF /* LoadableModuleScript.h */; settings = {ATTRIBUTES = (Private, ); }; };
50765075 E3150EA71DA7219300194012 /* DOMJITHelpers.h in Headers */ = {isa = PBXBuildFile; fileRef = E3150EA51DA7218D00194012 /* DOMJITHelpers.h */; };
50775076 E3201C1A1F8E82130076A032 /* ModuleFetchParameters.h in Headers */ = {isa = PBXBuildFile; fileRef = E38D06091F8E811900649CF2 /* ModuleFetchParameters.h */; settings = {ATTRIBUTES = (Private, ); }; };
50785077 E323CFFA1E5AF6AF00F0B4A0 /* JSDOMConvertPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = E323CFF91E5AF6A500F0B4A0 /* JSDOMConvertPromise.h */; settings = {ATTRIBUTES = (Private, ); }; };
 5078 E3432DE425D377E30058E612 /* WorkerModuleScriptLoader.h in Headers */ = {isa = PBXBuildFile; fileRef = E3432DE025D377E20058E612 /* WorkerModuleScriptLoader.h */; };
 5079 E347E5FA25D4F00000F17A5C /* WorkerScriptFetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = E347E5F825D4F00000F17A5C /* WorkerScriptFetcher.h */; settings = {ATTRIBUTES = (Private, ); }; };
 5080 E35188B425D387CF00A77AF3 /* ModuleScriptLoaderClient.h in Headers */ = {isa = PBXBuildFile; fileRef = E35188B325D387CF00A77AF3 /* ModuleScriptLoaderClient.h */; settings = {ATTRIBUTES = (Private, ); }; };
50795081 E3565B7B1DC2D6C900217DBD /* JSEventCustom.h in Headers */ = {isa = PBXBuildFile; fileRef = E34EE49F1DC2D57500EAA9D3 /* JSEventCustom.h */; settings = {ATTRIBUTES = (Private, ); }; };
50805082 E35802B61DC8435D00A9773C /* DOMJITIDLTypeFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = E35802B51DC8435800A9773C /* DOMJITIDLTypeFilter.h */; settings = {ATTRIBUTES = (Private, ); }; };
50815083 E3582C282527F66900D1B790 /* WebCoreJITOperations.h in Headers */ = {isa = PBXBuildFile; fileRef = E3582C262527F66800D1B790 /* WebCoreJITOperations.h */; settings = {ATTRIBUTES = (Private, ); }; };
50825084 E35B907F23F60A50000011FF /* LocalizedDeviceModel.h in Headers */ = {isa = PBXBuildFile; fileRef = E35B907C23F60677000011FF /* LocalizedDeviceModel.h */; settings = {ATTRIBUTES = (Private, ); }; };
 5085 E364321C25D37A6700F90E2A /* ModuleScriptLoader.h in Headers */ = {isa = PBXBuildFile; fileRef = E364321A25D37A6600F90E2A /* ModuleScriptLoader.h */; settings = {ATTRIBUTES = (Private, ); }; };
50835086 E377FE4D1DADE16500CDD025 /* NodeConstants.h in Headers */ = {isa = PBXBuildFile; fileRef = E3D049931DADC04500718F3C /* NodeConstants.h */; settings = {ATTRIBUTES = (Private, ); }; };
50845087 E37C86501EB63E3F0087C6CA /* JSDOMPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = E37C864F1EB63E2D0087C6CA /* JSDOMPromise.h */; settings = {ATTRIBUTES = (Private, ); }; };
50855088 E39628BF2395728F00658ECD /* DeviceOrientationUpdateProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = E39628BD2395728E00658ECD /* DeviceOrientationUpdateProvider.h */; settings = {ATTRIBUTES = (Private, ); }; };

1620216205 E30592661E27A3C600D57C98 /* CachedScriptFetcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CachedScriptFetcher.h; sourceTree = "<group>"; };
1620316206 E307DEC61D81E44800141CAF /* CachedModuleScriptLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CachedModuleScriptLoader.cpp; sourceTree = "<group>"; };
1620416207 E307DEC71D81E44800141CAF /* CachedModuleScriptLoader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CachedModuleScriptLoader.h; sourceTree = "<group>"; };
16205  E307DEC81D81E44800141CAF /* CachedModuleScriptLoaderClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CachedModuleScriptLoaderClient.h; sourceTree = "<group>"; };
1620616208 E307DED21D81E4ED00141CAF /* LoadableModuleScript.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LoadableModuleScript.cpp; sourceTree = "<group>"; };
1620716209 E307DED31D81E4ED00141CAF /* LoadableModuleScript.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LoadableModuleScript.h; sourceTree = "<group>"; };
1620816210 E3150EA51DA7218D00194012 /* DOMJITHelpers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DOMJITHelpers.h; sourceTree = "<group>"; };

1621516217 E329276322543F5900308A9A /* TypedOMCSSUnitValue.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TypedOMCSSUnitValue.cpp; sourceTree = "<group>"; };
1621616218 E329276622543FDE00308A9A /* DOMRectReadOnly.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = DOMRectReadOnly.cpp; sourceTree = "<group>"; };
1621716219 E334825E1DC93AA0009C9544 /* DOMJITAbstractHeapRepository.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DOMJITAbstractHeapRepository.h; path = DerivedSources/WebCore/DOMJITAbstractHeapRepository.h; sourceTree = BUILT_PRODUCTS_DIR; };
 16220 E3432DE025D377E20058E612 /* WorkerModuleScriptLoader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WorkerModuleScriptLoader.h; sourceTree = "<group>"; };
 16221 E3432DE325D377E30058E612 /* WorkerModuleScriptLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WorkerModuleScriptLoader.cpp; sourceTree = "<group>"; };
 16222 E347E5F825D4F00000F17A5C /* WorkerScriptFetcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WorkerScriptFetcher.h; sourceTree = "<group>"; };
1621816223 E34EE49F1DC2D57500EAA9D3 /* JSEventCustom.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSEventCustom.h; sourceTree = "<group>"; };
 16224 E35188B325D387CF00A77AF3 /* ModuleScriptLoaderClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ModuleScriptLoaderClient.h; sourceTree = "<group>"; };
1621916225 E35802B51DC8435800A9773C /* DOMJITIDLTypeFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DOMJITIDLTypeFilter.h; sourceTree = "<group>"; };
1622016226 E3582C242527F66800D1B790 /* WebCoreJITOperations.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WebCoreJITOperations.cpp; sourceTree = "<group>"; };
1622116227 E3582C262527F66800D1B790 /* WebCoreJITOperations.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebCoreJITOperations.h; sourceTree = "<group>"; };
1622216228 E35B907C23F60677000011FF /* LocalizedDeviceModel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LocalizedDeviceModel.h; sourceTree = "<group>"; };
1622316229 E35B907E23F60677000011FF /* LocalizedDeviceModel.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = LocalizedDeviceModel.mm; sourceTree = "<group>"; };
 16230 E364321A25D37A6600F90E2A /* ModuleScriptLoader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ModuleScriptLoader.h; sourceTree = "<group>"; };
1622416231 E37C864F1EB63E2D0087C6CA /* JSDOMPromise.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSDOMPromise.h; sourceTree = "<group>"; };
1622516232 E38838941BAD145F00D62EE3 /* ScriptModuleLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScriptModuleLoader.cpp; sourceTree = "<group>"; };
1622616233 E38838951BAD145F00D62EE3 /* ScriptModuleLoader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ScriptModuleLoader.h; sourceTree = "<group>"; };

2702127028 2DFA488E1DB541C200362B99 /* BufferSource.h */,
2702227029 E307DEC61D81E44800141CAF /* CachedModuleScriptLoader.cpp */,
2702327030 E307DEC71D81E44800141CAF /* CachedModuleScriptLoader.h */,
27024  E307DEC81D81E44800141CAF /* CachedModuleScriptLoaderClient.h */,
2702527031 E30592651E27A3C600D57C98 /* CachedScriptFetcher.cpp */,
2702627032 E30592661E27A3C600D57C98 /* CachedScriptFetcher.h */,
2702727033 BCD533630ED6848900887468 /* CachedScriptSourceProvider.h */,

2709527101 4BDEA32D218034050052DFCD /* JSWorkletGlobalScopeBase.cpp */,
2709627102 4BDEA32B218033EB0052DFCD /* JSWorkletGlobalScopeBase.h */,
2709727103 709A01FD1E3D0BCC006B0D4C /* ModuleFetchFailureKind.h */,
 27104 E364321A25D37A6600F90E2A /* ModuleScriptLoader.h */,
 27105 E35188B325D387CF00A77AF3 /* ModuleScriptLoaderClient.h */,
2709827106 41B459ED1F55EBC70000F6FD /* ReadableStream.cpp */,
2709927107 41B459DA1F4CADB90000F6FD /* ReadableStream.h */,
2710027108 418C395E1C8F0AAB0051C8A3 /* ReadableStreamDefaultController.cpp */,

2712627134 0F099D0717B968A100FF84B9 /* WebCoreTypedArrayController.h */,
2712727135 463521AC2081090E00C28922 /* WindowProxy.cpp */,
2712827136 463521AA2081090B00C28922 /* WindowProxy.h */,
 27137 E3432DE325D377E30058E612 /* WorkerModuleScriptLoader.cpp */,
 27138 E3432DE025D377E20058E612 /* WorkerModuleScriptLoader.h */,
 27139 E347E5F825D4F00000F17A5C /* WorkerScriptFetcher.h */,
2712927140 41418A0325643E1200363417 /* WritableStream.cpp */,
2713027141 41418A0425643E1300363417 /* WritableStream.h */,
2713127142 );

3139931410 BCB16C1C0979C3BD00467741 /* CachedImage.h in Headers */,
3140031411 319FBD5F15D2F464009640A6 /* CachedImageClient.h in Headers */,
3140131412 E307DED01D81E4C700141CAF /* CachedModuleScriptLoader.h in Headers */,
31402  E307DED11D81E4CB00141CAF /* CachedModuleScriptLoaderClient.h in Headers */,
3140331413 510184690B08602A004A825F /* CachedPage.h in Headers */,
3140431414 D0EDA775143E303C0028E383 /* CachedRawResource.h in Headers */,
3140531415 E1B533491717DEE300F205F9 /* CachedRawResourceClient.h in Headers */,

3387433884 C6D74AD509AA282E000B0A52 /* ModifySelectionListLevel.h in Headers */,
3387533885 709A01FE1E3D0BDD006B0D4C /* ModuleFetchFailureKind.h in Headers */,
3387633886 E3201C1A1F8E82130076A032 /* ModuleFetchParameters.h in Headers */,
 33887 E364321C25D37A6700F90E2A /* ModuleScriptLoader.h in Headers */,
 33888 E35188B425D387CF00A77AF3 /* ModuleScriptLoaderClient.h in Headers */,
3387733889 F55B3DC61251F12D003EF269 /* MonthInputType.h in Headers */,
3387833890 E39628C12395743100658ECD /* MotionManagerClient.h in Headers */,
3387933891 85031B460A44EFC700F992E0 /* MouseEvent.h in Headers */,

3552635538 18F831B80FD48C7800D8C56B /* WorkerLoaderProxy.h in Headers */,
3552735539 2E43464D0F546A8200B0F1BA /* WorkerLocation.h in Headers */,
3552835540 2E4346500F546A8200B0F1BA /* WorkerMessagingProxy.h in Headers */,
 35541 E3432DE425D377E30058E612 /* WorkerModuleScriptLoader.h in Headers */,
3552935542 E1271A0B0EEEC77A00F61213 /* WorkerNavigator.h in Headers */,
3553035543 A5CB05251FB51F3A00089B97 /* WorkerNetworkAgent.h in Headers */,
3553135544 2E4346510F546A8200B0F1BA /* WorkerObjectProxy.h in Headers */,

3553535548 416E29A6102FA962007FC14E /* WorkerReportingProxy.h in Headers */,
3553635549 2E4346530F546A8200B0F1BA /* WorkerRunLoop.h in Headers */,
3553735550 A5B81CCF1FAA44DE0037D1E6 /* WorkerRuntimeAgent.h in Headers */,
 35551 E347E5FA25D4F00000F17A5C /* WorkerScriptFetcher.h in Headers */,
3553835552 A7D6B3490F61104500B79FD1 /* WorkerScriptLoader.h in Headers */,
3553935553 2EA768040FE7126400AB9C8A /* WorkerScriptLoaderClient.h in Headers */,
3554035554 2E4346550F546A8200B0F1BA /* WorkerThread.h in Headers */,

Source/WebCore/bindings/js/CachedModuleScriptLoader.cpp

4040
4141namespace WebCore {
4242
43 Ref<CachedModuleScriptLoader> CachedModuleScriptLoader::create(CachedModuleScriptLoaderClient& client, DeferredPromise& promise, CachedScriptFetcher& scriptFetcher, RefPtr<ModuleFetchParameters>&& parameters)
 43Ref<CachedModuleScriptLoader> CachedModuleScriptLoader::create(ModuleScriptLoaderClient& client, DeferredPromise& promise, CachedScriptFetcher& scriptFetcher, RefPtr<ModuleFetchParameters>&& parameters)
4444{
4545 return adoptRef(*new CachedModuleScriptLoader(client, promise, scriptFetcher, WTFMove(parameters)));
4646}
4747
48 CachedModuleScriptLoader::CachedModuleScriptLoader(CachedModuleScriptLoaderClient& client, DeferredPromise& promise, CachedScriptFetcher& scriptFetcher, RefPtr<ModuleFetchParameters>&& parameters)
49  : m_client(&client)
50  , m_promise(&promise)
51  , m_scriptFetcher(scriptFetcher)
52  , m_parameters(WTFMove(parameters))
 48CachedModuleScriptLoader::CachedModuleScriptLoader(ModuleScriptLoaderClient& client, DeferredPromise& promise, CachedScriptFetcher& scriptFetcher, RefPtr<ModuleFetchParameters>&& parameters)
 49 : ModuleScriptLoader(client, promise, scriptFetcher, WTFMove(parameters))
5350{
5451}
5552

@@CachedModuleScriptLoader::~CachedModuleScriptLoader()
6158 }
6259}
6360
64 bool CachedModuleScriptLoader::load(Document& document, const URL& sourceURL)
 61bool CachedModuleScriptLoader::load(Document& document, URL&& sourceURL)
6562{
 63 ASSERT(m_promise);
6664 ASSERT(!m_cachedScript);
6765 String integrity = m_parameters ? m_parameters->integrity() : String { };
68  m_cachedScript = m_scriptFetcher->requestModuleScript(document, sourceURL, WTFMove(integrity));
 66 m_cachedScript = scriptFetcher().requestModuleScript(document, sourceURL, WTFMove(integrity));
6967 if (!m_cachedScript)
7068 return false;
71  m_sourceURL = sourceURL;
 69 m_sourceURL = WTFMove(sourceURL);
7270
7371 // If the content is already cached, this immediately calls notifyFinished.
7472 m_cachedScript->addClient(*this);

@@void CachedModuleScriptLoader::notifyFinished(CachedResource& resource, const Ne
8381
8482 Ref<CachedModuleScriptLoader> protectedThis(*this);
8583 if (m_client)
86  m_client->notifyFinished(*this, WTFMove(m_promise));
 84 m_client->notifyFinished(*this, WTFMove(m_sourceURL), m_promise.releaseNonNull());
8785
8886 // Remove the client after calling notifyFinished to keep the data buffer in
8987 // CachedResource alive while notifyFinished processes the resource.

Source/WebCore/bindings/js/CachedModuleScriptLoader.h

2727
2828#include "CachedResourceClient.h"
2929#include "CachedResourceHandle.h"
 30#include "CachedScriptFetcher.h"
 31#include "ModuleScriptLoader.h"
3032#include <wtf/Ref.h>
3133#include <wtf/RefCounted.h>
3234#include <wtf/RefPtr.h>

3436
3537namespace WebCore {
3638
37 class CachedModuleScriptLoaderClient;
 39class ModuleScriptLoaderClient;
3840class CachedScript;
39 class CachedScriptFetcher;
4041class DeferredPromise;
4142class Document;
4243class JSDOMGlobalObject;
4344class ModuleFetchParameters;
4445
45 class CachedModuleScriptLoader final : public RefCounted<CachedModuleScriptLoader>, private CachedResourceClient {
 46class CachedModuleScriptLoader final : public ModuleScriptLoader, private CachedResourceClient {
4647public:
47  static Ref<CachedModuleScriptLoader> create(CachedModuleScriptLoaderClient&, DeferredPromise&, CachedScriptFetcher&, RefPtr<ModuleFetchParameters>&&);
 48 static Ref<CachedModuleScriptLoader> create(ModuleScriptLoaderClient&, DeferredPromise&, CachedScriptFetcher&, RefPtr<ModuleFetchParameters>&&);
4849
4950 virtual ~CachedModuleScriptLoader();
5051
51  bool load(Document&, const URL& sourceURL);
 52 bool load(Document&, URL&& sourceURL);
5253
53  CachedScriptFetcher& scriptFetcher() { return m_scriptFetcher.get(); }
5454 CachedScript* cachedScript() { return m_cachedScript.get(); }
55  ModuleFetchParameters* parameters() { return m_parameters.get(); }
56  const URL& sourceURL() const { return m_sourceURL; }
57 
58  void clearClient()
59  {
60  ASSERT(m_client);
61  m_client = nullptr;
62  }
 55 CachedScriptFetcher& scriptFetcher() { return static_cast<CachedScriptFetcher&>(ModuleScriptLoader::scriptFetcher()); }
6356
6457private:
65  CachedModuleScriptLoader(CachedModuleScriptLoaderClient&, DeferredPromise&, CachedScriptFetcher&, RefPtr<ModuleFetchParameters>&&);
 58 CachedModuleScriptLoader(ModuleScriptLoaderClient&, DeferredPromise&, CachedScriptFetcher&, RefPtr<ModuleFetchParameters>&&);
6659
6760 void notifyFinished(CachedResource&, const NetworkLoadMetrics&) final;
6861
69  CachedModuleScriptLoaderClient* m_client { nullptr };
70  RefPtr<DeferredPromise> m_promise;
71  Ref<CachedScriptFetcher> m_scriptFetcher;
72  RefPtr<ModuleFetchParameters> m_parameters;
7362 CachedResourceHandle<CachedScript> m_cachedScript;
7463 URL m_sourceURL;
7564};

Source/WebCore/bindings/js/CachedModuleScriptLoaderClient.h

1 /*
2  * Copyright (C) 2016 Apple, Inc. All Rights Reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  * 1. Redistributions of source code must retain the above copyright
8  * notice, this list of conditions and the following disclaimer.
9  * 2. Redistributions in binary form must reproduce the above copyright
10  * notice, this list of conditions and the following disclaimer in the
11  * documentation and/or other materials provided with the distribution.
12  *
13  * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
14  * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
15  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
16  * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
17  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
18  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
19  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
20  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
21  * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
23  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 
26 #pragma once
27 
28 namespace WebCore {
29 
30 class CachedModuleScriptLoader;
31 class DeferredPromise;
32 
33 class CachedModuleScriptLoaderClient {
34 public:
35  virtual ~CachedModuleScriptLoaderClient() = default;
36 
37  virtual void notifyFinished(CachedModuleScriptLoader&, RefPtr<DeferredPromise>) = 0;
38 };
39 
40 }

Source/WebCore/bindings/js/CachedScriptFetcher.cpp

3232#include "CrossOriginAccessControl.h"
3333#include "Document.h"
3434#include "Settings.h"
 35#include "WorkerOrWorkletGlobalScope.h"
3536
3637namespace WebCore {
3738

@@CachedResourceHandle<CachedScript> CachedScriptFetcher::requestModuleScript(Docu
4748
4849CachedResourceHandle<CachedScript> CachedScriptFetcher::requestScriptWithCache(Document& document, const URL& sourceURL, const String& crossOriginMode, String&& integrity, Optional<ResourceLoadPriority> resourceLoadPriority) const
4950{
 51 // Without scripting, there is no way to start Workers.
5052 if (!document.settings().isScriptEnabled())
5153 return nullptr;
5254

Source/WebCore/bindings/js/JSDOMExceptionHandling.cpp

@@void reportException(JSGlobalObject* lexicalGlobalObject, JSValue exceptionValue
5252 reportException(lexicalGlobalObject, exception, cachedScript);
5353}
5454
 55String retrieveErrorMessageWithoutName(JSGlobalObject& lexicalGlobalObject, VM& vm, JSValue exception, CatchScope& catchScope)
 56{
 57 // FIXME: <http://webkit.org/b/115087> Web Inspector: WebCore::reportException should not evaluate JavaScript handling exceptions
 58 // If this is a custom exception object, call toString on it to try and get a nice string representation for the exception.
 59 String errorMessage;
 60 if (auto* error = jsDynamicCast<ErrorInstance*>(vm, exception))
 61 errorMessage = error->sanitizedMessageString(&lexicalGlobalObject);
 62 else
 63 errorMessage = exception.toWTFString(&lexicalGlobalObject);
 64
 65 // We need to clear any new exception that may be thrown in the toString() call above.
 66 // reportException() is not supposed to be making new exceptions.
 67 catchScope.clearException();
 68 vm.clearLastException();
 69 return errorMessage;
 70}
 71
5572String retrieveErrorMessage(JSGlobalObject& lexicalGlobalObject, VM& vm, JSValue exception, CatchScope& catchScope)
5673{
5774 // FIXME: <http://webkit.org/b/115087> Web Inspector: WebCore::reportException should not evaluate JavaScript handling exceptions

Source/WebCore/bindings/js/JSDOMExceptionHandling.h

@@WEBCORE_EXPORT JSC::EncodedJSValue rejectPromiseWithGetterTypeError(JSC::JSGloba
6565WEBCORE_EXPORT JSC::EncodedJSValue rejectPromiseWithThisTypeError(DeferredPromise&, const char* interfaceName, const char* operationName);
6666WEBCORE_EXPORT JSC::EncodedJSValue rejectPromiseWithThisTypeError(JSC::JSGlobalObject&, const char* interfaceName, const char* operationName);
6767
 68String retrieveErrorMessageWithoutName(JSC::JSGlobalObject&, JSC::VM&, JSC::JSValue exception, JSC::CatchScope&);
6869String retrieveErrorMessage(JSC::JSGlobalObject&, JSC::VM&, JSC::JSValue exception, JSC::CatchScope&);
6970WEBCORE_EXPORT void reportException(JSC::JSGlobalObject*, JSC::JSValue exception, CachedScript* = nullptr);
7071WEBCORE_EXPORT void reportException(JSC::JSGlobalObject*, JSC::Exception*, CachedScript* = nullptr, ExceptionDetails* = nullptr);

Source/WebCore/bindings/js/JSDOMGlobalObject.cpp

4747#include "JSWorkletGlobalScope.h"
4848#include "RejectedPromiseTracker.h"
4949#include "RuntimeEnabledFeatures.h"
 50#include "ScriptModuleLoader.h"
5051#include "StructuredClone.h"
5152#include "WebCoreJSClientData.h"
5253#include "WorkerGlobalScope.h"

@@JSC::JSPromise* JSDOMGlobalObject::instantiateStreaming(JSC::JSGlobalObject* glo
422423}
423424#endif
424425
 426static ScriptModuleLoader* scriptModuleLoader(JSDOMGlobalObject* globalObject)
 427{
 428 VM& vm = globalObject->vm();
 429 if (globalObject->inherits<JSDOMWindowBase>(vm)) {
 430 if (auto document = jsCast<const JSDOMWindowBase*>(globalObject)->wrapped().document())
 431 return &document->moduleLoader();
 432 return nullptr;
 433 }
 434 if (globalObject->inherits<JSRemoteDOMWindowBase>(vm))
 435 return nullptr;
 436 if (globalObject->inherits<JSWorkerGlobalScopeBase>(vm))
 437 return &jsCast<const JSWorkerGlobalScopeBase*>(globalObject)->wrapped().moduleLoader();
 438 if (globalObject->inherits<JSWorkletGlobalScopeBase>(vm))
 439 return &jsCast<const JSWorkletGlobalScopeBase*>(globalObject)->wrapped().moduleLoader();
 440#if ENABLE(INDEXED_DATABASE)
 441 if (globalObject->inherits<JSIDBSerializationGlobalObject>(vm))
 442 return nullptr;
 443#endif
 444 dataLog("Unexpected global object: ", JSValue(globalObject), "\n");
 445 RELEASE_ASSERT_NOT_REACHED();
 446 return nullptr;
 447}
 448
 449JSC::Identifier JSDOMGlobalObject::moduleLoaderResolve(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSValue moduleName, JSC::JSValue importerModuleKey, JSC::JSValue scriptFetcher)
 450{
 451 JSDOMGlobalObject* thisObject = JSC::jsCast<JSDOMGlobalObject*>(globalObject);
 452 if (auto* loader = scriptModuleLoader(thisObject))
 453 return loader->resolve(globalObject, moduleLoader, moduleName, importerModuleKey, scriptFetcher);
 454 return { };
 455}
 456
 457JSC::JSInternalPromise* JSDOMGlobalObject::moduleLoaderFetch(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSValue moduleKey, JSC::JSValue parameters, JSC::JSValue scriptFetcher)
 458{
 459 VM& vm = globalObject->vm();
 460 auto scope = DECLARE_THROW_SCOPE(vm);
 461 JSDOMGlobalObject* thisObject = JSC::jsCast<JSDOMGlobalObject*>(globalObject);
 462 if (auto* loader = scriptModuleLoader(thisObject))
 463 RELEASE_AND_RETURN(scope, loader->fetch(globalObject, moduleLoader, moduleKey, parameters, scriptFetcher));
 464 JSC::JSInternalPromise* promise = JSC::JSInternalPromise::create(vm, globalObject->internalPromiseStructure());
 465 scope.release();
 466 promise->reject(globalObject, jsUndefined());
 467 return promise;
 468}
 469
 470JSC::JSValue JSDOMGlobalObject::moduleLoaderEvaluate(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSValue moduleKey, JSC::JSValue moduleRecord, JSC::JSValue scriptFetcher)
 471{
 472 JSDOMGlobalObject* thisObject = JSC::jsCast<JSDOMGlobalObject*>(globalObject);
 473 if (auto* loader = scriptModuleLoader(thisObject))
 474 return loader->evaluate(globalObject, moduleLoader, moduleKey, moduleRecord, scriptFetcher);
 475 return JSC::jsUndefined();
 476}
 477
 478JSC::JSInternalPromise* JSDOMGlobalObject::moduleLoaderImportModule(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSString* moduleName, JSC::JSValue parameters, const JSC::SourceOrigin& sourceOrigin)
 479{
 480 VM& vm = globalObject->vm();
 481 auto scope = DECLARE_THROW_SCOPE(vm);
 482 JSDOMGlobalObject* thisObject = JSC::jsCast<JSDOMGlobalObject*>(globalObject);
 483 if (auto* loader = scriptModuleLoader(thisObject))
 484 RELEASE_AND_RETURN(scope, loader->importModule(globalObject, moduleLoader, moduleName, parameters, sourceOrigin));
 485 JSC::JSInternalPromise* promise = JSC::JSInternalPromise::create(vm, globalObject->internalPromiseStructure());
 486 scope.release();
 487 promise->reject(globalObject, jsUndefined());
 488 return promise;
 489}
 490
 491JSC::JSObject* JSDOMGlobalObject::moduleLoaderCreateImportMetaProperties(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSValue moduleKey, JSC::JSModuleRecord* moduleRecord, JSC::JSValue scriptFetcher)
 492{
 493 JSDOMGlobalObject* thisObject = JSC::jsCast<JSDOMGlobalObject*>(globalObject);
 494 if (auto* loader = scriptModuleLoader(thisObject))
 495 return loader->createImportMetaProperties(globalObject, moduleLoader, moduleKey, moduleRecord, scriptFetcher);
 496 return constructEmptyObject(globalObject->vm(), globalObject->nullPrototypeObjectStructure());
 497}
 498
425499JSDOMGlobalObject& callerGlobalObject(JSGlobalObject& lexicalGlobalObject, CallFrame& callFrame)
426500{
427501 class GetCallerGlobalObjectFunctor {

Source/WebCore/bindings/js/JSDOMGlobalObject.h

@@class WEBCORE_EXPORT JSDOMGlobalObject : public JSC::JSGlobalObject {
105105 static JSC::JSPromise* instantiateStreaming(JSC::JSGlobalObject*, JSC::JSValue, JSC::JSObject*);
106106#endif
107107
 108 static JSC::Identifier moduleLoaderResolve(JSC::JSGlobalObject*, JSC::JSModuleLoader*, JSC::JSValue, JSC::JSValue, JSC::JSValue);
 109 static JSC::JSInternalPromise* moduleLoaderFetch(JSC::JSGlobalObject*, JSC::JSModuleLoader*, JSC::JSValue, JSC::JSValue, JSC::JSValue);
 110 static JSC::JSValue moduleLoaderEvaluate(JSC::JSGlobalObject*, JSC::JSModuleLoader*, JSC::JSValue, JSC::JSValue, JSC::JSValue);
 111 static JSC::JSInternalPromise* moduleLoaderImportModule(JSC::JSGlobalObject*, JSC::JSModuleLoader*, JSC::JSString*, JSC::JSValue, const JSC::SourceOrigin&);
 112 static JSC::JSObject* moduleLoaderCreateImportMetaProperties(JSC::JSGlobalObject*, JSC::JSModuleLoader*, JSC::JSValue, JSC::JSModuleRecord*, JSC::JSValue);
 113
108114 JSDOMStructureMap m_structures;
109115 JSDOMConstructorMap m_constructors;
110116 DOMGuardedObjectSet m_guardedObjects;

Source/WebCore/bindings/js/JSDOMWindowBase.cpp

@@void JSDOMWindowBase::fireFrameClearedWatchpointsForWindow(DOMWindow* window)
339339 }
340340}
341341
342 JSC::Identifier JSDOMWindowBase::moduleLoaderResolve(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSValue moduleName, JSC::JSValue importerModuleKey, JSC::JSValue scriptFetcher)
343 {
344  JSDOMWindowBase* thisObject = JSC::jsCast<JSDOMWindowBase*>(globalObject);
345  if (RefPtr<Document> document = thisObject->wrapped().document())
346  return document->moduleLoader().resolve(globalObject, moduleLoader, moduleName, importerModuleKey, scriptFetcher);
347  return { };
348 }
349 
350 JSC::JSInternalPromise* JSDOMWindowBase::moduleLoaderFetch(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSValue moduleKey, JSC::JSValue parameters, JSC::JSValue scriptFetcher)
351 {
352  VM& vm = globalObject->vm();
353  auto scope = DECLARE_THROW_SCOPE(vm);
354  JSDOMWindowBase* thisObject = JSC::jsCast<JSDOMWindowBase*>(globalObject);
355  if (RefPtr<Document> document = thisObject->wrapped().document())
356  RELEASE_AND_RETURN(scope, document->moduleLoader().fetch(globalObject, moduleLoader, moduleKey, parameters, scriptFetcher));
357  JSC::JSInternalPromise* promise = JSC::JSInternalPromise::create(vm, globalObject->internalPromiseStructure());
358  scope.release();
359  promise->reject(globalObject, jsUndefined());
360  return promise;
361 }
362 
363 JSC::JSValue JSDOMWindowBase::moduleLoaderEvaluate(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSValue moduleKey, JSC::JSValue moduleRecord, JSC::JSValue scriptFetcher)
364 {
365  JSDOMWindowBase* thisObject = JSC::jsCast<JSDOMWindowBase*>(globalObject);
366  if (RefPtr<Document> document = thisObject->wrapped().document())
367  return document->moduleLoader().evaluate(globalObject, moduleLoader, moduleKey, moduleRecord, scriptFetcher);
368  return JSC::jsUndefined();
369 }
370 
371 JSC::JSInternalPromise* JSDOMWindowBase::moduleLoaderImportModule(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSString* moduleName, JSC::JSValue parameters, const JSC::SourceOrigin& sourceOrigin)
372 {
373  VM& vm = globalObject->vm();
374  auto scope = DECLARE_THROW_SCOPE(vm);
375  JSDOMWindowBase* thisObject = JSC::jsCast<JSDOMWindowBase*>(globalObject);
376  if (RefPtr<Document> document = thisObject->wrapped().document())
377  RELEASE_AND_RETURN(scope, document->moduleLoader().importModule(globalObject, moduleLoader, moduleName, parameters, sourceOrigin));
378  JSC::JSInternalPromise* promise = JSC::JSInternalPromise::create(vm, globalObject->internalPromiseStructure());
379  scope.release();
380  promise->reject(globalObject, jsUndefined());
381  return promise;
382 }
383 
384 JSC::JSObject* JSDOMWindowBase::moduleLoaderCreateImportMetaProperties(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSValue moduleKey, JSC::JSModuleRecord* moduleRecord, JSC::JSValue scriptFetcher)
385 {
386  JSDOMWindowBase* thisObject = JSC::jsCast<JSDOMWindowBase*>(globalObject);
387  if (RefPtr<Document> document = thisObject->wrapped().document())
388  return document->moduleLoader().createImportMetaProperties(globalObject, moduleLoader, moduleKey, moduleRecord, scriptFetcher);
389  return constructEmptyObject(globalObject->vm(), globalObject->nullPrototypeObjectStructure());
390 }
391 
392342} // namespace WebCore

Source/WebCore/bindings/js/JSDOMWindowBase.h

@@class WEBCORE_EXPORT JSDOMWindowBase : public JSDOMGlobalObject {
9999private:
100100 using ResponseCallback = WTF::Function<void(const char*, size_t)>;
101101
102  static JSC::Identifier moduleLoaderResolve(JSC::JSGlobalObject*, JSC::JSModuleLoader*, JSC::JSValue, JSC::JSValue, JSC::JSValue);
103  static JSC::JSInternalPromise* moduleLoaderFetch(JSC::JSGlobalObject*, JSC::JSModuleLoader*, JSC::JSValue, JSC::JSValue, JSC::JSValue);
104  static JSC::JSValue moduleLoaderEvaluate(JSC::JSGlobalObject*, JSC::JSModuleLoader*, JSC::JSValue, JSC::JSValue, JSC::JSValue);
105  static JSC::JSInternalPromise* moduleLoaderImportModule(JSC::JSGlobalObject*, JSC::JSModuleLoader*, JSC::JSString*, JSC::JSValue, const JSC::SourceOrigin&);
106  static JSC::JSObject* moduleLoaderCreateImportMetaProperties(JSC::JSGlobalObject*, JSC::JSModuleLoader*, JSC::JSValue, JSC::JSModuleRecord*, JSC::JSValue);
107 
108102 RefPtr<DOMWindow> m_wrapped;
109103 RefPtr<Event> m_currentEvent;
110104};

Source/WebCore/bindings/js/JSExecState.h

@@class JSExecState {
103103 return *JSC::loadModule(&lexicalGlobalObject, sourceCode, scriptFetcher);
104104 }
105105
 106 static JSC::JSInternalPromise& loadAndEvaluateModule(JSC::JSGlobalObject& lexicalGlobalObject, const String& moduleName, JSC::JSValue parameters, JSC::JSValue scriptFetcher)
 107 {
 108 JSExecState currentState(&lexicalGlobalObject);
 109 return *JSC::loadAndEvaluateModule(&lexicalGlobalObject, moduleName, parameters, scriptFetcher);
 110 }
 111
106112 static JSC::JSValue linkAndEvaluateModule(JSC::JSGlobalObject& lexicalGlobalObject, const JSC::Identifier& moduleKey, JSC::JSValue scriptFetcher, NakedPtr<JSC::Exception>& returnedException)
107113 {
108114 JSC::VM& vm = JSC::getVM(&lexicalGlobalObject);

Source/WebCore/bindings/js/JSWorkerGlobalScopeBase.cpp

@@const GlobalObjectMethodTable JSWorkerGlobalScopeBase::s_globalObjectMethodTable
5959 &javaScriptRuntimeFlags,
6060 &queueMicrotaskToEventLoop,
6161 &shouldInterruptScriptBeforeTimeout,
62  nullptr, // moduleLoaderImportModule
63  nullptr, // moduleLoaderResolve
64  nullptr, // moduleLoaderFetch
65  nullptr, // moduleLoaderCreateImportMetaProperties
66  nullptr, // moduleLoaderEvaluate
 62 &moduleLoaderImportModule,
 63 &moduleLoaderResolve,
 64 &moduleLoaderFetch,
 65 &moduleLoaderCreateImportMetaProperties,
 66 &moduleLoaderEvaluate,
6767 &promiseRejectionTracker,
6868 &reportUncaughtExceptionAtEventLoop,
6969 &currentScriptExecutionOwner,

Source/WebCore/bindings/js/JSWorkletGlobalScopeBase.cpp

@@const GlobalObjectMethodTable JSWorkletGlobalScopeBase::s_globalObjectMethodTabl
4949 &javaScriptRuntimeFlags,
5050 nullptr, // queueMicrotaskToEventLoop
5151 &shouldInterruptScriptBeforeTimeout,
52  nullptr, // moduleLoaderImportModule
53  nullptr, // moduleLoaderResolve
54  nullptr, // moduleLoaderFetch
55  nullptr, // moduleLoaderCreateImportMetaProperties
56  nullptr, // moduleLoaderEvaluate
 52 &moduleLoaderImportModule,
 53 &moduleLoaderResolve,
 54 &moduleLoaderFetch,
 55 &moduleLoaderCreateImportMetaProperties,
 56 &moduleLoaderEvaluate,
5757 &promiseRejectionTracker,
5858 &reportUncaughtExceptionAtEventLoop,
5959 &currentScriptExecutionOwner,

Source/WebCore/bindings/js/ModuleScriptLoader.h

 1/*
 2 * Copyright (C) 2021 Apple Inc. All rights reserved.
 3 *
 4 * Redistribution and use in source and binary forms, with or without
 5 * modification, are permitted provided that the following conditions
 6 * are met:
 7 * 1. Redistributions of source code must retain the above copyright
 8 * notice, this list of conditions and the following disclaimer.
 9 * 2. Redistributions in binary form must reproduce the above copyright
 10 * notice, this list of conditions and the following disclaimer in the
 11 * documentation and/or other materials provided with the distribution.
 12 *
 13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 23 * THE POSSIBILITY OF SUCH DAMAGE.
 24 */
 25
 26#pragma once
 27
 28#include "JSDOMPromiseDeferred.h"
 29#include "ModuleFetchParameters.h"
 30#include <JavaScriptCore/ScriptFetcher.h>
 31#include <wtf/RefCounted.h>
 32
 33namespace WebCore {
 34
 35class ModuleScriptLoaderClient;
 36
 37class ModuleScriptLoader : public RefCounted<ModuleScriptLoader> {
 38public:
 39 virtual ~ModuleScriptLoader() = default;
 40
 41 void clearClient()
 42 {
 43 ASSERT(m_client);
 44 m_client = nullptr;
 45 }
 46
 47 JSC::ScriptFetcher& scriptFetcher() { return m_scriptFetcher.get(); }
 48 ModuleFetchParameters* parameters() { return m_parameters.get(); }
 49
 50protected:
 51 ModuleScriptLoader(ModuleScriptLoaderClient& client, DeferredPromise& promise, JSC::ScriptFetcher& scriptFetcher, RefPtr<ModuleFetchParameters>&& parameters)
 52 : m_client(&client)
 53 , m_promise(&promise)
 54 , m_scriptFetcher(scriptFetcher)
 55 , m_parameters(WTFMove(parameters))
 56 {
 57 }
 58
 59 ModuleScriptLoaderClient* m_client;
 60 RefPtr<DeferredPromise> m_promise;
 61 Ref<JSC::ScriptFetcher> m_scriptFetcher;
 62 RefPtr<ModuleFetchParameters> m_parameters;
 63};
 64
 65} // namespace WebCore

Source/WebCore/bindings/js/ModuleScriptLoaderClient.h

 1/*
 2 * Copyright (C) 2021 Apple, Inc. All Rights Reserved.
 3 *
 4 * Redistribution and use in source and binary forms, with or without
 5 * modification, are permitted provided that the following conditions
 6 * are met:
 7 * 1. Redistributions of source code must retain the above copyright
 8 * notice, this list of conditions and the following disclaimer.
 9 * 2. Redistributions in binary form must reproduce the above copyright
 10 * notice, this list of conditions and the following disclaimer in the
 11 * documentation and/or other materials provided with the distribution.
 12 *
 13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
 14 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 15 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR
 17 * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
 18 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
 19 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
 20 * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
 21 * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 22 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 23 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 24 */
 25
 26#pragma once
 27
 28namespace WebCore {
 29
 30class ModuleScriptLoader;
 31class DeferredPromise;
 32
 33class ModuleScriptLoaderClient {
 34public:
 35 virtual ~ModuleScriptLoaderClient() = default;
 36
 37 virtual void notifyFinished(ModuleScriptLoader&, URL&&, Ref<DeferredPromise>) = 0;
 38};
 39
 40}

Source/WebCore/bindings/js/ScriptModuleLoader.cpp

2929#include "CachedModuleScriptLoader.h"
3030#include "CachedScript.h"
3131#include "CachedScriptFetcher.h"
32 #include "Document.h"
3332#include "Frame.h"
3433#include "JSDOMBinding.h"
3534#include "JSDOMPromiseDeferred.h"

4140#include "ScriptSourceCode.h"
4241#include "SubresourceIntegrity.h"
4342#include "WebCoreJSClientData.h"
 43#include "WorkerModuleScriptLoader.h"
 44#include "WorkerScriptFetcher.h"
4445#include <JavaScriptCore/Completion.h>
4546#include <JavaScriptCore/JSInternalPromise.h>
4647#include <JavaScriptCore/JSModuleRecord.h>

5253
5354namespace WebCore {
5455
55 ScriptModuleLoader::ScriptModuleLoader(Document& document)
56  : m_document(document)
 56ScriptModuleLoader::ScriptModuleLoader(ScriptExecutionContext& context, OwnerType ownerType)
 57 : m_context(context)
 58 , m_ownerType(ownerType)
5759{
5860}
5961

@@static bool isRootModule(JSC::JSValue importerModuleKey)
6870 return importerModuleKey.isSymbol() || importerModuleKey.isUndefined();
6971}
7072
71 static Expected<URL, String> resolveModuleSpecifier(Document& document, const String& specifier, const URL& baseURL)
 73static Expected<URL, String> resolveModuleSpecifier(ScriptExecutionContext& context, ScriptModuleLoader::OwnerType ownerType, const String& specifier, const URL& baseURL)
7274{
7375 // https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier
7476

@@static Expected<URL, String> resolveModuleSpecifier(Document& document, const St
7981 if (!specifier.startsWith('/') && !specifier.startsWith("./") && !specifier.startsWith("../"))
8082 return makeUnexpected(makeString("Module specifier, '"_s, specifier, "' does not start with \"/\", \"./\", or \"../\". Referenced from "_s, baseURL.string()));
8183
82  auto result = document.completeURL(specifier, baseURL);
 84 URL result;
 85 if (ownerType == ScriptModuleLoader::OwnerType::Document)
 86 result = downcast<Document>(context).completeURL(specifier, baseURL);
 87 else
 88 result = URL(baseURL, specifier);
 89
8390 if (!result.isValid())
8491 return makeUnexpected(makeString("Module name, '"_s, result.string(), "' does not resolve to a valid URL."_s));
8592 return result;

@@JSC::Identifier ScriptModuleLoader::resolve(JSC::JSGlobalObject* jsGlobalObject,
107114 URL baseURL = responseURLFromRequestURL(*jsGlobalObject, importerModuleKey);
108115 RETURN_IF_EXCEPTION(scope, { });
109116
110  auto result = resolveModuleSpecifier(m_document, specifier, baseURL);
 117 auto result = resolveModuleSpecifier(m_context, m_ownerType, specifier, baseURL);
111118 if (!result) {
112119 JSC::throwTypeError(jsGlobalObject, scope, result.error());
113120 return { };

@@JSC::JSInternalPromise* ScriptModuleLoader::fetch(JSC::JSGlobalObject* jsGlobalO
161168 if (auto* scriptFetchParameters = JSC::jsDynamicCast<JSC::JSScriptFetchParameters*>(vm, parameters))
162169 topLevelFetchParameters = static_cast<ModuleFetchParameters*>(&scriptFetchParameters->parameters());
163170
164  auto loader = CachedModuleScriptLoader::create(*this, deferred.get(), *static_cast<CachedScriptFetcher*>(JSC::jsCast<JSC::JSScriptFetcher*>(scriptFetcher)->fetcher()), WTFMove(topLevelFetchParameters));
165  m_loaders.add(loader.copyRef());
166  if (!loader->load(m_document, completedURL)) {
167  loader->clearClient();
168  m_loaders.remove(WTFMove(loader));
169  rejectToPropagateNetworkError(deferred.get(), ModuleFetchFailureKind::WasErrored, "Importing a module script failed."_s);
170  return jsPromise;
 171 if (m_ownerType == OwnerType::Document) {
 172 auto loader = CachedModuleScriptLoader::create(*this, deferred.get(), *static_cast<CachedScriptFetcher*>(JSC::jsCast<JSC::JSScriptFetcher*>(scriptFetcher)->fetcher()), WTFMove(topLevelFetchParameters));
 173 m_loaders.add(loader.copyRef());
 174 if (!loader->load(downcast<Document>(m_context), WTFMove(completedURL))) {
 175 loader->clearClient();
 176 m_loaders.remove(WTFMove(loader));
 177 rejectToPropagateNetworkError(deferred.get(), ModuleFetchFailureKind::WasErrored, "Importing a module script failed."_s);
 178 return jsPromise;
 179 }
 180 } else {
 181 auto loader = WorkerModuleScriptLoader::create(*this, deferred.get(), *static_cast<WorkerScriptFetcher*>(JSC::jsCast<JSC::JSScriptFetcher*>(scriptFetcher)->fetcher()), WTFMove(topLevelFetchParameters));
 182 m_loaders.add(loader.copyRef());
 183 loader->load(m_context, WTFMove(completedURL));
171184 }
172185
173186 return jsPromise;

@@JSC::JSInternalPromise* ScriptModuleLoader::fetch(JSC::JSGlobalObject* jsGlobalO
176189URL ScriptModuleLoader::moduleURL(JSC::JSGlobalObject& jsGlobalObject, JSC::JSValue moduleKeyValue)
177190{
178191 if (moduleKeyValue.isSymbol())
179  return m_document.url();
 192 return m_context.url();
180193
181194 ASSERT(moduleKeyValue.isString());
182195 return URL(URL(), asString(moduleKeyValue)->value(&jsGlobalObject));

@@URL ScriptModuleLoader::responseURLFromRequestURL(JSC::JSGlobalObject& jsGlobalO
187200 JSC::VM& vm = jsGlobalObject.vm();
188201 auto scope = DECLARE_THROW_SCOPE(vm);
189202
190  if (isRootModule(moduleKeyValue))
191  return m_document.baseURL();
 203 if (isRootModule(moduleKeyValue)) {
 204 if (m_ownerType == OwnerType::Document)
 205 return downcast<Document>(m_context).baseURL();
 206 return m_context.url();
 207 }
192208
193209 ASSERT(!isRootModule(moduleKeyValue));
194210 ASSERT(moduleKeyValue.isString());

@@JSC::JSValue ScriptModuleLoader::evaluate(JSC::JSGlobalObject* jsGlobalObject, J
219235 if (!sourceURL.isValid())
220236 return JSC::throwTypeError(jsGlobalObject, scope, "Module key is an invalid URL."_s);
221237
222  if (auto* frame = m_document.frame())
223  return frame->script().evaluateModule(sourceURL, *moduleRecord);
 238 if (m_ownerType == OwnerType::Document) {
 239 if (auto* frame = downcast<Document>(m_context).frame())
 240 return frame->script().evaluateModule(sourceURL, *moduleRecord);
 241 } else {
 242 ASSERT(is<WorkerOrWorkletGlobalScope>(m_context));
 243 if (auto* script = downcast<WorkerOrWorkletGlobalScope>(m_context).script())
 244 return script->evaluateModule(*moduleRecord);
 245 }
224246 return JSC::jsUndefined();
225247}
226248

@@JSC::JSInternalPromise* ScriptModuleLoader::importModule(JSC::JSGlobalObject* js
248270 URL baseURL;
249271 RefPtr<JSC::ScriptFetcher> scriptFetcher;
250272 if (sourceOrigin.isNull()) {
251  baseURL = m_document.baseURL();
252  scriptFetcher = CachedScriptFetcher::create(m_document.charset());
 273 if (m_ownerType == OwnerType::Document) {
 274 baseURL = downcast<Document>(m_context).baseURL();
 275 scriptFetcher = CachedScriptFetcher::create(downcast<Document>(m_context).charset());
 276 } else {
 277 baseURL = m_context.url();
 278 scriptFetcher = WorkerScriptFetcher::create(FetchOptions::Credentials::SameOrigin);
 279 }
253280 } else {
254281 baseURL = URL(URL(), sourceOrigin.string());
255282 if (!baseURL.isValid())

@@JSC::JSInternalPromise* ScriptModuleLoader::importModule(JSC::JSGlobalObject* js
257284
258285 if (sourceOrigin.fetcher())
259286 scriptFetcher = sourceOrigin.fetcher();
260  else
261  scriptFetcher = CachedScriptFetcher::create(m_document.charset());
 287
 288 if (!scriptFetcher) {
 289 if (m_ownerType == OwnerType::Document)
 290 scriptFetcher = CachedScriptFetcher::create(downcast<Document>(m_context).charset());
 291 else
 292 scriptFetcher = WorkerScriptFetcher::create(FetchOptions::Credentials::SameOrigin);
 293 }
262294 }
263295 ASSERT(baseURL.isValid());
264296 ASSERT(scriptFetcher);
265297
266298 auto specifier = moduleName->value(jsGlobalObject);
267  auto result = resolveModuleSpecifier(m_document, specifier, baseURL);
 299 auto result = resolveModuleSpecifier(m_context, m_ownerType, specifier, baseURL);
268300 if (!result)
269301 return rejectPromise(globalObject, TypeError, result.error());
270302

@@JSC::JSObject* ScriptModuleLoader::createImportMetaProperties(JSC::JSGlobalObjec
288320 return metaProperties;
289321}
290322
291 void ScriptModuleLoader::notifyFinished(CachedModuleScriptLoader& loader, RefPtr<DeferredPromise> promise)
 323void ScriptModuleLoader::notifyFinished(ModuleScriptLoader& moduleScriptLoader, URL&& sourceURL, Ref<DeferredPromise> promise)
292324{
293325 // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
294326
295  URL sourceURL = loader.sourceURL();
296  if (!m_loaders.remove(&loader))
 327 if (!m_loaders.remove(&moduleScriptLoader))
297328 return;
298  loader.clearClient();
 329 moduleScriptLoader.clearClient();
299330
300  auto& cachedScript = *loader.cachedScript();
 331 if (m_ownerType == OwnerType::Document) {
 332 auto& loader = static_cast<CachedModuleScriptLoader&>(moduleScriptLoader);
 333 auto& cachedScript = *loader.cachedScript();
301334
302  if (cachedScript.resourceError().isAccessControl()) {
303  promise->reject(TypeError, "Cross-origin script load denied by Cross-Origin Resource Sharing policy."_s);
304  return;
305  }
 335 if (cachedScript.resourceError().isAccessControl()) {
 336 promise->reject(TypeError, "Cross-origin script load denied by Cross-Origin Resource Sharing policy."_s);
 337 return;
 338 }
306339
307  if (cachedScript.errorOccurred()) {
308  rejectToPropagateNetworkError(*promise, ModuleFetchFailureKind::WasErrored, "Importing a module script failed."_s);
309  return;
310  }
 340 if (cachedScript.errorOccurred()) {
 341 rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasErrored, "Importing a module script failed."_s);
 342 return;
 343 }
311344
312  if (cachedScript.wasCanceled()) {
313  rejectToPropagateNetworkError(*promise, ModuleFetchFailureKind::WasCanceled, "Importing a module script is canceled."_s);
314  return;
315  }
 345 if (cachedScript.wasCanceled()) {
 346 rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasCanceled, "Importing a module script is canceled."_s);
 347 return;
 348 }
316349
317  if (!MIMETypeRegistry::isSupportedJavaScriptMIMEType(cachedScript.response().mimeType())) {
318  // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
319  // The result of extracting a MIME type from response's header list (ignoring parameters) is not a JavaScript MIME type.
320  // For historical reasons, fetching a classic script does not include MIME type checking. In contrast, module scripts will fail to load if they are not of a correct MIME type.
321  promise->reject(TypeError, makeString("'", cachedScript.response().mimeType(), "' is not a valid JavaScript MIME type."));
322  return;
323  }
 350 if (!MIMETypeRegistry::isSupportedJavaScriptMIMEType(cachedScript.response().mimeType())) {
 351 // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
 352 // The result of extracting a MIME type from response's header list (ignoring parameters) is not a JavaScript MIME type.
 353 // For historical reasons, fetching a classic script does not include MIME type checking. In contrast, module scripts will fail to load if they are not of a correct MIME type.
 354 promise->reject(TypeError, makeString("'", cachedScript.response().mimeType(), "' is not a valid JavaScript MIME type."));
 355 return;
 356 }
 357
 358 if (auto* parameters = loader.parameters()) {
 359 if (!matchIntegrityMetadata(cachedScript, parameters->integrity())) {
 360 promise->reject(TypeError, makeString("Cannot load script ", integrityMismatchDescription(cachedScript, parameters->integrity())));
 361 return;
 362 }
 363 }
 364
 365 URL responseURL = cachedScript.response().url();
 366 // If we do not have redirection, we must reserve the source URL's fragment explicitly here since ResourceResponse::url() is the one when we first cache it to MemoryCache.
 367 // FIXME: We should track fragments through redirections.
 368 // https://bugs.webkit.org/show_bug.cgi?id=158420
 369 // https://bugs.webkit.org/show_bug.cgi?id=210490
 370 if (!cachedScript.hasRedirections() && cachedScript.response().source() != ResourceResponse::Source::ServiceWorker) {
 371 if (sourceURL.hasFragmentIdentifier())
 372 responseURL.setFragmentIdentifier(sourceURL.fragmentIdentifier());
 373 }
 374
 375 m_requestURLToResponseURLMap.add(sourceURL.string(), WTFMove(responseURL));
 376 promise->resolveWithCallback([&] (JSDOMGlobalObject& jsGlobalObject) {
 377 return JSC::JSSourceCode::create(jsGlobalObject.vm(),
 378 JSC::SourceCode { ScriptSourceCode { &cachedScript, JSC::SourceProviderSourceType::Module, loader.scriptFetcher() }.jsSourceCode() });
 379 });
 380 } else {
 381 auto& loader = static_cast<WorkerModuleScriptLoader&>(moduleScriptLoader);
 382 auto& workerScriptLoader = loader.scriptLoader();
324383
325  if (auto* parameters = loader.parameters()) {
326  if (!matchIntegrityMetadata(cachedScript, parameters->integrity())) {
327  promise->reject(TypeError, makeString("Cannot load script ", integrityMismatchDescription(cachedScript, parameters->integrity())));
 384 if (workerScriptLoader.failed()) {
 385 if (workerScriptLoader.error().isAccessControl()) {
 386 promise->reject(TypeError, "Cross-origin script load denied by Cross-Origin Resource Sharing policy."_s);
 387 return;
 388 }
 389
 390 if (workerScriptLoader.error().isCancellation()) {
 391 rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasCanceled, "Importing a module script is canceled."_s);
 392 return;
 393 }
 394
 395 rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasErrored, "Importing a module script failed."_s);
328396 return;
329397 }
330  }
331398
332  URL responseURL = cachedScript.response().url();
333  // If we do not have redirection, we must reserve the source URL's fragment explicitly here since ResourceResponse::url() is the one when we first cache it to MemoryCache.
334  // FIXME: We should track fragments through redirections.
335  // https://bugs.webkit.org/show_bug.cgi?id=158420
336  // https://bugs.webkit.org/show_bug.cgi?id=210490
337  if (!cachedScript.hasRedirections() && cachedScript.response().source() != ResourceResponse::Source::ServiceWorker) {
338  if (sourceURL.hasFragmentIdentifier())
339  responseURL.setFragmentIdentifier(sourceURL.fragmentIdentifier());
340  }
 399 if (!MIMETypeRegistry::isSupportedJavaScriptMIMEType(workerScriptLoader.responseMIMEType())) {
 400 // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
 401 // The result of extracting a MIME type from response's header list (ignoring parameters) is not a JavaScript MIME type.
 402 // For historical reasons, fetching a classic script does not include MIME type checking. In contrast, module scripts will fail to load if they are not of a correct MIME type.
 403 promise->reject(TypeError, makeString("'", workerScriptLoader.responseMIMEType(), "' is not a valid JavaScript MIME type."));
 404 return;
 405 }
341406
342  m_requestURLToResponseURLMap.add(sourceURL.string(), WTFMove(responseURL));
343  promise->resolveWithCallback([&] (JSDOMGlobalObject& jsGlobalObject) {
344  return JSC::JSSourceCode::create(jsGlobalObject.vm(),
345  JSC::SourceCode { ScriptSourceCode { &cachedScript, JSC::SourceProviderSourceType::Module, loader.scriptFetcher() }.jsSourceCode() });
346  });
 407 URL responseURL = workerScriptLoader.responseURL();
 408
 409 // If we do not have redirection, we must reserve the source URL's fragment explicitly here since ResourceResponse::url() is the one when we first cache it to MemoryCache.
 410 // FIXME: We should track fragments through redirections.
 411 // https://bugs.webkit.org/show_bug.cgi?id=158420
 412 // https://bugs.webkit.org/show_bug.cgi?id=210490
 413 if (!workerScriptLoader.isRedirected() && workerScriptLoader.responseSource() != ResourceResponse::Source::ServiceWorker) {
 414 if (sourceURL.hasFragmentIdentifier())
 415 responseURL.setFragmentIdentifier(sourceURL.fragmentIdentifier());
 416 }
 417
 418 m_requestURLToResponseURLMap.add(sourceURL.string(), responseURL);
 419 promise->resolveWithCallback([&] (JSDOMGlobalObject& jsGlobalObject) {
 420 return JSC::JSSourceCode::create(jsGlobalObject.vm(),
 421 JSC::SourceCode { ScriptSourceCode { workerScriptLoader.script(), WTFMove(responseURL), { }, JSC::SourceProviderSourceType::Module, loader.scriptFetcher() }.jsSourceCode() });
 422 });
 423 }
347424}
348425
349426}

Source/WebCore/bindings/js/ScriptModuleLoader.h

2525
2626#pragma once
2727
28 #include "CachedModuleScriptLoader.h"
29 #include "CachedModuleScriptLoaderClient.h"
 28#include "ModuleScriptLoader.h"
 29#include "ModuleScriptLoaderClient.h"
3030#include <JavaScriptCore/JSCJSValue.h>
3131#include <wtf/HashSet.h>
3232#include <wtf/Noncopyable.h>

@@class SourceOrigin;
4545
4646namespace WebCore {
4747
48 class Document;
4948class JSDOMGlobalObject;
 49class ScriptExecutionContext;
5050
51 class ScriptModuleLoader final : private CachedModuleScriptLoaderClient {
 51class ScriptModuleLoader final : private ModuleScriptLoaderClient {
5252 WTF_MAKE_NONCOPYABLE(ScriptModuleLoader); WTF_MAKE_FAST_ALLOCATED;
5353public:
54  explicit ScriptModuleLoader(Document&);
 54 enum class OwnerType : uint8_t { Document, WorkerOrWorklet };
 55 explicit ScriptModuleLoader(ScriptExecutionContext&, OwnerType);
5556 ~ScriptModuleLoader();
5657
57  Document& document() { return m_document; }
 58 ScriptExecutionContext& context() { return m_context; }
5859
5960 JSC::Identifier resolve(JSC::JSGlobalObject*, JSC::JSModuleLoader*, JSC::JSValue moduleName, JSC::JSValue importerModuleKey, JSC::JSValue scriptFetcher);
6061 JSC::JSInternalPromise* fetch(JSC::JSGlobalObject*, JSC::JSModuleLoader*, JSC::JSValue moduleKey, JSC::JSValue parameters, JSC::JSValue scriptFetcher);

@@class ScriptModuleLoader final : private CachedModuleScriptLoaderClient {
6364 JSC::JSObject* createImportMetaProperties(JSC::JSGlobalObject*, JSC::JSModuleLoader*, JSC::JSValue, JSC::JSModuleRecord*, JSC::JSValue);
6465
6566private:
66  void notifyFinished(CachedModuleScriptLoader&, RefPtr<DeferredPromise>) final;
 67 void notifyFinished(ModuleScriptLoader&, URL&&, Ref<DeferredPromise>) final;
 68
6769 URL moduleURL(JSC::JSGlobalObject&, JSC::JSValue);
6870 URL responseURLFromRequestURL(JSC::JSGlobalObject&, JSC::JSValue);
6971
70  Document& m_document;
 72 ScriptExecutionContext& m_context;
7173 HashMap<String, URL> m_requestURLToResponseURLMap;
72  HashSet<Ref<CachedModuleScriptLoader>> m_loaders;
 74 HashSet<Ref<ModuleScriptLoader>> m_loaders;
 75 OwnerType m_ownerType;
7376};
7477
7578} // namespace WebCore

Source/WebCore/bindings/js/ScriptSourceCode.h

@@class ScriptSourceCode {
5757 {
5858 }
5959
60  ScriptSourceCode(const String& source, URL&& url, const TextPosition& startPosition, JSC::SourceProviderSourceType sourceType, Ref<CachedScriptFetcher>&& scriptFetcher)
 60 ScriptSourceCode(const String& source, URL&& url, const TextPosition& startPosition, JSC::SourceProviderSourceType sourceType, Ref<JSC::ScriptFetcher>&& scriptFetcher)
6161 : m_provider(JSC::StringSourceProvider::create(source, JSC::SourceOrigin { url, WTFMove(scriptFetcher) }, url.string(), startPosition, sourceType))
6262 , m_code(m_provider.copyRef(), startPosition.m_line.oneBasedInt(), startPosition.m_column.oneBasedInt())
6363 {

Source/WebCore/bindings/js/WorkerModuleScriptLoader.cpp

 1/*
 2 * Copyright (C) 2021 Apple Inc. All rights reserved.
 3 *
 4 * Redistribution and use in source and binary forms, with or without
 5 * modification, are permitted provided that the following conditions
 6 * are met:
 7 * 1. Redistributions of source code must retain the above copyright
 8 * notice, this list of conditions and the following disclaimer.
 9 * 2. Redistributions in binary form must reproduce the above copyright
 10 * notice, this list of conditions and the following disclaimer in the
 11 * documentation and/or other materials provided with the distribution.
 12 *
 13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 23 * THE POSSIBILITY OF SUCH DAMAGE.
 24 */
 25
 26#include "config.h"
 27#include "WorkerModuleScriptLoader.h"
 28
 29#include "CachedScriptFetcher.h"
 30#include "DOMWrapperWorld.h"
 31#include "Frame.h"
 32#include "JSDOMBinding.h"
 33#include "JSDOMPromiseDeferred.h"
 34#include "ModuleFetchParameters.h"
 35#include "ResourceLoaderOptions.h"
 36#include "ScriptController.h"
 37#include "ScriptModuleLoader.h"
 38#include "ScriptSourceCode.h"
 39#include "WorkerScriptFetcher.h"
 40#include "WorkerScriptLoader.h"
 41
 42namespace WebCore {
 43
 44Ref<WorkerModuleScriptLoader> WorkerModuleScriptLoader::create(ModuleScriptLoaderClient& client, DeferredPromise& promise, WorkerScriptFetcher& scriptFetcher, RefPtr<ModuleFetchParameters>&& parameters)
 45{
 46 return adoptRef(*new WorkerModuleScriptLoader(client, promise, scriptFetcher, WTFMove(parameters)));
 47}
 48
 49WorkerModuleScriptLoader::WorkerModuleScriptLoader(ModuleScriptLoaderClient& client, DeferredPromise& promise, WorkerScriptFetcher& scriptFetcher, RefPtr<ModuleFetchParameters>&& parameters)
 50 : ModuleScriptLoader(client, promise, scriptFetcher, WTFMove(parameters))
 51 , m_scriptLoader(WorkerScriptLoader::create())
 52{
 53}
 54
 55WorkerModuleScriptLoader::~WorkerModuleScriptLoader()
 56{
 57 m_scriptLoader->cancel();
 58}
 59
 60bool WorkerModuleScriptLoader::load(ScriptExecutionContext& context, URL&& sourceURL)
 61{
 62 m_sourceURL = WTFMove(sourceURL);
 63
 64 ResourceRequest request { m_sourceURL };
 65
 66 FetchOptions fetchOptions;
 67 fetchOptions.mode = FetchOptions::Mode::Cors;
 68 fetchOptions.cache = FetchOptions::Cache::Default;
 69 fetchOptions.redirect = FetchOptions::Redirect::Follow;
 70 fetchOptions.credentials = static_cast<WorkerScriptFetcher&>(scriptFetcher()).credentials();
 71 auto contentSecurityPolicyEnforcement = context.shouldBypassMainWorldContentSecurityPolicy() ? ContentSecurityPolicyEnforcement::DoNotEnforce : ContentSecurityPolicyEnforcement::EnforceChildSrcDirective;
 72
 73 String taskMode = "loadModulesInWorkerOrWorkletMode"_s;
 74 m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, *this, WTFMove(taskMode));
 75 return true;
 76}
 77
 78void WorkerModuleScriptLoader::notifyFinished()
 79{
 80 ASSERT(m_promise);
 81
 82 auto protectedThis = makeRef(*this);
 83 if (m_client)
 84 m_client->notifyFinished(*this, WTFMove(m_sourceURL), m_promise.releaseNonNull());
 85}
 86
 87}

Source/WebCore/bindings/js/WorkerModuleScriptLoader.h

 1/*
 2 * Copyright (C) 2021 Apple Inc. All rights reserved.
 3 *
 4 * Redistribution and use in source and binary forms, with or without
 5 * modification, are permitted provided that the following conditions
 6 * are met:
 7 * 1. Redistributions of source code must retain the above copyright
 8 * notice, this list of conditions and the following disclaimer.
 9 * 2. Redistributions in binary form must reproduce the above copyright
 10 * notice, this list of conditions and the following disclaimer in the
 11 * documentation and/or other materials provided with the distribution.
 12 *
 13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 23 * THE POSSIBILITY OF SUCH DAMAGE.
 24 */
 25
 26#pragma once
 27
 28#include "ModuleScriptLoader.h"
 29#include "WorkerScriptLoaderClient.h"
 30#include <wtf/Ref.h>
 31#include <wtf/RefCounted.h>
 32#include <wtf/RefPtr.h>
 33#include <wtf/URL.h>
 34
 35namespace WebCore {
 36
 37class DeferredPromise;
 38class JSDOMGlobalObject;
 39class ModuleFetchParameters;
 40class ScriptExecutionContext;
 41class ModuleScriptLoaderClient;
 42class WorkerScriptLoader;
 43
 44class WorkerModuleScriptLoader final : public ModuleScriptLoader, private WorkerScriptLoaderClient {
 45public:
 46 static Ref<WorkerModuleScriptLoader> create(ModuleScriptLoaderClient&, DeferredPromise&, WorkerScriptFetcher&, RefPtr<ModuleFetchParameters>&&);
 47
 48 virtual ~WorkerModuleScriptLoader();
 49
 50 bool load(ScriptExecutionContext&, URL&& sourceURL);
 51
 52 WorkerScriptLoader& scriptLoader() { return m_scriptLoader.get(); }
 53
 54private:
 55 WorkerModuleScriptLoader(ModuleScriptLoaderClient&, DeferredPromise&, WorkerScriptFetcher&, RefPtr<ModuleFetchParameters>&&);
 56
 57 void didReceiveResponse(unsigned long, const ResourceResponse&) final { }
 58 void notifyFinished() final;
 59
 60 Ref<WorkerScriptLoader> m_scriptLoader;
 61 URL m_sourceURL;
 62};
 63
 64} // namespace WebCore

Source/WebCore/bindings/js/WorkerScriptFetcher.h

 1/*
 2 * Copyright (C) 2021 Apple Inc. All rights reserved.
 3 *
 4 * Redistribution and use in source and binary forms, with or without
 5 * modification, are permitted provided that the following conditions
 6 * are met:
 7 * 1. Redistributions of source code must retain the above copyright
 8 * notice, this list of conditions and the following disclaimer.
 9 * 2. Redistributions in binary form must reproduce the above copyright
 10 * notice, this list of conditions and the following disclaimer in the
 11 * documentation and/or other materials provided with the distribution.
 12 *
 13 * THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
 14 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
 15 * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
 16 * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
 17 * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 18 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 19 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 20 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 21 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
 23 * THE POSSIBILITY OF SUCH DAMAGE.
 24 */
 25
 26#pragma once
 27
 28#include "LoadableScript.h"
 29#include <JavaScriptCore/ScriptFetcher.h>
 30#include <wtf/Optional.h>
 31#include <wtf/text/WTFString.h>
 32
 33namespace WebCore {
 34
 35class CachedScript;
 36class Document;
 37
 38class WorkerScriptFetcher final : public JSC::ScriptFetcher {
 39public:
 40 static Ref<WorkerScriptFetcher> create(FetchOptions::Credentials credentials)
 41 {
 42 return adoptRef(*new WorkerScriptFetcher(credentials));
 43 }
 44
 45 FetchOptions::Credentials credentials() const { return m_credentials; }
 46
 47 void notifyLoadCompleted(UniquedStringImpl& moduleKey)
 48 {
 49 m_moduleKey = &moduleKey;
 50 m_isLoaded = true;
 51 }
 52
 53 void notifyLoadFailed(LoadableScript::Error&& error)
 54 {
 55 m_error = WTFMove(error);
 56 m_isLoaded = true;
 57 }
 58
 59 void notifyLoadWasCanceled()
 60 {
 61 m_wasCanceled = true;
 62 m_isLoaded = true;
 63 }
 64
 65 bool isLoaded() const { return m_isLoaded; }
 66 Optional<LoadableScript::Error> error() const { return m_error; }
 67 bool wasCanceled() const { return m_wasCanceled; }
 68 UniquedStringImpl* moduleKey() const { return m_moduleKey.get(); }
 69
 70protected:
 71 WorkerScriptFetcher(FetchOptions::Credentials credentials)
 72 : m_credentials(credentials)
 73 {
 74 }
 75
 76private:
 77 FetchOptions::Credentials m_credentials;
 78 RefPtr<UniquedStringImpl> m_moduleKey;
 79 Optional<LoadableScript::Error> m_error;
 80 bool m_wasCanceled { false };
 81 bool m_isLoaded { false };
 82};
 83
 84} // namespace WebCore

Source/WebCore/dom/Document.cpp

@@Document::Document(Frame* frame, const Settings& settings, const URL& url, Docum
615615 , m_documentCreationTime(MonotonicTime::now())
616616#endif
617617 , m_scriptRunner(makeUnique<ScriptRunner>(*this))
618  , m_moduleLoader(makeUnique<ScriptModuleLoader>(*this))
 618 , m_moduleLoader(makeUnique<ScriptModuleLoader>(*this, ScriptModuleLoader::OwnerType::Document))
619619#if ENABLE(XSLT)
620620 , m_applyPendingXSLTransformsTimer(*this, &Document::applyPendingXSLTransformsTimerFired)
621621#endif

Source/WebCore/dom/LoadableModuleScript.cpp

@@void LoadableModuleScript::execute(ScriptElement& scriptElement)
8888 scriptElement.executeModuleScript(*this);
8989}
9090
91 void LoadableModuleScript::load(Document& document, const URL& rootURL)
92 {
93  if (auto* frame = document.frame())
94  frame->script().loadModuleScript(*this, rootURL.string(), m_parameters.copyRef());
95 }
96 
97 void LoadableModuleScript::load(Document& document, const ScriptSourceCode& sourceCode)
98 {
99  if (auto* frame = document.frame())
100  frame->script().loadModuleScript(*this, sourceCode);
101 }
102 
10391}

Source/WebCore/dom/LoadableModuleScript.h

@@class LoadableModuleScript final : public LoadableScript {
5050
5151 void setError(Error&&);
5252
53  void load(Document&, const URL& rootURL);
54  void load(Document&, const ScriptSourceCode&);
55 
5653 void notifyLoadCompleted(UniquedStringImpl&);
5754 void notifyLoadFailed(LoadableScript::Error&&);
5855 void notifyLoadWasCanceled();
5956
6057 UniquedStringImpl* moduleKey() const { return m_moduleKey.get(); }
6158
 59 ModuleFetchParameters& parameters() { return m_parameters.get(); }
 60
6261private:
6362 LoadableModuleScript(const String& nonce, const String& integrity, ReferrerPolicy, const String& crossOriginMode, const String& charset, const AtomString& initiatorName, bool isInUserAgentShadowTree);
6463

Source/WebCore/dom/ScriptElement.cpp

4242#include "LoadableClassicScript.h"
4343#include "LoadableModuleScript.h"
4444#include "MIMETypeRegistry.h"
 45#include "ModuleFetchParameters.h"
4546#include "PendingScript.h"
4647#include "RuntimeApplicationChecks.h"
4748#include "SVGScriptElement.h"

@@bool ScriptElement::requestModuleScript(const TextPosition& scriptStartPosition)
351352 scriptCharset(),
352353 m_element.localName(),
353354 m_element.isInUserAgentShadowTree());
354  script->load(m_element.document(), moduleScriptRootURL);
355355 m_loadableScript = WTFMove(script);
 356 if (auto* frame = m_element.document().frame()) {
 357 auto& script = downcast<LoadableModuleScript>(*m_loadableScript.get());
 358 frame->script().loadModuleScript(script, moduleScriptRootURL.string(), makeRef(script.parameters()));
 359 }
356360 return true;
357361 }
358362

@@bool ScriptElement::requestModuleScript(const TextPosition& scriptStartPosition)
367371 if (!contentSecurityPolicy.allowInlineScript(m_element.document().url().string(), m_startLineNumber, sourceCode.source().toStringWithoutCopying(), hasKnownNonce))
368372 return false;
369373
370  script->load(m_element.document(), sourceCode);
371374 m_loadableScript = WTFMove(script);
 375 if (auto* frame = m_element.document().frame())
 376 frame->script().loadModuleScript(downcast<LoadableModuleScript>(*m_loadableScript.get()), sourceCode);
372377 return true;
373378}
374379

Source/WebCore/loader/ThreadableLoader.cpp

@@ThreadableLoaderOptions ThreadableLoaderOptions::isolatedCopy() const
101101}
102102
103103
104 RefPtr<ThreadableLoader> ThreadableLoader::create(ScriptExecutionContext& context, ThreadableLoaderClient& client, ResourceRequest&& request, const ThreadableLoaderOptions& options, String&& referrer)
 104RefPtr<ThreadableLoader> ThreadableLoader::create(ScriptExecutionContext& context, ThreadableLoaderClient& client, ResourceRequest&& request, const ThreadableLoaderOptions& options, String&& referrer, String&& taskMode)
105105{
106106 if (is<WorkerGlobalScope>(context) || (is<WorkletGlobalScope>(context) && downcast<WorkletGlobalScope>(context).workerOrWorkletThread()))
107  return WorkerThreadableLoader::create(static_cast<WorkerOrWorkletGlobalScope&>(context), client, WorkerRunLoop::defaultMode(), WTFMove(request), options, WTFMove(referrer));
 107 return WorkerThreadableLoader::create(static_cast<WorkerOrWorkletGlobalScope&>(context), client, WTFMove(taskMode), WTFMove(request), options, WTFMove(referrer));
108108
109109 Document* document = nullptr;
110110 if (is<WorkletGlobalScope>(context))

Source/WebCore/loader/ThreadableLoader.h

@@namespace WebCore {
7474 WTF_MAKE_NONCOPYABLE(ThreadableLoader);
7575 public:
7676 static void loadResourceSynchronously(ScriptExecutionContext&, ResourceRequest&&, ThreadableLoaderClient&, const ThreadableLoaderOptions&);
77  static RefPtr<ThreadableLoader> create(ScriptExecutionContext&, ThreadableLoaderClient&, ResourceRequest&&, const ThreadableLoaderOptions&, String&& referrer = String());
 77 static RefPtr<ThreadableLoader> create(ScriptExecutionContext&, ThreadableLoaderClient&, ResourceRequest&&, const ThreadableLoaderOptions&, String&& referrer = String(), String&& taskMode = { });
7878
7979 virtual void computeIsDone() = 0;
8080 virtual void cancel() = 0;

Source/WebCore/workers/Worker.cpp

@@inline Worker::Worker(ScriptExecutionContext& context, JSC::RuntimeFlags runtime
7070 , m_identifier("worker:" + Inspector::IdentifiersFactory::createIdentifier())
7171 , m_contextProxy(WorkerGlobalScopeProxy::create(*this))
7272 , m_runtimeFlags(runtimeFlags)
 73 , m_type(options.type)
 74 , m_credentials(options.credentials)
7375{
7476 static bool addedListener;
7577 if (!addedListener) {

@@ExceptionOr<Ref<Worker>> Worker::create(ScriptExecutionContext& context, JSC::Ru
113115
114116 FetchOptions fetchOptions;
115117 fetchOptions.mode = FetchOptions::Mode::SameOrigin;
 118 if (worker->m_type == WorkerType::Module)
 119 fetchOptions.credentials = worker->m_credentials;
 120 else
 121 fetchOptions.credentials = FetchOptions::Credentials::SameOrigin;
116122 fetchOptions.cache = FetchOptions::Cache::Default;
117123 fetchOptions.redirect = FetchOptions::Redirect::Follow;
118124 fetchOptions.destination = FetchOptions::Destination::Worker;
119  worker->m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, worker);
 125 worker->m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, worker.get(), WorkerRunLoop::defaultMode());
 126
120127 return worker;
121128}
122129

@@void Worker::notifyFinished()
215222 ReferrerPolicy referrerPolicy = ReferrerPolicy::EmptyString;
216223 if (auto policy = parseReferrerPolicy(m_scriptLoader->referrerPolicy(), ReferrerPolicySource::HTTPHeader))
217224 referrerPolicy = *policy;
218  m_contextProxy.startWorkerGlobalScope(m_scriptLoader->url(), m_name, context->userAgent(m_scriptLoader->url()), isOnline, m_scriptLoader->script(), contentSecurityPolicyResponseHeaders, m_shouldBypassMainWorldContentSecurityPolicy, m_workerCreationTime, referrerPolicy, m_runtimeFlags);
 225
 226 URL responseURL = m_scriptLoader->responseURL();
 227 if (!m_scriptLoader->isRedirected() && m_scriptLoader->responseSource() != ResourceResponse::Source::ServiceWorker) {
 228 if (m_scriptLoader->url().hasFragmentIdentifier())
 229 responseURL.setFragmentIdentifier(m_scriptLoader->url().fragmentIdentifier());
 230 }
 231 m_contextProxy.startWorkerGlobalScope(responseURL, m_name, context->userAgent(responseURL), isOnline, m_scriptLoader->script(), contentSecurityPolicyResponseHeaders, m_shouldBypassMainWorldContentSecurityPolicy, m_workerCreationTime, referrerPolicy, m_type, m_credentials, m_runtimeFlags);
219232 InspectorInstrumentation::scriptImported(*context, m_scriptLoader->identifier(), m_scriptLoader->script());
220233}
221234

Source/WebCore/workers/Worker.h

2929#include "ActiveDOMObject.h"
3030#include "ContentSecurityPolicyResponseHeaders.h"
3131#include "EventTarget.h"
 32#include "FetchRequestCredentials.h"
3233#include "MessagePort.h"
3334#include "PostMessageOptions.h"
3435#include "WorkerScriptLoaderClient.h"
 36#include "WorkerType.h"
3537#include <JavaScriptCore/RuntimeFlags.h>
3638#include <wtf/MonotonicTime.h>
3739#include <wtf/Optional.h>

@@class Worker final : public AbstractWorker, public ActiveDOMObject, private Work
5557 WTF_MAKE_ISO_ALLOCATED(Worker);
5658public:
5759 struct Options {
 60 WorkerType type;
 61 FetchRequestCredentials credentials;
5862 String name;
5963 };
6064 static ExceptionOr<Ref<Worker>> create(ScriptExecutionContext&, JSC::RuntimeFlags, const String& url, const Options&);

@@class Worker final : public AbstractWorker, public ActiveDOMObject, private Work
7983 void postTaskToWorkerGlobalScope(Function<void(ScriptExecutionContext&)>&&);
8084#endif
8185
 86 WorkerType type() const { return m_type; }
 87
8288private:
8389 explicit Worker(ScriptExecutionContext&, JSC::RuntimeFlags, const Options&);
8490

@@class Worker final : public AbstractWorker, public ActiveDOMObject, private Work
112118#if ENABLE(WEB_RTC)
113119 HashSet<String> m_transformers;
114120#endif
 121 WorkerType m_type { WorkerType::Classic };
 122 FetchRequestCredentials m_credentials { FetchRequestCredentials::SameOrigin };
115123};
116124
117125} // namespace WebCore

Source/WebCore/workers/Worker.idl

3838};
3939
4040dictionary WorkerOptions {
 41 WorkerType type = "classic";
 42 FetchRequestCredentials credentials = "same-origin"; // credentials is only used if type is "module"
4143 DOMString name = "";
4244};
4345

Source/WebCore/workers/WorkerGlobalScope.cpp

@@WorkerGlobalScope::WorkerGlobalScope(WorkerThreadType type, const WorkerParamete
7474 , m_performance(Performance::create(this, params.timeOrigin))
7575 , m_referrerPolicy(params.referrerPolicy)
7676 , m_settingsValues(params.settingsValues)
 77 , m_workerType(params.workerType)
 78 , m_credentials(params.credentials)
7779{
7880#if !ENABLE(INDEXED_DATABASE)
7981 UNUSED_PARAM(connectionProxy);

@@ExceptionOr<void> WorkerGlobalScope::importScripts(const Vector<String>& urls)
274276{
275277 ASSERT(contentSecurityPolicy());
276278
 279 // https://html.spec.whatwg.org/multipage/workers.html#importing-scripts-and-libraries
 280 // 1. If worker global scope's type is "module", throw a TypeError exception.
 281 if (m_workerType == WorkerType::Module)
 282 return Exception { TypeError, "importScripts cannot be used if woerker type is \"module\""_s };
 283
277284 Vector<URL> completedURLs;
278285 completedURLs.reserveInitialCapacity(urls.size());
279286 for (auto& entry : urls) {

Source/WebCore/workers/WorkerGlobalScope.h

@@class WorkerGlobalScope : public Supplementable<WorkerGlobalScope>, public Base6
123123
124124 const Settings::Values& settingsValues() const final { return m_settingsValues; }
125125
 126 FetchOptions::Credentials credentials() const { return m_credentials; }
 127
126128protected:
127129 WorkerGlobalScope(WorkerThreadType, const WorkerParameters&, Ref<SecurityOrigin>&&, WorkerThread&, Ref<SecurityOrigin>&& topOrigin, IDBClient::IDBConnectionProxy*, SocketProvider*);
128130

@@class WorkerGlobalScope : public Supplementable<WorkerGlobalScope>, public Base6
163165 mutable RefPtr<WorkerLocation> m_location;
164166 mutable RefPtr<WorkerNavigator> m_navigator;
165167
166  std::unique_ptr<WorkerOrWorkletScriptController> m_script;
167 
168168 bool m_isOnline;
169169 bool m_shouldBypassMainWorldContentSecurityPolicy;
170170

@@class WorkerGlobalScope : public Supplementable<WorkerGlobalScope>, public Base6
187187 std::unique_ptr<CSSValuePool> m_cssValuePool;
188188 ReferrerPolicy m_referrerPolicy;
189189 Settings::Values m_settingsValues;
 190 WorkerType m_workerType;
 191 FetchOptions::Credentials m_credentials;
190192};
191193
192194} // namespace WebCore

Source/WebCore/workers/WorkerGlobalScopeProxy.h

@@class WorkerGlobalScopeProxy {
4848public:
4949 static WorkerGlobalScopeProxy& create(Worker&);
5050
51  virtual void startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const String& sourceCode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, MonotonicTime timeOrigin, ReferrerPolicy, JSC::RuntimeFlags) = 0;
 51 virtual void startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const String& sourceCode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, MonotonicTime timeOrigin, ReferrerPolicy, WorkerType, FetchRequestCredentials, JSC::RuntimeFlags) = 0;
5252 virtual void terminateWorkerGlobalScope() = 0;
5353 virtual void postMessageToWorkerGlobalScope(MessageWithMessagePorts&&) = 0;
5454 virtual void postTaskToWorkerGlobalScope(Function<void(ScriptExecutionContext&)>&&) = 0;

Source/WebCore/workers/WorkerMessagingProxy.cpp

@@WorkerMessagingProxy::~WorkerMessagingProxy()
7373 || (is<WorkerGlobalScope>(*m_scriptExecutionContext) && downcast<WorkerGlobalScope>(*m_scriptExecutionContext).thread().thread() == &Thread::current()));
7474}
7575
76 void WorkerMessagingProxy::startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const String& sourceCode, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders, bool shouldBypassMainWorldContentSecurityPolicy, MonotonicTime timeOrigin, ReferrerPolicy referrerPolicy, JSC::RuntimeFlags runtimeFlags)
 76void WorkerMessagingProxy::startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const String& sourceCode, const ContentSecurityPolicyResponseHeaders& contentSecurityPolicyResponseHeaders, bool shouldBypassMainWorldContentSecurityPolicy, MonotonicTime timeOrigin, ReferrerPolicy referrerPolicy, WorkerType workerType, FetchRequestCredentials credentials, JSC::RuntimeFlags runtimeFlags)
7777{
7878 // FIXME: This need to be revisited when we support nested worker one day
7979 ASSERT(m_scriptExecutionContext);

@@void WorkerMessagingProxy::startWorkerGlobalScope(const URL& scriptURL, const St
8989
9090 SocketProvider* socketProvider = document.socketProvider();
9191
92  WorkerParameters params = { scriptURL, name, identifier, userAgent, isOnline, contentSecurityPolicyResponseHeaders, shouldBypassMainWorldContentSecurityPolicy, timeOrigin, referrerPolicy, document.settingsValues() };
 92 WorkerParameters params = { scriptURL, name, identifier, userAgent, isOnline, contentSecurityPolicyResponseHeaders, shouldBypassMainWorldContentSecurityPolicy, timeOrigin, referrerPolicy, workerType, credentials, document.settingsValues() };
9393 auto thread = DedicatedWorkerThread::create(params, sourceCode, *this, *this, *this, startMode, document.topOrigin(), proxy, socketProvider, runtimeFlags);
9494
9595 workerThreadCreated(thread.get());

Source/WebCore/workers/WorkerMessagingProxy.h

@@class WorkerMessagingProxy final : public ThreadSafeRefCounted<WorkerMessagingPr
5050private:
5151 // Implementations of WorkerGlobalScopeProxy.
5252 // (Only use these functions in the worker object thread.)
53  void startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const String& sourceCode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, MonotonicTime timeOrigin, ReferrerPolicy, JSC::RuntimeFlags) final;
 53 void startWorkerGlobalScope(const URL& scriptURL, const String& name, const String& userAgent, bool isOnline, const String& sourceCode, const ContentSecurityPolicyResponseHeaders&, bool shouldBypassMainWorldContentSecurityPolicy, MonotonicTime timeOrigin, ReferrerPolicy, WorkerType, FetchRequestCredentials, JSC::RuntimeFlags) final;
5454 void terminateWorkerGlobalScope() final;
5555 void postMessageToWorkerGlobalScope(MessageWithMessagePorts&&) final;
5656 void postTaskToWorkerGlobalScope(Function<void(ScriptExecutionContext&)>&&) final;

Source/WebCore/workers/WorkerOrWorkletGlobalScope.cpp

2626#include "config.h"
2727#include "WorkerOrWorkletGlobalScope.h"
2828
 29#include "ScriptModuleLoader.h"
2930#include "WorkerEventLoop.h"
3031#include "WorkerInspectorController.h"
3132#include "WorkerOrWorkletScriptController.h"

@@WTF_MAKE_ISO_ALLOCATED_IMPL(WorkerOrWorkletGlobalScope);
3940
4041WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope(WorkerThreadType type, Ref<JSC::VM>&& vm, WorkerOrWorkletThread* thread)
4142 : m_script(makeUnique<WorkerOrWorkletScriptController>(type, WTFMove(vm), this))
 43 , m_moduleLoader(makeUnique<ScriptModuleLoader>(*this, ScriptModuleLoader::OwnerType::WorkerOrWorklet))
4244 , m_thread(thread)
4345 , m_inspectorController(makeUnique<WorkerInspectorController>(*this))
4446{

Source/WebCore/workers/WorkerOrWorkletGlobalScope.h

3232namespace WebCore {
3333
3434class EventLoopTaskGroup;
 35class ScriptModuleLoader;
3536class WorkerEventLoop;
3637class WorkerInspectorController;
3738class WorkerOrWorkletScriptController;

@@class WorkerOrWorkletGlobalScope : public ScriptExecutionContext, public RefCoun
5455
5556 unsigned long createUniqueIdentifier() { return m_uniqueIdentifier++; }
5657
 58 ScriptModuleLoader& moduleLoader() { return *m_moduleLoader; }
 59
5760 // ScriptExecutionContext.
5861 EventLoopTaskGroup& eventLoop() final;
5962 bool isContextThread() const final;

@@class WorkerOrWorkletGlobalScope : public ScriptExecutionContext, public RefCoun
8891 void derefEventTarget() final { deref(); }
8992
9093 std::unique_ptr<WorkerOrWorkletScriptController> m_script;
 94 std::unique_ptr<ScriptModuleLoader> m_moduleLoader;
9195 WorkerOrWorkletThread* m_thread;
9296 RefPtr<WorkerEventLoop> m_eventLoop;
9397 std::unique_ptr<EventLoopTaskGroup> m_defaultTaskGroup;

Source/WebCore/workers/WorkerOrWorkletScriptController.cpp

3535#include "JSExecState.h"
3636#include "JSPaintWorkletGlobalScope.h"
3737#include "JSServiceWorkerGlobalScope.h"
 38#include "ModuleFetchFailureKind.h"
 39#include "ModuleFetchParameters.h"
3840#include "ScriptSourceCode.h"
3941#include "WebCoreJSClientData.h"
4042#include "WorkerConsoleClient.h"
 43#include "WorkerScriptFetcher.h"
4144#include <JavaScriptCore/Completion.h>
4245#include <JavaScriptCore/DeferredWorkTimer.h>
4346#include <JavaScriptCore/Exception.h>
4447#include <JavaScriptCore/ExceptionHelpers.h>
4548#include <JavaScriptCore/GCActivityCallback.h>
 49#include <JavaScriptCore/JSInternalPromise.h>
4650#include <JavaScriptCore/JSLock.h>
 51#include <JavaScriptCore/JSModuleRecord.h>
 52#include <JavaScriptCore/JSNativeStdFunction.h>
 53#include <JavaScriptCore/JSScriptFetchParameters.h>
 54#include <JavaScriptCore/JSScriptFetcher.h>
4755#include <JavaScriptCore/StrongInlines.h>
4856
4957namespace WebCore {

@@void WorkerOrWorkletScriptController::evaluate(const ScriptSourceCode& sourceCod
228236 }
229237}
230238
 239static Identifier jsValueToModuleKey(JSGlobalObject* lexicalGlobalObject, JSValue value)
 240{
 241 if (value.isSymbol())
 242 return Identifier::fromUid(jsCast<Symbol*>(value)->privateName());
 243 ASSERT(value.isString());
 244 return asString(value)->toIdentifier(lexicalGlobalObject);
 245}
 246
 247JSC::JSValue WorkerOrWorkletScriptController::evaluateModule(JSC::JSModuleRecord& moduleRecord)
 248{
 249 auto& globalObject = *m_globalScopeWrapper.get();
 250 VM& vm = globalObject.vm();
 251 JSLockHolder lock { vm };
 252 return moduleRecord.evaluate(&globalObject);
 253}
 254
 255MessageQueueWaitResult WorkerOrWorkletScriptController::loadModuleSynchronously(WorkerScriptFetcher& scriptFetcher, const ScriptSourceCode& sourceCode)
 256{
 257 if (isExecutionForbidden())
 258 return MessageQueueTerminated;
 259
 260 initScriptIfNeeded();
 261
 262 auto& globalObject = *m_globalScopeWrapper.get();
 263 VM& vm = globalObject.vm();
 264 JSLockHolder lock { vm };
 265
 266 auto protector = makeRef(scriptFetcher);
 267 {
 268 auto& promise = JSExecState::loadModule(globalObject, sourceCode.jsSourceCode(), JSC::JSScriptFetcher::create(vm, { &scriptFetcher }));
 269
 270 auto& fulfillHandler = *JSNativeStdFunction::create(vm, &globalObject, 1, String(), [protector](JSGlobalObject* globalObject, CallFrame* callFrame) -> JSC::EncodedJSValue {
 271 VM& vm = globalObject->vm();
 272 JSLockHolder lock { vm };
 273 auto scope = DECLARE_THROW_SCOPE(vm);
 274 Identifier moduleKey = jsValueToModuleKey(globalObject, callFrame->argument(0));
 275 RETURN_IF_EXCEPTION(scope, { });
 276 protector->notifyLoadCompleted(*moduleKey.impl());
 277 return JSValue::encode(jsUndefined());
 278 });
 279
 280 auto& rejectHandler = *JSNativeStdFunction::create(vm, &globalObject, 1, String(), [protector](JSGlobalObject* globalObject, CallFrame* callFrame) {
 281 VM& vm = globalObject->vm();
 282 JSLockHolder lock { vm };
 283 JSValue errorValue = callFrame->argument(0);
 284 if (errorValue.isObject()) {
 285 auto* object = JSC::asObject(errorValue);
 286 if (JSValue failureKindValue = object->getDirect(vm, static_cast<JSVMClientData&>(*vm.clientData).builtinNames().failureKindPrivateName())) {
 287 // This is host propagated error in the module loader pipeline.
 288 switch (static_cast<ModuleFetchFailureKind>(failureKindValue.asInt32())) {
 289 case ModuleFetchFailureKind::WasErrored:
 290 protector->notifyLoadFailed(LoadableScript::Error {
 291 LoadableScript::ErrorType::CachedScript,
 292 WTF::nullopt
 293 });
 294 break;
 295 case ModuleFetchFailureKind::WasCanceled:
 296 protector->notifyLoadWasCanceled();
 297 break;
 298 }
 299 return JSValue::encode(jsUndefined());
 300 }
 301 }
 302
 303 auto scope = DECLARE_CATCH_SCOPE(vm);
 304 protector->notifyLoadFailed(LoadableScript::Error {
 305 LoadableScript::ErrorType::CachedScript,
 306 LoadableScript::ConsoleMessage {
 307 MessageSource::JS,
 308 MessageLevel::Error,
 309 retrieveErrorMessage(*globalObject, vm, errorValue, scope),
 310 }
 311 });
 312 return JSValue::encode(jsUndefined());
 313 });
 314
 315 promise.then(&globalObject, &fulfillHandler, &rejectHandler);
 316 }
 317 m_globalScope->eventLoop().performMicrotaskCheckpoint();
 318
 319 // Drive RunLoop until we get either of "Worker is terminated", "Loading is done", or "Loading is failed".
 320 WorkerRunLoop& runLoop = m_globalScope->workerOrWorkletThread()->runLoop();
 321
 322 // We do not want to receive messages that are not related to asynchronous resource loading.
 323 // Otherwise, a worker discards some messages from the main thread here in a racy way.
 324 // For example, the main thread can postMessage just after creating a Worker. In that case, postMessage's
 325 // task is queued in WorkerRunLoop before start running module scripts. This task should not be discarded
 326 // in the following driving of the RunLoop which mainly attempt to collect initial load of module scripts.
 327 String taskMode = "loadModulesInWorkerOrWorkletMode"_s;
 328 MessageQueueWaitResult result = MessageQueueMessageReceived;
 329 while ((!protector->isLoaded() && !protector->wasCanceled()) && result != MessageQueueTerminated) {
 330 result = runLoop.runInMode(m_globalScope, taskMode);
 331 if (result != MessageQueueTerminated)
 332 m_globalScope->eventLoop().performMicrotaskCheckpoint();
 333 }
 334
 335 return result;
 336}
 337
 338void WorkerOrWorkletScriptController::linkAndEvaluateModule(WorkerScriptFetcher& scriptFetcher, const ScriptSourceCode& sourceCode, String* returnedExceptionMessage)
 339{
 340 if (isExecutionForbidden())
 341 return;
 342
 343 initScriptIfNeeded();
 344
 345 auto& globalObject = *m_globalScopeWrapper.get();
 346 VM& vm = globalObject.vm();
 347 JSLockHolder lock { vm };
 348
 349 NakedPtr<JSC::Exception> returnedException;
 350 JSExecState::linkAndEvaluateModule(globalObject, Identifier::fromUid(vm, scriptFetcher.moduleKey()), jsUndefined(), returnedException);
 351 if ((returnedException && isTerminatedExecutionException(vm, returnedException)) || isTerminatingExecution()) {
 352 forbidExecution();
 353 return;
 354 }
 355
 356 if (returnedException) {
 357 if (m_globalScope->canIncludeErrorDetails(sourceCode.cachedScript(), sourceCode.url().string())) {
 358 // FIXME: It's not great that this can run arbitrary code to string-ify the value of the exception.
 359 // Do we need to do anything to handle that properly, if it, say, raises another exception?
 360 if (returnedExceptionMessage)
 361 *returnedExceptionMessage = returnedException->value().toWTFString(&globalObject);
 362 } else {
 363 // Overwrite the detailed error with a generic error.
 364 String genericErrorMessage { "Script error."_s };
 365 if (returnedExceptionMessage)
 366 *returnedExceptionMessage = genericErrorMessage;
 367 }
 368 }
 369}
 370
 371void WorkerOrWorkletScriptController::loadAndEvaluateModule(const URL& moduleURL, FetchOptions::Credentials credentials, CompletionHandler<void(Optional<Exception>&&)>&& completionHandler)
 372{
 373 if (isExecutionForbidden()) {
 374 completionHandler(Exception { NotAllowedError });
 375 return;
 376 }
 377
 378 initScriptIfNeeded();
 379
 380 auto& globalObject = *m_globalScopeWrapper.get();
 381 VM& vm = globalObject.vm();
 382 JSLockHolder lock { vm };
 383
 384 auto scriptFetcher = WorkerScriptFetcher::create(credentials);
 385 {
 386 auto& promise = JSExecState::loadModule(globalObject, moduleURL.string(), jsUndefined(), JSC::JSScriptFetcher::create(vm, { scriptFetcher.ptr() }));
 387
 388 auto task = createSharedTask<void(Optional<Exception>&&)>([completionHandler = WTFMove(completionHandler)](Optional<Exception>&& exception) mutable {
 389 completionHandler(WTFMove(exception));
 390 });
 391
 392 auto& fulfillHandler = *JSNativeStdFunction::create(vm, &globalObject, 1, String(), [task, scriptFetcher](JSGlobalObject* globalObject, CallFrame* callFrame) -> JSC::EncodedJSValue {
 393 // task->run(WTF::nullopt);
 394 VM& vm = globalObject->vm();
 395 JSLockHolder lock { vm };
 396 auto scope = DECLARE_THROW_SCOPE(vm);
 397
 398 Identifier moduleKey = jsValueToModuleKey(globalObject, callFrame->argument(0));
 399 RETURN_IF_EXCEPTION(scope, { });
 400 scriptFetcher->notifyLoadCompleted(*moduleKey.impl());
 401
 402 auto* context = downcast<WorkerOrWorkletGlobalScope>(jsCast<JSDOMGlobalObject*>(globalObject)->scriptExecutionContext());
 403 if (!context || !context->script()) {
 404 task->run(WTF::nullopt);
 405 return JSValue::encode(jsUndefined());
 406 }
 407
 408 NakedPtr<JSC::Exception> returnedException;
 409 JSExecState::linkAndEvaluateModule(*globalObject, moduleKey, jsUndefined(), returnedException);
 410 if ((returnedException && isTerminatedExecutionException(vm, returnedException)) || context->script()->isTerminatingExecution()) {
 411 if (context->script())
 412 context->script()->forbidExecution();
 413 task->run(WTF::nullopt);
 414 return JSValue::encode(jsUndefined());
 415 }
 416
 417 if (returnedException) {
 418 String message;
 419 if (context->canIncludeErrorDetails(nullptr, moduleKey.string())) {
 420 // FIXME: It's not great that this can run arbitrary code to string-ify the value of the exception.
 421 // Do we need to do anything to handle that properly, if it, say, raises another exception?
 422 message = returnedException->value().toWTFString(globalObject);
 423 } else {
 424 // Overwrite the detailed error with a generic error.
 425 message = "Script error."_s;
 426 }
 427 context->reportException(message, { }, { }, { }, { }, { });
 428 }
 429
 430 task->run(WTF::nullopt);
 431 return JSValue::encode(jsUndefined());
 432 });
 433
 434 auto& rejectHandler = *JSNativeStdFunction::create(vm, &globalObject, 1, String(), [task](JSGlobalObject* globalObject, CallFrame* callFrame) {
 435 VM& vm = globalObject->vm();
 436 JSLockHolder lock { vm };
 437 JSValue errorValue = callFrame->argument(0);
 438 if (errorValue.isObject()) {
 439 auto* object = JSC::asObject(errorValue);
 440 if (object->getDirect(vm, static_cast<JSVMClientData&>(*vm.clientData).builtinNames().failureKindPrivateName())) {
 441 task->run(Exception { AbortError });
 442 return JSValue::encode(jsUndefined());
 443 }
 444 if (object->inherits<ErrorInstance>(vm)) {
 445 auto* error = jsCast<ErrorInstance*>(object);
 446 switch (error->errorType()) {
 447 case ErrorType::SyntaxError: {
 448 auto catchScope = DECLARE_CATCH_SCOPE(vm);
 449 String message = retrieveErrorMessageWithoutName(*globalObject, vm, errorValue, catchScope);
 450 task->run(Exception { SyntaxError, message });
 451 return JSValue::encode(jsUndefined());
 452 }
 453 default:
 454 break;
 455 }
 456 }
 457 }
 458
 459 auto catchScope = DECLARE_CATCH_SCOPE(vm);
 460 String message = retrieveErrorMessageWithoutName(*globalObject, vm, errorValue, catchScope);
 461 task->run(Exception { AbortError, message });
 462 return JSValue::encode(jsUndefined());
 463 });
 464
 465 promise.then(&globalObject, &fulfillHandler, &rejectHandler);
 466 }
 467 m_globalScope->eventLoop().performMicrotaskCheckpoint();
 468}
 469
231470template<typename JSGlobalScopePrototype, typename JSGlobalScope, typename GlobalScope>
232471void WorkerOrWorkletScriptController::initScriptWithSubclass()
233472{

Source/WebCore/workers/WorkerOrWorkletScriptController.h

3131#include <JavaScriptCore/JSRunLoopTimer.h>
3232#include <wtf/Forward.h>
3333#include <wtf/Lock.h>
 34#include <wtf/MessageQueue.h>
3435#include <wtf/NakedPtr.h>
3536
3637namespace JSC {

@@class JSGlobalObject;
4445namespace WebCore {
4546
4647class JSDOMGlobalObject;
 48class LoadableModuleScript;
4749class ScriptSourceCode;
4850class WorkerConsoleClient;
4951class WorkerOrWorkletGlobalScope;
 52class WorkerScriptFetcher;
5053
5154class WorkerOrWorkletScriptController {
5255 WTF_MAKE_NONCOPYABLE(WorkerOrWorkletScriptController);

@@class WorkerOrWorkletScriptController {
9497 void evaluate(const ScriptSourceCode&, String* returnedExceptionMessage = nullptr);
9598 void evaluate(const ScriptSourceCode&, NakedPtr<JSC::Exception>& returnedException, String* returnedExceptionMessage = nullptr);
9699
 100 JSC::JSValue evaluateModule(JSC::JSModuleRecord&);
 101
 102 void linkAndEvaluateModule(WorkerScriptFetcher&, const ScriptSourceCode&, String* returnedExceptionMessage = nullptr);
 103 MessageQueueWaitResult loadModuleSynchronously(WorkerScriptFetcher&, const ScriptSourceCode&);
 104
 105 void loadAndEvaluateModule(const URL& moduleURL, FetchOptions::Credentials, CompletionHandler<void(Optional<Exception>&&)>&&);
 106
97107protected:
98108 WorkerOrWorkletGlobalScope* globalScope() const { return m_globalScope; }
99109

Source/WebCore/workers/WorkerScriptLoader.cpp

@@Optional<Exception> WorkerScriptLoader::loadSynchronously(ScriptExecutionContext
107107 return WTF::nullopt;
108108}
109109
110 void WorkerScriptLoader::loadAsynchronously(ScriptExecutionContext& scriptExecutionContext, ResourceRequest&& scriptRequest, FetchOptions&& fetchOptions, ContentSecurityPolicyEnforcement contentSecurityPolicyEnforcement, ServiceWorkersMode serviceWorkerMode, WorkerScriptLoaderClient& client)
 110void WorkerScriptLoader::loadAsynchronously(ScriptExecutionContext& scriptExecutionContext, ResourceRequest&& scriptRequest, FetchOptions&& fetchOptions, ContentSecurityPolicyEnforcement contentSecurityPolicyEnforcement, ServiceWorkersMode serviceWorkerMode, WorkerScriptLoaderClient& client, String&& taskMode)
111111{
112112 m_client = &client;
113113 m_url = scriptRequest.url();

@@void WorkerScriptLoader::loadAsynchronously(ScriptExecutionContext& scriptExecut
123123 ASSERT(fetchOptions.mode == FetchOptions::Mode::SameOrigin || (fetchOptions.destination != FetchOptions::Destination::Serviceworker && fetchOptions.destination != FetchOptions::Destination::Worker));
124124
125125 ThreadableLoaderOptions options { WTFMove(fetchOptions) };
126  // FIXME: We should add an option to set credential mode.
127  options.credentials = FetchOptions::Credentials::SameOrigin;
128126 options.sendLoadCallbacks = SendCallbackPolicy::SendCallbacks;
129127 options.contentSecurityPolicyEnforcement = contentSecurityPolicyEnforcement;
130128 if (fetchOptions.destination == FetchOptions::Destination::Serviceworker)

@@void WorkerScriptLoader::loadAsynchronously(ScriptExecutionContext& scriptExecut
143141
144142 // During create, callbacks may happen which remove the last reference to this object.
145143 Ref<WorkerScriptLoader> protectedThis(*this);
146  m_threadableLoader = ThreadableLoader::create(scriptExecutionContext, *this, WTFMove(*request), options);
 144 m_threadableLoader = ThreadableLoader::create(scriptExecutionContext, *this, WTFMove(*request), options, { }, WTFMove(taskMode));
147145}
148146
149147const URL& WorkerScriptLoader::responseURL() const

@@void WorkerScriptLoader::didReceiveResponse(unsigned long identifier, const Reso
190188 m_certificateInfo = response.certificateInfo() ? *response.certificateInfo() : CertificateInfo();
191189 m_responseMIMEType = response.mimeType();
192190 m_responseEncoding = response.textEncodingName();
 191 m_responseSource = response.source();
 192 m_isRedirected = response.isRedirected();
193193 m_contentSecurityPolicy = ContentSecurityPolicyResponseHeaders { response };
194194 m_referrerPolicy = response.httpHeaderField(HTTPHeaderName::ReferrerPolicy);
195195 if (m_client)

Source/WebCore/workers/WorkerScriptLoader.h

3131#include "FetchOptions.h"
3232#include "ResourceError.h"
3333#include "ResourceRequest.h"
 34#include "ResourceResponse.h"
3435#include "ThreadableLoader.h"
3536#include "ThreadableLoaderClient.h"
3637#include <memory>

4344namespace WebCore {
4445
4546class Exception;
46 class ResourceResponse;
4747class ScriptExecutionContext;
4848class TextResourceDecoder;
4949class WorkerScriptLoaderClient;

@@class WorkerScriptLoader : public RefCounted<WorkerScriptLoader>, public Threada
5858 }
5959
6060 Optional<Exception> loadSynchronously(ScriptExecutionContext*, const URL&, FetchOptions::Mode, FetchOptions::Cache, ContentSecurityPolicyEnforcement, const String& initiatorIdentifier);
61  void loadAsynchronously(ScriptExecutionContext&, ResourceRequest&&, FetchOptions&&, ContentSecurityPolicyEnforcement, ServiceWorkersMode, WorkerScriptLoaderClient&);
 61 void loadAsynchronously(ScriptExecutionContext&, ResourceRequest&&, FetchOptions&&, ContentSecurityPolicyEnforcement, ServiceWorkersMode, WorkerScriptLoaderClient&, String&& taskMode);
6262
6363 void notifyError();
6464

@@class WorkerScriptLoader : public RefCounted<WorkerScriptLoader>, public Threada
6767 const String& referrerPolicy() const { return m_referrerPolicy; }
6868 const URL& url() const { return m_url; }
6969 const URL& responseURL() const;
 70 ResourceResponse::Source responseSource() const { return m_responseSource; }
 71 bool isRedirected() const { return m_isRedirected; }
7072 const CertificateInfo& certificateInfo() const { return m_certificateInfo; }
7173 const String& responseMIMEType() const { return m_responseMIMEType; }
7274 bool failed() const { return m_failed; }

@@class WorkerScriptLoader : public RefCounted<WorkerScriptLoader>, public Threada
107109 unsigned long m_identifier { 0 };
108110 bool m_failed { false };
109111 bool m_finishing { false };
 112 bool m_isRedirected { false };
 113 ResourceResponse::Source m_responseSource { ResourceResponse::Source::Unknown };
110114 ResourceError m_error;
111115};
112116

Source/WebCore/workers/WorkerThread.cpp

3232#include "SecurityOrigin.h"
3333#include "SocketProvider.h"
3434#include "WorkerGlobalScope.h"
 35#include "WorkerScriptFetcher.h"
 36#include <JavaScriptCore/ScriptCallStack.h>
3537#include <wtf/Threading.h>
3638
3739namespace WebCore {

@@WorkerParameters WorkerParameters::isolatedCopy() const
5557 shouldBypassMainWorldContentSecurityPolicy,
5658 timeOrigin,
5759 referrerPolicy,
 60 workerType,
 61 credentials,
5862 settingsValues.isolatedCopy()
5963 };
6064}

@@bool WorkerThread::shouldWaitForWebInspectorOnStartup() const
123127
124128void WorkerThread::evaluateScriptIfNecessary(String& exceptionMessage)
125129{
126  globalScope()->script()->evaluate(ScriptSourceCode(m_startupData->sourceCode, URL(m_startupData->params.scriptURL)), &exceptionMessage);
127 
128  finishedEvaluatingScript();
 130 // We are currently holding only the initial script code. If the WorkerType is Module, we should fetch the entire graph before executing the rest of this.
 131 // We invoke module loader as if we are executing inline module script tag in Document.
 132
 133 if (m_startupData->params.workerType == WorkerType::Classic) {
 134 globalScope()->script()->evaluate(ScriptSourceCode(m_startupData->sourceCode, URL(m_startupData->params.scriptURL)), &exceptionMessage);
 135 finishedEvaluatingScript();
 136 } else {
 137 // FIXME crossOrigin mode should be converted.
 138 // FIXME fix initiator name.
 139 // FIXME pass URL to module loader.
 140 ScriptSourceCode sourceCode(m_startupData->sourceCode, URL(m_startupData->params.scriptURL), { }, JSC::SourceProviderSourceType::Module);
 141 auto scriptFetcher = WorkerScriptFetcher::create(globalScope()->credentials());
 142 MessageQueueWaitResult result = globalScope()->script()->loadModuleSynchronously(scriptFetcher.get(), sourceCode);
 143 if (result != MessageQueueTerminated) {
 144 if (Optional<LoadableScript::Error> error = scriptFetcher->error()) {
 145 if (Optional<LoadableScript::ConsoleMessage> message = error->consoleMessage)
 146 exceptionMessage = message->message;
 147 else
 148 exceptionMessage = "Importing a module script failed."_s;
 149 globalScope()->reportException(exceptionMessage, { }, { }, { }, { }, { });
 150 } else if (!scriptFetcher->wasCanceled()) {
 151 // Evaluate.
 152 globalScope()->script()->linkAndEvaluateModule(scriptFetcher.get(), sourceCode, &exceptionMessage);
 153 finishedEvaluatingScript();
 154 }
 155 }
 156 }
129157
130158 // Free the startup data to cause its member variable deref's happen on the worker's thread (since
131159 // all ref/derefs of these objects are happening on the thread at this point). Note that

Source/WebCore/workers/WorkerThread.h

2626#pragma once
2727
2828#include "ContentSecurityPolicyResponseHeaders.h"
 29#include "FetchRequestCredentials.h"
2930#include "WorkerOrWorkletThread.h"
 31#include "WorkerRunLoop.h"
 32#include "WorkerType.h"
3033#include <JavaScriptCore/RuntimeFlags.h>
3134#include <memory>
3235#include <wtf/URL.h>

@@struct WorkerParameters {
6366 bool shouldBypassMainWorldContentSecurityPolicy;
6467 MonotonicTime timeOrigin;
6568 ReferrerPolicy referrerPolicy;
 69 WorkerType workerType;
 70 FetchRequestCredentials credentials;
6671 Settings::Values settingsValues;
6772
6873 WorkerParameters isolatedCopy() const;

Source/WebCore/workers/WorkerType.h

2727
2828namespace WebCore {
2929
30 enum class WorkerType {
 30enum class WorkerType : uint8_t {
3131 Classic,
3232 Module,
3333};

Source/WebCore/workers/service/ServiceWorkerContainer.h

@@class NavigatorBase;
4747class ServiceWorker;
4848
4949enum class ServiceWorkerUpdateViaCache : uint8_t;
50 enum class WorkerType;
 50enum class WorkerType : uint8_t;
5151
5252template<typename IDLType> class DOMPromiseProxy;
5353

Source/WebCore/workers/service/ServiceWorkerJob.cpp

@@void ServiceWorkerJob::fetchScriptWithContext(ScriptExecutionContext& context, F
110110 options.cache = cachePolicy;
111111 options.redirect = FetchOptions::Redirect::Error;
112112 options.destination = FetchOptions::Destination::Serviceworker;
113  m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(options), ContentSecurityPolicyEnforcement::DoNotEnforce, ServiceWorkersMode::None, *this);
 113 options.credentials = FetchOptions::Credentials::SameOrigin;
 114 m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(options), ContentSecurityPolicyEnforcement::DoNotEnforce, ServiceWorkersMode::None, *this, WorkerRunLoop::defaultMode());
114115}
115116
116117ResourceError ServiceWorkerJob::validateServiceWorkerResponse(const ServiceWorkerJobData& jobData, const ResourceResponse& response)

Source/WebCore/workers/service/ServiceWorkerRegistrationOptions.h

3232namespace WebCore {
3333
3434enum class ServiceWorkerUpdateViaCache : uint8_t;
35 enum class WorkerType;
 35enum class WorkerType : uint8_t;
3636
3737struct ServiceWorkerRegistrationOptions {
3838 String scope;

Source/WebCore/workers/service/context/ServiceWorkerThread.cpp

@@class DummyServiceWorkerThreadProxy : public WorkerObjectProxy {
7373// FIXME: Use a valid WorkerObjectProxy
7474// FIXME: Use valid runtime flags
7575
 76// FIXME: Use a valid WorkerType and Credentails for module service workers.
7677ServiceWorkerThread::ServiceWorkerThread(const ServiceWorkerContextData& data, String&& userAgent, const Settings::Values& settingsValues, WorkerLoaderProxy& loaderProxy, WorkerDebuggerProxy& debuggerProxy, IDBClient::IDBConnectionProxy* idbConnectionProxy, SocketProvider* socketProvider)
77  : WorkerThread({ data.scriptURL, emptyString(), "serviceworker:" + Inspector::IdentifiersFactory::createIdentifier(), WTFMove(userAgent), platformStrategies()->loaderStrategy()->isOnLine(), data.contentSecurityPolicy, false, MonotonicTime::now(), { }, settingsValues }, data.script, loaderProxy, debuggerProxy, DummyServiceWorkerThreadProxy::shared(), WorkerThreadStartMode::Normal, data.registration.key.topOrigin().securityOrigin().get(), idbConnectionProxy, socketProvider, JSC::RuntimeFlags::createAllEnabled())
 78 : WorkerThread({ data.scriptURL, emptyString(), "serviceworker:" + Inspector::IdentifiersFactory::createIdentifier(), WTFMove(userAgent), platformStrategies()->loaderStrategy()->isOnLine(), data.contentSecurityPolicy, false, MonotonicTime::now(), { }, WorkerType::Classic, FetchRequestCredentials::SameOrigin, settingsValues }, data.script, loaderProxy, debuggerProxy, DummyServiceWorkerThreadProxy::shared(), WorkerThreadStartMode::Normal, data.registration.key.topOrigin().securityOrigin().get(), idbConnectionProxy, socketProvider, JSC::RuntimeFlags::createAllEnabled())
7879 , m_data(data.isolatedCopy())
7980 , m_workerObjectProxy(DummyServiceWorkerThreadProxy::shared())
8081 , m_heartBeatTimeout(SWContextManager::singleton().connection()->shouldUseShortTimeout() ? heartBeatTimeoutForTest : heartBeatTimeout)

Source/WebCore/workers/service/server/SWServerWorker.h

@@struct ServiceWorkerClientIdentifier;
5050struct ServiceWorkerClientQueryOptions;
5151struct ServiceWorkerContextData;
5252struct ServiceWorkerJobDataIdentifier;
53 enum class WorkerType;
 53enum class WorkerType : uint8_t;
5454
5555class SWServerWorker : public RefCounted<SWServerWorker> {
5656public:

Source/WebCore/worklets/WorkletGlobalScope.cpp

@@ReferrerPolicy WorkletGlobalScope::referrerPolicy() const
158158void WorkletGlobalScope::fetchAndInvokeScript(const URL& moduleURL, FetchRequestCredentials credentials, CompletionHandler<void(Optional<Exception>&&)>&& completionHandler)
159159{
160160 ASSERT(!isMainThread());
161  m_scriptFetchJobs.append({ moduleURL, credentials, WTFMove(completionHandler) });
162  processNextScriptFetchJobIfNeeded();
163 }
164 
165 void WorkletGlobalScope::processNextScriptFetchJobIfNeeded()
166 {
167  if (m_scriptFetchJobs.isEmpty() || m_scriptLoader)
168  return;
169 
170  auto& scriptFetchJob = m_scriptFetchJobs.first();
171 
172  ResourceRequest request { scriptFetchJob.moduleURL };
173 
174  FetchOptions fetchOptions;
175  fetchOptions.mode = FetchOptions::Mode::Cors;
176  fetchOptions.cache = FetchOptions::Cache::Default;
177  fetchOptions.redirect = FetchOptions::Redirect::Follow;
178  fetchOptions.credentials = scriptFetchJob.credentials;
179 #if ENABLE(WEB_AUDIO)
180  if (isAudioWorkletGlobalScope())
181  fetchOptions.destination = FetchOptions::Destination::Audioworklet;
182 #endif
183 #if ENABLE(CSS_PAINTING_API)
184  if (isPaintWorkletGlobalScope())
185  fetchOptions.destination = FetchOptions::Destination::Paintworklet;
186 #endif
187 
188  auto contentSecurityPolicyEnforcement = shouldBypassMainWorldContentSecurityPolicy() ? ContentSecurityPolicyEnforcement::DoNotEnforce : ContentSecurityPolicyEnforcement::EnforceChildSrcDirective;
189 
190  m_scriptLoader = WorkerScriptLoader::create();
191  m_scriptLoader->loadAsynchronously(*this, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, *this);
192 }
193 
194 void WorkletGlobalScope::didReceiveResponse(unsigned long, const ResourceResponse&)
195 {
196 }
197 
198 void WorkletGlobalScope::notifyFinished()
199 {
200  auto completedJob = m_scriptFetchJobs.takeFirst();
201 
202  if (m_scriptLoader->failed()) {
203  didCompleteScriptFetchJob(WTFMove(completedJob), Exception { AbortError, makeString("Failed to fetch module, error: ", m_scriptLoader->error().localizedDescription()) });
204  return;
205  }
206 
207  // FIXME: This should really be run as a module script but we don't support this in workers yet.
208  URL moduleURL(m_scriptLoader->responseURL());
209  auto addResult = m_evaluatedModules.add(moduleURL);
210  if (addResult.isNewEntry) {
211  NakedPtr<JSC::Exception> exception;
212  script()->evaluate(ScriptSourceCode(m_scriptLoader->script(), WTFMove(moduleURL)), exception);
213  if (exception)
214  script()->setException(exception);
215  }
216 
217  didCompleteScriptFetchJob(WTFMove(completedJob), { });
218 }
219 
220 void WorkletGlobalScope::didCompleteScriptFetchJob(ScriptFetchJob&& job, Optional<Exception> result)
221 {
222  m_scriptLoader = nullptr;
223 
224  job.completionHandler(WTFMove(result));
225 
226  processNextScriptFetchJobIfNeeded();
 161 script()->loadAndEvaluateModule(moduleURL, credentials, WTFMove(completionHandler));
227162}
228163
229164MessagePortChannelProvider& WorkletGlobalScope::messagePortChannelProvider()

Source/WebCore/worklets/WorkletGlobalScope.h

3333#include "ScriptSourceCode.h"
3434#include "WorkerOrWorkletGlobalScope.h"
3535#include "WorkerOrWorkletScriptController.h"
36 #include "WorkerScriptLoaderClient.h"
3736#include <JavaScriptCore/ConsoleMessage.h>
3837#include <JavaScriptCore/RuntimeFlags.h>
3938#include <wtf/CompletionHandler.h>

@@struct WorkletParameters;
5453enum WorkletGlobalScopeIdentifierType { };
5554using WorkletGlobalScopeIdentifier = ObjectIdentifier<WorkletGlobalScopeIdentifierType>;
5655
57 class WorkletGlobalScope : public WorkerOrWorkletGlobalScope, public WorkerScriptLoaderClient {
 56class WorkletGlobalScope : public WorkerOrWorkletGlobalScope {
5857 WTF_MAKE_ISO_ALLOCATED(WorkletGlobalScope);
5958public:
6059 virtual ~WorkletGlobalScope();

@@class WorkletGlobalScope : public WorkerOrWorkletGlobalScope, public WorkerScrip
111110 void addMessage(MessageSource, MessageLevel, const String&, const String&, unsigned, unsigned, RefPtr<Inspector::ScriptCallStack>&&, JSC::JSGlobalObject*, unsigned long) final;
112111 void addConsoleMessage(MessageSource, MessageLevel, const String&, unsigned long) final;
113112
114  // WorkerScriptLoaderClient.
115  void didReceiveResponse(unsigned long identifier, const ResourceResponse&) final;
116  void notifyFinished() final;
117 
118113 EventTarget* errorEventTarget() final { return this; }
119114
120115#if ENABLE(WEB_CRYPTO)

@@class WorkletGlobalScope : public WorkerOrWorkletGlobalScope, public WorkerScrip
125120 String userAgent(const URL&) const final;
126121 const Settings::Values& settingsValues() const final { return m_settingsValues; }
127122
128  struct ScriptFetchJob {
129  URL moduleURL;
130  FetchRequestCredentials credentials;
131  CompletionHandler<void(Optional<Exception>&&)> completionHandler;
132  };
133 
134  void processNextScriptFetchJobIfNeeded();
135  void didCompleteScriptFetchJob(ScriptFetchJob&&, Optional<Exception>);
136 
137123 WeakPtr<Document> m_document;
138124
139125 Ref<SecurityOrigin> m_topOrigin;

@@class WorkletGlobalScope : public WorkerOrWorkletGlobalScope, public WorkerScrip
144130
145131 std::unique_ptr<WorkerMessagePortChannelProvider> m_messagePortChannelProvider;
146132
147  RefPtr<WorkerScriptLoader> m_scriptLoader;
148  Deque<ScriptFetchJob> m_scriptFetchJobs;
149  HashSet<URL> m_evaluatedModules;
150133 Settings::Values m_settingsValues;
151134};
152135

LayoutTests/ChangeLog

 12021-02-11 Yusuke Suzuki <ysuzuki@apple.com>
 2
 3 JS Modules in Workers
 4 https://bugs.webkit.org/show_bug.cgi?id=164860
 5
 6 Reviewed by NOBODY (OOPS!).
 7
 8 * TestExpectations:
 9
1102021-02-10 Amir Mark Jr <amir_mark@apple.com>
211
312 [MacOS] animations/keyframe-pseudo-shadow.html is flakey failing.

LayoutTests/imported/w3c/ChangeLog

 12021-02-11 Yusuke Suzuki <ysuzuki@apple.com>
 2
 3 JS Modules in Workers
 4 https://bugs.webkit.org/show_bug.cgi?id=164860
 5
 6 Reviewed by NOBODY (OOPS!).
 7
 8 * web-platform-tests/html/semantics/scripting-1/the-script-element/json-module/non-object.tentative.any.worker-expected.txt:
 9 * web-platform-tests/html/semantics/scripting-1/the-script-element/microtasks/checkpoint-after-workerglobalscope-onerror-module-expected.txt:
 10 * web-platform-tests/html/semantics/scripting-1/the-script-element/module/dynamic-import/alpha/base-url-worker-importScripts-expected.txt:
 11 * web-platform-tests/html/semantics/scripting-1/the-script-element/module/dynamic-import/alpha/base-url-worker.sub-expected.txt:
 12 * web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-1-nothrow-worker-expected.txt:
 13 * web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-1-worker-expected.txt:
 14 * web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-2-import-worker-expected.txt:
 15 * web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-3-dynamic-worker-expected.txt:
 16 * web-platform-tests/service-workers/service-worker/import-module-scripts.https-expected.txt:
 17 * web-platform-tests/workers/baseurl/alpha/import-in-moduleworker-expected.txt:
 18 * web-platform-tests/workers/baseurl/alpha/importScripts-in-worker-expected.txt:
 19 * web-platform-tests/workers/baseurl/alpha/xhr-in-moduleworker-expected.txt:
 20 * web-platform-tests/workers/baseurl/alpha/xhr-in-worker-expected.txt:
 21 * web-platform-tests/workers/constructors/Worker/same-origin-expected.txt:
 22 * web-platform-tests/workers/interfaces/WorkerGlobalScope/location/redirect-expected.txt:
 23 * web-platform-tests/workers/interfaces/WorkerGlobalScope/location/redirect-module-expected.txt:
 24 * web-platform-tests/workers/modules/dedicated-worker-import-blob-url.any-expected.txt:
 25 * web-platform-tests/workers/modules/dedicated-worker-import-csp-expected.txt:
 26 * web-platform-tests/workers/modules/dedicated-worker-import-failure-expected.txt:
 27 * web-platform-tests/workers/modules/dedicated-worker-import-meta-expected.txt:
 28 * web-platform-tests/workers/modules/dedicated-worker-import-meta.html:
 29 * web-platform-tests/workers/modules/dedicated-worker-import-referrer-expected.txt:
 30 * web-platform-tests/workers/modules/dedicated-worker-import.any-expected.txt:
 31 * web-platform-tests/workers/modules/dedicated-worker-options-type-expected.txt:
 32 * web-platform-tests/workers/modules/dedicated-worker-parse-error-failure-expected.txt:
 33 * web-platform-tests/workers/name-property-expected.txt:
 34 * web-platform-tests/worklets/audio-worklet-credentials.https-expected.txt:
 35 * web-platform-tests/worklets/audio-worklet-csp.https-expected.txt:
 36 * web-platform-tests/worklets/audio-worklet-import.https-expected.txt:
 37 * web-platform-tests/worklets/audio-worklet-referrer.https-expected.txt:
 38 * web-platform-tests/xhr/open-url-redirected-worker-origin-expected.txt:
 39
1402021-02-10 Manuel Rego Casasnovas <rego@igalia.com>
241
342 Add support for modifier keys in test_driver.send_keys()

LayoutTests/TestExpectations

@@fast/dom/connected-subframe-counter-overflow.html [ Slow ]
642642[ Debug ] http/tests/workers/worker-messageport-2.html [ Slow ]
643643
644644# Skip workers tests that are timing out or are SharedWorker related only
645 imported/w3c/web-platform-tests/workers/constructors/Worker/same-origin.html [ Skip ]
646645imported/w3c/web-platform-tests/workers/data-url-shared.html [ Skip ]
647646imported/w3c/web-platform-tests/workers/examples/onconnect.any.html [ Skip ]
648647imported/w3c/web-platform-tests/workers/examples/onconnect.any.worker.html [ Skip ]

@@imported/w3c/web-platform-tests/workers/SharedWorker-replace-EventHandler.any.ht
665664imported/w3c/web-platform-tests/workers/SharedWorker-replace-EventHandler.any.worker.html [ Skip ]
666665imported/w3c/web-platform-tests/workers/SharedWorker-script-error.html [ Skip ]
667666imported/w3c/web-platform-tests/workers/SharedWorker-simple.html [ Skip ]
668 imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-referrer.html [ Skip ]
669667imported/w3c/web-platform-tests/workers/modules/dedicated-worker-options-credentials.html [ Skip ]
670668
671669imported/w3c/web-platform-tests/workers/constructors/SharedWorker [ Skip ]

LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/json-module/non-object.tentative.any.worker-expected.txt

11
2 FAIL Non-object: null promise_test: Unhandled rejection with value: object "Error: Could not import the module './null.json'."
3 FAIL Non-object: true promise_test: Unhandled rejection with value: object "Error: Could not import the module './true.json'."
4 FAIL Non-object: false promise_test: Unhandled rejection with value: object "Error: Could not import the module './false.json'."
5 FAIL Non-object: string promise_test: Unhandled rejection with value: object "Error: Could not import the module './string.json'."
6 FAIL Non-object: array promise_test: Unhandled rejection with value: object "Error: Could not import the module './array.json'."
 2FAIL Non-object: null promise_test: Unhandled rejection with value: object "TypeError: 'application/json' is not a valid JavaScript MIME type."
 3FAIL Non-object: true promise_test: Unhandled rejection with value: object "TypeError: 'application/json' is not a valid JavaScript MIME type."
 4FAIL Non-object: false promise_test: Unhandled rejection with value: object "TypeError: 'application/json' is not a valid JavaScript MIME type."
 5FAIL Non-object: string promise_test: Unhandled rejection with value: object "TypeError: 'application/json' is not a valid JavaScript MIME type."
 6FAIL Non-object: array promise_test: Unhandled rejection with value: object "TypeError: 'application/json' is not a valid JavaScript MIME type."
77

LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/microtasks/checkpoint-after-workerglobalscope-onerror-module-expected.txt

11
2 Harness Error (TIMEOUT), message = null
3 
 2FAIL Promise resolved during #report-the-error assert_array_equals: lengths differ, expected array ["handler 1", "handler 2", "handler 1 promise", "handler 2 promise"] length 4, got [] length 0
 3PASS Promise resolved during event handlers other than error
44

LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/module/dynamic-import/alpha/base-url-worker-importScripts-expected.txt

11
2 FAIL Relative URL-like from same-origin importScripts() promise_test: Unhandled rejection with value: object "Error: Could not import the module './import.js?pipe=header(Access-Control-Allow-Origin,*)&label=relative-cross-origin importScripts()'."
3 FAIL Absolute URL-like from same-origin importScripts() promise_test: Unhandled rejection with value: object "Error: Could not import the module 'http://127.0.0.1:8800/html/semantics/scripting-1/the-script-element/module/dynamic-import/gamma/import.js?pipe=header(Access-Control-Allow-Origin,*)&label=absolute-cross-origin importScripts()'."
4 PASS Relative URL-like from cross-origin importScripts()
5 FAIL Absolute URL-like from cross-origin importScripts() promise_test: Unhandled rejection with value: object "Error: Could not import the module 'http://127.0.0.1:8800/html/semantics/scripting-1/the-script-element/module/dynamic-import/gamma/import.js?pipe=header(Access-Control-Allow-Origin,*)&label=absolute-cross-origin importScripts()'."
 2PASS Relative URL-like from same-origin importScripts()
 3PASS Absolute URL-like from same-origin importScripts()
 4FAIL Relative URL-like from cross-origin importScripts() assert_equals: Relative URL-like specifier resolution should fail expected "(unreached)" but got "gamma/import.js"
 5PASS Absolute URL-like from cross-origin importScripts()
66

LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/module/dynamic-import/alpha/base-url-worker.sub-expected.txt

11
2 FAIL Relative URL-like from worker top-level script promise_test: Unhandled rejection with value: object "Error: Could not import the module './import.js?pipe=header(Access-Control-Allow-Origin,*)&label=relative-worker top-level script'."
3 FAIL Absolute URL-like from worker top-level script promise_test: Unhandled rejection with value: object "Error: Could not import the module 'http://127.0.0.1:8800/html/semantics/scripting-1/the-script-element/module/dynamic-import/gamma/import.js?pipe=header(Access-Control-Allow-Origin,*)&label=absolute-worker top-level script'."
 2PASS Relative URL-like from worker top-level script
 3PASS Absolute URL-like from worker top-level script
44

LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-1-nothrow-worker-expected.txt

11
2 Harness Error (TIMEOUT), message = null
3 
 2PASS Test evaluation order of modules
43

LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-1-worker-expected.txt

11
2 Harness Error (TIMEOUT), message = null
3 
 2FAIL Test evaluation order of modules assert_array_equals: lengths differ, expected array ["step-1-1", "step-1-2", "global-error", "error", "microtask"] length 5, got ["step-1-1", "step-1-2", "microtask"] length 3
43

LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-2-import-worker-expected.txt

11
2 Harness Error (TIMEOUT), message = null
3 
 2FAIL Test evaluation order of modules assert_array_equals: lengths differ, expected array ["step-2.2-1", "step-2.2-2", "global-error", "error", "microtask-2.2"] length 5, got ["step-2.2-1", "step-2.2-2", "microtask-2.2"] length 3
43

LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-3-dynamic-worker-expected.txt

11
2 Harness Error (TIMEOUT), message = null
3 
 2PASS Test evaluation order of modules
43

LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/import-module-scripts.https-expected.txt

22FAIL Static import. promise_test: Unhandled rejection with value: object "TypeError: SyntaxError: Unexpected token '*'. import call expects exactly one argument."
33FAIL Nested static import. promise_test: Unhandled rejection with value: object "TypeError: SyntaxError: Unexpected token '*'. import call expects exactly one argument."
44FAIL Static import and then dynamic import. promise_test: Unhandled rejection with value: object "TypeError: SyntaxError: Unexpected token '*'. import call expects exactly one argument."
5 FAIL Dynamic import. assert_array_equals: value is "Failed to do dynamic import: Error: Could not import the module './export-on-load-script.js'.", expected array
6 FAIL Nested dynamic import. assert_array_equals: value is "Failed to do dynamic import: Error: Could not import the module './export-on-dynamic-import-script.js'.", expected array
7 FAIL Dynamic import and then static import. assert_array_equals: value is "Failed to do dynamic import: Error: Could not import the module './export-on-static-import-script.js'.", expected array
8 FAIL eval(import()). assert_array_equals: value is "Failed to do dynamic import: Error: Could not import the module './export-on-load-script.js'.", expected array
 5PASS Dynamic import.
 6PASS Nested dynamic import.
 7PASS Dynamic import and then static import.
 8PASS eval(import()).
99

LayoutTests/imported/w3c/web-platform-tests/workers/baseurl/alpha/import-in-moduleworker-expected.txt

1 CONSOLE MESSAGE: SyntaxError: Unexpected identifier 'r'. import call expects exactly one argument.
21
3 FAIL Base URL in module dedicated workers: import assert_unreached: Got error event Reached unreachable code
 2PASS Base URL in module dedicated workers: import
43

LayoutTests/imported/w3c/web-platform-tests/workers/baseurl/alpha/importScripts-in-worker-expected.txt

11
2 FAIL importScripts assert_equals: expected "gamma/script.js" but got "beta/script.js"
 2PASS importScripts
33

LayoutTests/imported/w3c/web-platform-tests/workers/baseurl/alpha/xhr-in-moduleworker-expected.txt

11
2 FAIL Base URL in module dedicated workers: XHR assert_equals: expected "gamma\n" but got "beta\n"
 2PASS Base URL in module dedicated workers: XHR
33

LayoutTests/imported/w3c/web-platform-tests/workers/baseurl/alpha/xhr-in-worker-expected.txt

11
2 FAIL xhr-worker assert_equals: expected "gamma\n" but got "beta\n"
 2PASS xhr-worker
33

LayoutTests/imported/w3c/web-platform-tests/workers/constructors/Worker/same-origin-expected.txt

11
2 Harness Error (TIMEOUT), message = null
3 
42PASS unsupported_scheme
53FAIL data_url The operation is insecure.
6 TIMEOUT about_blank Test timed out
7 TIMEOUT example_invalid Test timed out
8 TIMEOUT port_81 Test timed out
9 TIMEOUT https_port_80 Test timed out
10 TIMEOUT https_port_8000 Test timed out
11 TIMEOUT http_post_8012 Test timed out
12 TIMEOUT javascript_url Test timed out
 4PASS about_blank
 5PASS example_invalid
 6PASS port_81
 7PASS https_port_80
 8PASS https_port_8000
 9PASS http_post_8012
 10PASS javascript_url
1311

LayoutTests/imported/w3c/web-platform-tests/workers/interfaces/WorkerGlobalScope/location/redirect-expected.txt

11
2 FAIL WorkerLocation with redirects: classic dedicated workers assert_equals: expected "http://localhost:8800/workers/interfaces/WorkerGlobalScope/location/post-location-members.js?a" but got "http://localhost:8800/workers/interfaces/WorkerGlobalScope/location/helper-redirect.py?fail"
 2PASS WorkerLocation with redirects: classic dedicated workers
33

LayoutTests/imported/w3c/web-platform-tests/workers/interfaces/WorkerGlobalScope/location/redirect-module-expected.txt

11
2 FAIL WorkerLocation with redirects: module dedicated workers assert_equals: expected "http://localhost:8800/workers/interfaces/WorkerGlobalScope/location/post-location-members.js?a" but got "http://localhost:8800/workers/interfaces/WorkerGlobalScope/location/helper-redirect.py?fail"
 2PASS WorkerLocation with redirects: module dedicated workers
33

LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-blob-url.any-expected.txt

1 CONSOLE MESSAGE: SyntaxError: Unexpected string literal "http://localhost:8800/workers/modules/resources/static-import-worker.js". import call expects exactly one argument.
2 CONSOLE MESSAGE: SyntaxError: Unexpected string literal "http://localhost:8800/workers/modules/resources/nested-static-import-worker.js". import call expects exactly one argument.
3 CONSOLE MESSAGE: SyntaxError: Unexpected string literal "http://localhost:8800/workers/modules/resources/static-import-and-then-dynamic-import-worker.js". import call expects exactly one argument.
4 CONSOLE MESSAGE: SyntaxError: Unexpected string literal "http://localhost:8800/workers/modules/resources/dynamic-import-worker.js". import call expects exactly one argument.
5 CONSOLE MESSAGE: SyntaxError: Unexpected string literal "http://localhost:8800/workers/modules/resources/nested-dynamic-import-worker.js". import call expects exactly one argument.
6 CONSOLE MESSAGE: SyntaxError: Unexpected string literal "http://localhost:8800/workers/modules/resources/dynamic-import-and-then-static-import-worker.js". import call expects exactly one argument.
7 CONSOLE MESSAGE: SyntaxError: Unexpected string literal "http://localhost:8800/workers/modules/resources/eval-dynamic-import-worker.js". import call expects exactly one argument.
81
9 Harness Error (FAIL), message = SyntaxError: Unexpected string literal "http://localhost:8800/workers/modules/resources/dynamic-import-and-then-static-import-worker.js". import call expects exactly one argument.
10 
11 FAIL Static import. promise_test: Unhandled rejection with value: "SyntaxError: Unexpected string literal \"http://localhost:8800/workers/modules/resources/static-import-worker.js\". import call expects exactly one argument."
12 FAIL Nested static import. promise_test: Unhandled rejection with value: "SyntaxError: Unexpected string literal \"http://localhost:8800/workers/modules/resources/nested-static-import-worker.js\". import call expects exactly one argument."
13 FAIL Static import and then dynamic import. promise_test: Unhandled rejection with value: "SyntaxError: Unexpected string literal \"http://localhost:8800/workers/modules/resources/static-import-and-then-dynamic-import-worker.js\". import call expects exactly one argument."
14 FAIL Dynamic import. promise_test: Unhandled rejection with value: "SyntaxError: Unexpected string literal \"http://localhost:8800/workers/modules/resources/dynamic-import-worker.js\". import call expects exactly one argument."
15 FAIL Nested dynamic import. promise_test: Unhandled rejection with value: "SyntaxError: Unexpected string literal \"http://localhost:8800/workers/modules/resources/nested-dynamic-import-worker.js\". import call expects exactly one argument."
16 FAIL Dynamic import and then static import. promise_test: Unhandled rejection with value: "SyntaxError: Unexpected string literal \"http://localhost:8800/workers/modules/resources/dynamic-import-and-then-static-import-worker.js\". import call expects exactly one argument."
17 FAIL eval(import()). promise_test: Unhandled rejection with value: "SyntaxError: Unexpected string literal \"http://localhost:8800/workers/modules/resources/eval-dynamic-import-worker.js\". import call expects exactly one argument."
 2PASS Static import.
 3PASS Nested static import.
 4PASS Static import and then dynamic import.
 5PASS Dynamic import.
 6PASS Nested dynamic import.
 7PASS Dynamic import and then static import.
 8PASS eval(import()).
189

LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-csp-expected.txt

11CONSOLE MESSAGE: Unrecognized Content-Security-Policy directive 'worker-src'.
22
 3Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-on-load-script.js
34CONSOLE MESSAGE: Unrecognized Content-Security-Policy directive 'worker-src'.
45
 6Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-on-load-script.js
 7Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-on-load-script.js
 8Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-on-load-script.js
59CONSOLE MESSAGE: Unrecognized Content-Security-Policy directive 'worker-src'.
610
 11Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-on-load-script.js
712CONSOLE MESSAGE: Unrecognized Content-Security-Policy directive 'worker-src'.
813
 14Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-on-load-script.js
 15Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-on-load-script.js
 16Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-on-load-script.js
917CONSOLE MESSAGE: Unrecognized Content-Security-Policy directive 'worker-src'.
1018
 19Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-on-load-script.js
1120
1221PASS worker-src 'self' directive should disallow cross origin static import.
1322FAIL worker-src * directive should allow cross origin static import. assert_array_equals: expected property 0 to be "export-on-load-script.js" but got "ERROR" (expected array ["export-on-load-script.js"] got ["ERROR"])

LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-failure-expected.txt

1 CONSOLE MESSAGE: SyntaxError: Unexpected string literal './non-existent-script.js'. import call expects exactly one argument.
 1CONSOLE MESSAGE: Importing a module script failed.
22
3 FAIL importScripts() on module worker should throw an exception. assert_equals: expected "TypeError" but got "LOADED"
 3PASS importScripts() on module worker should throw an exception.
44PASS Worker construction for non-existent script should dispatch an ErrorEvent.
55PASS Static import for non-existent script should dispatch an ErrorEvent.
6 FAIL Dynamic import for non-existent script should throw an exception. assert_equals: expected "TypeError" but got "Error"
 6PASS Dynamic import for non-existent script should throw an exception.
77PASS Worker construction for an invalid URL should throw an exception.
88PASS Worker construction for a file URL should throw an exception.
99

LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-meta-expected.txt

1 CONSOLE MESSAGE: SyntaxError: import.meta is only valid inside modules.
21
3 Harness Error (FAIL), message = SyntaxError: import.meta is only valid inside modules.
4 
5 FAIL Test import.meta.url on the top-level module script. promise_test: Unhandled rejection with value: "SyntaxError: import.meta is only valid inside modules."
6 FAIL Test import.meta.url on the imported module script. assert_true: expected true got false
7 FAIL Test import.meta.url on the imported module script with a fragment. assert_true: expected true got false
 2PASS Test import.meta.url on the top-level module script.
 3PASS Test import.meta.url on the imported module script.
 4PASS Test import.meta.url on the imported module script with a fragment.
85

LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-meta.html

5353 worker.postMessage('./' + script_url + '#1');
5454 return new Promise(resolve => worker.onmessage = resolve);
5555 })
56  .then(msg_event => assert_true(msg_event.data.endsWith(script_url)));
 56 .then(msg_event => assert_true(msg_event.data.endsWith(script_url + '#1')));
5757}, 'Test import.meta.url on the imported module script with a fragment.');
5858
5959</script>

LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-referrer-expected.txt

1 
2 Harness Error (TIMEOUT), message = null
 1Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-referrer-checker.py
 2Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-referrer-checker.py
 3Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-referrer-checker.py
 4Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-referrer-checker.py
 5Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-referrer-checker.py
 6Blocked access to external URL https://www1.localhost:9443/workers/modules/resources/export-referrer-checker.py
37
48PASS Same-origin top-level module script loading with "no-referrer" referrer policy
59PASS Same-origin top-level module script loading with "origin" referrer policy
610PASS Same-origin top-level module script loading with "same-origin" referrer policy
7 FAIL Same-origin static import with "no-referrer" referrer policy. promise_test: Unhandled rejection with value: object "TypeError: Type error"
8 FAIL Same-origin static import with "origin" referrer policy. promise_test: Unhandled rejection with value: object "TypeError: Type error"
9 FAIL Same-origin static import with "same-origin" referrer policy. promise_test: Unhandled rejection with value: object "TypeError: Type error"
 11PASS Same-origin static import with "no-referrer" referrer policy.
 12PASS Same-origin static import with "origin" referrer policy.
 13PASS Same-origin static import with "same-origin" referrer policy.
1014FAIL Cross-origin static import with "no-referrer" referrer policy. promise_test: Unhandled rejection with value: object "TypeError: Type error"
1115FAIL Cross-origin static import with "origin" referrer policy. promise_test: Unhandled rejection with value: object "TypeError: Type error"
1216FAIL Cross-origin static import with "same-origin" referrer policy. promise_test: Unhandled rejection with value: object "TypeError: Type error"
13 TIMEOUT Same-origin dynamic import with "no-referrer" referrer policy. Test timed out
14 NOTRUN Same-origin dynamic import with "origin" referrer policy.
15 NOTRUN Same-origin dynamic import with "same-origin" referrer policy.
16 NOTRUN Cross-origin dynamic import with "no-referrer" referrer policy.
17 NOTRUN Cross-origin dynamic import with "origin" referrer policy.
18 NOTRUN Cross-origin dynamic import with "same-origin" referrer policy.
 17FAIL Same-origin dynamic import with "no-referrer" referrer policy. assert_equals: expected "" but got "http://localhost:8800/workers/modules/resources/dynamic-import-same-origin-referrer-checker-worker.js"
 18FAIL Same-origin dynamic import with "origin" referrer policy. assert_equals: expected "http://localhost:8800/" but got "http://localhost:8800/workers/modules/resources/dynamic-import-same-origin-referrer-checker-worker.js"
 19PASS Same-origin dynamic import with "same-origin" referrer policy.
 20FAIL Cross-origin dynamic import with "no-referrer" referrer policy. promise_test: Unhandled rejection with value: object "TypeError: Type error"
 21FAIL Cross-origin dynamic import with "origin" referrer policy. promise_test: Unhandled rejection with value: object "TypeError: Type error"
 22FAIL Cross-origin dynamic import with "same-origin" referrer policy. promise_test: Unhandled rejection with value: object "TypeError: Type error"
1923

LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import.any-expected.txt

1 CONSOLE MESSAGE: SyntaxError: Unexpected token '*'. import call expects exactly one argument.
2 CONSOLE MESSAGE: SyntaxError: Unexpected token '*'. import call expects exactly one argument.
3 CONSOLE MESSAGE: SyntaxError: Unexpected token '*'. import call expects exactly one argument.
41
5 Harness Error (FAIL), message = SyntaxError: Unexpected token '*'. import call expects exactly one argument.
6 
7 FAIL Static import. promise_test: Unhandled rejection with value: "SyntaxError: Unexpected token '*'. import call expects exactly one argument."
8 FAIL Nested static import. promise_test: Unhandled rejection with value: "SyntaxError: Unexpected token '*'. import call expects exactly one argument."
9 FAIL Static import and then dynamic import. promise_test: Unhandled rejection with value: "SyntaxError: Unexpected token '*'. import call expects exactly one argument."
10 FAIL Dynamic import. assert_array_equals: value is "Failed to do dynamic import: Error: Could not import the module './export-on-load-script.js'.", expected array
11 FAIL Nested dynamic import. assert_array_equals: value is "Failed to do dynamic import: Error: Could not import the module './export-on-dynamic-import-script.js'.", expected array
12 FAIL Dynamic import and then static import. assert_array_equals: value is "Failed to do dynamic import: Error: Could not import the module './export-on-static-import-script.js'.", expected array
13 FAIL eval(import()). assert_array_equals: value is "Failed to do dynamic import: Error: Could not import the module './export-on-load-script.js'.", expected array
 2PASS Static import.
 3PASS Nested static import.
 4PASS Static import and then dynamic import.
 5PASS Dynamic import.
 6PASS Nested dynamic import.
 7PASS Dynamic import and then static import.
 8PASS eval(import()).
149

LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-options-type-expected.txt

22PASS Test worker construction with the default worker type.
33PASS Test worker construction with the "classic" worker type.
44PASS Test worker construction with the "module" worker type.
5 FAIL Test worker construction with an empty worker type. assert_throws_js: Worker construction with an empty type should throw an exception function "() => {
6  new Worker('resources/post-message-on-load-worker.js', { type: '' });
7  }" did not throw
8 FAIL Test worker construction with an unknown worker type. assert_throws_js: Worker construction with an unknown type should throw an exception function "() => {
9  new Worker('resources/post-message-on-load-worker.js',
10  { type: 'unknown' });
11  }" did not throw
 5PASS Test worker construction with an empty worker type.
 6PASS Test worker construction with an unknown worker type.
127

LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-parse-error-failure-expected.txt

1 CONSOLE MESSAGE: SyntaxError: Unexpected token '*'. import call expects exactly one argument.
 1CONSOLE MESSAGE: SyntaxError: Unexpected token ';'
 2CONSOLE MESSAGE: SyntaxError: Unexpected token ';'
23
3 Harness Error (FAIL), message = Error: assert_implements: Static import must be supported on module dedicated worker to run this test. undefined
4 
5 NOTRUN Module worker construction for script with syntax error should dispatch an event named error.
6 NOTRUN Static import on module worker for script with syntax error should dispatch an event named error.
 4FAIL Module worker construction for script with syntax error should dispatch an event named error. assert_equals: expected function "function Event() {
 5 [native code]
 6}" but got function "function ErrorEvent() {
 7 [native code]
 8}"
 9FAIL Static import on module worker for script with syntax error should dispatch an event named error. assert_equals: expected function "function Event() {
 10 [native code]
 11}" but got function "function ErrorEvent() {
 12 [native code]
 13}"
714

LayoutTests/imported/w3c/web-platform-tests/workers/name-property-expected.txt

11CONSOLE MESSAGE: Unhandled Promise Rejection: ReferenceError: Can't find variable: SharedWorker
22
3 FAIL Test the name property of shared and dedicated workers via the name constructor option Can't find variable: SharedWorker
4 PASS Declaring name as an accidental global must not cause a harness error for DedicatedWorkerGlobalScope
 3Harness Error (FAIL), message = Unhandled rejection: Can't find variable: SharedWorker
 4
55PASS name property value for DedicatedWorkerGlobalScope
66PASS name property is replaceable for DedicatedWorkerGlobalScope
 7PASS Declaring name as an accidental global must not cause a harness error for DedicatedWorkerGlobalScope
78

LayoutTests/imported/w3c/web-platform-tests/worklets/audio-worklet-credentials.https-expected.txt

11CONSOLE MESSAGE: Origin https://localhost:9443 is not allowed by Access-Control-Allow-Origin.
22
3 FAIL Importing a same-origin script with the default WorkletOptions should send the credentials promise_test: Unhandled rejection with value: object "AbortError: Failed to fetch module, error: Response is not 2xx"
 3FAIL Importing a same-origin script with the default WorkletOptions should send the credentials promise_test: Unhandled rejection with value: object "AbortError: The operation was aborted."
44PASS Importing a remote-origin script with the default WorkletOptions should not send the credentials
5 FAIL Importing a same-origin script with credentials=omit should not send the credentials promise_test: Unhandled rejection with value: object "AbortError: Failed to fetch module, error: Response is not 2xx"
 5FAIL Importing a same-origin script with credentials=omit should not send the credentials promise_test: Unhandled rejection with value: object "AbortError: The operation was aborted."
66PASS Importing a remote-origin script with credentials=omit should not send the credentials
7 FAIL Importing a same-origin script with credentials=same-origin should send the credentials promise_test: Unhandled rejection with value: object "AbortError: Failed to fetch module, error: Response is not 2xx"
 7FAIL Importing a same-origin script with credentials=same-origin should send the credentials promise_test: Unhandled rejection with value: object "AbortError: The operation was aborted."
88PASS Importing a remote-origin script with credentials=same-origin should not send the credentials
9 FAIL Importing a same-origin script with credentials=include should send the credentials promise_test: Unhandled rejection with value: object "AbortError: Failed to fetch module, error: Response is not 2xx"
10 FAIL Importing a remote-origin script with credentials=include should send the credentials promise_test: Unhandled rejection with value: object "AbortError: Failed to fetch module, error: Origin https://localhost:9443 is not allowed by Access-Control-Allow-Origin."
 9FAIL Importing a same-origin script with credentials=include should send the credentials promise_test: Unhandled rejection with value: object "AbortError: The operation was aborted."
 10FAIL Importing a remote-origin script with credentials=include should send the credentials promise_test: Unhandled rejection with value: object "AbortError: Cross-origin script load denied by Cross-Origin Resource Sharing policy."
1111

LayoutTests/imported/w3c/web-platform-tests/worklets/audio-worklet-csp.https-expected.txt

 1Blocked access to external URL https://www1.localhost:9443/worklets/resources/empty-worklet-script-with-cors-header.js
 2Blocked access to external URL https://www1.localhost:9443/worklets/resources/empty-worklet-script-with-cors-header.js
 3Blocked access to external URL https://www1.localhost:9443/worklets/resources/empty-worklet-script-with-cors-header.js
 4Blocked access to external URL https://www1.localhost:9443/worklets/resources/empty-worklet-script-with-cors-header.js
 5Blocked access to external URL https://www1.localhost:9443/worklets/resources/empty-worklet-script-with-cors-header.js
 6Blocked access to external URL https://www1.localhost:9443/worklets/resources/empty-worklet-script-with-cors-header.js
17CONSOLE MESSAGE: Unrecognized Content-Security-Policy directive 'worker-src'.
28
39CONSOLE MESSAGE: Unrecognized Content-Security-Policy directive 'worker-src'.
410
 11Blocked access to external URL https://www1.localhost:9443/worklets/resources/empty-worklet-script-with-cors-header.js
512CONSOLE MESSAGE: Unrecognized Content-Security-Policy directive 'worker-src'.
613
714CONSOLE MESSAGE: Unrecognized Content-Security-Policy directive 'worker-src'.
815
916CONSOLE MESSAGE: Unrecognized Content-Security-Policy directive 'worker-src'.
1017
 18Blocked access to external URL https://www1.localhost:9443/worklets/resources/empty-worklet-script-with-cors-header.js
1119CONSOLE MESSAGE: [blocked] The page at https://localhost:9443/worklets/resources/addmodule-window.html was not allowed to display insecure content from http://localhost:8800/worklets/resources/empty-worklet-script-with-cors-header.js.
1220
1321CONSOLE MESSAGE: [blocked] The page at https://localhost:9443/worklets/resources/addmodule-window.html was not allowed to display insecure content from http://localhost:8800/worklets/resources/empty-worklet-script-with-cors-header.js.
1422
 23CONSOLE MESSAGE: [blocked] The page at https://localhost:9443/worklets/resources/addmodule-window.html was not allowed to display insecure content from http://localhost:9443/worklets/resources/empty-worklet-script-with-cors-header.js.
 24
 25CONSOLE MESSAGE: [blocked] The page at https://localhost:9443/worklets/resources/addmodule-window.html was not allowed to display insecure content from http://localhost:9443/worklets/resources/empty-worklet-script-with-cors-header.js.
 26
1527
1628FAIL A remote-origin worklet should be blocked by the script-src 'self' directive. assert_equals: expected "REJECTED" but got "RESOLVED"
17 FAIL A same-origin worklet importing a remote-origin script should be blocked by the script-src 'self' directive. assert_equals: expected "REJECTED" but got "RESOLVED"
 29PASS A same-origin worklet importing a remote-origin script should be blocked by the script-src 'self' directive.
1830FAIL A remote-origin worklet importing a remote-origin script should be blocked by the script-src 'self' directive. assert_equals: expected "REJECTED" but got "RESOLVED"
1931FAIL A remote-origin-redirected worklet should be blocked by the script-src 'self' directive. assert_equals: expected "REJECTED" but got "RESOLVED"
20 FAIL A same-origin worklet importing a remote-origin-redirected script should be blocked by the script-src 'self' directive. assert_equals: expected "REJECTED" but got "RESOLVED"
 32PASS A same-origin worklet importing a remote-origin-redirected script should be blocked by the script-src 'self' directive.
2133PASS A remote-origin worklet should not be blocked because the script-src directive specifying the origin allows it.
22 PASS A same-origin worklet importing a remote-origin script should not be blocked because the script-src directive specifying the origin allows it.
 34FAIL A same-origin worklet importing a remote-origin script should not be blocked because the script-src directive specifying the origin allows it. assert_equals: expected "RESOLVED" but got "REJECTED"
2335PASS A remote-origin worklet importing a remote-origin script should not be blocked because the script-src directive specifying the origin allows it.
2436PASS A remote-origin-redirected worklet should not be blocked because the script-src directive specifying the origin allows it.
25 PASS A same-origin worklet importing a remote-origin-redirected script should not be blocked because the script-src directive specifying the origin allows it.
 37FAIL A same-origin worklet importing a remote-origin-redirected script should not be blocked because the script-src directive specifying the origin allows it. assert_equals: expected "RESOLVED" but got "REJECTED"
2638PASS A remote-origin worklet should not be blocked because the script-src * directive allows it.
27 PASS A same-origin worklet importing a remote-origin script should not be blocked because the script-src * directive allows it.
 39FAIL A same-origin worklet importing a remote-origin script should not be blocked because the script-src * directive allows it. assert_equals: expected "RESOLVED" but got "REJECTED"
2840PASS A remote-origin worklet importing a remote-origin script should not be blocked because the script-src * directive allows it.
2941PASS A remote-origin-redirected worklet should not be blocked because the script-src * directive allows it.
30 PASS A same-origin worklet importing a remote-origin-redirected script should not be blocked because the script-src * directive allows it.
 42FAIL A same-origin worklet importing a remote-origin-redirected script should not be blocked because the script-src * directive allows it. assert_equals: expected "RESOLVED" but got "REJECTED"
3143PASS A remote-origin worklet should not be blocked by the worker-src directive because worklets obey the script-src directive.
32 PASS A same-origin worklet importing a remote-origin script should not be blocked by the worker-src directive because worklets obey the script-src directive.
 44FAIL A same-origin worklet importing a remote-origin script should not be blocked by the worker-src directive because worklets obey the script-src directive. assert_equals: expected "RESOLVED" but got "REJECTED"
3345PASS A remote-origin worklet importing a remote-origin script should not be blocked by the worker-src directive because worklets obey the script-src directive.
3446PASS A remote-origin-redirected worklet should not be blocked by the worker-src directive because worklets obey the script-src directive.
35 PASS A same-origin worklet importing a remote-origin-redirected script should not be blocked by the worker-src directive because worklets obey the script-src directive.
 47FAIL A same-origin worklet importing a remote-origin-redirected script should not be blocked by the worker-src directive because worklets obey the script-src directive. assert_equals: expected "RESOLVED" but got "REJECTED"
3648PASS An insecure-origin worklet should be blocked because of mixed contents.
3749PASS An insecure-origin-redirected worklet should be blocked because of mixed contents.
38 FAIL A same-origin worklet importing an insecure-origin script should be blocked because of mixed contents. assert_equals: expected "REJECTED" but got "RESOLVED"
39 FAIL A same-origin worklet importing an insecure-origin-redirected script should be blocked because of mixed contents. assert_equals: expected "REJECTED" but got "RESOLVED"
 50PASS A same-origin worklet importing an insecure-origin script should be blocked because of mixed contents.
 51PASS A same-origin worklet importing an insecure-origin-redirected script should be blocked because of mixed contents.
4052

LayoutTests/imported/w3c/web-platform-tests/worklets/audio-worklet-import.https-expected.txt

@@PASS Importing a cross origin resource with the Access-Control-Allow-Origin head
1616PASS Importing a cross origin resource without the Access-Control-Allow-Origin header should reject the given promise
1717PASS Importing a cross-origin-redirected resource with the Access-Control-Allow-Origin header should resolve the given promise
1818PASS Importing a cross-origin-redirected resource without the Access-Control-Allow-Origin header should reject the given promise
19 FAIL Importing a script that has a syntax error should reject the given promise. assert_unreached: Should have rejected: undefined Reached unreachable code
20 FAIL Importing a nested script that has a syntax error should reject the given promise. assert_unreached: Should have rejected: undefined Reached unreachable code
21 FAIL Importing a script that imports an invalid identifier should reject the given promise. assert_unreached: Should have rejected: undefined Reached unreachable code
 19FAIL Importing a script that has a syntax error should reject the given promise. promise_rejects_js: function "function () { throw e }" threw object "SyntaxError: Unexpected token ')'" ("SyntaxError") expected instance of function "function SyntaxError() {
 20 [native code]
 21}" ("SyntaxError")
 22FAIL Importing a nested script that has a syntax error should reject the given promise. promise_rejects_js: function "function () { throw e }" threw object "SyntaxError: Unexpected token ')'" ("SyntaxError") expected instance of function "function SyntaxError() {
 23 [native code]
 24}" ("SyntaxError")
 25FAIL Importing a script that imports an invalid identifier should reject the given promise. promise_rejects_js: function "function () { throw e }" threw object "AbortError: Module specifier, 'invalid-specifier.js' does not start with "/", "./", or "../". Referenced from blob:https://localhost:9443/d16c4e5f-addb-4bda-9ffa-f7fbfdf08924" ("AbortError") expected instance of function "function TypeError() {
 26 [native code]
 27}" ("TypeError")
2228

LayoutTests/imported/w3c/web-platform-tests/worklets/audio-worklet-referrer.https-expected.txt

 1Blocked access to external URL https://www1.localhost:9443/worklets/resources/referrer-checker.py?referrer_policy=no-referrer&expected_referrer=
 2Blocked access to external URL https://www1.localhost:9443/worklets/resources/referrer-checker.py?referrer_policy=origin&expected_referrer=https://localhost:9443/
 3CONSOLE MESSAGE: Origin https://localhost:9443 is not allowed by Access-Control-Allow-Origin.
 4Blocked access to external URL https://www1.localhost:9443/worklets/resources/referrer-checker.py?referrer_policy=same-origin&expected_referrer=
 5CONSOLE MESSAGE: Origin https://localhost:9443 is not allowed by Access-Control-Allow-Origin.
16
27PASS Importing a same-origin script from a page that has "no-referrer" referrer policy should not send referrer.
38PASS Importing a remote-origin script from a page that has "no-referrer" referrer policy should not send referrer.

@@PASS Importing a remote-origin script from a page that has "origin" referrer pol
611PASS Importing a same-origin script from a page that has "same-origin" referrer policy should send referrer.
712PASS Importing a remote-origin script from a page that has "same-origin" referrer policy should not send referrer.
813PASS Importing a same-origin script from a same-origin worklet script that has "no-referrer" referrer policy should not send referrer.
9 PASS Importing a remote-origin script from a same-origin worklet script that has "no-referrer" referrer policy should not send referrer.
 14FAIL Importing a remote-origin script from a same-origin worklet script that has "no-referrer" referrer policy should not send referrer. assert_equals: expected "RESOLVED" but got "Cross-origin script load denied by Cross-Origin Resource Sharing policy."
1015PASS Importing a same-origin script from a remote-origin worklet script that has "no-referrer" referrer policy should not send referrer.
1116PASS Importing a remote-origin script from a remote-origin worklet script that has "no-referrer" referrer policy should not send referrer.
1217PASS Importing a same-origin script from a same-origin worklet script that has "origin" referrer policy should send referrer.
13 PASS Importing a remote-origin script from a same-origin worklet script that has "origin" referrer policy should send referrer.
14 PASS Importing a same-origin script from a remote-origin worklet script that has "origin" referrer policy should send referrer.
15 PASS Importing a remote-origin script from a remote-origin worklet script that has "origin" referrer policy should send referrer.
16 PASS Importing a same-origin script from a same-origin worklet script that has "same-origin" referrer policy should send referrer.
17 PASS Importing a remote-origin script from a same-origin worklet script that has "same-origin" referrer policy should not send referrer.
18 PASS Importing a same-origin script from a remote-origin worklet script that has "same-origin" referrer policy should not send referrer.
19 PASS Importing a remote-origin script from a remote-origin worklet script that has "same-origin" referrer policy should send referrer.
 18FAIL Importing a remote-origin script from a same-origin worklet script that has "origin" referrer policy should send referrer. assert_equals: expected "RESOLVED" but got "Cross-origin script load denied by Cross-Origin Resource Sharing policy."
 19FAIL Importing a same-origin script from a remote-origin worklet script that has "origin" referrer policy should send referrer. assert_equals: expected "RESOLVED" but got "The operation was aborted."
 20FAIL Importing a remote-origin script from a remote-origin worklet script that has "origin" referrer policy should send referrer. assert_equals: expected "RESOLVED" but got "Cross-origin script load denied by Cross-Origin Resource Sharing policy."
 21FAIL Importing a same-origin script from a same-origin worklet script that has "same-origin" referrer policy should send referrer. assert_equals: expected "RESOLVED" but got "The operation was aborted."
 22FAIL Importing a remote-origin script from a same-origin worklet script that has "same-origin" referrer policy should not send referrer. assert_equals: expected "RESOLVED" but got "Cross-origin script load denied by Cross-Origin Resource Sharing policy."
 23FAIL Importing a same-origin script from a remote-origin worklet script that has "same-origin" referrer policy should not send referrer. assert_equals: expected "RESOLVED" but got "The operation was aborted."
 24FAIL Importing a remote-origin script from a remote-origin worklet script that has "same-origin" referrer policy should send referrer. assert_equals: expected "RESOLVED" but got "Cross-origin script load denied by Cross-Origin Resource Sharing policy."
2025

LayoutTests/imported/w3c/web-platform-tests/xhr/open-url-redirected-worker-origin-expected.txt

11Blocked access to external URL http://www2.localhost:8800/xhr/resources/inspect-headers.py?filter_name=origin&cors
22
3 FAIL Referer header assert_equals: expected "Referer: http://localhost:8800/xhr/resources/workerxhr-origin-referrer.js\n" but got "Referer: http://localhost:8800/xhr/resources/redirect.py?location=workerxhr-origin-referrer.js\n"
 3PASS Referer header
44FAIL Origin header assert_equals: expected "Origin: http://localhost:8800\n" but got ""
55PASS Request URL test
66