Skip to main content

script/dom/workers/
workerglobalscope.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5#![cfg_attr(crown, allow(crown::jscontext_first_arg))]
6
7use std::cell::{Cell, OnceCell, RefCell, RefMut};
8use std::collections::HashSet;
9use std::default::Default;
10use std::rc::Rc;
11use std::sync::Arc;
12use std::sync::atomic::{AtomicBool, Ordering};
13use std::time::Duration;
14
15use bytes::{Bytes, BytesMut};
16use content_security_policy::CspList;
17#[cfg(feature = "devtools")]
18use devtools_traits::DevtoolScriptControlMsg;
19use dom_struct::dom_struct;
20use encoding_rs::UTF_8;
21use fonts::FontContext;
22use headers::{HeaderMapExt, ReferrerPolicy as ReferrerPolicyHeader};
23use js::context::JSContext;
24#[cfg(feature = "devtools")]
25use js::conversions::ToJSValConvertible;
26use js::jsapi::{Heap, JSContext as RawJSContext, Value};
27use js::realm::CurrentRealm;
28use js::rust::{HandleValue, MutableHandleValue, ParentRuntime};
29use mime::Mime;
30use net_traits::policy_container::PolicyContainer;
31use net_traits::request::{
32    CredentialsMode, Destination, InsecureRequestsPolicy, ParserMetadata, RequestBuilder, RequestId,
33};
34use net_traits::{FetchMetadata, Metadata, NetworkError, ReferrerPolicy, ResourceFetchTiming};
35use profile_traits::mem::{ProcessReports, perform_memory_report};
36use script_bindings::callback::RootedCallback;
37use script_bindings::cell::{DomRefCell, Ref};
38#[cfg(feature = "devtools")]
39use script_bindings::conversions::root_from_handlevalue;
40use script_bindings::domstring::TracedDOMString;
41#[cfg(feature = "devtools")]
42use script_bindings::reflector::DomObject;
43#[cfg(feature = "devtools")]
44use script_bindings::root::rooted_heap_handle;
45use script_bindings::trace::CustomTraceable;
46use servo_base::cross_process_instant::CrossProcessInstant;
47use servo_base::generic_channel::{GenericSend, GenericSender, RoutedReceiver};
48use servo_base::id::{PipelineId, PipelineNamespace, WorkerId};
49#[cfg(feature = "webgl")]
50use servo_canvas_traits::webgl::WebGLChan;
51use servo_constellation_traits::WorkerGlobalScopeInit;
52use servo_url::{MutableOrigin, ServoUrl};
53use style::Atom;
54use timers::TimerScheduler;
55use uuid::Uuid;
56
57use crate::dom::Window;
58use crate::dom::bindings::codegen::Bindings::ImageBitmapBinding::{
59    ImageBitmapOptions, ImageBitmapSource,
60};
61use crate::dom::bindings::codegen::Bindings::MessagePortBinding::StructuredSerializeOptions;
62use crate::dom::bindings::codegen::Bindings::ReportingObserverBinding::Report;
63use crate::dom::bindings::codegen::Bindings::RequestBinding::RequestInit;
64use crate::dom::bindings::codegen::Bindings::VoidFunctionBinding::VoidFunction;
65use crate::dom::bindings::codegen::Bindings::WorkerBinding::WorkerType;
66use crate::dom::bindings::codegen::Bindings::WorkerGlobalScopeBinding::WorkerGlobalScopeMethods;
67use crate::dom::bindings::codegen::UnionTypes::{
68    RequestOrUSVString, TrustedScriptOrString, TrustedScriptOrStringOrFunction,
69    TrustedScriptURLOrUSVString,
70};
71use crate::dom::bindings::error::{Error, ErrorResult, Fallible};
72use crate::dom::bindings::inheritance::Castable;
73use crate::dom::bindings::refcounted::Trusted;
74use crate::dom::bindings::root::{Dom, DomRoot, MutNullableDom};
75use crate::dom::bindings::str::{DOMString, USVString};
76use crate::dom::bindings::trace::HashMapTracedValues;
77use crate::dom::bindings::utils::define_all_exposed_interfaces;
78use crate::dom::crypto::Crypto;
79use crate::dom::csp::{GlobalCspReporting, Violation, parse_csp_list_from_metadata};
80use crate::dom::css::fontfaceset::FontFaceSet;
81#[cfg(feature = "devtools")]
82use crate::dom::debugger::debuggerglobalscope::DebuggerGlobalScope;
83use crate::dom::dedicatedworkerglobalscope::DedicatedWorkerGlobalScope;
84use crate::dom::globalscope::GlobalScope;
85use crate::dom::htmlscriptelement::{SCRIPT_JS_MIMES, Script};
86use crate::dom::idbfactory::IDBFactory;
87use crate::dom::performance::performance::Performance;
88use crate::dom::performance::performanceresourcetiming::InitiatorType;
89use crate::dom::promise::RootedPromise;
90use crate::dom::reporting::reportingendpoint::{ReportingEndpoint, SendReportsToEndpoints};
91use crate::dom::reporting::reportingobserver::ReportingObserver;
92use crate::dom::serviceworker::cachestorage::CacheStorage;
93use crate::dom::sharedworkerglobalscope::SharedWorkerGlobalScope;
94use crate::dom::trustedtypes::trustedscripturl::TrustedScriptURL;
95use crate::dom::trustedtypes::trustedtypepolicyfactory::TrustedTypePolicyFactory;
96use crate::dom::types::{EventTarget, ImageBitmap};
97#[cfg(feature = "webgpu")]
98use crate::dom::webgpu::identityhub::IdentityHub;
99use crate::dom::window::{base64_atob, base64_btoa};
100use crate::dom::workerlocation::WorkerLocation;
101use crate::dom::workernavigator::WorkerNavigator;
102use crate::event_loop::timers::{IsInterval, OneshotTimers, TimerCallback};
103use crate::fetch::fetch::{
104    CspViolationsProcessor, Fetch, RequestWithGlobalScope, load_whole_resource,
105};
106use crate::fetch::network_listener::{
107    FetchResponseListener, ResourceTimingListener, submit_timing,
108};
109use crate::messaging::{CommonScriptMsg, ScriptEventLoopReceiver, ScriptEventLoopSender};
110use crate::realms::enter_auto_realm;
111use crate::runtime::job_queue::{MicrotaskRunnable, UserMicrotask, job_queue_microtask_checkpoint};
112use crate::runtime::script_runtime::{IntroductionType, Runtime, get_reports};
113use crate::scripting::fetching_options::ScriptFetchOptions;
114use crate::scripting::script_execution::{RethrowErrors, ScriptOptions};
115use crate::scripting::script_module::{ModuleRequest, ModuleStatus};
116use crate::tasks::task::TaskCanceller;
117use crate::tasks::task_manager::TaskManager;
118use crate::url::ensure_blob_referenced_by_url_is_kept_alive;
119
120#[cfg(feature = "devtools")]
121pub(crate) type WorkerDevtoolsControlMsg = DevtoolScriptControlMsg;
122#[cfg(not(feature = "devtools"))]
123pub(crate) type WorkerDevtoolsControlMsg = ();
124
125#[cfg(feature = "devtools")]
126pub(crate) type WorkerDebuggerGlobalScope = DebuggerGlobalScope;
127#[cfg(not(feature = "devtools"))]
128pub(crate) type WorkerDebuggerGlobalScope = ();
129
130/// <https://html.spec.whatwg.org/multipage/#animation-frames>
131pub(crate) fn prepare_workerscope_init(
132    global: &GlobalScope,
133    #[cfg(feature = "devtools")] devtools_sender: Option<GenericSender<DevtoolScriptControlMsg>>,
134    worker_id: Option<WorkerId>,
135    #[cfg(feature = "webgl")] webgl_chan: Option<WebGLChan>,
136) -> WorkerGlobalScopeInit {
137    // An AnimationFrameProvider provider is considered supported if any of the following are true:
138    // - provider is a Window.
139    // - provider's owner set contains a Document object.
140    // - Any of the DedicatedWorkerGlobalScope objects in provider's owner set are supported.
141    let animation_frame_provider_supported = if global.downcast::<Window>().is_some() {
142        true
143    } else if let Some(dedicated) = global.downcast::<DedicatedWorkerGlobalScope>() {
144        dedicated.animation_frame_provider_supported()
145    } else {
146        false
147    };
148
149    WorkerGlobalScopeInit {
150        resource_threads: global.resource_threads().clone(),
151        storage_threads: global.storage_threads().clone(),
152        mem_profiler_chan: global.mem_profiler_chan().clone(),
153        #[cfg(feature = "devtools")]
154        to_devtools_sender: global.devtools_chan().cloned(),
155        time_profiler_chan: global.time_profiler_chan().clone(),
156        #[cfg(feature = "devtools")]
157        from_devtools_sender: devtools_sender,
158        script_to_constellation_chan: global.script_to_constellation_chan().sender,
159        script_to_embedder_chan: global.script_to_embedder_chan().clone(),
160        worker_id: worker_id.unwrap_or_else(|| WorkerId(Uuid::new_v4())),
161        animation_frame_provider_supported,
162        pipeline_id: global.pipeline_id(),
163        origin: global.origin().immutable().clone(),
164        inherited_secure_context: Some(global.is_secure_context()),
165        inherited_upgrade_insecure_navigations_set: global
166            .upgrade_insecure_navigations_set()
167            .clone(),
168        unminify_js: global.unminify_js(),
169        #[cfg(feature = "webgl")]
170        webgl_chan,
171        online: global.online(),
172    }
173}
174
175pub(crate) struct ScriptFetchContext {
176    response: Option<Metadata>,
177    body_bytes: BytesMut,
178    url: ServoUrl,
179    policy_container: Arc<PolicyContainer>,
180}
181
182impl ScriptFetchContext {
183    pub(crate) fn new(url: ServoUrl, policy_container: Arc<PolicyContainer>) -> ScriptFetchContext {
184        ScriptFetchContext {
185            response: None,
186            body_bytes: BytesMut::new(),
187            url,
188            policy_container,
189        }
190    }
191}
192
193impl FetchResponseListener for ScriptFetchContext {
194    fn process_request_body(&mut self, _: &GlobalScope, _request_id: RequestId) {}
195
196    fn process_response(
197        &mut self,
198        _: &mut JSContext,
199        _: &GlobalScope,
200        _request_id: RequestId,
201        metadata: Result<FetchMetadata, NetworkError>,
202    ) {
203        self.response = metadata.ok().map(Into::into);
204    }
205
206    fn process_response_chunk(
207        &mut self,
208        _: &mut JSContext,
209        _: &GlobalScope,
210        _: RequestId,
211        chunk: Bytes,
212    ) {
213        self.body_bytes.extend_from_slice(&chunk);
214    }
215
216    fn process_response_eof(
217        mut self,
218        cx: &mut JSContext,
219        global: &GlobalScope,
220        _request_id: RequestId,
221        response: Result<(), NetworkError>,
222        timing: ResourceFetchTiming,
223    ) {
224        let scope = global
225            .downcast::<WorkerGlobalScope>()
226            .expect("Should always be a WorkerGlobalScope here");
227        if response
228            .as_ref()
229            .inspect_err(|e| error!("error loading script {} ({:?})", self.url, e))
230            .is_err() ||
231            self.response.is_none()
232        {
233            scope.on_complete(cx, None);
234            return;
235        }
236        let metadata = self.response.take().unwrap();
237
238        // The processResponseConsumeBody steps defined inside
239        // [run a worker](https://html.spec.whatwg.org/multipage/#run-a-worker)
240        scope.process_response_for_workerscope(&metadata, &self.policy_container);
241
242        // The processResponseConsumeBody steps defined inside
243        // [fetch a classic worker script](https://html.spec.whatwg.org/multipage/#fetch-a-classic-worker-script)
244
245        // Step 1 Set response to response's unsafe response. Done in process_response
246
247        // Step 2 If any of the following are true: bodyBytes is null or failure; or response's status is not an ok status,
248        if !metadata.status.is_success() {
249            // then run onComplete given null, and abort these steps.
250            scope.on_complete(cx, None);
251            return;
252        }
253
254        // Step 3 If all of the following are true:
255        // response's URL's scheme is an HTTP(S) scheme;
256        let is_http_scheme = matches!(metadata.final_url.scheme(), "http" | "https");
257        // and the result of extracting a MIME type from response's header list is not a JavaScript MIME type,
258        let not_a_javascript_mime_type = !metadata.content_type.is_some_and(|ct| {
259            let mime: Mime = ct.into_inner().into();
260            SCRIPT_JS_MIMES.contains(&mime.essence_str())
261        });
262
263        if is_http_scheme && not_a_javascript_mime_type {
264            // then run onComplete given null, and abort these steps.
265            scope.on_complete(cx, None);
266            return;
267        }
268
269        // Step 4 Let sourceText be the result of UTF-8 decoding bodyBytes.
270        let (source, _) = UTF_8.decode_with_bom_removal(&self.body_bytes);
271
272        // Step 5 Let script be the result of creating a classic script using
273        // sourceText, settingsObject, response's URL, and the default script fetch options.
274        let script = global.create_a_classic_script(
275            cx,
276            source,
277            scope.worker_url.borrow().clone(),
278            ScriptOptions::External,
279            ScriptFetchOptions::default_classic_script(),
280            Some(IntroductionType::WORKER),
281            1,
282        );
283
284        // Step 6 Run onComplete given script.
285        scope.on_complete(cx, Some(Script::Classic(script)));
286
287        submit_timing(cx, global, &self, &response, &timing);
288    }
289
290    fn process_csp_violations(
291        &mut self,
292        _cx: &mut JSContext,
293        global: &GlobalScope,
294        _request_id: RequestId,
295        violations: Vec<content_security_policy::Violation>,
296    ) {
297        if let Some(worker_scope) = global.downcast::<DedicatedWorkerGlobalScope>() {
298            worker_scope.report_csp_violations(violations);
299        } else if let Some(worker_scope) = global.downcast::<SharedWorkerGlobalScope>() {
300            worker_scope.report_csp_violations(violations);
301        }
302    }
303
304    fn process_content_length(&mut self, _request_id: RequestId, size: usize) {
305        self.body_bytes
306            .reserve(size.saturating_sub(self.body_bytes.len()));
307    }
308}
309
310impl ResourceTimingListener for ScriptFetchContext {
311    fn resource_timing_information(&self) -> (InitiatorType, ServoUrl) {
312        (InitiatorType::Other, self.url.clone())
313    }
314}
315
316/// <https://html.spec.whatwg.org/multipage/#the-workerglobalscope-common-interface>
317#[dom_struct]
318pub(crate) struct WorkerGlobalScope {
319    globalscope: GlobalScope,
320
321    worker_name: TracedDOMString,
322    worker_type: WorkerType,
323
324    #[no_trace]
325    worker_id: WorkerId,
326    #[no_trace]
327    worker_url: DomRefCell<ServoUrl>,
328    #[conditional_malloc_size_of]
329    closing: Arc<AtomicBool>,
330    execution_ready: AtomicBool,
331    #[ignore_malloc_size_of = "Defined in js"]
332    runtime: DomRefCell<Option<Runtime>>,
333    location: MutNullableDom<WorkerLocation>,
334    navigator: MutNullableDom<WorkerNavigator>,
335    crypto: MutNullableDom<Crypto>,
336    fonts: MutNullableDom<FontFaceSet>,
337    #[no_trace]
338    /// <https://html.spec.whatwg.org/multipage/#the-workerglobalscope-common-interface:policy-container>
339    #[conditional_malloc_size_of]
340    policy_container: DomRefCell<Arc<PolicyContainer>>,
341
342    #[no_trace]
343    /// A `Sender` for sending messages to devtools. This is unused but is stored here to
344    /// keep the channel alive.
345    #[cfg(feature = "devtools")]
346    _devtools_sender: Option<GenericSender<DevtoolScriptControlMsg>>,
347
348    #[no_trace]
349    /// A `Receiver` for receiving messages from devtools.
350    #[cfg(feature = "devtools")]
351    devtools_receiver: Option<RoutedReceiver<DevtoolScriptControlMsg>>,
352
353    #[no_trace]
354    navigation_start: CrossProcessInstant,
355    performance: MutNullableDom<Performance>,
356    trusted_types: MutNullableDom<TrustedTypePolicyFactory>,
357
358    /// A [`TimerScheduler`] used to schedule timers for this [`WorkerGlobalScope`].
359    /// Timers are handled in the service worker event loop.
360    #[no_trace]
361    timer_scheduler: RefCell<TimerScheduler>,
362
363    /// The mechanism by which time-outs and intervals are scheduled.
364    /// <https://html.spec.whatwg.org/multipage/#timers>
365    timers: OnceCell<OneshotTimers>,
366
367    #[no_trace]
368    insecure_requests_policy: InsecureRequestsPolicy,
369
370    /// <https://w3c.github.io/reporting/#windoworworkerglobalscope-registered-reporting-observer-list>
371    reporting_observer_list: DomRefCell<Vec<Dom<ReportingObserver>>>,
372
373    /// <https://w3c.github.io/reporting/#windoworworkerglobalscope-reports>
374    report_list: DomRefCell<Vec<Report>>,
375
376    /// <https://w3c.github.io/reporting/#windoworworkerglobalscope-endpoints>
377    #[no_trace]
378    endpoints_list: DomRefCell<Vec<ReportingEndpoint>>,
379
380    /// The debugger global object associated with this worker global.
381    /// All traced members of DOM objects must be same-compartment with the
382    /// realm being traced, so this is the debugger global object wrapped into
383    /// this global's compartment.
384    #[ignore_malloc_size_of = "Measured by the JS engine"]
385    debugger_global: Heap<Value>,
386
387    #[no_trace]
388    pipeline_id: PipelineId,
389
390    /// <https://w3c.github.io/ServiceWorker/#global-caches-attribute>
391    caches: MutNullableDom<CacheStorage>,
392
393    /// The [`TaskManager`] for this [`WorkerGlobalScope`].
394    #[conditional_malloc_size_of]
395    task_manager: Rc<TaskManager>,
396
397    #[no_trace]
398    origin: MutableOrigin,
399
400    /// The [`FontContext`] for this worker, used by any offscreen canvas.
401    #[conditional_malloc_size_of]
402    #[no_trace]
403    font_context: Arc<FontContext>,
404
405    /// module map is used when importing JavaScript modules
406    /// <https://html.spec.whatwg.org/multipage/#concept-settings-object-module-map>
407    #[ignore_malloc_size_of = "mozjs"]
408    module_map: DomRefCell<HashMapTracedValues<ModuleRequest, ModuleStatus>>,
409
410    /// Whether the network is considered to be online as reported by the embedder.
411    online: Cell<bool>,
412}
413
414impl WorkerGlobalScope {
415    #[allow(clippy::too_many_arguments)]
416    pub(crate) fn new_inherited(
417        init: WorkerGlobalScopeInit,
418        worker_name: DOMString,
419        worker_type: WorkerType,
420        worker_url: ServoUrl,
421        runtime: Runtime,
422        devtools_receiver: Option<RoutedReceiver<WorkerDevtoolsControlMsg>>,
423        closing: Arc<AtomicBool>,
424        #[cfg(feature = "webgpu")] gpu_id_hub: Arc<IdentityHub>,
425        insecure_requests_policy: InsecureRequestsPolicy,
426        font_context: Arc<FontContext>,
427        event_loop_sender: Option<ScriptEventLoopSender>,
428    ) -> Self {
429        // Install a pipeline-namespace in the current thread.
430        PipelineNamespace::auto_install();
431
432        #[cfg(feature = "devtools")]
433        let devtools_receiver = init.from_devtools_sender.as_ref().and(devtools_receiver);
434
435        Self {
436            globalscope: GlobalScope::new_inherited(
437                #[cfg(feature = "devtools")]
438                init.to_devtools_sender,
439                init.mem_profiler_chan,
440                init.time_profiler_chan,
441                init.script_to_constellation_chan,
442                init.script_to_embedder_chan,
443                init.resource_threads,
444                init.storage_threads,
445                worker_url.clone(),
446                None,
447                #[cfg(feature = "webgpu")]
448                gpu_id_hub,
449                init.inherited_secure_context,
450                init.inherited_upgrade_insecure_navigations_set,
451                init.unminify_js,
452            ),
453            caches: Default::default(),
454            worker_id: init.worker_id,
455            worker_name: worker_name.traced(),
456            worker_type,
457            worker_url: DomRefCell::new(worker_url),
458            closing: closing.clone(),
459            execution_ready: AtomicBool::new(false),
460            runtime: DomRefCell::new(Some(runtime)),
461            location: Default::default(),
462            navigator: Default::default(),
463            crypto: Default::default(),
464            fonts: Default::default(),
465            policy_container: Default::default(),
466            #[cfg(feature = "devtools")]
467            devtools_receiver,
468            #[cfg(feature = "devtools")]
469            _devtools_sender: init.from_devtools_sender,
470            navigation_start: CrossProcessInstant::now(),
471            performance: Default::default(),
472            timer_scheduler: RefCell::default(),
473            timers: Default::default(),
474            insecure_requests_policy,
475            trusted_types: Default::default(),
476            reporting_observer_list: Default::default(),
477            report_list: Default::default(),
478            endpoints_list: Default::default(),
479            debugger_global: Default::default(),
480            pipeline_id: init.pipeline_id,
481            task_manager: Rc::new(TaskManager::new(
482                event_loop_sender,
483                init.pipeline_id,
484                Some(TaskCanceller { cancelled: closing }),
485            )),
486            origin: MutableOrigin::new(init.origin),
487            font_context,
488            module_map: Default::default(),
489            online: init.online.into(),
490        }
491    }
492
493    pub(crate) fn online(&self) -> bool {
494        self.online.get()
495    }
496
497    pub(crate) fn module_map(
498        &self,
499    ) -> &DomRefCell<HashMapTracedValues<ModuleRequest, ModuleStatus>> {
500        &self.module_map
501    }
502
503    pub(crate) fn font_context(&self) -> Arc<FontContext> {
504        self.font_context.clone()
505    }
506
507    pub(crate) fn timers(&self) -> &OneshotTimers {
508        self.timers
509            .get_or_init(|| OneshotTimers::new(self.upcast()))
510    }
511
512    pub(crate) fn enqueue_microtask(&self, cx: &JSContext, job: Box<dyn MicrotaskRunnable>) {
513        crate::runtime::job_queue::enqueue(cx, job);
514    }
515
516    /// Perform a microtask checkpoint.
517    pub(crate) fn perform_a_microtask_checkpoint(&self, cx: &mut JSContext) {
518        // Only perform the checkpoint if we're not shutting down.
519        if !self.is_closing() {
520            job_queue_microtask_checkpoint(cx, vec![DomRoot::from_ref(&self.globalscope)]);
521        }
522    }
523
524    /// Returns a policy value that should be used by fetches initiated by this worker.
525    pub(crate) fn insecure_requests_policy(&self) -> InsecureRequestsPolicy {
526        self.insecure_requests_policy
527    }
528
529    /// Clear various items when the worker event-loop shuts-down.
530    pub(crate) fn clear_js_runtime(&self) {
531        self.upcast::<GlobalScope>()
532            .remove_web_messaging_and_dedicated_workers_infra();
533
534        // Drop the runtime.
535        let runtime = self.runtime.borrow_mut().take();
536        drop(runtime);
537    }
538
539    pub(crate) fn runtime_handle(&self) -> ParentRuntime {
540        self.runtime
541            .borrow()
542            .as_ref()
543            .unwrap()
544            .prepare_for_new_child()
545    }
546
547    #[cfg(feature = "devtools")]
548    pub(crate) fn devtools_receiver(&self) -> Option<&RoutedReceiver<DevtoolScriptControlMsg>> {
549        self.devtools_receiver.as_ref()
550    }
551
552    pub(crate) fn is_closing(&self) -> bool {
553        self.closing.load(Ordering::SeqCst)
554    }
555
556    pub(crate) fn is_execution_ready(&self) -> bool {
557        self.execution_ready.load(Ordering::Relaxed)
558    }
559
560    pub(crate) fn get_url(&self) -> Ref<'_, ServoUrl> {
561        self.worker_url.borrow()
562    }
563
564    pub(crate) fn set_url(&self, url: ServoUrl) {
565        *self.worker_url.borrow_mut() = url;
566    }
567
568    pub(crate) fn worker_name(&self) -> DOMString {
569        self.worker_name.clone().root()
570    }
571
572    pub(crate) fn worker_id(&self) -> WorkerId {
573        self.worker_id
574    }
575
576    /// The debugger global for this worker, if devtools created one.
577    #[cfg(feature = "devtools")]
578    pub(crate) fn debugger_global(
579        &self,
580        cx: &mut JSContext,
581    ) -> Option<DomRoot<DebuggerGlobalScope>> {
582        let debugger_global_handle = rooted_heap_handle(self, |this| &this.debugger_global);
583        root_from_handlevalue::<DebuggerGlobalScope>(cx, debugger_global_handle).ok()
584    }
585
586    pub(crate) fn pipeline_id(&self) -> PipelineId {
587        self.pipeline_id
588    }
589
590    pub(crate) fn task_manager(&self) -> Rc<TaskManager> {
591        self.task_manager.clone()
592    }
593
594    pub(crate) fn policy_container(&self) -> Ref<'_, Arc<PolicyContainer>> {
595        self.policy_container.borrow()
596    }
597
598    pub(crate) fn set_csp_list(&self, csp_list: Option<CspList>) {
599        Arc::make_mut(&mut *self.policy_container.borrow_mut()).set_csp_list(csp_list);
600    }
601
602    pub(crate) fn set_referrer_policy(&self, referrer_policy: ReferrerPolicy) {
603        Arc::make_mut(&mut *self.policy_container.borrow_mut())
604            .set_referrer_policy(referrer_policy);
605    }
606
607    pub(crate) fn append_reporting_observer(&self, reporting_observer: &ReportingObserver) {
608        self.reporting_observer_list
609            .borrow_mut()
610            .push(Dom::from_ref(reporting_observer));
611    }
612
613    pub(crate) fn remove_reporting_observer(&self, reporting_observer: &ReportingObserver) {
614        if let Some(index) = self
615            .reporting_observer_list
616            .borrow()
617            .iter()
618            .position(|observer| &**observer == reporting_observer)
619        {
620            self.reporting_observer_list.borrow_mut().remove(index);
621        }
622    }
623
624    pub(crate) fn registered_reporting_observers(&self) -> Vec<DomRoot<ReportingObserver>> {
625        self.reporting_observer_list
626            .borrow()
627            .iter()
628            .map(|observer| DomRoot::from_ref(&**observer))
629            .collect()
630    }
631
632    pub(crate) fn append_report(&self, report: Report) {
633        self.report_list.borrow_mut().push(report);
634        let trusted_worker = Trusted::new(self);
635        self.upcast::<GlobalScope>()
636            .task_manager()
637            .dom_manipulation_task_source()
638            .queue(task!(send_to_reporting_endpoints: move || {
639                let worker = trusted_worker.root();
640                let reports = std::mem::take(&mut *worker.report_list.borrow_mut());
641                worker.upcast::<GlobalScope>().send_reports_to_endpoints(
642                    reports,
643                    worker.endpoints_list.borrow().clone(),
644                );
645            }));
646    }
647
648    pub(crate) fn buffered_reports(&self) -> Vec<Report> {
649        self.report_list.borrow().clone()
650    }
651
652    pub(crate) fn set_endpoints_list(&self, endpoints: Option<Vec<ReportingEndpoint>>) {
653        if let Some(endpoints) = endpoints {
654            *self.endpoints_list.borrow_mut() = endpoints;
655        }
656    }
657
658    /// Get a mutable reference to the [`TimerScheduler`] for this [`ServiceWorkerGlobalScope`].
659    pub(crate) fn timer_scheduler(&self) -> RefMut<'_, TimerScheduler> {
660        self.timer_scheduler.borrow_mut()
661    }
662
663    /// <https://html.spec.whatwg.org/multipage/#initialize-worker-policy-container> and
664    /// <https://html.spec.whatwg.org/multipage/#creating-a-policy-container-from-a-fetch-response>
665    fn initialize_policy_container_for_worker_global_scope(
666        &self,
667        metadata: &Metadata,
668        parent_policy_container: &PolicyContainer,
669    ) {
670        // Step 1. If workerGlobalScope's url is local but its scheme is not "blob":
671        //
672        // Note that we also allow for blob here, as the parent_policy_container is in both cases
673        // the container that we need to clone.
674        if metadata.final_url.is_local_scheme() {
675            // Step 1.2. Set workerGlobalScope's policy container to a clone of workerGlobalScope's
676            // owner set[0]'s relevant settings object's policy container.
677            //
678            // Step 1. If response's URL's scheme is "blob", then return a clone of response's URL's
679            // blob URL entry's environment's policy container.
680            self.set_csp_list(parent_policy_container.csp_list.clone());
681            self.set_referrer_policy(parent_policy_container.get_referrer_policy());
682            return;
683        }
684        // Step 3. Set result's CSP list to the result of parsing a response's Content Security Policies given response.
685        self.set_csp_list(parse_csp_list_from_metadata(&metadata.headers));
686        // Step 5. Set result's referrer policy to the result of parsing the `Referrer-Policy`
687        // header given response. [REFERRERPOLICY]
688        let referrer_policy = metadata
689            .headers
690            .as_ref()
691            .and_then(|headers| headers.typed_get::<ReferrerPolicyHeader>())
692            .into();
693        self.set_referrer_policy(referrer_policy);
694    }
695
696    /// onComplete algorithm defined inside <https://html.spec.whatwg.org/multipage/#run-a-worker>
697    #[expect(unsafe_code)]
698    pub(crate) fn on_complete(&self, cx: &mut JSContext, script: Option<Script>) {
699        // Step 1. If script is null or if script's error to rethrow is non-null, then:
700        let script = match script {
701            Some(Script::Classic(script)) if !script.has_rethrow_error() => Script::Classic(script),
702            Some(Script::Module(module)) if !module.has_rethrow_error() => Script::Module(module),
703            _ => {
704                // Step 1.1. Queue a global task on the DOM manipulation task source given
705                // worker's relevant global object to fire an event named error at worker.
706                if let Some(dedicated) = self.downcast::<DedicatedWorkerGlobalScope>() {
707                    dedicated.forward_simple_error_at_worker();
708                } else if let Some(shared) = self.downcast::<SharedWorkerGlobalScope>() {
709                    shared.forward_simple_error_at_worker();
710                }
711
712                // TODO Step 1.2. Run the environment discarding steps for inside settings.
713                // Step 1.3 Abort these steps.
714                return;
715            },
716        };
717
718        unsafe {
719            // Handle interrupt requests
720            js::rust::wrappers2::JS_AddInterruptCallback(cx, Some(interrupt_callback));
721        }
722
723        if self.is_closing() {
724            return;
725        }
726
727        {
728            let mut realm = enter_auto_realm(cx, self);
729            let cx = &mut realm.current_realm();
730            define_all_exposed_interfaces(cx, self.upcast());
731            // Step 9. Set inside settings's execution ready flag.
732            self.execution_ready.store(true, Ordering::Relaxed);
733            match script {
734                Script::Classic(script) => {
735                    _ = self.globalscope.run_a_classic_script(
736                        cx,
737                        script,
738                        RethrowErrors::No,
739                        None, // return_value
740                    );
741                },
742                Script::Module(module_tree) => {
743                    self.globalscope.run_a_module_script(cx, module_tree, false);
744                },
745                _ => unreachable!(),
746            }
747            if let Some(dedicated) = self.downcast::<DedicatedWorkerGlobalScope>() {
748                dedicated.fire_queued_messages(cx);
749            } else if let Some(shared) = self.downcast::<SharedWorkerGlobalScope>() {
750                // Step 11. Enable outside port's port message queue.
751                shared.enable_outside_port_message_queue();
752                // Step 13. If the initial Connect arrived before execution-ready,
753                // queue the global task to fire its connect event now.
754                shared.fire_pending_connect(cx);
755            }
756        }
757    }
758
759    // The processResponseConsumeBody steps defined inside
760    // [run a worker](https://html.spec.whatwg.org/multipage/#run-a-worker)
761    pub(crate) fn process_response_for_workerscope(
762        &self,
763        metadata: &Metadata,
764        policy_container: &PolicyContainer,
765    ) {
766        // Step 1. Set worker global scope's url to response's url.
767        self.set_url(metadata.final_url.clone());
768
769        // Step 2. Set inside settings's creation URL to response's url.
770        self.globalscope
771            .set_creation_url(metadata.final_url.clone());
772
773        // Step 3. Initialize worker global scope's policy container given worker global scope, response, and inside settings.
774        self.initialize_policy_container_for_worker_global_scope(metadata, policy_container);
775        self.set_endpoints_list(ReportingEndpoint::parse_reporting_endpoints_header(
776            &metadata.final_url,
777            &metadata.headers,
778        ));
779    }
780
781    pub(crate) fn origin(&self) -> MutableOrigin {
782        self.origin.clone()
783    }
784
785    /// Set the network online state of this worker, returning `true` if anything changed
786    /// and `false` otherwise.
787    pub(crate) fn set_network_online_state(&self, online: bool) -> bool {
788        let previously_online = self.online.replace(online);
789        if previously_online == online {
790            return false;
791        }
792
793        let event_name = Atom::from(if online { "online" } else { "offline" });
794        self.globalscope
795            .task_manager()
796            .networking_task_source()
797            .queue_simple_event(self.globalscope.upcast::<EventTarget>(), event_name);
798        true
799    }
800}
801
802impl WorkerGlobalScopeMethods<crate::DomTypeHolder> for WorkerGlobalScope {
803    /// <https://html.spec.whatwg.org/multipage/#dom-workerglobalscope-self>
804    fn Self_(&self) -> DomRoot<WorkerGlobalScope> {
805        DomRoot::from_ref(self)
806    }
807
808    /// <https://w3c.github.io/IndexedDB/#factory-interface>
809    fn IndexedDB(&self, cx: &mut JSContext) -> DomRoot<IDBFactory> {
810        self.upcast::<GlobalScope>().ensure_indexeddb_factory(cx)
811    }
812
813    /// <https://html.spec.whatwg.org/multipage/#dom-workerglobalscope-location>
814    fn Location(&self, cx: &mut JSContext) -> DomRoot<WorkerLocation> {
815        self.location
816            .or_init(|| WorkerLocation::new(cx, self, self.worker_url.borrow().clone()))
817    }
818
819    /// <https://html.spec.whatwg.org/multipage/#dom-workerglobalscope-importscripts>
820    fn ImportScripts(
821        &self,
822        cx: &mut JSContext,
823        url_strings: Vec<TrustedScriptURLOrUSVString>,
824    ) -> ErrorResult {
825        // https://html.spec.whatwg.org/multipage/#import-scripts-into-worker-global-scope
826        // Step 1: If worker global scope's type is "module", throw a TypeError exception.
827        if self.worker_type == WorkerType::Module {
828            return Err(Error::Type(
829                c"importScripts() is not allowed in module workers".to_owned(),
830            ));
831        }
832
833        // Step 4: Let urlStrings be « ».
834        let mut urls = Vec::with_capacity(url_strings.len());
835        // Step 5: For each url of urls:
836        for url in url_strings {
837            // Step 3: Append the result of invoking the Get Trusted Type compliant string algorithm
838            // with TrustedScriptURL, this's relevant global object, url, "WorkerGlobalScope importScripts",
839            // and "script" to urlStrings.
840            let global_scope = self.upcast::<GlobalScope>();
841            let url = TrustedScriptURL::get_trusted_type_compliant_string(
842                cx,
843                global_scope,
844                url,
845                "WorkerGlobalScope importScripts",
846            )?;
847            let url = self.worker_url.borrow().join(&url.str());
848            let url = match url {
849                Ok(url) => ensure_blob_referenced_by_url_is_kept_alive(global_scope, url),
850                Err(_) => return Err(Error::Syntax(None)),
851            };
852            urls.push(url);
853        }
854
855        for url in urls {
856            let global_scope = self.upcast::<GlobalScope>();
857            let request =
858                RequestBuilder::new(global_scope.webview_id(), url, global_scope.get_referrer())
859                    .destination(Destination::Script)
860                    .credentials_mode(CredentialsMode::Include)
861                    .parser_metadata(ParserMetadata::NotParserInserted)
862                    .use_url_credentials(true)
863                    .with_global_scope(global_scope);
864
865            // https://html.spec.whatwg.org/multipage/#fetch-a-classic-worker-imported-script
866            let (url, bytes, muted_errors) = match load_whole_resource(
867                request,
868                &global_scope.resource_threads().sender(),
869                global_scope,
870                &WorkerCspProcessor {
871                    global_scope: DomRoot::from_ref(global_scope),
872                },
873                cx,
874            ) {
875                Err(_) => return Err(Error::Network(None)),
876                Ok((metadata, bytes, muted_errors)) => {
877                    // Step 7: Check if response status is not an ok status
878                    if !metadata.status.is_success() {
879                        return Err(Error::Network(None));
880                    }
881
882                    // Step 7: Check if the MIME type is not a JavaScript MIME type
883                    let not_a_javascript_mime_type =
884                        !metadata.content_type.is_some_and(|content_type| {
885                            let mime: Mime = content_type.into_inner().into();
886                            SCRIPT_JS_MIMES.contains(&mime.essence_str())
887                        });
888                    if not_a_javascript_mime_type {
889                        return Err(Error::Network(None));
890                    }
891
892                    (metadata.final_url, bytes, muted_errors)
893                },
894            };
895
896            // Step 8. Let sourceText be the result of UTF-8 decoding bodyBytes.
897            let (source, _) = UTF_8.decode_with_bom_removal(&bytes);
898
899            // Step 9. Let mutedErrors be true if response was CORS-cross-origin, and false otherwise.
900            // Note: done inside load_whole_resource
901
902            // Step 10. Let script be the result of creating a classic script
903            // given sourceText, settingsObject, response's URL, the default script fetch options, and mutedErrors.
904            let mut script_options = ScriptOptions::External;
905            script_options.set(ScriptOptions::MutedErrors, muted_errors);
906            let script = self.globalscope.create_a_classic_script(
907                cx,
908                source,
909                url,
910                script_options,
911                ScriptFetchOptions::default_classic_script(),
912                Some(IntroductionType::WORKER),
913                1,
914            );
915
916            // Run the classic script script, with rethrow errors set to true.
917            let result = self.globalscope.run_a_classic_script(
918                cx,
919                script,
920                RethrowErrors::Yes,
921                None, // return_value
922            );
923
924            if let Err(error) = result {
925                if self.is_closing() {
926                    // Don't return JSFailed as we might not have
927                    // any pending exceptions.
928                    error!("evaluate_script failed (terminated)");
929                } else {
930                    error!("evaluate_script failed");
931                    return Err(error);
932                }
933            }
934        }
935
936        Ok(())
937    }
938
939    // https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-onerror
940    error_event_handler!(error, GetOnerror, SetOnerror);
941
942    // https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-onlanguagechange
943    event_handler!(languagechange, GetOnlanguagechange, SetOnlanguagechange);
944
945    // https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-onoffline
946    event_handler!(offline, GetOnoffline, SetOnoffline);
947
948    // https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-ononline
949    event_handler!(online, GetOnonline, SetOnonline);
950
951    // https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-onrejectionhandled
952    event_handler!(
953        rejectionhandled,
954        GetOnrejectionhandled,
955        SetOnrejectionhandled
956    );
957
958    // https://html.spec.whatwg.org/multipage/#handler-workerglobalscope-onunhandledrejection
959    event_handler!(
960        unhandledrejection,
961        GetOnunhandledrejection,
962        SetOnunhandledrejection
963    );
964
965    /// <https://html.spec.whatwg.org/multipage/#dom-worker-navigator>
966    fn Navigator(&self, cx: &mut JSContext) -> DomRoot<WorkerNavigator> {
967        self.navigator.or_init(|| WorkerNavigator::new(cx, self))
968    }
969
970    /// <https://drafts.csswg.org/css-font-loading/#font-face-source>
971    fn Fonts(&self, cx: &mut JSContext) -> DomRoot<FontFaceSet> {
972        self.fonts.or_init(|| {
973            let fonts = FontFaceSet::new(cx, self.upcast(), None);
974            // A worker's font source starts out empty, so there is nothing to wait for.
975            fonts.maybe_switch_worker_set_to_loaded(cx);
976            fonts
977        })
978    }
979
980    /// <https://html.spec.whatwg.org/multipage/#dfn-Crypto>
981    fn Crypto(&self, cx: &mut JSContext) -> DomRoot<Crypto> {
982        self.crypto
983            .or_init(|| Crypto::new(cx, self.upcast::<GlobalScope>()))
984    }
985
986    /// <https://html.spec.whatwg.org/multipage/#dom-reporterror>
987    fn ReportError(&self, cx: &mut JSContext, error: HandleValue) {
988        self.upcast::<GlobalScope>().report_an_exception(cx, error);
989    }
990
991    /// <https://html.spec.whatwg.org/multipage/#dom-windowbase64-btoa>
992    fn Btoa(&self, btoa: DOMString) -> Fallible<DOMString> {
993        base64_btoa(btoa)
994    }
995
996    /// <https://html.spec.whatwg.org/multipage/#dom-windowbase64-atob>
997    fn Atob(&self, atob: DOMString) -> Fallible<DOMString> {
998        base64_atob(atob)
999    }
1000
1001    /// <https://html.spec.whatwg.org/multipage/#dom-windowtimers-settimeout>
1002    fn SetTimeout(
1003        &self,
1004        cx: &mut JSContext,
1005        callback: TrustedScriptOrStringOrFunction,
1006        timeout: i32,
1007        args: Vec<HandleValue>,
1008    ) -> Fallible<i32> {
1009        let callback = match callback {
1010            TrustedScriptOrStringOrFunction::String(i) => {
1011                TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1012            },
1013            TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1014                TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1015            },
1016            TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1017        };
1018        self.upcast::<GlobalScope>().set_timeout_or_interval(
1019            cx,
1020            callback,
1021            args,
1022            Duration::from_millis(timeout.max(0) as u64),
1023            IsInterval::NonInterval,
1024        )
1025    }
1026
1027    /// <https://html.spec.whatwg.org/multipage/#dom-windowtimers-cleartimeout>
1028    fn ClearTimeout(&self, handle: i32) {
1029        self.upcast::<GlobalScope>()
1030            .clear_timeout_or_interval(handle);
1031    }
1032
1033    /// <https://html.spec.whatwg.org/multipage/#dom-windowtimers-setinterval>
1034    fn SetInterval(
1035        &self,
1036        cx: &mut JSContext,
1037        callback: TrustedScriptOrStringOrFunction,
1038        timeout: i32,
1039        args: Vec<HandleValue>,
1040    ) -> Fallible<i32> {
1041        let callback = match callback {
1042            TrustedScriptOrStringOrFunction::String(i) => {
1043                TimerCallback::StringTimerCallback(TrustedScriptOrString::String(i))
1044            },
1045            TrustedScriptOrStringOrFunction::TrustedScript(i) => {
1046                TimerCallback::StringTimerCallback(TrustedScriptOrString::TrustedScript(i))
1047            },
1048            TrustedScriptOrStringOrFunction::Function(i) => TimerCallback::FunctionTimerCallback(i),
1049        };
1050        self.upcast::<GlobalScope>().set_timeout_or_interval(
1051            cx,
1052            callback,
1053            args,
1054            Duration::from_millis(timeout.max(0) as u64),
1055            IsInterval::Interval,
1056        )
1057    }
1058
1059    /// <https://w3c.github.io/ServiceWorker/#global-caches-attribute>
1060    fn Caches(&self, cx: &mut JSContext) -> DomRoot<CacheStorage> {
1061        self.caches
1062            .or_init(|| CacheStorage::new(cx, self.upcast::<GlobalScope>()))
1063    }
1064
1065    /// <https://html.spec.whatwg.org/multipage/#dom-windowtimers-clearinterval>
1066    fn ClearInterval(&self, handle: i32) {
1067        self.ClearTimeout(handle);
1068    }
1069
1070    /// <https://html.spec.whatwg.org/multipage/#dom-queuemicrotask>
1071    fn QueueMicrotask(&self, cx: &mut JSContext, callback: RootedCallback<VoidFunction>) {
1072        self.enqueue_microtask(
1073            cx,
1074            Box::new(UserMicrotask {
1075                callback: callback.to_traced(),
1076                global: Dom::from_ref(&self.globalscope),
1077            }),
1078        );
1079    }
1080
1081    /// <https://html.spec.whatwg.org/multipage/#dom-createimagebitmap>
1082    fn CreateImageBitmap(
1083        &self,
1084        realm: &mut CurrentRealm,
1085        image: ImageBitmapSource,
1086        options: &ImageBitmapOptions,
1087    ) -> RootedPromise {
1088        ImageBitmap::create_image_bitmap(self.upcast(), image, 0, 0, None, None, options, realm)
1089    }
1090
1091    /// <https://html.spec.whatwg.org/multipage/#dom-createimagebitmap>
1092    fn CreateImageBitmap_(
1093        &self,
1094        realm: &mut CurrentRealm,
1095        image: ImageBitmapSource,
1096        sx: i32,
1097        sy: i32,
1098        sw: i32,
1099        sh: i32,
1100        options: &ImageBitmapOptions,
1101    ) -> RootedPromise {
1102        ImageBitmap::create_image_bitmap(
1103            self.upcast(),
1104            image,
1105            sx,
1106            sy,
1107            Some(sw),
1108            Some(sh),
1109            options,
1110            realm,
1111        )
1112    }
1113
1114    /// <https://fetch.spec.whatwg.org/#dom-global-fetch>
1115    fn Fetch(
1116        &self,
1117        realm: &mut CurrentRealm,
1118        input: RequestOrUSVString,
1119        init: &RequestInit,
1120    ) -> RootedPromise {
1121        Fetch(self.upcast(), input, init, realm)
1122    }
1123
1124    /// <https://w3c.github.io/hr-time/#the-performance-attribute>
1125    fn Performance(&self, cx: &mut JSContext) -> DomRoot<Performance> {
1126        self.performance.or_init(|| {
1127            let global_scope = self.upcast::<GlobalScope>();
1128            Performance::new(cx, global_scope, self.navigation_start)
1129        })
1130    }
1131
1132    /// <https://html.spec.whatwg.org/multipage/#dom-origin>
1133    fn Origin(&self) -> USVString {
1134        USVString(
1135            self.upcast::<GlobalScope>()
1136                .origin()
1137                .immutable()
1138                .ascii_serialization()
1139                .into_owned(),
1140        )
1141    }
1142
1143    /// <https://w3c.github.io/webappsec-secure-contexts/#dom-windoworworkerglobalscope-issecurecontext>
1144    fn IsSecureContext(&self) -> bool {
1145        self.upcast::<GlobalScope>().is_secure_context()
1146    }
1147
1148    /// <https://html.spec.whatwg.org/multipage/#dom-structuredclone>
1149    fn StructuredClone(
1150        &self,
1151        cx: &mut JSContext,
1152        value: HandleValue,
1153        options: &StructuredSerializeOptions,
1154        retval: MutableHandleValue,
1155    ) -> Fallible<()> {
1156        self.upcast::<GlobalScope>()
1157            .structured_clone(cx, value, options, retval)
1158    }
1159
1160    /// <https://www.w3.org/TR/trusted-types/#dom-windoworworkerglobalscope-trustedtypes>
1161    fn TrustedTypes(&self, cx: &mut JSContext) -> DomRoot<TrustedTypePolicyFactory> {
1162        self.trusted_types.or_init(|| {
1163            let global_scope = self.upcast::<GlobalScope>();
1164            TrustedTypePolicyFactory::new(cx, global_scope)
1165        })
1166    }
1167}
1168
1169impl WorkerGlobalScope {
1170    pub(crate) fn new_script_pair(&self) -> (ScriptEventLoopSender, ScriptEventLoopReceiver) {
1171        let dedicated = self.downcast::<DedicatedWorkerGlobalScope>();
1172        if let Some(dedicated) = dedicated {
1173            dedicated.new_script_pair()
1174        } else if let Some(shared) = self.downcast::<SharedWorkerGlobalScope>() {
1175            shared.new_script_pair()
1176        } else {
1177            panic!("need to implement a sender for ServiceWorker")
1178        }
1179    }
1180
1181    /// Process a single event as if it were the next event
1182    /// in the queue for this worker event-loop.
1183    /// Returns a boolean indicating whether further events should be processed.
1184    pub(crate) fn process_event(&self, msg: CommonScriptMsg, cx: &mut JSContext) -> bool {
1185        if self.is_closing() {
1186            return false;
1187        }
1188
1189        let mut realm = enter_auto_realm(cx, self);
1190        let cx = &mut realm;
1191
1192        match msg {
1193            CommonScriptMsg::Task(_, task, _, _) => task.run_box(cx),
1194            CommonScriptMsg::CollectReports(reports_chan) => {
1195                perform_memory_report(|ops| {
1196                    let reports =
1197                        get_reports(cx, format!("url({})", self.get_url()), ops, HashSet::new());
1198                    reports_chan.send(ProcessReports::new(reports));
1199                });
1200            },
1201            CommonScriptMsg::ReportCspViolations(_, violations) => {
1202                self.upcast::<GlobalScope>()
1203                    .report_csp_violations(cx, violations, None, None);
1204            },
1205        }
1206        true
1207    }
1208
1209    /// <https://html.spec.whatwg.org/multipage/#close-a-worker>
1210    pub(crate) fn close(&self) {
1211        // Step 1. Discard any tasks that have been added to workerGlobal's relevant
1212        // agent's event loop's task queues.
1213        //
1214        // Worker rAF callbacks are stored outside the task queues.
1215        if let Some(dedicated) = self.downcast::<DedicatedWorkerGlobalScope>() {
1216            dedicated.clear_animation_frame_callbacks_and_unregister();
1217        }
1218
1219        // Step 2. Set workerGlobal's closing flag to true. (This prevents any
1220        // further tasks from being queued.)
1221        self.closing.store(true, Ordering::SeqCst);
1222        self.upcast::<GlobalScope>()
1223            .task_manager()
1224            .cancel_all_tasks_and_ignore_future_tasks();
1225
1226        // From <https://w3c.github.io/IndexedDB/#database-connection>
1227        // > The connection can be closed through several means. If the execution context where
1228        // > the connection was created is destroyed (for example due to the user navigating away
1229        // > from that page), the connection is closed.
1230        if let Some(factory) = self.upcast::<GlobalScope>().indexeddb_factory() {
1231            factory.abort_pending_upgrades_and_close_databases();
1232        }
1233    }
1234}
1235
1236#[cfg(feature = "devtools")]
1237impl WorkerGlobalScope {
1238    pub(crate) fn init_debugger_global(
1239        &self,
1240        debugger_global: Option<&DebuggerGlobalScope>,
1241        cx: &mut JSContext,
1242    ) {
1243        let Some(debugger_global) = debugger_global else {
1244            return;
1245        };
1246
1247        let mut realm = enter_auto_realm(cx, self);
1248        let cx = &mut realm.current_realm();
1249
1250        // Convert the debugger global’s reflector to a Value, wrapping it from its originating realm (debugger realm)
1251        // into the active realm (debuggee realm) so that it can be passed across compartments.
1252        rooted!(&in(cx) let mut wrapped_global: Value);
1253        debugger_global
1254            .reflector()
1255            .to_jsval(cx, wrapped_global.handle_mut());
1256        self.debugger_global.set(*wrapped_global);
1257    }
1258
1259    pub(crate) fn handle_devtools_message(&self, msg: DevtoolScriptControlMsg, cx: &mut JSContext) {
1260        match msg {
1261            DevtoolScriptControlMsg::WantsLiveNotifications(_pipe_id, _wants_updates) => {},
1262            DevtoolScriptControlMsg::Eval(code, id, frame_actor_id, eager, reply) => {
1263                let debugger_global_handle = rooted_heap_handle(self, |this| &this.debugger_global);
1264                let debugger_global =
1265                    root_from_handlevalue::<DebuggerGlobalScope>(cx, debugger_global_handle)
1266                        .expect("must be a debugger global scope");
1267
1268                debugger_global.fire_eval(
1269                    cx,
1270                    code.into(),
1271                    id,
1272                    Some(self.worker_id()),
1273                    frame_actor_id,
1274                    eager,
1275                    reply,
1276                );
1277            },
1278            _ => debug!("got an unusable devtools control message inside the worker!"),
1279        }
1280    }
1281}
1282
1283#[expect(unsafe_code)]
1284unsafe extern "C" fn interrupt_callback(cx: *mut RawJSContext) -> bool {
1285    // SAFETY: it is safe to construct a JSContext from engine hook.
1286    let mut cx = unsafe { JSContext::from_ptr(std::ptr::NonNull::new(cx).unwrap()) };
1287    let mut realm = CurrentRealm::assert(&mut cx);
1288
1289    let global = GlobalScope::from_current_realm(&mut realm);
1290
1291    // If we are running the debugger script, just exit immediately.
1292    let Some(worker) = global.downcast::<WorkerGlobalScope>() else {
1293        return false;
1294    };
1295
1296    // A false response causes the script to terminate.
1297    !worker.is_closing()
1298}
1299
1300struct WorkerCspProcessor {
1301    global_scope: DomRoot<GlobalScope>,
1302}
1303
1304impl CspViolationsProcessor for WorkerCspProcessor {
1305    fn process_csp_violations(&self, cx: &mut JSContext, violations: Vec<Violation>) {
1306        self.global_scope
1307            .report_csp_violations(cx, violations, None, None);
1308    }
1309}