Changeset 273203 in webkit


Ignore:
Timestamp:
Feb 20, 2021 12:28:27 PM (17 months ago)
Author:
ysuzuki@apple.com
Message:

JS Modules in Workers
https://bugs.webkit.org/show_bug.cgi?id=164860

Reviewed by Saam Barati.

LayoutTests/imported/w3c:

Some of worklet failures in WPT is because,

  1. Previously, worklet does not support module. These tests are passing incorrectly when modules are not supported. Now, modules are supported, and some edge features are missing, so start failing
  2. WPT is using www1.localhost in some tests (CSP tests), and this is not supported in WebKit's WPT testing. So failing incorrectly.
  • web-platform-tests/html/semantics/scripting-1/the-script-element/json-module/non-object.tentative.any.worker-expected.txt:
  • web-platform-tests/html/semantics/scripting-1/the-script-element/microtasks/checkpoint-after-workerglobalscope-onerror-module-expected.txt:
  • web-platform-tests/html/semantics/scripting-1/the-script-element/module/dynamic-import/alpha/base-url-worker-importScripts-expected.txt:
  • web-platform-tests/html/semantics/scripting-1/the-script-element/module/dynamic-import/alpha/base-url-worker.sub-expected.txt:
  • web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-1-nothrow-worker-expected.txt:
  • web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-1-worker-expected.txt:
  • web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-2-import-worker-expected.txt:
  • web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-3-dynamic-worker-expected.txt:
  • web-platform-tests/service-workers/service-worker/import-module-scripts.https-expected.txt:
  • web-platform-tests/workers/baseurl/alpha/import-in-moduleworker-expected.txt:
  • web-platform-tests/workers/baseurl/alpha/importScripts-in-worker-expected.txt:
  • web-platform-tests/workers/baseurl/alpha/xhr-in-moduleworker-expected.txt:
  • web-platform-tests/workers/baseurl/alpha/xhr-in-worker-expected.txt:
  • web-platform-tests/workers/constructors/Worker/same-origin-expected.txt:
  • web-platform-tests/workers/interfaces/WorkerGlobalScope/location/redirect-expected.txt:
  • web-platform-tests/workers/interfaces/WorkerGlobalScope/location/redirect-module-expected.txt:
  • web-platform-tests/workers/modules/dedicated-worker-import-blob-url.any-expected.txt:
  • web-platform-tests/workers/modules/dedicated-worker-import-csp-expected.txt:
  • web-platform-tests/workers/modules/dedicated-worker-import-failure-expected.txt:
  • web-platform-tests/workers/modules/dedicated-worker-import-meta-expected.txt:
  • web-platform-tests/workers/modules/dedicated-worker-import-meta.html:
  • web-platform-tests/workers/modules/dedicated-worker-import-referrer-expected.txt:
  • web-platform-tests/workers/modules/dedicated-worker-import.any-expected.txt:
  • web-platform-tests/workers/modules/dedicated-worker-options-type-expected.txt:
  • web-platform-tests/workers/modules/dedicated-worker-parse-error-failure-expected.txt:
  • web-platform-tests/workers/name-property-expected.txt:
  • web-platform-tests/worklets/audio-worklet-credentials.https-expected.txt:
  • web-platform-tests/worklets/audio-worklet-csp.https-expected.txt:
  • web-platform-tests/worklets/audio-worklet-import.https-expected.txt:
  • web-platform-tests/worklets/audio-worklet-referrer.https-expected.txt:
  • web-platform-tests/xhr/open-url-redirected-worker-origin-expected.txt:

Source/JavaScriptCore:

Add error information to extract this in WebCore's module loader.
Currently, we are using Promise pipeline, and this makes it a bit difficult to extract error information.
This error information attached in this patch allows us to extract SyntaxError in WebCore, and throwing
JS SyntaxError instead of AbortError.

We are planning to update our module pipieline not using Promises in the future. The current design derived
from the original module loader pipeline where using Promises is critical. But now, that proposal was abandoned,
so we can just simplify the module loader.

  • runtime/AggregateError.cpp:

(JSC::AggregateError::AggregateError):

  • runtime/Error.cpp:

(JSC::createError):
(JSC::createEvalError):
(JSC::createRangeError):
(JSC::createReferenceError):
(JSC::createSyntaxError):
(JSC::createTypeError):
(JSC::createURIError):
(JSC::createGetterTypeError):
(JSC::throwSyntaxError):

  • runtime/Error.h:
  • runtime/ErrorConstructor.cpp:

(JSC::JSC_DEFINE_HOST_FUNCTION):

  • runtime/ErrorInstance.cpp:

(JSC::ErrorInstance::ErrorInstance):
(JSC::ErrorInstance::create):
(JSC::ErrorInstance::sanitizedMessageString):
(JSC::ErrorInstance::sanitizedNameString):
(JSC::ErrorInstance::sanitizedToString):

  • runtime/ErrorInstance.h:

(JSC::ErrorInstance::create):
(JSC::ErrorInstance::errorType const):

  • runtime/JSGlobalObjectFunctions.cpp:

(JSC::JSC_DEFINE_HOST_FUNCTION):

  • runtime/NativeErrorConstructor.cpp:

(JSC::NativeErrorConstructor<errorType>::constructImpl):
(JSC::NativeErrorConstructor<errorType>::callImpl):

  • runtime/NullSetterFunction.cpp:

(JSC::NullSetterFunctionInternal::JSC_DEFINE_HOST_FUNCTION):

  • wasm/js/JSWebAssemblyCompileError.cpp:

(JSC::JSWebAssemblyCompileError::JSWebAssemblyCompileError):

  • wasm/js/JSWebAssemblyLinkError.cpp:

(JSC::JSWebAssemblyLinkError::JSWebAssemblyLinkError):

  • wasm/js/JSWebAssemblyRuntimeError.cpp:

(JSC::JSWebAssemblyRuntimeError::JSWebAssemblyRuntimeError):

  • wasm/js/WebAssemblyCompileErrorConstructor.cpp:

(JSC::JSC_DEFINE_HOST_FUNCTION):

  • wasm/js/WebAssemblyLinkErrorConstructor.cpp:

(JSC::JSC_DEFINE_HOST_FUNCTION):

  • wasm/js/WebAssemblyRuntimeErrorConstructor.cpp:

(JSC::JSC_DEFINE_HOST_FUNCTION):

Source/WebCore:

This patch implements JS modules in Workers and Worklets. We are not supporting modules in ServiceWorkers' initialization yet.
But service-worker can import modules via JS import().

The worker can be executed as a module if we pass, type: "module" to worker options. Worklet is executed as modules by default.

  1. In Worker, we first fetch the initial code. And then, analyze the dependencies and load subsequent modules. We iterate run-loop to load all the dependent modules in the module loader. At that time, we annotate run-loop tasks with special taskMode to iterate tasks with this taskMode. This prevents us from discarding different tasks in this run-loop driving phase. (e.g. postMessage can be called from the main thread while loading module graph, in that case, we should not discard this task.)
  1. In Worklet, we just request module loading to ScriptModuleLoader, and run it after loading module graph. This is OK since worklet thread is already running. So we can just request modules and worklet thread automatically drives module loading via run-loop.
  • Headers.cmake:
  • Modules/webaudio/AudioWorkletGlobalScope.h:

(WebCore::AudioWorkletGlobalScope::currentFrame const): Deleted.
(WebCore::AudioWorkletGlobalScope::sampleRate const): Deleted.
(WebCore::AudioWorkletGlobalScope::currentTime const): Deleted.

  • Sources.txt:
  • WebCore.xcodeproj/project.pbxproj:
  • bindings/js/CachedModuleScriptLoader.cpp:

(WebCore::CachedModuleScriptLoader::create):
(WebCore::CachedModuleScriptLoader::CachedModuleScriptLoader):
(WebCore::CachedModuleScriptLoader::load):
(WebCore::CachedModuleScriptLoader::notifyFinished):

  • bindings/js/CachedModuleScriptLoader.h:
  • bindings/js/CachedScriptFetcher.cpp:
  • bindings/js/JSDOMExceptionHandling.cpp:

(WebCore::retrieveErrorMessageWithoutName):
(WebCore::createDOMException):

  • bindings/js/JSDOMExceptionHandling.h:
  • bindings/js/JSDOMGlobalObject.cpp:

(WebCore::scriptModuleLoader):
(WebCore::JSDOMGlobalObject::moduleLoaderResolve):
(WebCore::JSDOMGlobalObject::moduleLoaderFetch):
(WebCore::JSDOMGlobalObject::moduleLoaderEvaluate):
(WebCore::JSDOMGlobalObject::moduleLoaderImportModule):
(WebCore::JSDOMGlobalObject::moduleLoaderCreateImportMetaProperties):

  • bindings/js/JSDOMGlobalObject.h:
  • bindings/js/JSDOMWindowBase.cpp:

(WebCore::JSDOMWindowBase::moduleLoaderResolve): Deleted.
(WebCore::JSDOMWindowBase::moduleLoaderFetch): Deleted.
(WebCore::JSDOMWindowBase::moduleLoaderEvaluate): Deleted.
(WebCore::JSDOMWindowBase::moduleLoaderImportModule): Deleted.
(WebCore::JSDOMWindowBase::moduleLoaderCreateImportMetaProperties): Deleted.

  • bindings/js/JSDOMWindowBase.h:
  • bindings/js/JSWorkerGlobalScopeBase.cpp:
  • bindings/js/JSWorkletGlobalScopeBase.cpp:
  • bindings/js/ModuleScriptLoader.h: Copied from Source/WebCore/dom/ModuleFetchParameters.h.

(WebCore::ModuleScriptLoader::clearClient):
(WebCore::ModuleScriptLoader::scriptFetcher):
(WebCore::ModuleScriptLoader::parameters):
(WebCore::ModuleScriptLoader::ModuleScriptLoader):

  • bindings/js/ModuleScriptLoaderClient.h: Renamed from Source/WebCore/bindings/js/CachedModuleScriptLoaderClient.h.
  • bindings/js/ScriptModuleLoader.cpp:

(WebCore::ScriptModuleLoader::ScriptModuleLoader):
(WebCore::resolveModuleSpecifier):
(WebCore::ScriptModuleLoader::resolve):
(WebCore::ScriptModuleLoader::fetch):
(WebCore::ScriptModuleLoader::moduleURL):
(WebCore::ScriptModuleLoader::responseURLFromRequestURL):
(WebCore::ScriptModuleLoader::evaluate):
(WebCore::ScriptModuleLoader::importModule):
(WebCore::ScriptModuleLoader::notifyFinished):

  • bindings/js/ScriptModuleLoader.h:
  • bindings/js/ScriptSourceCode.h:

(WebCore::ScriptSourceCode::ScriptSourceCode):

  • bindings/js/WorkerModuleScriptLoader.cpp: Added.

(WebCore::WorkerModuleScriptLoader::create):
(WebCore::WorkerModuleScriptLoader::WorkerModuleScriptLoader):
(WebCore::WorkerModuleScriptLoader::~WorkerModuleScriptLoader):
(WebCore::WorkerModuleScriptLoader::load):
(WebCore::WorkerModuleScriptLoader::referrerPolicy):
(WebCore::WorkerModuleScriptLoader::notifyFinished):
(WebCore::WorkerModuleScriptLoader::taskMode):

  • bindings/js/WorkerModuleScriptLoader.h: Copied from Source/WebCore/dom/ModuleFetchParameters.h.
  • bindings/js/WorkerScriptFetcher.h: Added.
  • dom/Document.cpp:
  • dom/ExceptionCode.h:
  • dom/LoadableModuleScript.cpp:

(WebCore::LoadableModuleScript::LoadableModuleScript):
(WebCore::LoadableModuleScript::load): Deleted.

  • dom/LoadableModuleScript.h:
  • dom/ModuleFetchParameters.h:

(WebCore::ModuleFetchParameters::create):
(WebCore::ModuleFetchParameters::isTopLevelModule const):
(WebCore::ModuleFetchParameters::ModuleFetchParameters):

  • dom/ScriptElement.cpp:

(WebCore::ScriptElement::requestModuleScript):

  • loader/ThreadableLoader.cpp:

(WebCore::ThreadableLoader::create):

  • loader/ThreadableLoader.h:

(WebCore::ThreadableLoader::create):

  • workers/DedicatedWorkerGlobalScope.h:
  • workers/Worker.cpp:

(WebCore::Worker::Worker):
(WebCore::Worker::create):
(WebCore::Worker::notifyFinished):

  • workers/Worker.h:
  • workers/Worker.idl:
  • workers/WorkerGlobalScope.cpp:

(WebCore::WorkerGlobalScope::WorkerGlobalScope):
(WebCore::WorkerGlobalScope::importScripts):

  • workers/WorkerGlobalScope.h:

(WebCore::WorkerGlobalScope::credentials const):

  • workers/WorkerGlobalScopeProxy.h:
  • workers/WorkerMessagingProxy.cpp:

(WebCore::WorkerMessagingProxy::startWorkerGlobalScope):

  • workers/WorkerMessagingProxy.h:
  • workers/WorkerOrWorkletGlobalScope.cpp:

(WebCore::WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope):

  • workers/WorkerOrWorkletGlobalScope.h:

(WebCore::WorkerOrWorkletGlobalScope::moduleLoader):

  • workers/WorkerOrWorkletScriptController.cpp:

(WebCore::jsValueToModuleKey):
(WebCore::WorkerOrWorkletScriptController::evaluateModule):
(WebCore::WorkerOrWorkletScriptController::loadModuleSynchronously):
(WebCore::WorkerOrWorkletScriptController::linkAndEvaluateModule):
(WebCore::WorkerOrWorkletScriptController::loadAndEvaluateModule):

  • workers/WorkerOrWorkletScriptController.h:
  • workers/WorkerScriptLoader.cpp:

(WebCore::WorkerScriptLoader::loadAsynchronously):
(WebCore::WorkerScriptLoader::didReceiveResponse):

  • workers/WorkerScriptLoader.h:

(WebCore::WorkerScriptLoader::responseSource const):
(WebCore::WorkerScriptLoader::isRedirected const):

  • workers/WorkerThread.cpp:

(WebCore::WorkerParameters::isolatedCopy const):
(WebCore::WorkerThread::evaluateScriptIfNecessary):

  • workers/WorkerThread.h:
  • workers/WorkerType.h:
  • workers/service/ServiceWorkerContainer.h:
  • workers/service/ServiceWorkerGlobalScope.h:
  • workers/service/ServiceWorkerJob.cpp:

(WebCore::ServiceWorkerJob::fetchScriptWithContext):

  • workers/service/ServiceWorkerRegistrationOptions.h:
  • workers/service/context/ServiceWorkerThread.cpp:

(WebCore::ServiceWorkerThread::ServiceWorkerThread):

  • workers/service/server/SWServerWorker.h:
  • worklets/PaintWorkletGlobalScope.h:

(WebCore::PaintWorkletGlobalScope::paintDefinitionMap): Deleted.
(WebCore::PaintWorkletGlobalScope::paintDefinitionLock): Deleted.
(WebCore::PaintWorkletGlobalScope::~PaintWorkletGlobalScope): Deleted.

  • worklets/WorkletGlobalScope.cpp:

(WebCore::WorkletGlobalScope::fetchAndInvokeScript):
(WebCore::WorkletGlobalScope::processNextScriptFetchJobIfNeeded): Deleted.
(WebCore::WorkletGlobalScope::didReceiveResponse): Deleted.
(WebCore::WorkletGlobalScope::notifyFinished): Deleted.
(WebCore::WorkletGlobalScope::didCompleteScriptFetchJob): Deleted.

  • worklets/WorkletGlobalScope.h:

LayoutTests:

  • TestExpectations:
  • http/tests/security/contentSecurityPolicy/1.1/module-scriptnonce-redirect-expected.txt:
  • http/tests/subresource-integrity/sri-module-expected.txt:
  • webaudio/audioworklet-addModule-failure-expected.txt:
  • webaudio/worklet-crash-expected.txt:
Location:
trunk
Files:
2 added
108 edited
2 copied
1 moved

Legend:

Unmodified
Added
Removed
  • trunk/LayoutTests/ChangeLog

    r273193 r273203  
     12021-02-19  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 Saam Barati.
     7
     8        * TestExpectations:
     9        * http/tests/security/contentSecurityPolicy/1.1/module-scriptnonce-redirect-expected.txt:
     10        * http/tests/subresource-integrity/sri-module-expected.txt:
     11        * webaudio/audioworklet-addModule-failure-expected.txt:
     12        * webaudio/worklet-crash-expected.txt:
     13
    1142021-02-19  Rob Buis  <rbuis@igalia.com>
    215
  • trunk/LayoutTests/TestExpectations

    r273193 r273203  
    641641
    642642# Skip workers tests that are timing out or are SharedWorker related only
    643 imported/w3c/web-platform-tests/workers/constructors/Worker/same-origin.html [ Skip ]
    644643imported/w3c/web-platform-tests/workers/data-url-shared.html [ Skip ]
    645644imported/w3c/web-platform-tests/workers/examples/onconnect.any.html [ Skip ]
     
    664663imported/w3c/web-platform-tests/workers/SharedWorker-script-error.html [ Skip ]
    665664imported/w3c/web-platform-tests/workers/SharedWorker-simple.html [ Skip ]
    666 imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-referrer.html [ Skip ]
    667665imported/w3c/web-platform-tests/workers/modules/dedicated-worker-options-credentials.html [ Skip ]
    668666
  • trunk/LayoutTests/http/tests/security/contentSecurityPolicy/1.1/module-scriptnonce-redirect-expected.txt

    r259900 r273203  
    11CONSOLE MESSAGE: Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.
    2 CONSOLE MESSAGE: TypeError: Cross-origin script load denied by Cross-Origin Resource Sharing policy.
    32This tests whether a deferred script load caused by a redirect is properly allowed by a nonce.
  • trunk/LayoutTests/http/tests/subresource-integrity/sri-module-expected.txt

    r267644 r273203  
    44CONSOLE MESSAGE: TypeError: Cannot load script http://localhost:8000/subresource-integrity/resources/crossorigin-creds-script-module.js. Failed integrity metadata check. Content length: 38, Expected content length: 38, Expected metadata: sha256-deadbeef2S+pTRZgiw3DWrhC6JLDlt2zRyGpwH7unU8=
    55CONSOLE MESSAGE: Origin http://127.0.0.1:8000 is not allowed by Access-Control-Allow-Origin.
    6 CONSOLE MESSAGE: TypeError: Cross-origin script load denied by Cross-Origin Resource Sharing policy.
    76CONSOLE MESSAGE: TypeError: Cannot load script http://127.0.0.1:8000/subresource-integrity/resources/matching-digest-module.js. Failed integrity metadata check. Content length: 29, Expected content length: 29, Expected metadata: sha256-cWh9nPfm7_mRbKhzarnRYlsJWz5XTNcsqPFzKEx+zSU=
    87CONSOLE MESSAGE: TypeError: Cannot load script http://127.0.0.1:8000/subresource-integrity/resources/matching-digest-module.js. Failed integrity metadata check. Content length: 29, Expected content length: 29, Expected metadata: sha256-U9WYDtBWkcHx13+9UKk/3Q5eoqDc4YGxYb07EPWzb9e=?foo=bar?spam=eggs
  • trunk/LayoutTests/imported/w3c/ChangeLog

    r273136 r273203  
     12021-02-19  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 Saam Barati.
     7
     8        Some of worklet failures in WPT is because,
     9
     10            1. Previously, worklet does not support module. These tests are passing incorrectly when modules are not supported.
     11               Now, modules are supported, and some edge features are missing, so start failing
     12            2. WPT is using www1.localhost in some tests (CSP tests), and this is not supported in WebKit's WPT testing. So failing incorrectly.
     13
     14        * web-platform-tests/html/semantics/scripting-1/the-script-element/json-module/non-object.tentative.any.worker-expected.txt:
     15        * web-platform-tests/html/semantics/scripting-1/the-script-element/microtasks/checkpoint-after-workerglobalscope-onerror-module-expected.txt:
     16        * web-platform-tests/html/semantics/scripting-1/the-script-element/module/dynamic-import/alpha/base-url-worker-importScripts-expected.txt:
     17        * web-platform-tests/html/semantics/scripting-1/the-script-element/module/dynamic-import/alpha/base-url-worker.sub-expected.txt:
     18        * web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-1-nothrow-worker-expected.txt:
     19        * web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-1-worker-expected.txt:
     20        * web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-2-import-worker-expected.txt:
     21        * web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-3-dynamic-worker-expected.txt:
     22        * web-platform-tests/service-workers/service-worker/import-module-scripts.https-expected.txt:
     23        * web-platform-tests/workers/baseurl/alpha/import-in-moduleworker-expected.txt:
     24        * web-platform-tests/workers/baseurl/alpha/importScripts-in-worker-expected.txt:
     25        * web-platform-tests/workers/baseurl/alpha/xhr-in-moduleworker-expected.txt:
     26        * web-platform-tests/workers/baseurl/alpha/xhr-in-worker-expected.txt:
     27        * web-platform-tests/workers/constructors/Worker/same-origin-expected.txt:
     28        * web-platform-tests/workers/interfaces/WorkerGlobalScope/location/redirect-expected.txt:
     29        * web-platform-tests/workers/interfaces/WorkerGlobalScope/location/redirect-module-expected.txt:
     30        * web-platform-tests/workers/modules/dedicated-worker-import-blob-url.any-expected.txt:
     31        * web-platform-tests/workers/modules/dedicated-worker-import-csp-expected.txt:
     32        * web-platform-tests/workers/modules/dedicated-worker-import-failure-expected.txt:
     33        * web-platform-tests/workers/modules/dedicated-worker-import-meta-expected.txt:
     34        * web-platform-tests/workers/modules/dedicated-worker-import-meta.html:
     35        * web-platform-tests/workers/modules/dedicated-worker-import-referrer-expected.txt:
     36        * web-platform-tests/workers/modules/dedicated-worker-import.any-expected.txt:
     37        * web-platform-tests/workers/modules/dedicated-worker-options-type-expected.txt:
     38        * web-platform-tests/workers/modules/dedicated-worker-parse-error-failure-expected.txt:
     39        * web-platform-tests/workers/name-property-expected.txt:
     40        * web-platform-tests/worklets/audio-worklet-credentials.https-expected.txt:
     41        * web-platform-tests/worklets/audio-worklet-csp.https-expected.txt:
     42        * web-platform-tests/worklets/audio-worklet-import.https-expected.txt:
     43        * web-platform-tests/worklets/audio-worklet-referrer.https-expected.txt:
     44        * web-platform-tests/xhr/open-url-redirected-worker-origin-expected.txt:
     45
    1462021-02-19  Manuel Rego Casasnovas  <rego@igalia.com>
    247
  • trunk/LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/json-module/non-object.tentative.any.worker-expected.txt

    r253791 r273203  
    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
  • trunk/LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/microtasks/checkpoint-after-workerglobalscope-onerror-module-expected.txt

    r269598 r273203  
    11
    2 Harness Error (TIMEOUT), message = null
     2FAIL Promise resolved during #report-the-error assert_array_equals: lengths differ, expected array ["handler 1", "handler 2", "handler 1 promise", "handler 2 promise"] length 4, got [] length 0
     3PASS Promise resolved during event handlers other than error
    34
    4 
  • trunk/LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/module/dynamic-import/alpha/base-url-worker-importScripts-expected.txt

    r269598 r273203  
    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
  • trunk/LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/module/dynamic-import/alpha/base-url-worker.sub-expected.txt

    r269598 r273203  
    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
  • trunk/LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-1-nothrow-worker-expected.txt

    r269598 r273203  
    11
    2 Harness Error (TIMEOUT), message = null
     2PASS Test evaluation order of modules
    33
    4 
  • trunk/LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-1-worker-expected.txt

    r269598 r273203  
    11
    2 Harness Error (TIMEOUT), message = null
     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
    33
    4 
  • trunk/LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-2-import-worker-expected.txt

    r269598 r273203  
    11
    2 Harness Error (TIMEOUT), message = null
     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
    33
    4 
  • trunk/LayoutTests/imported/w3c/web-platform-tests/html/semantics/scripting-1/the-script-element/module/evaluation-order-3-dynamic-worker-expected.txt

    r269598 r273203  
    11
    2 Harness Error (TIMEOUT), message = null
     2PASS Test evaluation order of modules
    33
    4 
  • trunk/LayoutTests/imported/w3c/web-platform-tests/service-workers/service-worker/import-module-scripts.https-expected.txt

    r249719 r273203  
    33FAIL Nested static import. promise_test: Unhandled rejection with value: object "TypeError: SyntaxError: Unexpected token '*'. import call expects exactly one argument."
    44FAIL Static import and then dynamic import. promise_test: Unhandled rejection with value: object "TypeError: SyntaxError: Unexpected token '*'. import call expects exactly one argument."
    5 FAIL Dynamic import. assert_array_equals: value is "Failed to do dynamic import: Error: Could not import the module './export-on-load-script.js'.", expected array
    6 FAIL Nested dynamic import. assert_array_equals: value is "Failed to do dynamic import: Error: Could not import the module './export-on-dynamic-import-script.js'.", expected array
    7 FAIL Dynamic import and then static import. assert_array_equals: value is "Failed to do dynamic import: Error: Could not import the module './export-on-static-import-script.js'.", expected array
    8 FAIL eval(import()). assert_array_equals: value is "Failed to do dynamic import: Error: Could not import the module './export-on-load-script.js'.", expected array
     5PASS Dynamic import.
     6PASS Nested dynamic import.
     7PASS Dynamic import and then static import.
     8PASS eval(import()).
    99
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/baseurl/alpha/import-in-moduleworker-expected.txt

    r259900 r273203  
    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
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/baseurl/alpha/importScripts-in-worker-expected.txt

    r249977 r273203  
    11
    2 FAIL importScripts assert_equals: expected "gamma/script.js" but got "beta/script.js"
     2PASS importScripts
    33
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/baseurl/alpha/xhr-in-moduleworker-expected.txt

    r249719 r273203  
    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
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/baseurl/alpha/xhr-in-worker-expected.txt

    r249977 r273203  
    11
    2 FAIL xhr-worker assert_equals: expected "gamma\n" but got "beta\n"
     2PASS xhr-worker
    33
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/constructors/Worker/same-origin-expected.txt

    r267649 r273203  
    1 
    2 Harness Error (TIMEOUT), message = null
    31
    42PASS unsupported_scheme
    53FAIL data_url The operation is insecure.
    6 TIMEOUT about_blank Test timed out
    7 TIMEOUT example_invalid Test timed out
    8 TIMEOUT port_81 Test timed out
    9 TIMEOUT https_port_80 Test timed out
    10 TIMEOUT https_port_8000 Test timed out
    11 TIMEOUT http_post_8012 Test timed out
    12 TIMEOUT javascript_url Test timed out
     4PASS about_blank
     5PASS example_invalid
     6PASS port_81
     7PASS https_port_80
     8PASS https_port_8000
     9PASS http_post_8012
     10PASS javascript_url
    1311
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/interfaces/WorkerGlobalScope/location/redirect-expected.txt

    r249719 r273203  
    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
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/interfaces/WorkerGlobalScope/location/redirect-module-expected.txt

    r249719 r273203  
    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
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-blob-url.any-expected.txt

    r259900 r273203  
    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.
     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()).
    109
    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."
    18 
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-csp-expected.txt

    r267649 r273203  
    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.
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-failure-expected.txt

    r267649 r273203  
    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.
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-meta-expected.txt

    r259900 r273203  
    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.
     2PASS Test import.meta.url on the top-level module script.
     3PASS Test import.meta.url on the imported module script.
     4PASS Test import.meta.url on the imported module script with a fragment.
    45
    5 FAIL Test import.meta.url on the top-level module script. promise_test: Unhandled rejection with value: "SyntaxError: import.meta is only valid inside modules."
    6 FAIL Test import.meta.url on the imported module script. assert_true: expected true got false
    7 FAIL Test import.meta.url on the imported module script with a fragment. assert_true: expected true got false
    8 
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-meta.html

    r264183 r273203  
    5454        return new Promise(resolve => worker.onmessage = resolve);
    5555      })
    56       .then(msg_event => assert_true(msg_event.data.endsWith(script_url)));
     56      .then(msg_event => assert_true(msg_event.data.endsWith(script_url + '#1')));
    5757}, 'Test import.meta.url on the imported module script with a fragment.');
    5858
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-import-referrer-expected.txt

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

    r259900 r273203  
    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.
     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()).
    69
    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
    14 
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-options-type-expected.txt

    r267649 r273203  
    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
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/modules/dedicated-worker-parse-error-failure-expected.txt

    r267649 r273203  
    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
     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}"
    414
    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.
    7 
  • trunk/LayoutTests/imported/w3c/web-platform-tests/workers/name-property-expected.txt

    r267649 r273203  
    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
  • trunk/LayoutTests/imported/w3c/web-platform-tests/worklets/audio-worklet-credentials.https-expected.txt

    r270033 r273203  
    11CONSOLE MESSAGE: Origin https://localhost:9443 is not allowed by Access-Control-Allow-Origin.
    22
    3 FAIL Importing a same-origin script with the default WorkletOptions should send the credentials promise_test: Unhandled rejection with value: object "AbortError: Failed to fetch module, error: Response is not 2xx"
     3FAIL Importing a same-origin script with the default WorkletOptions should send the credentials promise_test: Unhandled rejection with value: object "AbortError: Importing a module script failed."
    44PASS Importing a remote-origin script with the default WorkletOptions should not send the credentials
    5 FAIL Importing a same-origin script with credentials=omit should not send the credentials promise_test: Unhandled rejection with value: object "AbortError: Failed to fetch module, error: Response is not 2xx"
     5FAIL Importing a same-origin script with credentials=omit should not send the credentials promise_test: Unhandled rejection with value: object "AbortError: Importing a module script failed."
    66PASS Importing a remote-origin script with credentials=omit should not send the credentials
    7 FAIL Importing a same-origin script with credentials=same-origin should send the credentials promise_test: Unhandled rejection with value: object "AbortError: Failed to fetch module, error: Response is not 2xx"
     7FAIL Importing a same-origin script with credentials=same-origin should send the credentials promise_test: Unhandled rejection with value: object "AbortError: Importing a module script failed."
    88PASS Importing a remote-origin script with credentials=same-origin should not send the credentials
    9 FAIL Importing a same-origin script with credentials=include should send the credentials promise_test: Unhandled rejection with value: object "AbortError: Failed to fetch module, error: Response is not 2xx"
    10 FAIL Importing a remote-origin script with credentials=include should send the credentials promise_test: Unhandled rejection with value: object "AbortError: Failed to fetch module, error: Origin https://localhost:9443 is not allowed by Access-Control-Allow-Origin."
     9FAIL Importing a same-origin script with credentials=include should send the credentials promise_test: Unhandled rejection with value: object "AbortError: Importing a module script failed."
     10FAIL Importing a remote-origin script with credentials=include should send the credentials promise_test: Unhandled rejection with value: object "AbortError: Cross-origin script load denied by Cross-Origin Resource Sharing policy."
    1111
  • trunk/LayoutTests/imported/w3c/web-platform-tests/worklets/audio-worklet-csp.https-expected.txt

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

    r270046 r273203  
    1717PASS Importing a cross-origin-redirected resource with the Access-Control-Allow-Origin header should resolve the given promise
    1818PASS Importing a cross-origin-redirected resource without the Access-Control-Allow-Origin header should reject the given promise
    19 FAIL Importing a script that has a syntax error should reject the given promise. assert_unreached: Should have rejected: undefined Reached unreachable code
    20 FAIL Importing a nested script that has a syntax error should reject the given promise. assert_unreached: Should have rejected: undefined Reached unreachable code
    21 FAIL Importing a script that imports an invalid identifier should reject the given promise. assert_unreached: Should have rejected: undefined Reached unreachable code
     19PASS Importing a script that has a syntax error should reject the given promise.
     20PASS Importing a nested script that has a syntax error should reject the given promise.
     21PASS Importing a script that imports an invalid identifier should reject the given promise.
    2222
  • trunk/LayoutTests/imported/w3c/web-platform-tests/worklets/audio-worklet-referrer.https-expected.txt

    r270016 r273203  
     1CONSOLE MESSAGE: Origin https://localhost:9443 is not allowed by Access-Control-Allow-Origin.
     2Blocked access to external URL https://www1.localhost:9443/worklets/resources/referrer-checker.py?referrer_policy=no-referrer&expected_referrer=
     3Blocked access to external URL https://www1.localhost:9443/worklets/resources/referrer-checker.py?referrer_policy=origin&expected_referrer=https://localhost:9443/
     4CONSOLE MESSAGE: Origin https://localhost:9443 is not allowed by Access-Control-Allow-Origin.
     5Blocked access to external URL https://www1.localhost:9443/worklets/resources/referrer-checker.py?referrer_policy=same-origin&expected_referrer=
     6CONSOLE MESSAGE: Origin https://localhost:9443 is not allowed by Access-Control-Allow-Origin.
    17
    28PASS Importing a same-origin script from a page that has "no-referrer" referrer policy should not send referrer.
    39PASS Importing a remote-origin script from a page that has "no-referrer" referrer policy should not send referrer.
    4 PASS Importing a same-origin script from a page that has "origin" referrer policy should send only an origin as referrer.
    5 PASS Importing a remote-origin script from a page that has "origin" referrer policy should send only an origin as referrer.
    6 PASS Importing a same-origin script from a page that has "same-origin" referrer policy should send referrer.
     10FAIL Importing a same-origin script from a page that has "origin" referrer policy should send only an origin as referrer. assert_equals: expected "RESOLVED" but got "Importing a module script failed."
     11FAIL Importing a remote-origin script from a page that has "origin" referrer policy should send only an origin as referrer. assert_equals: expected "RESOLVED" but got "Cross-origin script load denied by Cross-Origin Resource Sharing policy."
     12FAIL Importing a same-origin script from a page that has "same-origin" referrer policy should send referrer. assert_equals: expected "RESOLVED" but got "Importing a module script failed."
    713PASS Importing a remote-origin script from a page that has "same-origin" referrer policy should not send referrer.
    814PASS Importing a same-origin script from a same-origin worklet script that has "no-referrer" referrer policy should not send referrer.
    9 PASS Importing a remote-origin script from a same-origin worklet script that has "no-referrer" referrer policy should not send referrer.
     15FAIL Importing a remote-origin script from a same-origin worklet script that has "no-referrer" referrer policy should not send referrer. assert_equals: expected "RESOLVED" but got "Cross-origin script load denied by Cross-Origin Resource Sharing policy."
    1016PASS Importing a same-origin script from a remote-origin worklet script that has "no-referrer" referrer policy should not send referrer.
    1117PASS Importing a remote-origin script from a remote-origin worklet script that has "no-referrer" referrer policy should not send referrer.
    1218PASS Importing a same-origin script from a same-origin worklet script that has "origin" referrer policy should send referrer.
    13 PASS Importing a remote-origin script from a same-origin worklet script that has "origin" referrer policy should send referrer.
    14 PASS Importing a same-origin script from a remote-origin worklet script that has "origin" referrer policy should send referrer.
    15 PASS Importing a remote-origin script from a remote-origin worklet script that has "origin" referrer policy should send referrer.
    16 PASS Importing a same-origin script from a same-origin worklet script that has "same-origin" referrer policy should send referrer.
    17 PASS Importing a remote-origin script from a same-origin worklet script that has "same-origin" referrer policy should not send referrer.
    18 PASS Importing a same-origin script from a remote-origin worklet script that has "same-origin" referrer policy should not send referrer.
    19 PASS Importing a remote-origin script from a remote-origin worklet script that has "same-origin" referrer policy should send referrer.
     19FAIL Importing a remote-origin script from a same-origin worklet script that has "origin" referrer policy should send referrer. assert_equals: expected "RESOLVED" but got "Cross-origin script load denied by Cross-Origin Resource Sharing policy."
     20FAIL Importing a same-origin script from a remote-origin worklet script that has "origin" referrer policy should send referrer. assert_equals: expected "RESOLVED" but got "Importing a module script failed."
     21FAIL Importing a remote-origin script from a remote-origin worklet script that has "origin" referrer policy should send referrer. assert_equals: expected "RESOLVED" but got "Cross-origin script load denied by Cross-Origin Resource Sharing policy."
     22FAIL Importing a same-origin script from a same-origin worklet script that has "same-origin" referrer policy should send referrer. assert_equals: expected "RESOLVED" but got "Importing a module script failed."
     23FAIL Importing a remote-origin script from a same-origin worklet script that has "same-origin" referrer policy should not send referrer. assert_equals: expected "RESOLVED" but got "Cross-origin script load denied by Cross-Origin Resource Sharing policy."
     24FAIL Importing a same-origin script from a remote-origin worklet script that has "same-origin" referrer policy should not send referrer. assert_equals: expected "RESOLVED" but got "Importing a module script failed."
     25FAIL Importing a remote-origin script from a remote-origin worklet script that has "same-origin" referrer policy should send referrer. assert_equals: expected "RESOLVED" but got "Cross-origin script load denied by Cross-Origin Resource Sharing policy."
    2026
  • trunk/LayoutTests/imported/w3c/web-platform-tests/xhr/open-url-redirected-worker-origin-expected.txt

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

    r270033 r273203  
    55
    66PASS context.audioWorklet.addModule(invalidURL); rejected promise  with SyntaxError: Module URL is invalid.
    7 PASS context.audioWorklet.addModule('doesnotExist.js'); rejected promise  with AbortError: Failed to fetch module, error: The requested URL was not found on this server..
     7PASS context.audioWorklet.addModule('doesnotExist.js'); rejected promise  with AbortError: Importing a module script failed..
    88PASS successfullyParsed is true
    99
  • trunk/LayoutTests/webaudio/worklet-crash-expected.txt

    r270056 r273203  
     1CONSOLE MESSAGE: TypeError: 'text/html' is not a valid JavaScript MIME type.
    12This test passes if it does not crash.
  • trunk/Source/JavaScriptCore/ChangeLog

    r273194 r273203  
     12021-02-19  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 Saam Barati.
     7
     8        Add error information to extract this in WebCore's module loader.
     9        Currently, we are using Promise pipeline, and this makes it a bit difficult to extract error information.
     10        This error information attached in this patch allows us to extract SyntaxError in WebCore, and throwing
     11        JS SyntaxError instead of AbortError.
     12
     13        We are planning to update our module pipieline not using Promises in the future. The current design derived
     14        from the original module loader pipeline where using Promises is critical. But now, that proposal was abandoned,
     15        so we can just simplify the module loader.
     16
     17        * runtime/AggregateError.cpp:
     18        (JSC::AggregateError::AggregateError):
     19        * runtime/Error.cpp:
     20        (JSC::createError):
     21        (JSC::createEvalError):
     22        (JSC::createRangeError):
     23        (JSC::createReferenceError):
     24        (JSC::createSyntaxError):
     25        (JSC::createTypeError):
     26        (JSC::createURIError):
     27        (JSC::createGetterTypeError):
     28        (JSC::throwSyntaxError):
     29        * runtime/Error.h:
     30        * runtime/ErrorConstructor.cpp:
     31        (JSC::JSC_DEFINE_HOST_FUNCTION):
     32        * runtime/ErrorInstance.cpp:
     33        (JSC::ErrorInstance::ErrorInstance):
     34        (JSC::ErrorInstance::create):
     35        (JSC::ErrorInstance::sanitizedMessageString):
     36        (JSC::ErrorInstance::sanitizedNameString):
     37        (JSC::ErrorInstance::sanitizedToString):
     38        * runtime/ErrorInstance.h:
     39        (JSC::ErrorInstance::create):
     40        (JSC::ErrorInstance::errorType const):
     41        * runtime/JSGlobalObjectFunctions.cpp:
     42        (JSC::JSC_DEFINE_HOST_FUNCTION):
     43        * runtime/NativeErrorConstructor.cpp:
     44        (JSC::NativeErrorConstructor<errorType>::constructImpl):
     45        (JSC::NativeErrorConstructor<errorType>::callImpl):
     46        * runtime/NullSetterFunction.cpp:
     47        (JSC::NullSetterFunctionInternal::JSC_DEFINE_HOST_FUNCTION):
     48        * wasm/js/JSWebAssemblyCompileError.cpp:
     49        (JSC::JSWebAssemblyCompileError::JSWebAssemblyCompileError):
     50        * wasm/js/JSWebAssemblyLinkError.cpp:
     51        (JSC::JSWebAssemblyLinkError::JSWebAssemblyLinkError):
     52        * wasm/js/JSWebAssemblyRuntimeError.cpp:
     53        (JSC::JSWebAssemblyRuntimeError::JSWebAssemblyRuntimeError):
     54        * wasm/js/WebAssemblyCompileErrorConstructor.cpp:
     55        (JSC::JSC_DEFINE_HOST_FUNCTION):
     56        * wasm/js/WebAssemblyLinkErrorConstructor.cpp:
     57        (JSC::JSC_DEFINE_HOST_FUNCTION):
     58        * wasm/js/WebAssemblyRuntimeErrorConstructor.cpp:
     59        (JSC::JSC_DEFINE_HOST_FUNCTION):
     60
    1612021-02-19  Chris Dumez  <cdumez@apple.com>
    262
  • trunk/Source/JavaScriptCore/runtime/AggregateError.cpp

    r263006 r273203  
    3737
    3838AggregateError::AggregateError(VM& vm, Structure* structure)
    39     : Base(vm, structure)
     39    : Base(vm, structure, ErrorType::AggregateError)
    4040{
    4141}
  • trunk/Source/JavaScriptCore/runtime/Error.cpp

    r264304 r273203  
    3636{
    3737    ASSERT(!message.isEmpty());
    38     return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(), message, appender, TypeNothing, true);
     38    return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(), message, appender, TypeNothing, ErrorType::Error, true);
    3939}
    4040
     
    4242{
    4343    ASSERT(!message.isEmpty());
    44     return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::EvalError), message, appender, TypeNothing, true);
     44    return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::EvalError), message, appender, TypeNothing, ErrorType::EvalError, true);
    4545}
    4646
     
    4848{
    4949    ASSERT(!message.isEmpty());
    50     return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::RangeError), message, appender, TypeNothing, true);
     50    return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::RangeError), message, appender, TypeNothing, ErrorType::RangeError, true);
    5151}
    5252
     
    5454{
    5555    ASSERT(!message.isEmpty());
    56     return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::ReferenceError), message, appender, TypeNothing, true);
     56    return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::ReferenceError), message, appender, TypeNothing, ErrorType::ReferenceError, true);
    5757}
    5858
     
    6060{
    6161    ASSERT(!message.isEmpty());
    62     return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::SyntaxError), message, appender, TypeNothing, true);
     62    return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::SyntaxError), message, appender, TypeNothing, ErrorType::SyntaxError, true);
    6363}
    6464
     
    6666{
    6767    ASSERT(!message.isEmpty());
    68     return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::TypeError), message, appender, type, true);
     68    return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::TypeError), message, appender, type, ErrorType::TypeError, true);
    6969}
    7070
     
    7777{
    7878    ASSERT(!message.isEmpty());
    79     return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::URIError), message, appender, TypeNothing, true);
     79    return ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::URIError), message, appender, TypeNothing, ErrorType::URIError, true);
    8080}
    8181
     
    114114{
    115115    ASSERT(!message.isEmpty());
    116     auto* error = ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::TypeError), message);
     116    auto* error = ErrorInstance::create(globalObject, globalObject->vm(), globalObject->errorStructure(ErrorType::TypeError), message, nullptr, TypeNothing, ErrorType::TypeError);
    117117    error->setNativeGetterTypeError();
    118118    return error;
     
    275275Exception* throwSyntaxError(JSGlobalObject* globalObject, ThrowScope& scope)
    276276{
    277     return throwException(globalObject, scope, createSyntaxError(globalObject, "Syntax error"_s));
     277    return throwException(globalObject, scope, createSyntaxError(globalObject));
    278278}
    279279
     
    316316{
    317317    return createSyntaxError(globalObject, message, nullptr);
     318}
     319
     320JSObject* createSyntaxError(JSGlobalObject* globalObject)
     321{
     322    return createSyntaxError(globalObject, "Syntax error"_s, nullptr);
    318323}
    319324
  • trunk/Source/JavaScriptCore/runtime/Error.h

    r261780 r273203  
    5656JS_EXPORT_PRIVATE JSObject* createReferenceError(JSGlobalObject*, const String&);
    5757JS_EXPORT_PRIVATE JSObject* createSyntaxError(JSGlobalObject*, const String&);
     58JS_EXPORT_PRIVATE JSObject* createSyntaxError(JSGlobalObject*);
    5859JS_EXPORT_PRIVATE JSObject* createTypeError(JSGlobalObject*);
    5960JS_EXPORT_PRIVATE JSObject* createTypeError(JSGlobalObject*, const String&);
  • trunk/Source/JavaScriptCore/runtime/ErrorConstructor.cpp

    r267594 r273203  
    6161    RETURN_IF_EXCEPTION(scope, { });
    6262
    63     RELEASE_AND_RETURN(scope, JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false)));
     63    RELEASE_AND_RETURN(scope, JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, ErrorType::Error, false)));
    6464}
    6565
     
    6868    JSValue message = callFrame->argument(0);
    6969    Structure* errorStructure = globalObject->errorStructure();
    70     return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false));
     70    return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, ErrorType::Error, false));
    7171}
    7272
  • trunk/Source/JavaScriptCore/runtime/ErrorInstance.cpp

    r271269 r273203  
    3535const ClassInfo ErrorInstance::s_info = { "Error", &JSNonFinalObject::s_info, nullptr, nullptr, CREATE_METHOD_TABLE(ErrorInstance) };
    3636
    37 ErrorInstance::ErrorInstance(VM& vm, Structure* structure)
     37ErrorInstance::ErrorInstance(VM& vm, Structure* structure, ErrorType errorType)
    3838    : Base(vm, structure)
    39 {
    40 }
    41 
    42 ErrorInstance* ErrorInstance::create(JSGlobalObject* globalObject, Structure* structure, JSValue message, SourceAppender appender, RuntimeType type, bool useCurrentFrame)
     39    , m_errorType(errorType)
     40    , m_stackOverflowError(false)
     41    , m_outOfMemoryError(false)
     42    , m_errorInfoMaterialized(false)
     43    , m_nativeGetterTypeError(false)
     44{
     45}
     46
     47ErrorInstance* ErrorInstance::create(JSGlobalObject* globalObject, Structure* structure, JSValue message, SourceAppender appender, RuntimeType type, ErrorType errorType, bool useCurrentFrame)
    4348{
    4449    VM& vm = globalObject->vm();
     
    4651    String messageString = message.isUndefined() ? String() : message.toWTFString(globalObject);
    4752    RETURN_IF_EXCEPTION(scope, nullptr);
    48     return create(globalObject, vm, structure, messageString, appender, type, useCurrentFrame);
     53    return create(globalObject, vm, structure, messageString, appender, type, errorType, useCurrentFrame);
    4954}
    5055
     
    132137// have no observable side effects to the user (i.e. does not call proxies,
    133138// and getters).
    134 String ErrorInstance::sanitizedToString(JSGlobalObject* globalObject)
     139String ErrorInstance::sanitizedMessageString(JSGlobalObject* globalObject)
     140{
     141    VM& vm = globalObject->vm();
     142    auto scope = DECLARE_THROW_SCOPE(vm);
     143    Integrity::auditStructureID(vm, structureID());
     144
     145    JSValue messageValue;
     146    auto messagePropertName = vm.propertyNames->message;
     147    PropertySlot messageSlot(this, PropertySlot::InternalMethodType::VMInquiry, &vm);
     148    if (JSObject::getOwnPropertySlot(this, globalObject, messagePropertName, messageSlot) && messageSlot.isValue())
     149        messageValue = messageSlot.getValue(globalObject, messagePropertName);
     150    scope.assertNoException();
     151
     152    if (!messageValue)
     153        return String();
     154    RELEASE_AND_RETURN(scope, messageValue.toWTFString(globalObject));
     155}
     156
     157String ErrorInstance::sanitizedNameString(JSGlobalObject* globalObject)
    135158{
    136159    VM& vm = globalObject->vm();
     
    158181    scope.assertNoException();
    159182
    160     String nameString;
    161183    if (!nameValue)
    162         nameString = "Error"_s;
    163     else {
    164         nameString = nameValue.toWTFString(globalObject);
    165         RETURN_IF_EXCEPTION(scope, String());
    166     }
    167 
    168     JSValue messageValue;
    169     auto messagePropertName = vm.propertyNames->message;
    170     PropertySlot messageSlot(this, PropertySlot::InternalMethodType::VMInquiry, &vm);
    171     if (JSObject::getOwnPropertySlot(this, globalObject, messagePropertName, messageSlot) && messageSlot.isValue())
    172         messageValue = messageSlot.getValue(globalObject, messagePropertName);
    173     scope.assertNoException();
    174 
    175     String messageString;
    176     if (!messageValue)
    177         messageString = String();
    178     else {
    179         messageString = messageValue.toWTFString(globalObject);
    180         RETURN_IF_EXCEPTION(scope, String());
    181     }
     184        return "Error"_s;
     185    RELEASE_AND_RETURN(scope, nameValue.toWTFString(globalObject));
     186}
     187
     188String ErrorInstance::sanitizedToString(JSGlobalObject* globalObject)
     189{
     190    VM& vm = globalObject->vm();
     191    auto scope = DECLARE_THROW_SCOPE(vm);
     192    Integrity::auditStructureID(vm, structureID());
     193
     194    String nameString = sanitizedNameString(globalObject);
     195    RETURN_IF_EXCEPTION(scope, String());
     196
     197    String messageString = sanitizedMessageString(globalObject);
     198    RETURN_IF_EXCEPTION(scope, String());
    182199
    183200    if (!nameString.length())
  • trunk/Source/JavaScriptCore/runtime/ErrorInstance.h

    r271269 r273203  
    2121#pragma once
    2222
     23#include "ErrorType.h"
    2324#include "JSObject.h"
    2425#include "RuntimeType.h"
     
    5455    }
    5556
    56     static ErrorInstance* create(JSGlobalObject* globalObject, VM& vm, Structure* structure, const String& message, SourceAppender appender = nullptr, RuntimeType type = TypeNothing, bool useCurrentFrame = true)
     57    static ErrorInstance* create(JSGlobalObject* globalObject, VM& vm, Structure* structure, const String& message, SourceAppender appender = nullptr, RuntimeType type = TypeNothing, ErrorType errorType = ErrorType::Error, bool useCurrentFrame = true)
    5758    {
    58         ErrorInstance* instance = new (NotNull, allocateCell<ErrorInstance>(vm.heap)) ErrorInstance(vm, structure);
     59        ErrorInstance* instance = new (NotNull, allocateCell<ErrorInstance>(vm.heap)) ErrorInstance(vm, structure, errorType);
    5960        instance->finishCreation(vm, globalObject, message, appender, type, useCurrentFrame);
    6061        return instance;
    6162    }
    6263
    63     static ErrorInstance* create(JSGlobalObject*, Structure*, JSValue message, SourceAppender = nullptr, RuntimeType = TypeNothing, bool useCurrentFrame = true);
     64    static ErrorInstance* create(JSGlobalObject*, Structure*, JSValue message, SourceAppender = nullptr, RuntimeType = TypeNothing, ErrorType = ErrorType::Error, bool useCurrentFrame = true);
    6465
    6566    bool hasSourceAppender() const { return !!m_sourceAppender; }
     
    7172    void clearRuntimeTypeForCause() { m_runtimeTypeForCause = TypeNothing; }
    7273
     74    ErrorType errorType() const { return m_errorType; }
    7375    void setStackOverflowError() { m_stackOverflowError = true; }
    7476    bool isStackOverflowError() const { return m_stackOverflowError; }
     
    8082
    8183    JS_EXPORT_PRIVATE String sanitizedToString(JSGlobalObject*);
     84    JS_EXPORT_PRIVATE String sanitizedMessageString(JSGlobalObject*);
     85    JS_EXPORT_PRIVATE String sanitizedNameString(JSGlobalObject*);
    8286   
    8387    Vector<StackFrame>* stackTrace() { return m_stackTrace.get(); }
     
    8993
    9094protected:
    91     explicit ErrorInstance(VM&, Structure*);
     95    explicit ErrorInstance(VM&, Structure*, ErrorType);
    9296
    9397    void finishCreation(VM&, JSGlobalObject*, const String&, SourceAppender = nullptr, RuntimeType = TypeNothing, bool useCurrentFrame = true);
     
    109113    String m_stackString;
    110114    RuntimeType m_runtimeTypeForCause { TypeNothing };
    111     bool m_stackOverflowError { false };
    112     bool m_outOfMemoryError { false };
    113     bool m_errorInfoMaterialized { false };
    114     bool m_nativeGetterTypeError { false };
     115    ErrorType m_errorType { ErrorType::Error };
     116    bool m_stackOverflowError : 1;
     117    bool m_outOfMemoryError : 1;
     118    bool m_errorInfoMaterialized : 1;
     119    bool m_nativeGetterTypeError : 1;
    115120};
    116121
  • trunk/Source/JavaScriptCore/runtime/JSGlobalObjectFunctions.cpp

    r273135 r273203  
    696696{
    697697    Structure* errorStructure = globalObject->errorStructure(ErrorType::TypeError);
    698     return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, callFrame->argument(0), nullptr, TypeNothing, false));
     698    return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, callFrame->argument(0), nullptr, TypeNothing, ErrorType::TypeError, false));
    699699}
    700700
  • trunk/Source/JavaScriptCore/runtime/NativeErrorConstructor.cpp

    r267594 r273203  
    5959    ASSERT(errorStructure);
    6060
    61     RELEASE_AND_RETURN(scope, JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false)));
     61    RELEASE_AND_RETURN(scope, JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, errorType, false)));
    6262}
    6363
     
    6767    JSValue message = callFrame->argument(0);
    6868    Structure* errorStructure = globalObject->errorStructure(errorType);
    69     return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false));
     69    return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, errorType, false));
    7070}
    7171
  • trunk/Source/JavaScriptCore/runtime/NullSetterFunction.cpp

    r267594 r273203  
    9595    // This function is only called from IC. And we do not want to include this frame in Error's stack.
    9696    constexpr bool useCurrentFrame = false;
    97     throwException(globalObject, scope, ErrorInstance::create(globalObject, vm, globalObject->errorStructure(ErrorType::TypeError), ReadonlyPropertyWriteError, nullptr, TypeNothing, useCurrentFrame));
     97    throwException(globalObject, scope, ErrorInstance::create(globalObject, vm, globalObject->errorStructure(ErrorType::TypeError), ReadonlyPropertyWriteError, nullptr, TypeNothing, ErrorType::TypeError, useCurrentFrame));
    9898    return { };
    9999}
  • trunk/Source/JavaScriptCore/wasm/js/JSWebAssemblyCompileError.cpp

    r261755 r273203  
    4242
    4343JSWebAssemblyCompileError::JSWebAssemblyCompileError(VM& vm, Structure* structure)
    44     : Base(vm, structure)
     44    : Base(vm, structure, ErrorType::Error)
    4545{
    4646}
  • trunk/Source/JavaScriptCore/wasm/js/JSWebAssemblyLinkError.cpp

    r261755 r273203  
    4242
    4343JSWebAssemblyLinkError::JSWebAssemblyLinkError(VM& vm, Structure* structure)
    44     : Base(vm, structure)
     44    : Base(vm, structure, ErrorType::Error)
    4545{
    4646}
  • trunk/Source/JavaScriptCore/wasm/js/JSWebAssemblyRuntimeError.cpp

    r261755 r273203  
    4242
    4343JSWebAssemblyRuntimeError::JSWebAssemblyRuntimeError(VM& vm, Structure* structure)
    44     : Base(vm, structure)
     44    : Base(vm, structure, ErrorType::Error)
    4545{
    4646}
  • trunk/Source/JavaScriptCore/wasm/js/WebAssemblyCompileErrorConstructor.cpp

    r267594 r273203  
    6666    JSValue message = callFrame->argument(0);
    6767    Structure* errorStructure = globalObject->webAssemblyCompileErrorStructure();
    68     return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false));
     68    return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, ErrorType::Error, false));
    6969}
    7070
  • trunk/Source/JavaScriptCore/wasm/js/WebAssemblyLinkErrorConstructor.cpp

    r267594 r273203  
    6666    JSValue message = callFrame->argument(0);
    6767    Structure* errorStructure = globalObject->webAssemblyLinkErrorStructure();
    68     return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false));
     68    return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, ErrorType::Error, false));
    6969}
    7070
  • trunk/Source/JavaScriptCore/wasm/js/WebAssemblyRuntimeErrorConstructor.cpp

    r267594 r273203  
    6868    JSValue message = callFrame->argument(0);
    6969    Structure* errorStructure = globalObject->webAssemblyRuntimeErrorStructure();
    70     return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, false));
     70    return JSValue::encode(ErrorInstance::create(globalObject, errorStructure, message, nullptr, TypeNothing, ErrorType::Error, false));
    7171}
    7272
  • trunk/Source/WebCore/ChangeLog

    r273198 r273203  
     12021-02-19  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 Saam Barati.
     7
     8        This patch implements JS modules in Workers and Worklets. We are not supporting modules in ServiceWorkers' initialization yet.
     9        But service-worker can import modules via JS `import()`.
     10
     11        The worker can be executed as a module if we pass, `type: "module"` to worker options. Worklet is executed as modules by default.
     12
     13        1. In Worker, we first fetch the initial code. And then, analyze the dependencies and load subsequent modules.
     14           We iterate run-loop to load all the dependent modules in the module loader. At that time, we annotate run-loop tasks with
     15           special taskMode to iterate tasks with this taskMode. This prevents us from discarding different tasks in this run-loop driving
     16           phase. (e.g. postMessage can be called from the main thread while loading module graph, in that case, we should not discard this
     17           task.)
     18
     19        2. In Worklet, we just request module loading to ScriptModuleLoader, and run it after loading module graph. This is OK since worklet
     20           thread is already running. So we can just request modules and worklet thread automatically drives module loading via run-loop.
     21
     22        * Headers.cmake:
     23        * Modules/webaudio/AudioWorkletGlobalScope.h:
     24        (WebCore::AudioWorkletGlobalScope::currentFrame const): Deleted.
     25        (WebCore::AudioWorkletGlobalScope::sampleRate const): Deleted.
     26        (WebCore::AudioWorkletGlobalScope::currentTime const): Deleted.
     27        * Sources.txt:
     28        * WebCore.xcodeproj/project.pbxproj:
     29        * bindings/js/CachedModuleScriptLoader.cpp:
     30        (WebCore::CachedModuleScriptLoader::create):
     31        (WebCore::CachedModuleScriptLoader::CachedModuleScriptLoader):
     32        (WebCore::CachedModuleScriptLoader::load):
     33        (WebCore::CachedModuleScriptLoader::notifyFinished):
     34        * bindings/js/CachedModuleScriptLoader.h:
     35        * bindings/js/CachedScriptFetcher.cpp:
     36        * bindings/js/JSDOMExceptionHandling.cpp:
     37        (WebCore::retrieveErrorMessageWithoutName):
     38        (WebCore::createDOMException):
     39        * bindings/js/JSDOMExceptionHandling.h:
     40        * bindings/js/JSDOMGlobalObject.cpp:
     41        (WebCore::scriptModuleLoader):
     42        (WebCore::JSDOMGlobalObject::moduleLoaderResolve):
     43        (WebCore::JSDOMGlobalObject::moduleLoaderFetch):
     44        (WebCore::JSDOMGlobalObject::moduleLoaderEvaluate):
     45        (WebCore::JSDOMGlobalObject::moduleLoaderImportModule):
     46        (WebCore::JSDOMGlobalObject::moduleLoaderCreateImportMetaProperties):
     47        * bindings/js/JSDOMGlobalObject.h:
     48        * bindings/js/JSDOMWindowBase.cpp:
     49        (WebCore::JSDOMWindowBase::moduleLoaderResolve): Deleted.
     50        (WebCore::JSDOMWindowBase::moduleLoaderFetch): Deleted.
     51        (WebCore::JSDOMWindowBase::moduleLoaderEvaluate): Deleted.
     52        (WebCore::JSDOMWindowBase::moduleLoaderImportModule): Deleted.
     53        (WebCore::JSDOMWindowBase::moduleLoaderCreateImportMetaProperties): Deleted.
     54        * bindings/js/JSDOMWindowBase.h:
     55        * bindings/js/JSWorkerGlobalScopeBase.cpp:
     56        * bindings/js/JSWorkletGlobalScopeBase.cpp:
     57        * bindings/js/ModuleScriptLoader.h: Copied from Source/WebCore/dom/ModuleFetchParameters.h.
     58        (WebCore::ModuleScriptLoader::clearClient):
     59        (WebCore::ModuleScriptLoader::scriptFetcher):
     60        (WebCore::ModuleScriptLoader::parameters):
     61        (WebCore::ModuleScriptLoader::ModuleScriptLoader):
     62        * bindings/js/ModuleScriptLoaderClient.h: Renamed from Source/WebCore/bindings/js/CachedModuleScriptLoaderClient.h.
     63        * bindings/js/ScriptModuleLoader.cpp:
     64        (WebCore::ScriptModuleLoader::ScriptModuleLoader):
     65        (WebCore::resolveModuleSpecifier):
     66        (WebCore::ScriptModuleLoader::resolve):
     67        (WebCore::ScriptModuleLoader::fetch):
     68        (WebCore::ScriptModuleLoader::moduleURL):
     69        (WebCore::ScriptModuleLoader::responseURLFromRequestURL):
     70        (WebCore::ScriptModuleLoader::evaluate):
     71        (WebCore::ScriptModuleLoader::importModule):
     72        (WebCore::ScriptModuleLoader::notifyFinished):
     73        * bindings/js/ScriptModuleLoader.h:
     74        * bindings/js/ScriptSourceCode.h:
     75        (WebCore::ScriptSourceCode::ScriptSourceCode):
     76        * bindings/js/WorkerModuleScriptLoader.cpp: Added.
     77        (WebCore::WorkerModuleScriptLoader::create):
     78        (WebCore::WorkerModuleScriptLoader::WorkerModuleScriptLoader):
     79        (WebCore::WorkerModuleScriptLoader::~WorkerModuleScriptLoader):
     80        (WebCore::WorkerModuleScriptLoader::load):
     81        (WebCore::WorkerModuleScriptLoader::referrerPolicy):
     82        (WebCore::WorkerModuleScriptLoader::notifyFinished):
     83        (WebCore::WorkerModuleScriptLoader::taskMode):
     84        * bindings/js/WorkerModuleScriptLoader.h: Copied from Source/WebCore/dom/ModuleFetchParameters.h.
     85        * bindings/js/WorkerScriptFetcher.h: Added.
     86        * dom/Document.cpp:
     87        * dom/ExceptionCode.h:
     88        * dom/LoadableModuleScript.cpp:
     89        (WebCore::LoadableModuleScript::LoadableModuleScript):
     90        (WebCore::LoadableModuleScript::load): Deleted.
     91        * dom/LoadableModuleScript.h:
     92        * dom/ModuleFetchParameters.h:
     93        (WebCore::ModuleFetchParameters::create):
     94        (WebCore::ModuleFetchParameters::isTopLevelModule const):
     95        (WebCore::ModuleFetchParameters::ModuleFetchParameters):
     96        * dom/ScriptElement.cpp:
     97        (WebCore::ScriptElement::requestModuleScript):
     98        * loader/ThreadableLoader.cpp:
     99        (WebCore::ThreadableLoader::create):
     100        * loader/ThreadableLoader.h:
     101        (WebCore::ThreadableLoader::create):
     102        * workers/DedicatedWorkerGlobalScope.h:
     103        * workers/Worker.cpp:
     104        (WebCore::Worker::Worker):
     105        (WebCore::Worker::create):
     106        (WebCore::Worker::notifyFinished):
     107        * workers/Worker.h:
     108        * workers/Worker.idl:
     109        * workers/WorkerGlobalScope.cpp:
     110        (WebCore::WorkerGlobalScope::WorkerGlobalScope):
     111        (WebCore::WorkerGlobalScope::importScripts):
     112        * workers/WorkerGlobalScope.h:
     113        (WebCore::WorkerGlobalScope::credentials const):
     114        * workers/WorkerGlobalScopeProxy.h:
     115        * workers/WorkerMessagingProxy.cpp:
     116        (WebCore::WorkerMessagingProxy::startWorkerGlobalScope):
     117        * workers/WorkerMessagingProxy.h:
     118        * workers/WorkerOrWorkletGlobalScope.cpp:
     119        (WebCore::WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope):
     120        * workers/WorkerOrWorkletGlobalScope.h:
     121        (WebCore::WorkerOrWorkletGlobalScope::moduleLoader):
     122        * workers/WorkerOrWorkletScriptController.cpp:
     123        (WebCore::jsValueToModuleKey):
     124        (WebCore::WorkerOrWorkletScriptController::evaluateModule):
     125        (WebCore::WorkerOrWorkletScriptController::loadModuleSynchronously):
     126        (WebCore::WorkerOrWorkletScriptController::linkAndEvaluateModule):
     127        (WebCore::WorkerOrWorkletScriptController::loadAndEvaluateModule):
     128        * workers/WorkerOrWorkletScriptController.h:
     129        * workers/WorkerScriptLoader.cpp:
     130        (WebCore::WorkerScriptLoader::loadAsynchronously):
     131        (WebCore::WorkerScriptLoader::didReceiveResponse):
     132        * workers/WorkerScriptLoader.h:
     133        (WebCore::WorkerScriptLoader::responseSource const):
     134        (WebCore::WorkerScriptLoader::isRedirected const):
     135        * workers/WorkerThread.cpp:
     136        (WebCore::WorkerParameters::isolatedCopy const):
     137        (WebCore::WorkerThread::evaluateScriptIfNecessary):
     138        * workers/WorkerThread.h:
     139        * workers/WorkerType.h:
     140        * workers/service/ServiceWorkerContainer.h:
     141        * workers/service/ServiceWorkerGlobalScope.h:
     142        * workers/service/ServiceWorkerJob.cpp:
     143        (WebCore::ServiceWorkerJob::fetchScriptWithContext):
     144        * workers/service/ServiceWorkerRegistrationOptions.h:
     145        * workers/service/context/ServiceWorkerThread.cpp:
     146        (WebCore::ServiceWorkerThread::ServiceWorkerThread):
     147        * workers/service/server/SWServerWorker.h:
     148        * worklets/PaintWorkletGlobalScope.h:
     149        (WebCore::PaintWorkletGlobalScope::paintDefinitionMap): Deleted.
     150        (WebCore::PaintWorkletGlobalScope::paintDefinitionLock): Deleted.
     151        (WebCore::PaintWorkletGlobalScope::~PaintWorkletGlobalScope): Deleted.
     152        * worklets/WorkletGlobalScope.cpp:
     153        (WebCore::WorkletGlobalScope::fetchAndInvokeScript):
     154        (WebCore::WorkletGlobalScope::processNextScriptFetchJobIfNeeded): Deleted.
     155        (WebCore::WorkletGlobalScope::didReceiveResponse): Deleted.
     156        (WebCore::WorkletGlobalScope::notifyFinished): Deleted.
     157        (WebCore::WorkletGlobalScope::didCompleteScriptFetchJob): Deleted.
     158        * worklets/WorkletGlobalScope.h:
     159
    11602021-02-20  Zalan Bujtas  <zalan@apple.com>
    2161
  • trunk/Source/WebCore/Headers.cmake

    r273184 r273203  
    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
     
    289290    bindings/js/WebCoreTypedArrayController.h
    290291    bindings/js/WindowProxy.h
     292    bindings/js/WorkerScriptFetcher.h
    291293
    292294    bridge/Bridge.h
  • trunk/Source/WebCore/Modules/webaudio/AudioWorkletGlobalScope.h

    r272393 r273203  
    4747struct WorkletParameters;
    4848
    49 class AudioWorkletGlobalScope : public WorkletGlobalScope {
     49class AudioWorkletGlobalScope final : public WorkletGlobalScope {
    5050    WTF_MAKE_ISO_ALLOCATED(AudioWorkletGlobalScope);
    5151public:
     
    7070    void handlePostRenderTasks(size_t currentFrame);
    7171
     72    FetchOptions::Destination destination() const final { return FetchOptions::Destination::Audioworklet; }
     73
    7274private:
    7375    AudioWorkletGlobalScope(AudioWorkletThread&, Ref<JSC::VM>&&, const WorkletParameters&);
  • trunk/Source/WebCore/Sources.txt

    r273158 r273203  
    641641bindings/js/WebCoreJSClientData.cpp
    642642bindings/js/WebCoreTypedArrayController.cpp
     643bindings/js/WorkerModuleScriptLoader.cpp
    643644bindings/js/WindowProxy.cpp
    644645bindings/js/WritableStream.cpp
  • trunk/Source/WebCore/WebCore.xcodeproj/project.pbxproj

    r273192 r273203  
    50835083                E30592681E27A3D100D57C98 /* CachedScriptFetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = E30592661E27A3C600D57C98 /* CachedScriptFetcher.h */; settings = {ATTRIBUTES = (Private, ); }; };
    50845084                E307DED01D81E4C700141CAF /* CachedModuleScriptLoader.h in Headers */ = {isa = PBXBuildFile; fileRef = E307DEC71D81E44800141CAF /* CachedModuleScriptLoader.h */; settings = {ATTRIBUTES = (Private, ); }; };
    5085                 E307DED11D81E4CB00141CAF /* CachedModuleScriptLoaderClient.h in Headers */ = {isa = PBXBuildFile; fileRef = E307DEC81D81E44800141CAF /* CachedModuleScriptLoaderClient.h */; settings = {ATTRIBUTES = (Private, ); }; };
    50865085                E307DED51D81E4F200141CAF /* LoadableModuleScript.h in Headers */ = {isa = PBXBuildFile; fileRef = E307DED31D81E4ED00141CAF /* LoadableModuleScript.h */; settings = {ATTRIBUTES = (Private, ); }; };
    50875086                E3150EA71DA7219300194012 /* DOMJITHelpers.h in Headers */ = {isa = PBXBuildFile; fileRef = E3150EA51DA7218D00194012 /* DOMJITHelpers.h */; };
    50885087                E3201C1A1F8E82130076A032 /* ModuleFetchParameters.h in Headers */ = {isa = PBXBuildFile; fileRef = E38D06091F8E811900649CF2 /* ModuleFetchParameters.h */; settings = {ATTRIBUTES = (Private, ); }; };
    50895088                E323CFFA1E5AF6AF00F0B4A0 /* JSDOMConvertPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = E323CFF91E5AF6A500F0B4A0 /* JSDOMConvertPromise.h */; settings = {ATTRIBUTES = (Private, ); }; };
     5089                E3432DE425D377E30058E612 /* WorkerModuleScriptLoader.h in Headers */ = {isa = PBXBuildFile; fileRef = E3432DE025D377E20058E612 /* WorkerModuleScriptLoader.h */; };
     5090                E347E5FA25D4F00000F17A5C /* WorkerScriptFetcher.h in Headers */ = {isa = PBXBuildFile; fileRef = E347E5F825D4F00000F17A5C /* WorkerScriptFetcher.h */; settings = {ATTRIBUTES = (Private, ); }; };
     5091                E35188B425D387CF00A77AF3 /* ModuleScriptLoaderClient.h in Headers */ = {isa = PBXBuildFile; fileRef = E35188B325D387CF00A77AF3 /* ModuleScriptLoaderClient.h */; settings = {ATTRIBUTES = (Private, ); }; };
    50905092                E3565B7B1DC2D6C900217DBD /* JSEventCustom.h in Headers */ = {isa = PBXBuildFile; fileRef = E34EE49F1DC2D57500EAA9D3 /* JSEventCustom.h */; settings = {ATTRIBUTES = (Private, ); }; };
    50915093                E35802B61DC8435D00A9773C /* DOMJITIDLTypeFilter.h in Headers */ = {isa = PBXBuildFile; fileRef = E35802B51DC8435800A9773C /* DOMJITIDLTypeFilter.h */; settings = {ATTRIBUTES = (Private, ); }; };
    50925094                E3582C282527F66900D1B790 /* WebCoreJITOperations.h in Headers */ = {isa = PBXBuildFile; fileRef = E3582C262527F66800D1B790 /* WebCoreJITOperations.h */; settings = {ATTRIBUTES = (Private, ); }; };
    50935095                E35B907F23F60A50000011FF /* LocalizedDeviceModel.h in Headers */ = {isa = PBXBuildFile; fileRef = E35B907C23F60677000011FF /* LocalizedDeviceModel.h */; settings = {ATTRIBUTES = (Private, ); }; };
     5096                E364321C25D37A6700F90E2A /* ModuleScriptLoader.h in Headers */ = {isa = PBXBuildFile; fileRef = E364321A25D37A6600F90E2A /* ModuleScriptLoader.h */; settings = {ATTRIBUTES = (Private, ); }; };
    50945097                E377FE4D1DADE16500CDD025 /* NodeConstants.h in Headers */ = {isa = PBXBuildFile; fileRef = E3D049931DADC04500718F3C /* NodeConstants.h */; settings = {ATTRIBUTES = (Private, ); }; };
    50955098                E37C86501EB63E3F0087C6CA /* JSDOMPromise.h in Headers */ = {isa = PBXBuildFile; fileRef = E37C864F1EB63E2D0087C6CA /* JSDOMPromise.h */; settings = {ATTRIBUTES = (Private, ); }; };
     
    1623716240                E307DEC61D81E44800141CAF /* CachedModuleScriptLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = CachedModuleScriptLoader.cpp; sourceTree = "<group>"; };
    1623816241                E307DEC71D81E44800141CAF /* CachedModuleScriptLoader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CachedModuleScriptLoader.h; sourceTree = "<group>"; };
    16239                 E307DEC81D81E44800141CAF /* CachedModuleScriptLoaderClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CachedModuleScriptLoaderClient.h; sourceTree = "<group>"; };
    1624016242                E307DED21D81E4ED00141CAF /* LoadableModuleScript.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = LoadableModuleScript.cpp; sourceTree = "<group>"; };
    1624116243                E307DED31D81E4ED00141CAF /* LoadableModuleScript.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LoadableModuleScript.h; sourceTree = "<group>"; };
     
    1625016252                E329276622543FDE00308A9A /* DOMRectReadOnly.cpp */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.cpp.cpp; path = DOMRectReadOnly.cpp; sourceTree = "<group>"; };
    1625116253                E334825E1DC93AA0009C9544 /* DOMJITAbstractHeapRepository.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; name = DOMJITAbstractHeapRepository.h; path = DerivedSources/WebCore/DOMJITAbstractHeapRepository.h; sourceTree = BUILT_PRODUCTS_DIR; };
     16254                E3432DE025D377E20058E612 /* WorkerModuleScriptLoader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WorkerModuleScriptLoader.h; sourceTree = "<group>"; };
     16255                E3432DE325D377E30058E612 /* WorkerModuleScriptLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WorkerModuleScriptLoader.cpp; sourceTree = "<group>"; };
     16256                E347E5F825D4F00000F17A5C /* WorkerScriptFetcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WorkerScriptFetcher.h; sourceTree = "<group>"; };
    1625216257                E34EE49F1DC2D57500EAA9D3 /* JSEventCustom.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSEventCustom.h; sourceTree = "<group>"; };
     16258                E35188B325D387CF00A77AF3 /* ModuleScriptLoaderClient.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ModuleScriptLoaderClient.h; sourceTree = "<group>"; };
    1625316259                E35802B51DC8435800A9773C /* DOMJITIDLTypeFilter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DOMJITIDLTypeFilter.h; sourceTree = "<group>"; };
    1625416260                E3582C242527F66800D1B790 /* WebCoreJITOperations.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WebCoreJITOperations.cpp; sourceTree = "<group>"; };
     
    1625616262                E35B907C23F60677000011FF /* LocalizedDeviceModel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = LocalizedDeviceModel.h; sourceTree = "<group>"; };
    1625716263                E35B907E23F60677000011FF /* LocalizedDeviceModel.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = LocalizedDeviceModel.mm; sourceTree = "<group>"; };
     16264                E364321A25D37A6600F90E2A /* ModuleScriptLoader.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ModuleScriptLoader.h; sourceTree = "<group>"; };
    1625816265                E37C864F1EB63E2D0087C6CA /* JSDOMPromise.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSDOMPromise.h; sourceTree = "<group>"; };
    1625916266                E38838941BAD145F00D62EE3 /* ScriptModuleLoader.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ScriptModuleLoader.cpp; sourceTree = "<group>"; };
     
    2707427081                                E307DEC61D81E44800141CAF /* CachedModuleScriptLoader.cpp */,
    2707527082                                E307DEC71D81E44800141CAF /* CachedModuleScriptLoader.h */,
    27076                                 E307DEC81D81E44800141CAF /* CachedModuleScriptLoaderClient.h */,
    2707727083                                E30592651E27A3C600D57C98 /* CachedScriptFetcher.cpp */,
    2707827084                                E30592661E27A3C600D57C98 /* CachedScriptFetcher.h */,
     
    2714827154                                4BDEA32B218033EB0052DFCD /* JSWorkletGlobalScopeBase.h */,
    2714927155                                709A01FD1E3D0BCC006B0D4C /* ModuleFetchFailureKind.h */,
     27156                                E364321A25D37A6600F90E2A /* ModuleScriptLoader.h */,
     27157                                E35188B325D387CF00A77AF3 /* ModuleScriptLoaderClient.h */,
    2715027158                                41B459ED1F55EBC70000F6FD /* ReadableStream.cpp */,
    2715127159                                41B459DA1F4CADB90000F6FD /* ReadableStream.h */,
     
    2717927187                                463521AC2081090E00C28922 /* WindowProxy.cpp */,
    2718027188                                463521AA2081090B00C28922 /* WindowProxy.h */,
     27189                                E3432DE325D377E30058E612 /* WorkerModuleScriptLoader.cpp */,
     27190                                E3432DE025D377E20058E612 /* WorkerModuleScriptLoader.h */,
     27191                                E347E5F825D4F00000F17A5C /* WorkerScriptFetcher.h */,
    2718127192                                41418A0325643E1200363417 /* WritableStream.cpp */,
    2718227193                                41418A0425643E1300363417 /* WritableStream.h */,
     
    3146531476                                319FBD5F15D2F464009640A6 /* CachedImageClient.h in Headers */,
    3146631477                                E307DED01D81E4C700141CAF /* CachedModuleScriptLoader.h in Headers */,
    31467                                 E307DED11D81E4CB00141CAF /* CachedModuleScriptLoaderClient.h in Headers */,
    3146831478                                510184690B08602A004A825F /* CachedPage.h in Headers */,
    3146931479                                D0EDA775143E303C0028E383 /* CachedRawResource.h in Headers */,
     
    3394633956                                709A01FE1E3D0BDD006B0D4C /* ModuleFetchFailureKind.h in Headers */,
    3394733957                                E3201C1A1F8E82130076A032 /* ModuleFetchParameters.h in Headers */,
     33958                                E364321C25D37A6700F90E2A /* ModuleScriptLoader.h in Headers */,
     33959                                E35188B425D387CF00A77AF3 /* ModuleScriptLoaderClient.h in Headers */,
    3394833960                                F55B3DC61251F12D003EF269 /* MonthInputType.h in Headers */,
    3394933961                                E39628C12395743100658ECD /* MotionManagerClient.h in Headers */,
     
    3559935611                                2E43464D0F546A8200B0F1BA /* WorkerLocation.h in Headers */,
    3560035612                                2E4346500F546A8200B0F1BA /* WorkerMessagingProxy.h in Headers */,
     35613                                E3432DE425D377E30058E612 /* WorkerModuleScriptLoader.h in Headers */,
    3560135614                                E1271A0B0EEEC77A00F61213 /* WorkerNavigator.h in Headers */,
    3560235615                                A5CB05251FB51F3A00089B97 /* WorkerNetworkAgent.h in Headers */,
     
    3560835621                                2E4346530F546A8200B0F1BA /* WorkerRunLoop.h in Headers */,
    3560935622                                A5B81CCF1FAA44DE0037D1E6 /* WorkerRuntimeAgent.h in Headers */,
     35623                                E347E5FA25D4F00000F17A5C /* WorkerScriptFetcher.h in Headers */,
    3561035624                                A7D6B3490F61104500B79FD1 /* WorkerScriptLoader.h in Headers */,
    3561135625                                2EA768040FE7126400AB9C8A /* WorkerScriptLoaderClient.h in Headers */,
  • trunk/Source/WebCore/bindings/js/CachedModuleScriptLoader.cpp

    r261597 r273203  
    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}
     
    6259}
    6360
    64 bool CachedModuleScriptLoader::load(Document& document, const URL& sourceURL)
     61bool CachedModuleScriptLoader::load(Document& document, URL&& sourceURL)
    6562{
     63    ASSERT(m_promise);
    6664    ASSERT(!m_cachedScript);
    6765    String integrity = m_parameters ? m_parameters->integrity() : String { };
    68     m_cachedScript = m_scriptFetcher->requestModuleScript(document, sourceURL, WTFMove(integrity));
     66    m_cachedScript = scriptFetcher().requestModuleScript(document, sourceURL, WTFMove(integrity));
    6967    if (!m_cachedScript)
    7068        return false;
    71     m_sourceURL = sourceURL;
     69    m_sourceURL = WTFMove(sourceURL);
    7270
    7371    // If the content is already cached, this immediately calls notifyFinished.
     
    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
  • trunk/Source/WebCore/bindings/js/CachedModuleScriptLoader.h

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

    r257566 r273203  
    3333#include "Document.h"
    3434#include "Settings.h"
     35#include "WorkerOrWorkletGlobalScope.h"
    3536
    3637namespace WebCore {
  • trunk/Source/WebCore/bindings/js/JSDOMExceptionHandling.cpp

    r264413 r273203  
    5353}
    5454
     55String retrieveErrorMessageWithoutName(JSGlobalObject& lexicalGlobalObject, VM& vm, JSValue exception, CatchScope& catchScope)
     56{
     57    // FIXME: <http://webkit.org/b/115087> Web Inspector: WebCore::reportException should not evaluate JavaScript handling exceptions
     58    // If this is a custom exception object, call toString on it to try and get a nice string representation for the exception.
     59    String errorMessage;
     60    if (auto* error = jsDynamicCast<ErrorInstance*>(vm, exception))
     61        errorMessage = error->sanitizedMessageString(&lexicalGlobalObject);
     62    else if (auto* error = jsDynamicCast<JSDOMException*>(vm, exception))
     63        errorMessage = error->wrapped().message();
     64    else
     65        errorMessage = exception.toWTFString(&lexicalGlobalObject);
     66
     67    // We need to clear any new exception that may be thrown in the toString() call above.
     68    // reportException() is not supposed to be making new exceptions.
     69    catchScope.clearException();
     70    vm.clearLastException();
     71    return errorMessage;
     72}
     73
    5574String retrieveErrorMessage(JSGlobalObject& lexicalGlobalObject, VM& vm, JSValue exception, CatchScope& catchScope)
    5675{
     
    122141JSValue createDOMException(JSGlobalObject* lexicalGlobalObject, ExceptionCode ec, const String& message)
    123142{
    124     if (ec == ExistingExceptionError)
     143    switch (ec) {
     144    case ExistingExceptionError:
    125145        return jsUndefined();
    126146
    127147    // FIXME: Handle other WebIDL exception types.
    128     if (ec == TypeError) {
     148    case TypeError:
    129149        if (message.isEmpty())
    130150            return createTypeError(lexicalGlobalObject);
    131151        return createTypeError(lexicalGlobalObject, message);
    132     }
    133 
    134     if (ec == RangeError) {
     152
     153    case RangeError:
    135154        if (message.isEmpty())
    136155            return createRangeError(lexicalGlobalObject, "Bad value"_s);
    137156        return createRangeError(lexicalGlobalObject, message);
    138     }
    139 
    140     if (ec == StackOverflowError)
     157
     158    case JSSyntaxError:
     159        if (message.isEmpty())
     160            return createSyntaxError(lexicalGlobalObject);
     161        return createSyntaxError(lexicalGlobalObject, message);
     162
     163    case StackOverflowError:
    141164        return createStackOverflowError(lexicalGlobalObject);
    142     if (ec == OutOfMemoryError)
     165
     166    case OutOfMemoryError:
    143167        return createOutOfMemoryError(lexicalGlobalObject);
    144168
    145     // FIXME: All callers to createDOMException need to pass in the correct global object.
    146     // For now, we're going to assume the lexicalGlobalObject. Which is wrong in cases like this:
    147     // frames[0].document.createElement(null, null); // throws an exception which should have the subframe's prototypes.
    148     JSDOMGlobalObject* globalObject = deprecatedGlobalObjectForPrototype(lexicalGlobalObject);
    149     JSValue errorObject = toJS(lexicalGlobalObject, globalObject, DOMException::create(ec, message));
    150    
    151     ASSERT(errorObject);
    152     addErrorInfo(lexicalGlobalObject, asObject(errorObject), true);
    153     return errorObject;
     169    default: {
     170        // FIXME: All callers to createDOMException need to pass in the correct global object.
     171        // For now, we're going to assume the lexicalGlobalObject. Which is wrong in cases like this:
     172        // frames[0].document.createElement(null, null); // throws an exception which should have the subframe's prototypes.
     173        // https://bugs.webkit.org/show_bug.cgi?id=222229
     174        JSDOMGlobalObject* globalObject = deprecatedGlobalObjectForPrototype(lexicalGlobalObject);
     175        JSValue errorObject = toJS(lexicalGlobalObject, globalObject, DOMException::create(ec, message));
     176
     177        ASSERT(errorObject);
     178        addErrorInfo(lexicalGlobalObject, asObject(errorObject), true);
     179        return errorObject;
     180    }
     181    }
     182    return { };
    154183}
    155184
  • trunk/Source/WebCore/bindings/js/JSDOMExceptionHandling.h

    r267007 r273203  
    6666WEBCORE_EXPORT JSC::EncodedJSValue rejectPromiseWithThisTypeError(JSC::JSGlobalObject&, const char* interfaceName, const char* operationName);
    6767
     68String retrieveErrorMessageWithoutName(JSC::JSGlobalObject&, JSC::VM&, JSC::JSValue exception, JSC::CatchScope&);
    6869String retrieveErrorMessage(JSC::JSGlobalObject&, JSC::VM&, JSC::JSValue exception, JSC::CatchScope&);
    6970WEBCORE_EXPORT void reportException(JSC::JSGlobalObject*, JSC::JSValue exception, CachedScript* = nullptr);
  • trunk/Source/WebCore/bindings/js/JSDOMGlobalObject.cpp

    r273138 r273203  
    4848#include "RejectedPromiseTracker.h"
    4949#include "RuntimeEnabledFeatures.h"
     50#include "ScriptModuleLoader.h"
    5051#include "StructuredClone.h"
    5152#include "WebCoreJSClientData.h"
     
    426427#endif
    427428
     429static ScriptModuleLoader* scriptModuleLoader(JSDOMGlobalObject* globalObject)
     430{
     431    VM& vm = globalObject->vm();
     432    if (globalObject->inherits<JSDOMWindowBase>(vm)) {
     433        if (auto document = jsCast<const JSDOMWindowBase*>(globalObject)->wrapped().document())
     434            return &document->moduleLoader();
     435        return nullptr;
     436    }
     437    if (globalObject->inherits<JSRemoteDOMWindowBase>(vm))
     438        return nullptr;
     439    if (globalObject->inherits<JSWorkerGlobalScopeBase>(vm))
     440        return &jsCast<const JSWorkerGlobalScopeBase*>(globalObject)->wrapped().moduleLoader();
     441    if (globalObject->inherits<JSWorkletGlobalScopeBase>(vm))
     442        return &jsCast<const JSWorkletGlobalScopeBase*>(globalObject)->wrapped().moduleLoader();
     443#if ENABLE(INDEXED_DATABASE)
     444    if (globalObject->inherits<JSIDBSerializationGlobalObject>(vm))
     445        return nullptr;
     446#endif
     447    dataLog("Unexpected global object: ", JSValue(globalObject), "\n");
     448    RELEASE_ASSERT_NOT_REACHED();
     449    return nullptr;
     450}
     451
     452JSC::Identifier JSDOMGlobalObject::moduleLoaderResolve(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSValue moduleName, JSC::JSValue importerModuleKey, JSC::JSValue scriptFetcher)
     453{
     454    JSDOMGlobalObject* thisObject = JSC::jsCast<JSDOMGlobalObject*>(globalObject);
     455    if (auto* loader = scriptModuleLoader(thisObject))
     456        return loader->resolve(globalObject, moduleLoader, moduleName, importerModuleKey, scriptFetcher);
     457    return { };
     458}
     459
     460JSC::JSInternalPromise* JSDOMGlobalObject::moduleLoaderFetch(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSValue moduleKey, JSC::JSValue parameters, JSC::JSValue scriptFetcher)
     461{
     462    VM& vm = globalObject->vm();
     463    auto scope = DECLARE_THROW_SCOPE(vm);
     464    JSDOMGlobalObject* thisObject = JSC::jsCast<JSDOMGlobalObject*>(globalObject);
     465    if (auto* loader = scriptModuleLoader(thisObject))
     466        RELEASE_AND_RETURN(scope, loader->fetch(globalObject, moduleLoader, moduleKey, parameters, scriptFetcher));
     467    JSC::JSInternalPromise* promise = JSC::JSInternalPromise::create(vm, globalObject->internalPromiseStructure());
     468    scope.release();
     469    promise->reject(globalObject, jsUndefined());
     470    return promise;
     471}
     472
     473JSC::JSValue JSDOMGlobalObject::moduleLoaderEvaluate(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSValue moduleKey, JSC::JSValue moduleRecord, JSC::JSValue scriptFetcher)
     474{
     475    JSDOMGlobalObject* thisObject = JSC::jsCast<JSDOMGlobalObject*>(globalObject);
     476    if (auto* loader = scriptModuleLoader(thisObject))
     477        return loader->evaluate(globalObject, moduleLoader, moduleKey, moduleRecord, scriptFetcher);
     478    return JSC::jsUndefined();
     479}
     480
     481JSC::JSInternalPromise* JSDOMGlobalObject::moduleLoaderImportModule(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSString* moduleName, JSC::JSValue parameters, const JSC::SourceOrigin& sourceOrigin)
     482{
     483    VM& vm = globalObject->vm();
     484    auto scope = DECLARE_THROW_SCOPE(vm);
     485    JSDOMGlobalObject* thisObject = JSC::jsCast<JSDOMGlobalObject*>(globalObject);
     486    if (auto* loader = scriptModuleLoader(thisObject))
     487        RELEASE_AND_RETURN(scope, loader->importModule(globalObject, moduleLoader, moduleName, parameters, sourceOrigin));
     488    JSC::JSInternalPromise* promise = JSC::JSInternalPromise::create(vm, globalObject->internalPromiseStructure());
     489    scope.release();
     490    promise->reject(globalObject, jsUndefined());
     491    return promise;
     492}
     493
     494JSC::JSObject* JSDOMGlobalObject::moduleLoaderCreateImportMetaProperties(JSC::JSGlobalObject* globalObject, JSC::JSModuleLoader* moduleLoader, JSC::JSValue moduleKey, JSC::JSModuleRecord* moduleRecord, JSC::JSValue scriptFetcher)
     495{
     496    JSDOMGlobalObject* thisObject = JSC::jsCast<JSDOMGlobalObject*>(globalObject);
     497    if (auto* loader = scriptModuleLoader(thisObject))
     498        return loader->createImportMetaProperties(globalObject, moduleLoader, moduleKey, moduleRecord, scriptFetcher);
     499    return constructEmptyObject(globalObject->vm(), globalObject->nullPrototypeObjectStructure());
     500}
     501
    428502JSDOMGlobalObject& callerGlobalObject(JSGlobalObject& lexicalGlobalObject, CallFrame& callFrame)
    429503{
  • trunk/Source/WebCore/bindings/js/JSDOMGlobalObject.h

    r273138 r273203  
    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;
  • trunk/Source/WebCore/bindings/js/JSDOMWindowBase.cpp

    r272174 r273203  
    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
  • trunk/Source/WebCore/bindings/js/JSDOMWindowBase.h

    r272174 r273203  
    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;
  • trunk/Source/WebCore/bindings/js/JSWorkerGlobalScopeBase.cpp

    r273138 r273203  
    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,
  • trunk/Source/WebCore/bindings/js/JSWorkletGlobalScopeBase.cpp

    r273138 r273203  
    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,
  • trunk/Source/WebCore/bindings/js/ModuleScriptLoader.h

    r273202 r273203  
    11/*
    2  * Copyright (C) 2017 Yusuke Suzuki <utatane.tea@gmail.com>
     2 * Copyright (C) 2021 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    2626#pragma once
    2727
    28 #include <JavaScriptCore/ScriptFetchParameters.h>
     28#include "JSDOMPromiseDeferred.h"
     29#include "ModuleFetchParameters.h"
     30#include <JavaScriptCore/ScriptFetcher.h>
     31#include <wtf/RefCounted.h>
    2932
    3033namespace WebCore {
    3134
    32 class ModuleFetchParameters : public JSC::ScriptFetchParameters {
     35class ModuleScriptLoaderClient;
     36
     37class ModuleScriptLoader : public RefCounted<ModuleScriptLoader> {
    3338public:
    34     static Ref<ModuleFetchParameters> create(const String& integrity)
     39    virtual ~ModuleScriptLoader() = default;
     40
     41    void clearClient()
    3542    {
    36         return adoptRef(*new ModuleFetchParameters(integrity));
     43        ASSERT(m_client);
     44        m_client = nullptr;
    3745    }
    3846
    39     const String& integrity() const { return m_integrity; }
     47    JSC::ScriptFetcher& scriptFetcher() { return m_scriptFetcher.get(); }
     48    ModuleFetchParameters* parameters() { return m_parameters.get(); }
    4049
    41 private:
    42     ModuleFetchParameters(const String& integrity)
    43         : m_integrity(integrity)
     50protected:
     51    ModuleScriptLoader(ModuleScriptLoaderClient& client, DeferredPromise& promise, JSC::ScriptFetcher& scriptFetcher, RefPtr<ModuleFetchParameters>&& parameters)
     52        : m_client(&client)
     53        , m_promise(&promise)
     54        , m_scriptFetcher(scriptFetcher)
     55        , m_parameters(WTFMove(parameters))
    4456    {
    4557    }
    4658
    47     String m_integrity;
     59    ModuleScriptLoaderClient* m_client;
     60    RefPtr<DeferredPromise> m_promise;
     61    Ref<JSC::ScriptFetcher> m_scriptFetcher;
     62    RefPtr<ModuleFetchParameters> m_parameters;
    4863};
    4964
  • trunk/Source/WebCore/bindings/js/ModuleScriptLoaderClient.h

    r273202 r273203  
    11/*
    2  * Copyright (C) 2016 Apple, Inc. All Rights Reserved.
     2 * Copyright (C) 2021 Apple, Inc. All Rights Reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    2828namespace WebCore {
    2929
    30 class CachedModuleScriptLoader;
     30class ModuleScriptLoader;
    3131class DeferredPromise;
    3232
    33 class CachedModuleScriptLoaderClient {
     33class ModuleScriptLoaderClient {
    3434public:
    35     virtual ~CachedModuleScriptLoaderClient() = default;
     35    virtual ~ModuleScriptLoaderClient() = default;
    3636
    37     virtual void notifyFinished(CachedModuleScriptLoader&, RefPtr<DeferredPromise>) = 0;
     37    virtual void notifyFinished(ModuleScriptLoader&, URL&&, Ref<DeferredPromise>) = 0;
    3838};
    3939
  • trunk/Source/WebCore/bindings/js/ScriptModuleLoader.cpp

    r264304 r273203  
    3030#include "CachedScript.h"
    3131#include "CachedScriptFetcher.h"
    32 #include "Document.h"
    3332#include "Frame.h"
    3433#include "JSDOMBinding.h"
     
    4241#include "SubresourceIntegrity.h"
    4342#include "WebCoreJSClientData.h"
     43#include "WorkerModuleScriptLoader.h"
     44#include "WorkerScriptFetcher.h"
     45#include "WorkerScriptLoader.h"
    4446#include <JavaScriptCore/Completion.h>
    4547#include <JavaScriptCore/JSInternalPromise.h>
     
    5355namespace WebCore {
    5456
    55 ScriptModuleLoader::ScriptModuleLoader(Document& document)
    56     : m_document(document)
     57ScriptModuleLoader::ScriptModuleLoader(ScriptExecutionContext& context, OwnerType ownerType)
     58    : m_context(context)
     59    , m_ownerType(ownerType)
    5760{
    5861}
     
    6972}
    7073
    71 static Expected<URL, String> resolveModuleSpecifier(Document& document, const String& specifier, const URL& baseURL)
     74static Expected<URL, String> resolveModuleSpecifier(ScriptExecutionContext& context, ScriptModuleLoader::OwnerType ownerType, const String& specifier, const URL& baseURL)
    7275{
    7376    // https://html.spec.whatwg.org/multipage/webappapis.html#resolve-a-module-specifier
     
    8083        return makeUnexpected(makeString("Module specifier, '"_s, specifier, "' does not start with \"/\", \"./\", or \"../\". Referenced from "_s, baseURL.string()));
    8184
    82     auto result = document.completeURL(specifier, baseURL);
     85    URL result;
     86    if (ownerType == ScriptModuleLoader::OwnerType::Document)
     87        result = downcast<Document>(context).completeURL(specifier, baseURL);
     88    else
     89        result = URL(baseURL, specifier);
     90
    8391    if (!result.isValid())
    8492        return makeUnexpected(makeString("Module name, '"_s, result.string(), "' does not resolve to a valid URL."_s));
     
    108116    RETURN_IF_EXCEPTION(scope, { });
    109117
    110     auto result = resolveModuleSpecifier(m_document, specifier, baseURL);
     118    auto result = resolveModuleSpecifier(m_context, m_ownerType, specifier, baseURL);
    111119    if (!result) {
    112120        JSC::throwTypeError(jsGlobalObject, scope, result.error());
     
    162170        topLevelFetchParameters = static_cast<ModuleFetchParameters*>(&scriptFetchParameters->parameters());
    163171
    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;
     172    if (m_ownerType == OwnerType::Document) {
     173        auto loader = CachedModuleScriptLoader::create(*this, deferred.get(), *static_cast<CachedScriptFetcher*>(JSC::jsCast<JSC::JSScriptFetcher*>(scriptFetcher)->fetcher()), WTFMove(topLevelFetchParameters));
     174        m_loaders.add(loader.copyRef());
     175        if (!loader->load(downcast<Document>(m_context), WTFMove(completedURL))) {
     176            loader->clearClient();
     177            m_loaders.remove(WTFMove(loader));
     178            rejectToPropagateNetworkError(deferred.get(), ModuleFetchFailureKind::WasErrored, "Importing a module script failed."_s);
     179            return jsPromise;
     180        }
     181    } else {
     182        auto loader = WorkerModuleScriptLoader::create(*this, deferred.get(), *static_cast<WorkerScriptFetcher*>(JSC::jsCast<JSC::JSScriptFetcher*>(scriptFetcher)->fetcher()), WTFMove(topLevelFetchParameters));
     183        m_loaders.add(loader.copyRef());
     184        loader->load(m_context, WTFMove(completedURL));
    171185    }
    172186
     
    177191{
    178192    if (moduleKeyValue.isSymbol())
    179         return m_document.url();
     193        return m_context.url();
    180194
    181195    ASSERT(moduleKeyValue.isString());
     
    188202    auto scope = DECLARE_THROW_SCOPE(vm);
    189203
    190     if (isRootModule(moduleKeyValue))
    191         return m_document.baseURL();
     204    if (isRootModule(moduleKeyValue)) {
     205        if (m_ownerType == OwnerType::Document)
     206            return downcast<Document>(m_context).baseURL();
     207        return m_context.url();
     208    }
    192209
    193210    ASSERT(!isRootModule(moduleKeyValue));
     
    220237        return JSC::throwTypeError(jsGlobalObject, scope, "Module key is an invalid URL."_s);
    221238
    222     if (auto* frame = m_document.frame())
    223         return frame->script().evaluateModule(sourceURL, *moduleRecord);
     239    if (m_ownerType == OwnerType::Document) {
     240        if (auto* frame = downcast<Document>(m_context).frame())
     241            return frame->script().evaluateModule(sourceURL, *moduleRecord);
     242    } else {
     243        ASSERT(is<WorkerOrWorkletGlobalScope>(m_context));
     244        if (auto* script = downcast<WorkerOrWorkletGlobalScope>(m_context).script())
     245            return script->evaluateModule(*moduleRecord);
     246    }
    224247    return JSC::jsUndefined();
    225248}
     
    249272    RefPtr<JSC::ScriptFetcher> scriptFetcher;
    250273    if (sourceOrigin.isNull()) {
    251         baseURL = m_document.baseURL();
    252         scriptFetcher = CachedScriptFetcher::create(m_document.charset());
     274        if (m_ownerType == OwnerType::Document) {
     275            baseURL = downcast<Document>(m_context).baseURL();
     276            scriptFetcher = CachedScriptFetcher::create(downcast<Document>(m_context).charset());
     277        } else {
     278            // https://html.spec.whatwg.org/multipage/webappapis.html#default-classic-script-fetch-options
     279            baseURL = m_context.url();
     280            scriptFetcher = WorkerScriptFetcher::create(FetchOptions::Credentials::SameOrigin, FetchOptions::Destination::Script, ReferrerPolicy::EmptyString);
     281        }
    253282    } else {
    254283        baseURL = URL(URL(), sourceOrigin.string());
     
    256285            return rejectPromise(globalObject, TypeError, "Importer module key is not a Symbol or a String."_s);
    257286
    258         if (sourceOrigin.fetcher())
     287        if (sourceOrigin.fetcher()) {
    259288            scriptFetcher = sourceOrigin.fetcher();
    260         else
    261             scriptFetcher = CachedScriptFetcher::create(m_document.charset());
     289            // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-an-import()-module-script-graph
     290            // Destination should be "script" for dynamic-import.
     291            if (m_ownerType == OwnerType::WorkerOrWorklet) {
     292                auto& fetcher = static_cast<WorkerScriptFetcher&>(*scriptFetcher);
     293                scriptFetcher = WorkerScriptFetcher::create(fetcher.credentials(), FetchOptions::Destination::Script, fetcher.referrerPolicy());
     294            }
     295        }
     296
     297        if (!scriptFetcher) {
     298            if (m_ownerType == OwnerType::Document)
     299                scriptFetcher = CachedScriptFetcher::create(downcast<Document>(m_context).charset());
     300            else
     301                scriptFetcher = WorkerScriptFetcher::create(FetchOptions::Credentials::SameOrigin, FetchOptions::Destination::Script, ReferrerPolicy::EmptyString);
     302        }
    262303    }
    263304    ASSERT(baseURL.isValid());
     
    265306
    266307    auto specifier = moduleName->value(jsGlobalObject);
    267     auto result = resolveModuleSpecifier(m_document, specifier, baseURL);
     308    auto result = resolveModuleSpecifier(m_context, m_ownerType, specifier, baseURL);
    268309    if (!result)
    269310        return rejectPromise(globalObject, TypeError, result.error());
     
    289330}
    290331
    291 void ScriptModuleLoader::notifyFinished(CachedModuleScriptLoader& loader, RefPtr<DeferredPromise> promise)
     332void ScriptModuleLoader::notifyFinished(ModuleScriptLoader& moduleScriptLoader, URL&& sourceURL, Ref<DeferredPromise> promise)
    292333{
    293334    // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
    294335
    295     URL sourceURL = loader.sourceURL();
    296     if (!m_loaders.remove(&loader))
     336    if (!m_loaders.remove(&moduleScriptLoader))
    297337        return;
    298     loader.clearClient();
    299 
    300     auto& cachedScript = *loader.cachedScript();
    301 
    302     if (cachedScript.resourceError().isAccessControl()) {
    303         promise->reject(TypeError, "Cross-origin script load denied by Cross-Origin Resource Sharing policy."_s);
    304         return;
    305     }
    306 
    307     if (cachedScript.errorOccurred()) {
    308         rejectToPropagateNetworkError(*promise, ModuleFetchFailureKind::WasErrored, "Importing a module script failed."_s);
    309         return;
    310     }
    311 
    312     if (cachedScript.wasCanceled()) {
    313         rejectToPropagateNetworkError(*promise, ModuleFetchFailureKind::WasCanceled, "Importing a module script is canceled."_s);
    314         return;
    315     }
    316 
    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     }
    324 
    325     if (auto* parameters = loader.parameters()) {
    326         if (!matchIntegrityMetadata(cachedScript, parameters->integrity())) {
    327             promise->reject(TypeError, makeString("Cannot load script ", integrityMismatchDescription(cachedScript, parameters->integrity())));
    328             return;
    329         }
    330     }
    331 
    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     }
    341 
    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     });
    347 }
    348 
    349 }
     338    moduleScriptLoader.clearClient();
     339
     340    auto canonicalizeAndRegisterResponseURL = [&] (URL responseURL, bool hasRedirections, ResourceResponse::Source source) {
     341        // 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.
     342        // FIXME: We should track fragments through redirections.
     343        // https://bugs.webkit.org/show_bug.cgi?id=158420
     344        // https://bugs.webkit.org/show_bug.cgi?id=210490
     345        if (!hasRedirections && source != ResourceResponse::Source::ServiceWorker) {
     346            if (sourceURL.hasFragmentIdentifier())
     347                responseURL.setFragmentIdentifier(sourceURL.fragmentIdentifier());
     348        }
     349
     350        m_requestURLToResponseURLMap.add(sourceURL.string(), responseURL);
     351        return responseURL;
     352    };
     353
     354    if (m_ownerType == OwnerType::Document) {
     355        auto& loader = static_cast<CachedModuleScriptLoader&>(moduleScriptLoader);
     356        auto& cachedScript = *loader.cachedScript();
     357
     358        if (cachedScript.resourceError().isAccessControl()) {
     359            rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasErrored, "Cross-origin script load denied by Cross-Origin Resource Sharing policy."_s);
     360            return;
     361        }
     362
     363        if (cachedScript.errorOccurred()) {
     364            rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasErrored, "Importing a module script failed."_s);
     365            return;
     366        }
     367
     368        if (cachedScript.wasCanceled()) {
     369            rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasCanceled, "Importing a module script is canceled."_s);
     370            return;
     371        }
     372
     373        if (!MIMETypeRegistry::isSupportedJavaScriptMIMEType(cachedScript.response().mimeType())) {
     374            // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
     375            // The result of extracting a MIME type from response's header list (ignoring parameters) is not a JavaScript MIME type.
     376            // 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.
     377            promise->reject(TypeError, makeString("'", cachedScript.response().mimeType(), "' is not a valid JavaScript MIME type."));
     378            return;
     379        }
     380
     381        if (auto* parameters = loader.parameters()) {
     382            if (!matchIntegrityMetadata(cachedScript, parameters->integrity())) {
     383                promise->reject(TypeError, makeString("Cannot load script ", integrityMismatchDescription(cachedScript, parameters->integrity())));
     384                return;
     385            }
     386        }
     387
     388        canonicalizeAndRegisterResponseURL(cachedScript.response().url(), cachedScript.hasRedirections(), cachedScript.response().source());
     389        promise->resolveWithCallback([&] (JSDOMGlobalObject& jsGlobalObject) {
     390            return JSC::JSSourceCode::create(jsGlobalObject.vm(),
     391                JSC::SourceCode { ScriptSourceCode { &cachedScript, JSC::SourceProviderSourceType::Module, loader.scriptFetcher() }.jsSourceCode() });
     392        });
     393    } else {
     394        auto& loader = static_cast<WorkerModuleScriptLoader&>(moduleScriptLoader);
     395        auto& workerScriptLoader = loader.scriptLoader();
     396
     397        if (workerScriptLoader.failed()) {
     398            if (workerScriptLoader.error().isAccessControl()) {
     399                rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasErrored, "Cross-origin script load denied by Cross-Origin Resource Sharing policy."_s);
     400                return;
     401            }
     402
     403            if (workerScriptLoader.error().isCancellation()) {
     404                rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasCanceled, "Importing a module script is canceled."_s);
     405                return;
     406            }
     407
     408            rejectToPropagateNetworkError(promise.get(), ModuleFetchFailureKind::WasErrored, "Importing a module script failed."_s);
     409            return;
     410        }
     411
     412        if (!MIMETypeRegistry::isSupportedJavaScriptMIMEType(workerScriptLoader.responseMIMEType())) {
     413            // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
     414            // The result of extracting a MIME type from response's header list (ignoring parameters) is not a JavaScript MIME type.
     415            // 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.
     416            promise->reject(TypeError, makeString("'", workerScriptLoader.responseMIMEType(), "' is not a valid JavaScript MIME type."));
     417            return;
     418        }
     419
     420        if (auto* parameters = loader.parameters()) {
     421            // If this is top-level-module, then we extract referrer-policy and apply to the dependent modules.
     422            if (parameters->isTopLevelModule())
     423                static_cast<WorkerScriptFetcher&>(loader.scriptFetcher()).setReferrerPolicy(loader.referrerPolicy());
     424        }
     425
     426        URL responseURL = canonicalizeAndRegisterResponseURL(workerScriptLoader.responseURL(), workerScriptLoader.isRedirected(), workerScriptLoader.responseSource());
     427        promise->resolveWithCallback([&] (JSDOMGlobalObject& jsGlobalObject) {
     428            return JSC::JSSourceCode::create(jsGlobalObject.vm(),
     429                JSC::SourceCode { ScriptSourceCode { workerScriptLoader.script(), WTFMove(responseURL), { }, JSC::SourceProviderSourceType::Module, loader.scriptFetcher() }.jsSourceCode() });
     430        });
     431    }
     432}
     433
     434}
  • trunk/Source/WebCore/bindings/js/ScriptModuleLoader.h

    r260131 r273203  
    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>
     
    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);
     
    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
  • trunk/Source/WebCore/bindings/js/ScriptSourceCode.h

    r264304 r273203  
    5858    }
    5959
    60     ScriptSourceCode(const String& source, URL&& url, const TextPosition& startPosition, JSC::SourceProviderSourceType sourceType, Ref<CachedScriptFetcher>&& scriptFetcher)
     60    ScriptSourceCode(const String& source, URL&& url, const TextPosition& startPosition, JSC::SourceProviderSourceType sourceType, Ref<JSC::ScriptFetcher>&& scriptFetcher)
    6161        : m_provider(JSC::StringSourceProvider::create(source, JSC::SourceOrigin { url, WTFMove(scriptFetcher) }, url.string(), startPosition, sourceType))
    6262        , m_code(m_provider.copyRef(), startPosition.m_line.oneBasedInt(), startPosition.m_column.oneBasedInt())
  • trunk/Source/WebCore/bindings/js/WorkerModuleScriptLoader.h

    r273202 r273203  
    11/*
    2  * Copyright (C) 2017 Yusuke Suzuki <utatane.tea@gmail.com>
     2 * Copyright (C) 2021 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    2626#pragma once
    2727
    28 #include <JavaScriptCore/ScriptFetchParameters.h>
     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>
    2934
    3035namespace WebCore {
    3136
    32 class ModuleFetchParameters : public JSC::ScriptFetchParameters {
     37class DeferredPromise;
     38class JSDOMGlobalObject;
     39class ModuleFetchParameters;
     40class ScriptExecutionContext;
     41class ModuleScriptLoaderClient;
     42class WorkerScriptLoader;
     43
     44class WorkerModuleScriptLoader final : public ModuleScriptLoader, private WorkerScriptLoaderClient {
    3345public:
    34     static Ref<ModuleFetchParameters> create(const String& integrity)
    35     {
    36         return adoptRef(*new ModuleFetchParameters(integrity));
    37     }
     46    static Ref<WorkerModuleScriptLoader> create(ModuleScriptLoaderClient&, DeferredPromise&, WorkerScriptFetcher&, RefPtr<ModuleFetchParameters>&&);
    3847
    39     const String& integrity() const { return m_integrity; }
     48    virtual ~WorkerModuleScriptLoader();
     49
     50    bool load(ScriptExecutionContext&, URL&& sourceURL);
     51
     52    WorkerScriptLoader& scriptLoader() { return m_scriptLoader.get(); }
     53
     54    static String taskMode();
     55    ReferrerPolicy referrerPolicy();
    4056
    4157private:
    42     ModuleFetchParameters(const String& integrity)
    43         : m_integrity(integrity)
    44     {
    45     }
     58    WorkerModuleScriptLoader(ModuleScriptLoaderClient&, DeferredPromise&, WorkerScriptFetcher&, RefPtr<ModuleFetchParameters>&&);
    4659
    47     String m_integrity;
     60    void didReceiveResponse(unsigned long, const ResourceResponse&) final { }
     61    void notifyFinished() final;
     62
     63    Ref<WorkerScriptLoader> m_scriptLoader;
     64    URL m_sourceURL;
    4865};
    4966
  • trunk/Source/WebCore/dom/Document.cpp

    r273083 r273203  
    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)
  • trunk/Source/WebCore/dom/ExceptionCode.h

    r264413 r273203  
    6262    RangeError,
    6363    TypeError,
     64    JSSyntaxError, // Different from DOM SYNTAX_ERR.
    6465
    6566    // Non-standard error.
     
    112113    WebCore::ExceptionCode::RangeError,
    113114    WebCore::ExceptionCode::TypeError,
     115    WebCore::ExceptionCode::JSSyntaxError,
    114116    WebCore::ExceptionCode::StackOverflowError,
    115117    WebCore::ExceptionCode::ExistingExceptionError
  • trunk/Source/WebCore/dom/LoadableModuleScript.cpp

    r247509 r273203  
    4242LoadableModuleScript::LoadableModuleScript(const String& nonce, const String& integrity, ReferrerPolicy policy, const String& crossOriginMode, const String& charset, const AtomString& initiatorName, bool isInUserAgentShadowTree)
    4343    : LoadableScript(nonce, policy, crossOriginMode, charset, initiatorName, isInUserAgentShadowTree)
    44     , m_parameters(ModuleFetchParameters::create(integrity))
     44    , m_parameters(ModuleFetchParameters::create(integrity, /* isTopLevelModule */ true))
    4545{
    4646}
     
    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());
    9591}
    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 
    103 }
  • trunk/Source/WebCore/dom/LoadableModuleScript.h

    r247509 r273203  
    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&&);
     
    5956
    6057    UniquedStringImpl* moduleKey() const { return m_moduleKey.get(); }
     58
     59    ModuleFetchParameters& parameters() { return m_parameters.get(); }
    6160
    6261private:
  • trunk/Source/WebCore/dom/ModuleFetchParameters.h

    r228218 r273203  
    3232class ModuleFetchParameters : public JSC::ScriptFetchParameters {
    3333public:
    34     static Ref<ModuleFetchParameters> create(const String& integrity)
     34    static Ref<ModuleFetchParameters> create(const String& integrity, bool isTopLevelModule)
    3535    {
    36         return adoptRef(*new ModuleFetchParameters(integrity));
     36        return adoptRef(*new ModuleFetchParameters(integrity, isTopLevelModule));
    3737    }
    3838
    3939    const String& integrity() const { return m_integrity; }
     40    bool isTopLevelModule() const { return m_isTopLevelModule; }
    4041
    4142private:
    42     ModuleFetchParameters(const String& integrity)
     43    ModuleFetchParameters(const String& integrity, bool isTopLevelModule)
    4344        : m_integrity(integrity)
     45        , m_isTopLevelModule(isTopLevelModule)
    4446    {
    4547    }
    4648
    4749    String m_integrity;
     50    bool m_isTopLevelModule;
    4851};
    4952
  • trunk/Source/WebCore/dom/ScriptElement.cpp

    r262945 r273203  
    4343#include "LoadableModuleScript.h"
    4444#include "MIMETypeRegistry.h"
     45#include "ModuleFetchParameters.h"
    4546#include "PendingScript.h"
    4647#include "RuntimeApplicationChecks.h"
     
    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    }
     
    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}
  • trunk/Source/WebCore/loader/ThreadableLoader.cpp

    r268057 r273203  
    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;
  • trunk/Source/WebCore/loader/ThreadableLoader.h

    r267227 r273203  
    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;
  • trunk/Source/WebCore/workers/DedicatedWorkerGlobalScope.h

    r270303 r273203  
    8282#endif
    8383
     84    FetchOptions::Destination destination() const final { return FetchOptions::Destination::Worker; }
     85
    8486private:
    8587    using Base = WorkerGlobalScope;
  • trunk/Source/WebCore/workers/Worker.cpp

    r272721 r273203  
    7575    , m_contextProxy(WorkerGlobalScopeProxy::create(*this))
    7676    , m_runtimeFlags(runtimeFlags)
     77    , m_type(options.type)
     78    , m_credentials(options.credentials)
    7779{
    7880    static bool addedListener;
     
    118120    FetchOptions fetchOptions;
    119121    fetchOptions.mode = FetchOptions::Mode::SameOrigin;
     122    if (worker->m_type == WorkerType::Module)
     123        fetchOptions.credentials = worker->m_credentials;
     124    else
     125        fetchOptions.credentials = FetchOptions::Credentials::SameOrigin;
    120126    fetchOptions.cache = FetchOptions::Cache::Default;
    121127    fetchOptions.redirect = FetchOptions::Redirect::Follow;
    122128    fetchOptions.destination = FetchOptions::Destination::Worker;
    123     worker->m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, worker);
     129    worker->m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(fetchOptions), contentSecurityPolicyEnforcement, ServiceWorkersMode::All, worker.get(), WorkerRunLoop::defaultMode());
     130
    124131    return worker;
    125132}
     
    220227    if (auto policy = parseReferrerPolicy(m_scriptLoader->referrerPolicy(), ReferrerPolicySource::HTTPHeader))
    221228        referrerPolicy = *policy;
    222     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);
     229
     230    URL responseURL = m_scriptLoader->responseURL();
     231    if (!m_scriptLoader->isRedirected() && m_scriptLoader->responseSource() != ResourceResponse::Source::ServiceWorker) {
     232        if (m_scriptLoader->url().hasFragmentIdentifier())
     233            responseURL.setFragmentIdentifier(m_scriptLoader->url().fragmentIdentifier());
     234    }
     235    m_contextProxy.startWorkerGlobalScope(responseURL, m_name, context->userAgent(responseURL), isOnline, m_scriptLoader->script(), contentSecurityPolicyResponseHeaders, m_shouldBypassMainWorldContentSecurityPolicy, m_workerCreationTime, referrerPolicy, m_type, m_credentials, m_runtimeFlags);
    223236    InspectorInstrumentation::scriptImported(*context, m_scriptLoader->identifier(), m_scriptLoader->script());
    224237}
  • trunk/Source/WebCore/workers/Worker.h

    r270107 r273203  
    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>
     
    5658public:
    5759    struct Options {
     60        WorkerType type;
     61        FetchRequestCredentials credentials;
    5862        String name;
    5963    };
     
    7983    void postTaskToWorkerGlobalScope(Function<void(ScriptExecutionContext&)>&&);
    8084#endif
     85
     86    WorkerType type() const { return m_type; }
    8187
    8288private:
     
    113119    HashSet<String> m_transformers;
    114120#endif
     121    WorkerType m_type { WorkerType::Classic };
     122    FetchRequestCredentials m_credentials { FetchRequestCredentials::SameOrigin };
    115123};
    116124
  • trunk/Source/WebCore/workers/Worker.idl

    r267813 r273203  
    3939
    4040dictionary WorkerOptions {
     41    WorkerType type = "classic";
     42    FetchRequestCredentials credentials = "same-origin"; // credentials is only used if type is "module"
    4143    DOMString name = "";
    4244};
  • trunk/Source/WebCore/workers/WorkerGlobalScope.cpp

    r270762 r273203  
    7575    , m_referrerPolicy(params.referrerPolicy)
    7676    , m_settingsValues(params.settingsValues)
     77    , m_workerType(params.workerType)
     78    , m_credentials(params.credentials)
    7779{
    7880#if !ENABLE(INDEXED_DATABASE)
     
    274276{
    275277    ASSERT(contentSecurityPolicy());
     278
     279    // https://html.spec.whatwg.org/multipage/workers.html#importing-scripts-and-libraries
     280    // 1. If worker global scope's type is "module", throw a TypeError exception.
     281    if (m_workerType == WorkerType::Module)
     282        return Exception { TypeError, "importScripts cannot be used if worker type is \"module\""_s };
    276283
    277284    Vector<URL> completedURLs;
  • trunk/Source/WebCore/workers/WorkerGlobalScope.h

    r271743 r273203  
    124124    const Settings::Values& settingsValues() const final { return m_settingsValues; }
    125125
     126    FetchOptions::Credentials credentials() const { return m_credentials; }
     127
    126128protected:
    127129    WorkerGlobalScope(WorkerThreadType, const WorkerParameters&, Ref<SecurityOrigin>&&, WorkerThread&, Ref<SecurityOrigin>&& topOrigin, IDBClient::IDBConnectionProxy*, SocketProvider*);
     
    164166    mutable RefPtr<WorkerNavigator> m_navigator;
    165167
    166     std::unique_ptr<WorkerOrWorkletScriptController> m_script;
    167 
    168168    bool m_isOnline;
    169169    bool m_shouldBypassMainWorldContentSecurityPolicy;
     
    188188    ReferrerPolicy m_referrerPolicy;
    189189    Settings::Values m_settingsValues;
     190    WorkerType m_workerType;
     191    FetchOptions::Credentials m_credentials;
    190192};
    191193
  • trunk/Source/WebCore/workers/WorkerGlobalScopeProxy.h

    r270107 r273203  
    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;
  • trunk/Source/WebCore/workers/WorkerMessagingProxy.cpp

    r270762 r273203  
    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
     
    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
  • trunk/Source/WebCore/workers/WorkerMessagingProxy.h

    r270107 r273203  
    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;
  • trunk/Source/WebCore/workers/WorkerOrWorkletGlobalScope.cpp

    r269974 r273203  
    2727#include "WorkerOrWorkletGlobalScope.h"
    2828
     29#include "ScriptModuleLoader.h"
     30#include "ServiceWorkerGlobalScope.h"
    2931#include "WorkerEventLoop.h"
    3032#include "WorkerInspectorController.h"
     
    3234#include "WorkerOrWorkletThread.h"
    3335#include "WorkerRunLoop.h"
     36#include "WorkletGlobalScope.h"
    3437#include <wtf/IsoMallocInlines.h>
    3538
     
    4043WorkerOrWorkletGlobalScope::WorkerOrWorkletGlobalScope(WorkerThreadType type, Ref<JSC::VM>&& vm, WorkerOrWorkletThread* thread)
    4144    : m_script(makeUnique<WorkerOrWorkletScriptController>(type, WTFMove(vm), this))
     45    , m_moduleLoader(makeUnique<ScriptModuleLoader>(*this, ScriptModuleLoader::OwnerType::WorkerOrWorklet))
    4246    , m_thread(thread)
    4347    , m_inspectorController(makeUnique<WorkerInspectorController>(*this))
  • trunk/Source/WebCore/workers/WorkerOrWorkletGlobalScope.h

    r269974 r273203  
    2727
    2828#include "EventTarget.h"
     29#include "FetchOptions.h"
    2930#include "ScriptExecutionContext.h"
    3031#include "WorkerThreadType.h"
     
    3334
    3435class EventLoopTaskGroup;
     36class ScriptModuleLoader;
    3537class WorkerEventLoop;
    3638class WorkerInspectorController;
     
    5557    unsigned long createUniqueIdentifier() { return m_uniqueIdentifier++; }
    5658
     59    ScriptModuleLoader& moduleLoader() { return *m_moduleLoader; }
     60
    5761    // ScriptExecutionContext.
    5862    EventLoopTaskGroup& eventLoop() final;
     
    6771    virtual void suspend() { }
    6872    virtual void resume() { }
     73
     74    virtual FetchOptions::Destination destination() const = 0;
    6975
    7076protected:
     
    8995
    9096    std::unique_ptr<WorkerOrWorkletScriptController> m_script;
     97    std::unique_ptr<ScriptModuleLoader> m_moduleLoader;
    9198    WorkerOrWorkletThread* m_thread;
    9299    RefPtr<WorkerEventLoop> m_eventLoop;
  • trunk/Source/WebCore/workers/WorkerOrWorkletScriptController.cpp

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

    r269974 r273203  
    3232#include <wtf/Forward.h>
    3333#include <wtf/Lock.h>
     34#include <wtf/MessageQueue.h>
    3435#include <wtf/NakedPtr.h>
    3536
     
    4849class WorkerConsoleClient;
    4950class WorkerOrWorkletGlobalScope;
     51class WorkerScriptFetcher;
    5052
    5153class WorkerOrWorkletScriptController {
     
    9597    void evaluate(const ScriptSourceCode&, NakedPtr<JSC::Exception>& returnedException, String* returnedExceptionMessage = nullptr);
    9698
     99    JSC::JSValue evaluateModule(JSC::JSModuleRecord&);
     100
     101    void linkAndEvaluateModule(WorkerScriptFetcher&, const ScriptSourceCode&, String* returnedExceptionMessage = nullptr);
     102    MessageQueueWaitResult loadModuleSynchronously(WorkerScriptFetcher&, const ScriptSourceCode&);
     103
     104    void loadAndEvaluateModule(const URL& moduleURL, FetchOptions::Credentials, CompletionHandler<void(Optional<Exception>&&)>&&);
     105
    97106protected:
    98107    WorkerOrWorkletGlobalScope* globalScope() const { return m_globalScope; }
  • trunk/Source/WebCore/workers/WorkerScriptLoader.cpp

    r270046 r273203  
    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;
     
    120120        return;
    121121
    122     // https://html.spec.whatwg.org/multipage/webappapis.html#fetch-a-single-module-script
    123     ASSERT(fetchOptions.mode == FetchOptions::Mode::SameOrigin || (fetchOptions.destination != FetchOptions::Destination::Serviceworker && fetchOptions.destination != FetchOptions::Destination::Worker));
    124 
    125122    ThreadableLoaderOptions options { WTFMove(fetchOptions) };
    126     // FIXME: We should add an option to set credential mode.
    127     options.credentials = FetchOptions::Credentials::SameOrigin;
    128123    options.sendLoadCallbacks = SendCallbackPolicy::SendCallbacks;
    129124    options.contentSecurityPolicyEnforcement = contentSecurityPolicyEnforcement;
     
    144139    // During create, callbacks may happen which remove the last reference to this object.
    145140    Ref<WorkerScriptLoader> protectedThis(*this);
    146     m_threadableLoader = ThreadableLoader::create(scriptExecutionContext, *this, WTFMove(*request), options);
     141    m_threadableLoader = ThreadableLoader::create(scriptExecutionContext, *this, WTFMove(*request), options, { }, WTFMove(taskMode));
    147142}
    148143
     
    191186    m_responseMIMEType = response.mimeType();
    192187    m_responseEncoding = response.textEncodingName();
     188    m_responseSource = response.source();
     189    m_isRedirected = response.isRedirected();
    193190    m_contentSecurityPolicy = ContentSecurityPolicyResponseHeaders { response };
    194191    m_referrerPolicy = response.httpHeaderField(HTTPHeaderName::ReferrerPolicy);
  • trunk/Source/WebCore/workers/WorkerScriptLoader.h

    r265039 r273203  
    3232#include "ResourceError.h"
    3333#include "ResourceRequest.h"
     34#include "ResourceResponse.h"
    3435#include "ThreadableLoader.h"
    3536#include "ThreadableLoaderClient.h"
     
    4445
    4546class Exception;
    46 class ResourceResponse;
    4747class ScriptExecutionContext;
    4848class TextResourceDecoder;
     
    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();
     
    6868    const URL& url() const { return m_url; }
    6969    const URL& responseURL() const;
     70    ResourceResponse::Source responseSource() const { return m_responseSource; }
     71    bool isRedirected() const { return m_isRedirected; }
    7072    const CertificateInfo& certificateInfo() const { return m_certificateInfo; }
    7173    const String& responseMIMEType() const { return m_responseMIMEType; }
     
    108110    bool m_failed { false };
    109111    bool m_finishing { false };
     112    bool m_isRedirected { false };
     113    ResourceResponse::Source m_responseSource { ResourceResponse::Source::Unknown };
    110114    ResourceError m_error;
    111115};
  • trunk/Source/WebCore/workers/WorkerThread.cpp

    r272393 r273203  
    3333#include "SocketProvider.h"
    3434#include "WorkerGlobalScope.h"
     35#include "WorkerScriptFetcher.h"
     36#include <JavaScriptCore/ScriptCallStack.h>
    3537#include <wtf/Threading.h>
    3638
     
    5658        timeOrigin,
    5759        referrerPolicy,
     60        workerType,
     61        credentials,
    5862        settingsValues.isolatedCopy()
    5963    };
     
    124128void WorkerThread::evaluateScriptIfNecessary(String& exceptionMessage)
    125129{
    126     globalScope()->script()->evaluate(ScriptSourceCode(m_startupData->sourceCode, URL(m_startupData->params.scriptURL)), &exceptionMessage);
     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.
    127132
    128     finishedEvaluatingScript();
     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        auto scriptFetcher = WorkerScriptFetcher::create(globalScope()->credentials(), globalScope()->destination(), globalScope()->referrerPolicy());
     138        ScriptSourceCode sourceCode(m_startupData->sourceCode, URL(m_startupData->params.scriptURL), { }, JSC::SourceProviderSourceType::Module, scriptFetcher.copyRef());
     139        MessageQueueWaitResult result = globalScope()->script()->loadModuleSynchronously(scriptFetcher.get(), sourceCode);
     140        if (result != MessageQueueTerminated) {
     141            if (Optional<LoadableScript::Error> error = scriptFetcher->error()) {
     142                if (Optional<LoadableScript::ConsoleMessage> message = error->consoleMessage)
     143                    exceptionMessage = message->message;
     144                else
     145                    exceptionMessage = "Importing a module script failed."_s;
     146                globalScope()->reportException(exceptionMessage, { }, { }, { }, { }, { });
     147            } else if (!scriptFetcher->wasCanceled()) {
     148                globalScope()->script()->linkAndEvaluateModule(scriptFetcher.get(), sourceCode, &exceptionMessage);
     149                finishedEvaluatingScript();
     150            }
     151        }
     152    }
    129153
    130154    // Free the startup data to cause its member variable deref's happen on the worker's thread (since
  • trunk/Source/WebCore/workers/WorkerThread.h

    r272393 r273203  
    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>
     
    6467    MonotonicTime timeOrigin;
    6568    ReferrerPolicy referrerPolicy;
     69    WorkerType workerType;
     70    FetchRequestCredentials credentials;
    6671    Settings::Values settingsValues;
    6772
  • trunk/Source/WebCore/workers/WorkerType.h

    r220344 r273203  
    2828namespace WebCore {
    2929
    30 enum class WorkerType {
     30enum class WorkerType : uint8_t {
    3131    Classic,
    3232    Module,
  • trunk/Source/WebCore/workers/service/ServiceWorkerContainer.h

    r271806 r273203  
    4848
    4949enum class ServiceWorkerUpdateViaCache : uint8_t;
    50 enum class WorkerType;
     50enum class WorkerType : uint8_t;
    5151
    5252template<typename IDLType> class DOMPromiseProxy;
  • trunk/Source/WebCore/workers/service/ServiceWorkerGlobalScope.h

    r264724 r273203  
    7070
    7171    const CertificateInfo& certificateInfo() const { return m_contextData.certificateInfo; }
     72
     73    FetchOptions::Destination destination() const final { return FetchOptions::Destination::Serviceworker; }
    7274   
    7375private:
  • trunk/Source/WebCore/workers/service/ServiceWorkerJob.cpp

    r264724 r273203  
    111111    options.redirect = FetchOptions::Redirect::Error;
    112112    options.destination = FetchOptions::Destination::Serviceworker;
    113     m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(options), ContentSecurityPolicyEnforcement::DoNotEnforce, ServiceWorkersMode::None, *this);
     113    options.credentials = FetchOptions::Credentials::SameOrigin;
     114    m_scriptLoader->loadAsynchronously(context, WTFMove(request), WTFMove(options), ContentSecurityPolicyEnforcement::DoNotEnforce, ServiceWorkersMode::None, *this, WorkerRunLoop::defaultMode());
    114115}
    115116
  • trunk/Source/WebCore/workers/service/ServiceWorkerRegistrationOptions.h

    r239427 r273203  
    3333
    3434enum class ServiceWorkerUpdateViaCache : uint8_t;
    35 enum class WorkerType;
     35enum class WorkerType : uint8_t;
    3636
    3737struct ServiceWorkerRegistrationOptions {
  • trunk/Source/WebCore/workers/service/context/ServiceWorkerThread.cpp

    r270762 r273203  
    7474// FIXME: Use valid runtime flags
    7575
     76// FIXME: Support modules in service-workers.
     77// https://bugs.webkit.org/show_bug.cgi?id=222155
    7678ServiceWorkerThread::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())
     79    : 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())
    7880    , m_data(data.isolatedCopy())
    7981    , m_workerObjectProxy(DummyServiceWorkerThreadProxy::shared())
  • trunk/Source/WebCore/workers/service/server/SWServerWorker.h

    r265150 r273203  
    5151struct ServiceWorkerContextData;
    5252struct ServiceWorkerJobDataIdentifier;
    53 enum class WorkerType;
     53enum class WorkerType : uint8_t;
    5454
    5555class SWServerWorker : public RefCounted<SWServerWorker> {
  • trunk/Source/WebCore/worklets/PaintWorkletGlobalScope.h

    r269275 r273203  
    4141class JSDOMGlobalObject;
    4242
    43 class PaintWorkletGlobalScope : public WorkletGlobalScope {
     43class PaintWorkletGlobalScope final : public WorkletGlobalScope {
    4444    WTF_MAKE_ISO_ALLOCATED(PaintWorkletGlobalScope);
    4545public:
     
    7777    }
    7878
     79    FetchOptions::Destination destination() const final { return FetchOptions::Destination::Paintworklet; }
     80
    7981private:
    8082    PaintWorkletGlobalScope(Document&, Ref<JSC::VM>&&, ScriptSourceCode&&);
  • trunk/Source/WebCore/worklets/WorkletGlobalScope.cpp

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

    r272393 r273203  
    3434#include "WorkerOrWorkletGlobalScope.h"
    3535#include "WorkerOrWorkletScriptController.h"
    36 #include "WorkerScriptLoaderClient.h"
    3736#include <JavaScriptCore/ConsoleMessage.h>
    3837#include <JavaScriptCore/RuntimeFlags.h>
     
    5554using WorkletGlobalScopeIdentifier = ObjectIdentifier<WorkletGlobalScopeIdentifierType>;
    5655
    57 class WorkletGlobalScope : public WorkerOrWorkletGlobalScope, public WorkerScriptLoaderClient {
     56class WorkletGlobalScope : public WorkerOrWorkletGlobalScope {
    5857    WTF_MAKE_ISO_ALLOCATED(WorkletGlobalScope);
    5958public:
     
    112111    void addConsoleMessage(MessageSource, MessageLevel, const String&, unsigned long) final;
    113112
    114     // WorkerScriptLoaderClient.
    115     void didReceiveResponse(unsigned long identifier, const ResourceResponse&) final;
    116     void notifyFinished() final;
    117 
    118113    EventTarget* errorEventTarget() final { return this; }
    119114
     
    125120    String userAgent(const URL&) const final;
    126121    const Settings::Values& settingsValues() const final { return m_settingsValues; }
    127 
    128     struct ScriptFetchJob {
    129         URL moduleURL;
    130         FetchRequestCredentials credentials;
    131         CompletionHandler<void(Optional<Exception>&&)> completionHandler;
    132     };
    133 
    134     void processNextScriptFetchJobIfNeeded();
    135     void didCompleteScriptFetchJob(ScriptFetchJob&&, Optional<Exception>);
    136122
    137123    WeakPtr<Document> m_document;
     
    145131    std::unique_ptr<WorkerMessagePortChannelProvider> m_messagePortChannelProvider;
    146132
    147     RefPtr<WorkerScriptLoader> m_scriptLoader;
    148     Deque<ScriptFetchJob> m_scriptFetchJobs;
    149     HashSet<URL> m_evaluatedModules;
    150133    Settings::Values m_settingsValues;
    151134};
Note: See TracChangeset for help on using the changeset viewer.