Source/WebCore/ChangeLog

 12021-02-10 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/JSDOMGlobalObject.cpp:
 20 (WebCore::scriptModuleLoader):
 21 (WebCore::JSDOMGlobalObject::moduleLoaderResolve):
 22 (WebCore::JSDOMGlobalObject::moduleLoaderFetch):
 23 (WebCore::JSDOMGlobalObject::moduleLoaderEvaluate):
 24 (WebCore::JSDOMGlobalObject::moduleLoaderImportModule):
 25 (WebCore::JSDOMGlobalObject::moduleLoaderCreateImportMetaProperties):
 26 * bindings/js/JSDOMGlobalObject.h:
 27 * bindings/js/JSDOMWindowBase.cpp:
 28 (WebCore::JSDOMWindowBase::moduleLoaderResolve): Deleted.
 29 (WebCore::JSDOMWindowBase::moduleLoaderFetch): Deleted.
 30 (WebCore::JSDOMWindowBase::moduleLoaderEvaluate): Deleted.
 31 (WebCore::JSDOMWindowBase::moduleLoaderImportModule): Deleted.
 32 (WebCore::JSDOMWindowBase::moduleLoaderCreateImportMetaProperties): Deleted.
 33 * bindings/js/JSDOMWindowBase.h:
 34 * bindings/js/JSWorkerGlobalScopeBase.cpp:
 35 * bindings/js/JSWorkletGlobalScopeBase.cpp:
 36 * bindings/js/ModuleScriptLoader.h: Copied from Source/WebCore/bindings/js/CachedModuleScriptLoader.h.
 37 (WebCore::ModuleScriptLoader::clearClient):
 38 (WebCore::ModuleScriptLoader::scriptFetcher):
 39 (WebCore::ModuleScriptLoader::parameters):
 40 (WebCore::ModuleScriptLoader::ModuleScriptLoader):
 41 * bindings/js/ModuleScriptLoaderClient.h: Renamed from Source/WebCore/bindings/js/CachedModuleScriptLoaderClient.h.
 42 * bindings/js/ScriptModuleLoader.cpp:
 43 (WebCore::ScriptModuleLoader::ScriptModuleLoader):
 44 (WebCore::resolveModuleSpecifier):
 45 (WebCore::ScriptModuleLoader::resolve):
 46 (WebCore::ScriptModuleLoader::fetch):
 47 (WebCore::ScriptModuleLoader::moduleURL):
 48 (WebCore::ScriptModuleLoader::responseURLFromRequestURL):
 49 (WebCore::ScriptModuleLoader::evaluate):
 50 (WebCore::ScriptModuleLoader::importModule):
 51 (WebCore::ScriptModuleLoader::notifyFinished):
 52 * bindings/js/ScriptModuleLoader.h:
 53 * bindings/js/WorkerModuleScriptLoader.cpp: Added.
 54 (WebCore::WorkerModuleScriptLoader::create):
 55 (WebCore::WorkerModuleScriptLoader::WorkerModuleScriptLoader):
 56 (WebCore::WorkerModuleScriptLoader::~WorkerModuleScriptLoader):
 57 (WebCore::WorkerModuleScriptLoader::load):
 58 (WebCore::WorkerModuleScriptLoader::notifyFinished):
 59 * bindings/js/WorkerModuleScriptLoader.h: Copied from Source/WebCore/workers/WorkerType.h.
 60 * dom/Document.cpp:
 61 * dom/LoadableModuleScript.cpp:
 62 (WebCore::LoadableModuleScript::load): Deleted.
 63 * dom/LoadableModuleScript.h:
 64 * dom/ScriptElement.cpp:
 65 (WebCore::ScriptElement::requestModuleScript):
 66 * loader/ThreadableLoader.cpp:
 67 (WebCore::ThreadableLoader::create):
 68 * loader/ThreadableLoader.h:
 69 (WebCore::ThreadableLoader::create):
 70 * workers/Worker.cpp:
 71 (WebCore::Worker::Worker):
 72 (WebCore::Worker::create):
 73 (WebCore::Worker::notifyFinished):
 74 * workers/Worker.h:
 75 * workers/Worker.idl:
 76 * workers/WorkerGlobalScope.cpp:
 77 (WebCore::WorkerGlobalScope::WorkerGlobalScope):
 78 (WebCore::WorkerGlobalScope::importScripts):
 79 * workers/WorkerGlobalScope.h:
 80 * workers/WorkerGlobalScopeProxy.h:
 81 * workers/WorkerMessagingProxy.cpp:
 82 (WebCore::WorkerMessagingProxy::startWorkerGlobalScope):
 83 * workers/WorkerMessagingProxy.h:
 84 * workers/WorkerOrWorkletGlobalScope.cpp:
 85 (WebCore::WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope):
 86 * workers/WorkerOrWorkletGlobalScope.h:
 87 (WebCore::WorkerOrWorkletGlobalScope::moduleLoader):
 88 * workers/WorkerOrWorkletScriptController.cpp:
 89 (WebCore::WorkerOrWorkletScriptController::evaluate):
 90 (WebCore::jsValueToModuleKey):
 91 (WebCore::WorkerOrWorkletScriptController::evaluateModule):
 92 (WebCore::WorkerOrWorkletScriptController::loadModuleSynchronously):
 93 (WebCore::WorkerOrWorkletScriptController::linkAndEvaluateModule):
 94 * workers/WorkerOrWorkletScriptController.h:
 95 * workers/WorkerScriptLoader.cpp:
 96 (WebCore::WorkerScriptLoader::loadAsynchronously):
 97 * workers/WorkerScriptLoader.h:
 98 * workers/WorkerThread.cpp:
 99 (WebCore::WorkerParameters::isolatedCopy const):
 100 (WebCore::WorkerThread::evaluateScriptIfNecessary):
 101 * workers/WorkerThread.h:
 102 * workers/WorkerType.h:
 103 * workers/service/ServiceWorkerContainer.h:
 104 * workers/service/ServiceWorkerJob.cpp:
 105 (WebCore::ServiceWorkerJob::fetchScriptWithContext):
 106 * workers/service/ServiceWorkerRegistrationOptions.h:
 107 * workers/service/context/ServiceWorkerThread.cpp:
 108 (WebCore::ServiceWorkerThread::ServiceWorkerThread):
 109 * workers/service/server/SWServerWorker.h:
 110 * worklets/WorkletGlobalScope.cpp:
 111 (WebCore::WorkletGlobalScope::processNextScriptFetchJobIfNeeded):
 112
11132021-02-10 Alexey Proskuryakov <ap@apple.com>
2114
3115 Do not differentiate between Release and Production via ENABLE_DEVELOPER_MODE

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

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 E35188B425D387CF00A77AF3 /* ModuleScriptLoaderClient.h in Headers */ = {isa = PBXBuildFile; fileRef = E35188B325D387CF00A77AF3 /* ModuleScriptLoaderClient.h */; settings = {ATTRIBUTES = (Private, ); }; };
50795080 E3565B7B1DC2D6C900217DBD /* JSEventCustom.h in Headers */ = {isa = PBXBuildFile; fileRef = E34EE49F1DC2D57500EAA9D3 /* JSEventCustom.h */; settings = {ATTRIBUTES = (Private, ); }; };
50805081 E35802B61DC8435D00A9773C /* DOMJITIDLTypeFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = E35802B51DC8435800A9773C /* DOMJITIDLTypeFilter.h */; settings = {ATTRIBUTES = (Private, ); }; };
50815082 E3582C282527F66900D1B790 /* WebCoreJITOperations.h in Headers */ = {isa = PBXBuildFile; fileRef = E3582C262527F66800D1B790 /* WebCoreJITOperations.h */; settings = {ATTRIBUTES = (Private, ); }; };
50825083 E35B907F23F60A50000011FF /* LocalizedDeviceModel.h in Headers */ = {isa = PBXBuildFile; fileRef = E35B907C23F60677000011FF /* LocalizedDeviceModel.h */; settings = {ATTRIBUTES = (Private, ); }; };
 5084 E364321C25D37A6700F90E2A /* ModuleScriptLoader.h in Headers */ = {isa = PBXBuildFile; fileRef = E364321A25D37A6600F90E2A /* ModuleScriptLoader.h */; settings = {ATTRIBUTES = (Private, ); }; };
50835085 E377FE4D1DADE16500CDD025 /* NodeConstants.h in Headers */ = {isa = PBXBuildFile; fileRef = E3D049931DADC04500718F3C /* NodeConstants.h */; settings = {ATTRIBUTES = (Private, ); }; };
50845086 E37C86501EB63E3F0087C6CA /* JSDOMPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = E37C864F1EB63E2D0087C6CA /* JSDOMPromise.h */; settings = {ATTRIBUTES = (Private, ); }; };
50855087 E39628BF2395728F00658ECD /* DeviceOrientationUpdateProvider.h in Headers */ = {isa = PBXBuildFile; fileRef = E39628BD2395728E00658ECD /* DeviceOrientationUpdateProvider.h */; settings = {ATTRIBUTES = (Private, ); }; };

1620216204 E30592661E27A3C600D57C98 /* CachedScriptFetcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CachedScriptFetcher.h; sourceTree = "<group>"; };
1620316205 E307DEC61D81E44800141CAF /* CachedModuleScriptLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CachedModuleScriptLoader.cpp; sourceTree = "<group>"; };
1620416206 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>"; };
1620616207 E307DED21D81E4ED00141CAF /* LoadableModuleScript.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LoadableModuleScript.cpp; sourceTree = "<group>"; };
1620716208 E307DED31D81E4ED00141CAF /* LoadableModuleScript.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LoadableModuleScript.h; sourceTree = "<group>"; };
1620816209 E3150EA51DA7218D00194012 /* DOMJITHelpers.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DOMJITHelpers.h; sourceTree = "<group>"; };

1621516216 E329276322543F5900308A9A /* TypedOMCSSUnitValue.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = TypedOMCSSUnitValue.cpp; sourceTree = "<group>"; };
1621616217 E329276622543FDE00308A9A /* DOMRectReadOnly.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = DOMRectReadOnly.cpp; sourceTree = "<group>"; };
1621716218 E334825E1DC93AA0009C9544 /* DOMJITAbstractHeapRepository.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DOMJITAbstractHeapRepository.h; path = DerivedSources/WebCore/DOMJITAbstractHeapRepository.h; sourceTree = BUILT_PRODUCTS_DIR; };
 16219 E3432DE025D377E20058E612 /* WorkerModuleScriptLoader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WorkerModuleScriptLoader.h; sourceTree = "<group>"; };
 16220 E3432DE325D377E30058E612 /* WorkerModuleScriptLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WorkerModuleScriptLoader.cpp; sourceTree = "<group>"; };
1621816221 E34EE49F1DC2D57500EAA9D3 /* JSEventCustom.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSEventCustom.h; sourceTree = "<group>"; };
 16222 E35188B325D387CF00A77AF3 /* ModuleScriptLoaderClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ModuleScriptLoaderClient.h; sourceTree = "<group>"; };
1621916223 E35802B51DC8435800A9773C /* DOMJITIDLTypeFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DOMJITIDLTypeFilter.h; sourceTree = "<group>"; };
1622016224 E3582C242527F66800D1B790 /* WebCoreJITOperations.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WebCoreJITOperations.cpp; sourceTree = "<group>"; };
1622116225 E3582C262527F66800D1B790 /* WebCoreJITOperations.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WebCoreJITOperations.h; sourceTree = "<group>"; };
1622216226 E35B907C23F60677000011FF /* LocalizedDeviceModel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LocalizedDeviceModel.h; sourceTree = "<group>"; };
1622316227 E35B907E23F60677000011FF /* LocalizedDeviceModel.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = LocalizedDeviceModel.mm; sourceTree = "<group>"; };
 16228 E364321A25D37A6600F90E2A /* ModuleScriptLoader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ModuleScriptLoader.h; sourceTree = "<group>"; };
1622416229 E37C864F1EB63E2D0087C6CA /* JSDOMPromise.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSDOMPromise.h; sourceTree = "<group>"; };
1622516230 E38838941BAD145F00D62EE3 /* ScriptModuleLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScriptModuleLoader.cpp; sourceTree = "<group>"; };
1622616231 E38838951BAD145F00D62EE3 /* ScriptModuleLoader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ScriptModuleLoader.h; sourceTree = "<group>"; };

2702127026 2DFA488E1DB541C200362B99 /* BufferSource.h */,
2702227027 E307DEC61D81E44800141CAF /* CachedModuleScriptLoader.cpp */,
2702327028 E307DEC71D81E44800141CAF /* CachedModuleScriptLoader.h */,
27024  E307DEC81D81E44800141CAF /* CachedModuleScriptLoaderClient.h */,
2702527029 E30592651E27A3C600D57C98 /* CachedScriptFetcher.cpp */,
2702627030 E30592661E27A3C600D57C98 /* CachedScriptFetcher.h */,
2702727031 BCD533630ED6848900887468 /* CachedScriptSourceProvider.h */,

2709527099 4BDEA32D218034050052DFCD /* JSWorkletGlobalScopeBase.cpp */,
2709627100 4BDEA32B218033EB0052DFCD /* JSWorkletGlobalScopeBase.h */,
2709727101 709A01FD1E3D0BCC006B0D4C /* ModuleFetchFailureKind.h */,
 27102 E364321A25D37A6600F90E2A /* ModuleScriptLoader.h */,
 27103 E35188B325D387CF00A77AF3 /* ModuleScriptLoaderClient.h */,
2709827104 41B459ED1F55EBC70000F6FD /* ReadableStream.cpp */,
2709927105 41B459DA1F4CADB90000F6FD /* ReadableStream.h */,
2710027106 418C395E1C8F0AAB0051C8A3 /* ReadableStreamDefaultController.cpp */,

2712627132 0F099D0717B968A100FF84B9 /* WebCoreTypedArrayController.h */,
2712727133 463521AC2081090E00C28922 /* WindowProxy.cpp */,
2712827134 463521AA2081090B00C28922 /* WindowProxy.h */,
 27135 E3432DE325D377E30058E612 /* WorkerModuleScriptLoader.cpp */,
 27136 E3432DE025D377E20058E612 /* WorkerModuleScriptLoader.h */,
2712927137 41418A0325643E1200363417 /* WritableStream.cpp */,
2713027138 41418A0425643E1300363417 /* WritableStream.h */,
2713127139 );

3139931407 BCB16C1C0979C3BD00467741 /* CachedImage.h in Headers */,
3140031408 319FBD5F15D2F464009640A6 /* CachedImageClient.h in Headers */,
3140131409 E307DED01D81E4C700141CAF /* CachedModuleScriptLoader.h in Headers */,
31402  E307DED11D81E4CB00141CAF /* CachedModuleScriptLoaderClient.h in Headers */,
3140331410 510184690B08602A004A825F /* CachedPage.h in Headers */,
3140431411 D0EDA775143E303C0028E383 /* CachedRawResource.h in Headers */,
3140531412 E1B533491717DEE300F205F9 /* CachedRawResourceClient.h in Headers */,

3387433881 C6D74AD509AA282E000B0A52 /* ModifySelectionListLevel.h in Headers */,
3387533882 709A01FE1E3D0BDD006B0D4C /* ModuleFetchFailureKind.h in Headers */,
3387633883 E3201C1A1F8E82130076A032 /* ModuleFetchParameters.h in Headers */,
 33884 E364321C25D37A6700F90E2A /* ModuleScriptLoader.h in Headers */,
 33885 E35188B425D387CF00A77AF3 /* ModuleScriptLoaderClient.h in Headers */,
3387733886 F55B3DC61251F12D003EF269 /* MonthInputType.h in Headers */,
3387833887 E39628C12395743100658ECD /* MotionManagerClient.h in Headers */,
3387933888 85031B460A44EFC700F992E0 /* MouseEvent.h in Headers */,

3552635535 18F831B80FD48C7800D8C56B /* WorkerLoaderProxy.h in Headers */,
3552735536 2E43464D0F546A8200B0F1BA /* WorkerLocation.h in Headers */,
3552835537 2E4346500F546A8200B0F1BA /* WorkerMessagingProxy.h in Headers */,
 35538 E3432DE425D377E30058E612 /* WorkerModuleScriptLoader.h in Headers */,
3552935539 E1271A0B0EEEC77A00F61213 /* WorkerNavigator.h in Headers */,
3553035540 A5CB05251FB51F3A00089B97 /* WorkerNetworkAgent.h in Headers */,
3553135541 2E4346510F546A8200B0F1BA /* WorkerObjectProxy.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 { };
6866 m_cachedScript = m_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 "ModuleScriptLoader.h"
3031#include <wtf/Ref.h>
3132#include <wtf/RefCounted.h>
3233#include <wtf/RefPtr.h>

3435
3536namespace WebCore {
3637
37 class CachedModuleScriptLoaderClient;
 38class ModuleScriptLoaderClient;
3839class CachedScript;
3940class CachedScriptFetcher;
4041class DeferredPromise;

@@class 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  }
6355
6456private:
65  CachedModuleScriptLoader(CachedModuleScriptLoaderClient&, DeferredPromise&, CachedScriptFetcher&, RefPtr<ModuleFetchParameters>&&);
 57 CachedModuleScriptLoader(ModuleScriptLoaderClient&, DeferredPromise&, CachedScriptFetcher&, RefPtr<ModuleFetchParameters>&&);
6658
6759 void notifyFinished(CachedResource&, const NetworkLoadMetrics&) final;
6860
69  CachedModuleScriptLoaderClient* m_client { nullptr };
70  RefPtr<DeferredPromise> m_promise;
71  Ref<CachedScriptFetcher> m_scriptFetcher;
72  RefPtr<ModuleFetchParameters> m_parameters;
7361 CachedResourceHandle<CachedScript> m_cachedScript;
7462 URL m_sourceURL;
7563};

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/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/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 "CachedScriptFetcher.h"
 29#include "JSDOMPromiseDeferred.h"
 30#include "ModuleFetchParameters.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 CachedScriptFetcher& scriptFetcher() { return m_scriptFetcher.get(); }
 48 ModuleFetchParameters* parameters() { return m_parameters.get(); }
 49
 50protected:
 51 ModuleScriptLoader(ModuleScriptLoaderClient& client, DeferredPromise& promise, CachedScriptFetcher& 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<CachedScriptFetcher> 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"
4444#include <JavaScriptCore/Completion.h>
4545#include <JavaScriptCore/JSInternalPromise.h>
4646#include <JavaScriptCore/JSModuleRecord.h>

5252
5353namespace WebCore {
5454
55 ScriptModuleLoader::ScriptModuleLoader(Document& document)
56  : m_document(document)
 55ScriptModuleLoader::ScriptModuleLoader(ScriptExecutionContext& context, OwnerType ownerType)
 56 : m_context(context)
 57 , m_ownerType(ownerType)
5758{
5859}
5960

@@static bool isRootModule(JSC::JSValue importerModuleKey)
6869 return importerModuleKey.isSymbol() || importerModuleKey.isUndefined();
6970}
7071
71 static Expected<URL, String> resolveModuleSpecifier(Document& document, const String& specifier, const URL& baseURL)
 72static Expected<URL, String> resolveModuleSpecifier(ScriptExecutionContext& context, ScriptModuleLoader::OwnerType ownerType, const String& specifier, const URL& baseURL)
7273{
7374 // https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier
7475

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

@@JSC::Identifier ScriptModuleLoader::resolve(JSC::JSGlobalObject* jsGlobalObject,
107113 URL baseURL = responseURLFromRequestURL(*jsGlobalObject, importerModuleKey);
108114 RETURN_IF_EXCEPTION(scope, { });
109115
110  auto result = resolveModuleSpecifier(m_document, specifier, baseURL);
 116 auto result = resolveModuleSpecifier(m_context, m_ownerType, specifier, baseURL);
111117 if (!result) {
112118 JSC::throwTypeError(jsGlobalObject, scope, result.error());
113119 return { };

@@JSC::JSInternalPromise* ScriptModuleLoader::fetch(JSC::JSGlobalObject* jsGlobalO
161167 if (auto* scriptFetchParameters = JSC::jsDynamicCast<JSC::JSScriptFetchParameters*>(vm, parameters))
162168 topLevelFetchParameters = static_cast<ModuleFetchParameters*>(&scriptFetchParameters->parameters());
163169
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;
 170 if (m_ownerType == OwnerType::Document) {
 171 auto loader = CachedModuleScriptLoader::create(*this, deferred.get(), *static_cast<CachedScriptFetcher*>(JSC::jsCast<JSC::JSScriptFetcher*>(scriptFetcher)->fetcher()), WTFMove(topLevelFetchParameters));
 172 m_loaders.add(loader.copyRef());
 173 if (!loader->load(downcast<Document>(m_context), WTFMove(completedURL))) {
 174 loader->clearClient();
 175 m_loaders.remove(WTFMove(loader));
 176 rejectToPropagateNetworkError(deferred.get(), ModuleFetchFailureKind::WasErrored, "Importing a module script failed."_s);
 177 return jsPromise;
 178 }
 179 } else {
 180 auto loader = WorkerModuleScriptLoader::create(*this, deferred.get(), *static_cast<CachedScriptFetcher*>(JSC::jsCast<JSC::JSScriptFetcher*>(scriptFetcher)->fetcher()), WTFMove(topLevelFetchParameters));
 181 m_loaders.add(loader.copyRef());
 182 loader->load(m_context, WTFMove(completedURL));
171183 }
172184
173185 return jsPromise;

@@JSC::JSInternalPromise* ScriptModuleLoader::fetch(JSC::JSGlobalObject* jsGlobalO
176188URL ScriptModuleLoader::moduleURL(JSC::JSGlobalObject& jsGlobalObject, JSC::JSValue moduleKeyValue)
177189{
178190 if (moduleKeyValue.isSymbol())
179  return m_document.url();
 191 return m_context.url();
180192
181193 ASSERT(moduleKeyValue.isString());
182194 return URL(URL(), asString(moduleKeyValue)->value(&jsGlobalObject));

@@URL ScriptModuleLoader::responseURLFromRequestURL(JSC::JSGlobalObject& jsGlobalO
187199 JSC::VM& vm = jsGlobalObject.vm();
188200 auto scope = DECLARE_THROW_SCOPE(vm);
189201
190  if (isRootModule(moduleKeyValue))
191  return m_document.baseURL();
 202 if (isRootModule(moduleKeyValue)) {
 203 if (m_ownerType == OwnerType::Document)
 204 return downcast<Document>(m_context).baseURL();
 205 return m_context.url();
 206 }
192207
193208 ASSERT(!isRootModule(moduleKeyValue));
194209 ASSERT(moduleKeyValue.isString());

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

@@JSC::JSInternalPromise* ScriptModuleLoader::importModule(JSC::JSGlobalObject* js
248269 URL baseURL;
249270 RefPtr<JSC::ScriptFetcher> scriptFetcher;
250271 if (sourceOrigin.isNull()) {
251  baseURL = m_document.baseURL();
252  scriptFetcher = CachedScriptFetcher::create(m_document.charset());
 272 String charset;
 273 if (m_ownerType == OwnerType::Document) {
 274 baseURL = downcast<Document>(m_context).baseURL();
 275 charset = downcast<Document>(m_context).charset();
 276 } else {
 277 baseURL = m_context.url();
 278 charset = "utf-8"_s;
 279 }
 280 scriptFetcher = CachedScriptFetcher::create(WTFMove(charset));
253281 } else {
254282 baseURL = URL(URL(), sourceOrigin.string());
255283 if (!baseURL.isValid())
256284 return rejectPromise(globalObject, TypeError, "Importer module key is not a Symbol or a String."_s);
257285
 286 String charset;
 287 if (m_ownerType == OwnerType::Document)
 288 charset = downcast<Document>(m_context).charset();
 289 else
 290 charset = "utf-8"_s;
 291
258292 if (sourceOrigin.fetcher())
259293 scriptFetcher = sourceOrigin.fetcher();
260294 else
261  scriptFetcher = CachedScriptFetcher::create(m_document.charset());
 295 scriptFetcher = CachedScriptFetcher::create(WTFMove(charset));
262296 }
263297 ASSERT(baseURL.isValid());
264298 ASSERT(scriptFetcher);
265299
266300 auto specifier = moduleName->value(jsGlobalObject);
267  auto result = resolveModuleSpecifier(m_document, specifier, baseURL);
 301 auto result = resolveModuleSpecifier(m_context, m_ownerType, specifier, baseURL);
268302 if (!result)
269303 return rejectPromise(globalObject, TypeError, result.error());
270304

@@JSC::JSObject* ScriptModuleLoader::createImportMetaProperties(JSC::JSGlobalObjec
288322 return metaProperties;
289323}
290324
291 void ScriptModuleLoader::notifyFinished(CachedModuleScriptLoader& loader, RefPtr<DeferredPromise> promise)
 325void ScriptModuleLoader::notifyFinished(ModuleScriptLoader& moduleScriptLoader, URL&& sourceURL, Ref<DeferredPromise> promise)
292326{
293327 // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
294328
295  URL sourceURL = loader.sourceURL();
296  if (!m_loaders.remove(&loader))
 329 if (!m_loaders.remove(&moduleScriptLoader))
297330 return;
298  loader.clearClient();
 331 moduleScriptLoader.clearClient();
299332
300  auto& cachedScript = *loader.cachedScript();
 333 if (m_ownerType == OwnerType::Document) {
 334 auto& loader = static_cast<CachedModuleScriptLoader&>(moduleScriptLoader);
 335 auto& cachedScript = *loader.cachedScript();
301336
302  if (cachedScript.resourceError().isAccessControl()) {
303  promise->reject(TypeError, "Cross-origin script load denied by Cross-Origin Resource Sharing policy."_s);
304  return;
305  }
 337 if (cachedScript.resourceError().isAccessControl()) {
 338 promise->reject(TypeError, "Cross-origin script load denied by Cross-Origin Resource Sharing policy."_s);
 339 return;
 340 }
306341
307  if (cachedScript.errorOccurred()) {
308  rejectToPropagateNetworkError(*promise, ModuleFetchFailureKind::WasErrored, "Importing a module script failed."_s);
309  return;
310  }
 342 if (cachedScript.errorOccurred()) {
 343 rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasErrored, "Importing a module script failed."_s);
 344 return;
 345 }
311346
312  if (cachedScript.wasCanceled()) {
313  rejectToPropagateNetworkError(*promise, ModuleFetchFailureKind::WasCanceled, "Importing a module script is canceled."_s);
314  return;
315  }
 347 if (cachedScript.wasCanceled()) {
 348 rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasCanceled, "Importing a module script is canceled."_s);
 349 return;
 350 }
316351
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  }
 352 if (!MIMETypeRegistry::isSupportedJavaScriptMIMEType(cachedScript.response().mimeType())) {
 353 // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
 354 // The result of extracting a MIME type from response's header list (ignoring parameters) is not a JavaScript MIME type.
 355 // 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.
 356 promise->reject(TypeError, makeString("'", cachedScript.response().mimeType(), "' is not a valid JavaScript MIME type."));
 357 return;
 358 }
324359
325  if (auto* parameters = loader.parameters()) {
326  if (!matchIntegrityMetadata(cachedScript, parameters->integrity())) {
327  promise->reject(TypeError, makeString("Cannot load script ", integrityMismatchDescription(cachedScript, parameters->integrity())));
 360 if (auto* parameters = loader.parameters()) {
 361 if (!matchIntegrityMetadata(cachedScript, parameters->integrity())) {
 362 promise->reject(TypeError, makeString("Cannot load script ", integrityMismatchDescription(cachedScript, parameters->integrity())));
 363 return;
 364 }
 365 }
 366
 367 URL responseURL = cachedScript.response().url();
 368 // 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.
 369 // FIXME: We should track fragments through redirections.
 370 // https://bugs.webkit.org/show_bug.cgi?id=158420
 371 // https://bugs.webkit.org/show_bug.cgi?id=210490
 372 if (!cachedScript.hasRedirections() && cachedScript.response().source() != ResourceResponse::Source::ServiceWorker) {
 373 if (sourceURL.hasFragmentIdentifier())
 374 responseURL.setFragmentIdentifier(sourceURL.fragmentIdentifier());
 375 }
 376
 377 m_requestURLToResponseURLMap.add(sourceURL.string(), WTFMove(responseURL));
 378 promise->resolveWithCallback([&] (JSDOMGlobalObject& jsGlobalObject) {
 379 return JSC::JSSourceCode::create(jsGlobalObject.vm(),
 380 JSC::SourceCode { ScriptSourceCode { &cachedScript, JSC::SourceProviderSourceType::Module, loader.scriptFetcher() }.jsSourceCode() });
 381 });
 382 } else {
 383 auto& loader = static_cast<WorkerModuleScriptLoader&>(moduleScriptLoader);
 384 auto& workerScriptLoader = loader.scriptLoader();
 385
 386 if (workerScriptLoader.failed()) {
 387 if (workerScriptLoader.error().isAccessControl()) {
 388 promise->reject(TypeError, "Cross-origin script load denied by Cross-Origin Resource Sharing policy."_s);
 389 return;
 390 }
 391
 392 if (workerScriptLoader.error().isCancellation()) {
 393 rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasCanceled, "Importing a module script is canceled."_s);
 394 return;
 395 }
 396
 397 rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasErrored, "Importing a module script failed."_s);
328398 return;
329399 }
330  }
331400
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  }
 401 if (!MIMETypeRegistry::isSupportedJavaScriptMIMEType(workerScriptLoader.responseMIMEType())) {
 402 // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
 403 // The result of extracting a MIME type from response's header list (ignoring parameters) is not a JavaScript MIME type.
 404 // 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.
 405 promise->reject(TypeError, makeString("'", workerScriptLoader.responseMIMEType(), "' is not a valid JavaScript MIME type."));
 406 return;
 407 }
341408
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  });
 409 URL responseURL = workerScriptLoader.responseURL();
 410
 411 m_requestURLToResponseURLMap.add(sourceURL.string(), responseURL);
 412 promise->resolveWithCallback([&] (JSDOMGlobalObject& jsGlobalObject) {
 413 return JSC::JSSourceCode::create(jsGlobalObject.vm(),
 414 JSC::SourceCode { ScriptSourceCode { workerScriptLoader.script(), WTFMove(responseURL), { }, JSC::SourceProviderSourceType::Module, loader.scriptFetcher() }.jsSourceCode() });
 415 });
 416 }
347417}
348418
349419}

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/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 "WorkerScriptLoader.h"
 40
 41namespace WebCore {
 42
 43Ref<WorkerModuleScriptLoader> WorkerModuleScriptLoader::create(ModuleScriptLoaderClient& client, DeferredPromise& promise, CachedScriptFetcher& scriptFetcher, RefPtr<ModuleFetchParameters>&& parameters)
 44{
 45 return adoptRef(*new WorkerModuleScriptLoader(client, promise, scriptFetcher, WTFMove(parameters)));
 46}
 47
 48WorkerModuleScriptLoader::WorkerModuleScriptLoader(ModuleScriptLoaderClient& client, DeferredPromise& promise, CachedScriptFetcher& scriptFetcher, RefPtr<ModuleFetchParameters>&& parameters)
 49 : ModuleScriptLoader(client, promise, scriptFetcher, WTFMove(parameters))
 50 , m_scriptLoader(WorkerScriptLoader::create())
 51{
 52}
 53
 54WorkerModuleScriptLoader::~WorkerModuleScriptLoader()
 55{
 56 m_scriptLoader->cancel();
 57}
 58
 59bool WorkerModuleScriptLoader::load(ScriptExecutionContext& context, URL&& sourceURL)
 60{
 61 m_sourceURL = WTFMove(sourceURL);
 62
 63 ResourceRequest request { m_sourceURL };
 64
 65 FetchOptions fetchOptions;
 66 fetchOptions.mode = FetchOptions::Mode::Cors;
 67 fetchOptions.cache = FetchOptions::Cache::Default;
 68 fetchOptions.redirect = FetchOptions::Redirect::Follow;
 69 // FIXME: Propagate credentials.
 70 // fetchOptions.credentials = scriptFetchJob.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&, CachedScriptFetcher&, 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&, CachedScriptFetcher&, 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/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;
116120 fetchOptions.cache = FetchOptions::Cache::Default;
117121 fetchOptions.redirect = FetchOptions::Redirect::Follow;
118122 fetchOptions.destination = FetchOptions::Destination::Worker;
119  worker->m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, worker);
 123 worker->m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, worker.get(), WorkerRunLoop::defaultMode());
 124
120125 return worker;
121126}
122127

@@void Worker::notifyFinished()
215220 ReferrerPolicy referrerPolicy = ReferrerPolicy::EmptyString;
216221 if (auto policy = parseReferrerPolicy(m_scriptLoader->referrerPolicy(), ReferrerPolicySource::HTTPHeader))
217222 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);
 223 m_contextProxy.startWorkerGlobalScope(m_scriptLoader->responseURL(), m_name, context->userAgent(m_scriptLoader->responseURL()), isOnline, m_scriptLoader->script(), contentSecurityPolicyResponseHeaders, m_shouldBypassMainWorldContentSecurityPolicy, m_workerCreationTime, referrerPolicy, m_type, m_credentials, m_runtimeFlags);
219224 InspectorInstrumentation::scriptImported(*context, m_scriptLoader->identifier(), m_scriptLoader->script());
220225}
221226

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)
7778{
7879#if !ENABLE(INDEXED_DATABASE)
7980 UNUSED_PARAM(connectionProxy);

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

Source/WebCore/workers/WorkerGlobalScope.h

@@class WorkerGlobalScope : public Supplementable<WorkerGlobalScope>, public Base6
163163 mutable RefPtr<WorkerLocation> m_location;
164164 mutable RefPtr<WorkerNavigator> m_navigator;
165165
166  std::unique_ptr<WorkerOrWorkletScriptController> m_script;
167 
168166 bool m_isOnline;
169167 bool m_shouldBypassMainWorldContentSecurityPolicy;
170168

@@class WorkerGlobalScope : public Supplementable<WorkerGlobalScope>, public Base6
187185 std::unique_ptr<CSSValuePool> m_cssValuePool;
188186 ReferrerPolicy m_referrerPolicy;
189187 Settings::Values m_settingsValues;
 188 WorkerType m_workerType;
190189};
191190
192191} // 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 "LoadableModuleScript.h"
 39#include "ModuleFetchFailureKind.h"
 40#include "ModuleFetchParameters.h"
3841#include "ScriptSourceCode.h"
3942#include "WebCoreJSClientData.h"
4043#include "WorkerConsoleClient.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(LoadableModuleScript& moduleScript, 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 RefPtr<LoadableModuleScript> moduleScriptRef;
 267 {
 268 auto& promise = JSExecState::loadModule(globalObject, sourceCode.jsSourceCode(), JSC::JSScriptFetcher::create(vm, { &moduleScript }));
 269
 270 moduleScriptRef = &moduleScript;
 271
 272 auto& fulfillHandler = *JSNativeStdFunction::create(vm, &globalObject, 1, String(), [moduleScriptRef](JSGlobalObject* globalObject, CallFrame* callFrame) -> JSC::EncodedJSValue {
 273 // dataLogLn("FULFILLED");
 274 VM& vm = globalObject->vm();
 275 auto scope = DECLARE_THROW_SCOPE(vm);
 276 Identifier moduleKey = jsValueToModuleKey(globalObject, callFrame->argument(0));
 277 RETURN_IF_EXCEPTION(scope, { });
 278 moduleScriptRef->notifyLoadCompleted(*moduleKey.impl());
 279 return JSValue::encode(jsUndefined());
 280 });
 281
 282 auto& rejectHandler = *JSNativeStdFunction::create(vm, &globalObject, 1, String(), [moduleScriptRef](JSGlobalObject* globalObject, CallFrame* callFrame) {
 283 // dataLogLn("REJECTED");
 284 VM& vm = globalObject->vm();
 285 JSValue errorValue = callFrame->argument(0);
 286 if (errorValue.isObject()) {
 287 auto* object = JSC::asObject(errorValue);
 288 if (JSValue failureKindValue = object->getDirect(vm, static_cast<JSVMClientData&>(*vm.clientData).builtinNames().failureKindPrivateName())) {
 289 // This is host propagated error in the module loader pipeline.
 290 switch (static_cast<ModuleFetchFailureKind>(failureKindValue.asInt32())) {
 291 case ModuleFetchFailureKind::WasErrored:
 292 moduleScriptRef->notifyLoadFailed(LoadableScript::Error {
 293 LoadableScript::ErrorType::CachedScript,
 294 WTF::nullopt
 295 });
 296 break;
 297 case ModuleFetchFailureKind::WasCanceled:
 298 moduleScriptRef->notifyLoadWasCanceled();
 299 break;
 300 }
 301 return JSValue::encode(jsUndefined());
 302 }
 303 }
 304
 305 auto scope = DECLARE_CATCH_SCOPE(vm);
 306 moduleScriptRef->notifyLoadFailed(LoadableScript::Error {
 307 LoadableScript::ErrorType::CachedScript,
 308 LoadableScript::ConsoleMessage {
 309 MessageSource::JS,
 310 MessageLevel::Error,
 311 retrieveErrorMessage(*globalObject, vm, errorValue, scope),
 312 }
 313 });
 314 return JSValue::encode(jsUndefined());
 315 });
 316
 317 promise.then(&globalObject, &fulfillHandler, &rejectHandler);
 318 }
 319 m_globalScope->eventLoop().performMicrotaskCheckpoint();
 320
 321 // Drive RunLoop until we get either of "Worker is terminated", "Loading is done", or "Loading is failed".
 322 WorkerRunLoop& runLoop = m_globalScope->workerOrWorkletThread()->runLoop();
 323
 324 // We do not want to receive messages that are not related to asynchronous resource loading.
 325 // Otherwise, a worker discards some messages from the main thread here in a racy way.
 326 // For example, the main thread can postMessage just after creating a Worker. In that case, postMessage's
 327 // task is queued in WorkerRunLoop before start running module scripts. This task should not be discarded
 328 // in the following driving of the RunLoop which mainly attempt to collect initial load of module scripts.
 329 String taskMode = "loadModulesInWorkerOrWorkletMode"_s;
 330 MessageQueueWaitResult result = MessageQueueMessageReceived;
 331 while ((!moduleScriptRef->isLoaded() && !moduleScriptRef->wasCanceled()) && result != MessageQueueTerminated) {
 332 result = runLoop.runInMode(m_globalScope, taskMode);
 333 if (result != MessageQueueTerminated)
 334 m_globalScope->eventLoop().performMicrotaskCheckpoint();
 335 }
 336
 337 // FIXME: Currently we are not offering cancelling.
 338 // if (!loader->done() && result == MessageQueueTerminated)
 339 // loader->cancel();
 340
 341 return result;
 342}
 343
 344void WorkerOrWorkletScriptController::linkAndEvaluateModule(LoadableModuleScript& moduleScript, const ScriptSourceCode& sourceCode, String* returnedExceptionMessage)
 345{
 346 if (isExecutionForbidden())
 347 return;
 348
 349 initScriptIfNeeded();
 350
 351 auto& globalObject = *m_globalScopeWrapper.get();
 352 VM& vm = globalObject.vm();
 353 JSLockHolder lock { vm };
 354
 355 NakedPtr<JSC::Exception> returnedException;
 356 JSExecState::linkAndEvaluateModule(globalObject, Identifier::fromUid(vm, moduleScript.moduleKey()), jsUndefined(), returnedException);
 357 if ((returnedException && isTerminatedExecutionException(vm, returnedException)) || isTerminatingExecution()) {
 358 forbidExecution();
 359 return;
 360 }
 361
 362 if (returnedException) {
 363 if (m_globalScope->canIncludeErrorDetails(sourceCode.cachedScript(), sourceCode.url().string())) {
 364 // FIXME: It's not great that this can run arbitrary code to string-ify the value of the exception.
 365 // Do we need to do anything to handle that properly, if it, say, raises another exception?
 366 if (returnedExceptionMessage)
 367 *returnedExceptionMessage = returnedException->value().toWTFString(&globalObject);
 368 } else {
 369 // Overwrite the detailed error with a generic error.
 370 String genericErrorMessage { "Script error."_s };
 371 if (returnedExceptionMessage)
 372 *returnedExceptionMessage = genericErrorMessage;
 373 returnedException = JSC::Exception::create(vm, createError(&globalObject, genericErrorMessage));
 374 }
 375 }
 376}
 377
231378template<typename JSGlobalScopePrototype, typename JSGlobalScope, typename GlobalScope>
232379void WorkerOrWorkletScriptController::initScriptWithSubclass()
233380{

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;

@@class WorkerOrWorkletScriptController {
9496 void evaluate(const ScriptSourceCode&, String* returnedExceptionMessage = nullptr);
9597 void evaluate(const ScriptSourceCode&, NakedPtr<JSC::Exception>& returnedException, String* returnedExceptionMessage = nullptr);
9698
 99 JSC::JSValue evaluateModule(JSC::JSModuleRecord&);
 100
 101 void linkAndEvaluateModule(LoadableModuleScript&, const ScriptSourceCode&, String* returnedExceptionMessage = nullptr);
 102 MessageQueueWaitResult loadModuleSynchronously(LoadableModuleScript&, const ScriptSourceCode&);
 103
97104protected:
98105 WorkerOrWorkletGlobalScope* globalScope() const { return m_globalScope; }
99106

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
143143
144144 // During create, callbacks may happen which remove the last reference to this object.
145145 Ref<WorkerScriptLoader> protectedThis(*this);
146  m_threadableLoader = ThreadableLoader::create(scriptExecutionContext, *this, WTFMove(*request), options);
 146 m_threadableLoader = ThreadableLoader::create(scriptExecutionContext, *this, WTFMove(*request), options, { }, WTFMove(taskMode));
147147}
148148
149149const URL& WorkerScriptLoader::responseURL() const

Source/WebCore/workers/WorkerScriptLoader.h

@@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

Source/WebCore/workers/WorkerThread.cpp

2828#include "WorkerThread.h"
2929
3030#include "IDBConnectionProxy.h"
 31#include "LoadableModuleScript.h"
3132#include "ScriptSourceCode.h"
3233#include "SecurityOrigin.h"
3334#include "SocketProvider.h"
3435#include "WorkerGlobalScope.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 moduleScript = LoadableModuleScript::create(emptyString(), emptyString(), m_startupData->params.referrerPolicy, ScriptElementCachedScriptFetcher::defaultCrossOriginModeForModule, emptyString(), emptyAtom(), false);
 142 MessageQueueWaitResult result = globalScope()->script()->loadModuleSynchronously(moduleScript.get(), sourceCode);
 143 if (result != MessageQueueTerminated) {
 144 if (Optional<LoadableScript::Error> error = moduleScript->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 (!moduleScript->wasCanceled()) {
 151 // Evaluate.
 152 globalScope()->script()->linkAndEvaluateModule(moduleScript.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 m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(options), ContentSecurityPolicyEnforcement::DoNotEnforce, ServiceWorkersMode::None, *this, WorkerRunLoop::defaultMode());
114114}
115115
116116ResourceError 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

@@void WorkletGlobalScope::processNextScriptFetchJobIfNeeded()
188188 auto contentSecurityPolicyEnforcement = shouldBypassMainWorldContentSecurityPolicy() ? ContentSecurityPolicyEnforcement::DoNotEnforce : ContentSecurityPolicyEnforcement::EnforceChildSrcDirective;
189189
190190 m_scriptLoader = WorkerScriptLoader::create();
191  m_scriptLoader->loadAsynchronously(*this, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, *this);
 191 m_scriptLoader->loadAsynchronously(*this, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, *this, WorkerRunLoop::defaultMode());
192192}
193193
194194void WorkletGlobalScope::didReceiveResponse(unsigned long, const ResourceResponse&)

LayoutTests/imported/w3c/ChangeLog

 12021-02-10 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/workers/baseurl/alpha/import-in-moduleworker-expected.txt:
 17 * web-platform-tests/workers/baseurl/alpha/importScripts-in-worker-expected.txt:
 18 * web-platform-tests/workers/baseurl/alpha/xhr-in-moduleworker-expected.txt:
 19 * web-platform-tests/workers/baseurl/alpha/xhr-in-worker-expected.txt:
 20 * web-platform-tests/workers/interfaces/WorkerGlobalScope/location/redirect-expected.txt:
 21 * web-platform-tests/workers/interfaces/WorkerGlobalScope/location/redirect-module-expected.txt:
 22 * web-platform-tests/workers/modules/dedicated-worker-import-blob-url.any-expected.txt:
 23 * web-platform-tests/workers/modules/dedicated-worker-import-csp-expected.txt:
 24 * web-platform-tests/workers/modules/dedicated-worker-import-failure-expected.txt:
 25 * web-platform-tests/workers/modules/dedicated-worker-import-meta-expected.txt:
 26 * web-platform-tests/workers/modules/dedicated-worker-import.any-expected.txt:
 27 * web-platform-tests/workers/modules/dedicated-worker-options-type-expected.txt:
 28 * web-platform-tests/workers/modules/dedicated-worker-parse-error-failure-expected.txt:
 29 * web-platform-tests/workers/name-property-expected.txt:
 30
1312021-02-10 Manuel Rego Casasnovas <rego@igalia.com>
232
333 Add support for modifier keys in test_driver.send_keys()

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
22Harness Error (TIMEOUT), message = null
33
 4FAIL 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
 5NOTRUN Promise resolved during event handlers other than error
46

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/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/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
 2PASS Test import.meta.url on the top-level module script.
 3PASS Test import.meta.url on the imported module script.
74FAIL Test import.meta.url on the imported module script with a fragment. assert_true: expected true got false
85

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