Skip to main content

sk_runtime/
app_devtools.rs

1//! `appDevtools`: an app switching the devtools off at runtime (`disable()`, or `"devtools": false`),
2//! back on, or opening the inspector. Without a [`DevtoolsHost`] (`--features no-devtools`) it answers
3//! inertly instead of throwing, so `disable()` in an entry module is harmless.
4
5use std::cell::RefCell;
6use std::ffi::c_void;
7
8use redjs::ffi::{redjs_protect, redjs_unprotect};
9use redjs::webapi::util::*;
10
11use crate::host::{self, warn_compat};
12
13#[derive(Default)]
14pub struct DevtoolsInfo {
15    pub enabled: bool,
16    /// `SK_DEVTOOLS=1`, which refuses `disable()`.
17    pub locked: bool,
18    pub port: Option<u16>,
19    pub pid: u32,
20    /// The `SK_DEVTOOLS_KEY` gate on F12.
21    pub key: bool,
22    pub inspectors: usize,
23    /// The dist slot whose `devtools.json` the host publishes into.
24    pub slot: String,
25}
26
27pub trait DevtoolsHost {
28    fn info(&self) -> DevtoolsInfo;
29    /// The state afterwards, or why the change was refused.
30    fn set_enabled(&self, on: bool) -> Result<bool, String>;
31    fn open(&self) -> Result<bool, String>;
32}
33
34thread_local! {
35    static HOST: RefCell<Option<Box<dyn DevtoolsHost>>> = const { RefCell::new(None) };
36    static WATCHERS: RefCell<Vec<u64>> = const { RefCell::new(Vec::new()) };
37}
38
39const NO_DEVTOOLS: &str = "this host was built with `--features no-devtools`";
40
41fn info() -> Option<DevtoolsInfo> {
42    HOST.with(|h| h.borrow().as_ref().map(|h| h.info()))
43}
44
45fn enabled() -> bool {
46    info().is_some_and(|i| i.enabled)
47}
48
49unsafe fn notify(g: *mut c_void, on: bool) {
50    let watchers = WATCHERS.with(|w| w.borrow().clone());
51    for f in watchers {
52        if let Err(e) = call(g, f, UNDEF, &[enc_bool(on)]) {
53            let e = host::string_arg(g, e).unwrap_or_default();
54            warn_compat(
55                g,
56                "appDevtools.onChange",
57                &format!("a change listener threw and was ignored: {e}"),
58            );
59        }
60    }
61}
62
63unsafe fn set(g: *mut c_void, on: bool) -> u64 {
64    let was = enabled();
65    let Some(outcome) = HOST.with(|h| h.borrow().as_ref().map(|h| h.set_enabled(on))) else {
66        if on {
67            warn_compat(
68                g,
69                "appDevtools",
70                &format!("{NO_DEVTOOLS}, so there are no devtools to enable — `appDevtools.enable()` did nothing."),
71            );
72        }
73        return FALSE;
74    };
75    match outcome {
76        Ok(now) => {
77            if now != was {
78                notify(g, now);
79            }
80            enc_bool(now)
81        }
82        Err(e) => {
83            let verb = if on { "enable" } else { "disable" };
84            warn_compat(g, "appDevtools", &format!("{verb}() was refused: {e}"));
85            enc_bool(was)
86        }
87    }
88}
89
90crate::host_fn!(fn available(_g, _args) {
91    enc_bool(HOST.with(|h| h.borrow().is_some()))
92});
93
94crate::host_fn!(fn is_enabled(_g, _args) {
95    enc_bool(enabled())
96});
97
98crate::host_fn!(fn enable(g, _args) {
99    unsafe { set(g, true) }
100});
101
102crate::host_fn!(fn disable(g, _args) {
103    unsafe { set(g, false) }
104});
105
106crate::host_fn!(fn open(g, _args) {
107    let outcome = HOST.with(|h| h.borrow().as_ref().map(|h| h.open()));
108    let refusal = match outcome {
109        Some(Ok(opened)) => return enc_bool(opened),
110        Some(Err(e)) => format!("open() did not open an inspector: {e}"),
111        None => format!("{NO_DEVTOOLS} — `appDevtools.open()` has no inspector to open."),
112    };
113    unsafe { warn_compat(g, "appDevtools", &refusal) };
114    FALSE
115});
116
117crate::host_fn!(fn info_js(g, _args) {
118    let i = info().unwrap_or_default();
119    let info = serde_json::json!({
120        "enabled": i.enabled, "locked": i.locked, "port": i.port, "pid": i.pid, "key": i.key,
121        "inspectors": i.inspectors, "slot": i.slot,
122    });
123    unsafe { host::to_js(g, &info) }
124});
125
126crate::host_fn!(fn on_change(g, args) {
127    unsafe {
128        let f = args.arg(0).0;
129        if !is_cell(f) || get(g, f, "call") == UNDEF {
130            return host::throw(g, "TypeError", "appDevtools.onChange expects a function");
131        }
132        let fresh = WATCHERS.with(|w| {
133            let mut w = w.borrow_mut();
134            let fresh = !w.contains(&f);
135            if fresh {
136                w.push(f);
137            }
138            fresh
139        });
140        if fresh {
141            redjs_protect(g, f);
142        }
143        let off = make_fn(g, "off", 0, off);
144        call(g, get(g, off, "bind"), off, &[f]).unwrap_or(UNDEF)
145    }
146});
147
148crate::host_fn!(fn off(g, args) {
149    let f = args.this().0;
150    let removed = WATCHERS.with(|w| {
151        let mut w = w.borrow_mut();
152        let before = w.len();
153        w.retain(|x| *x != f);
154        before != w.len()
155    });
156    if removed {
157        unsafe { redjs_unprotect(g, f) };
158    }
159    UNDEF
160});
161
162/// Installs `__sk_appDevtools` over `host`, or the inert one for `None`.
163pub unsafe fn install(g: *mut c_void, host: Option<Box<dyn DevtoolsHost>>) {
164    HOST.with(|h| *h.borrow_mut() = host);
165    let obj = host::install_object(g, "__sk_appDevtools", UNDEF);
166    host::getter(g, obj, "available", available);
167    host::method(g, obj, "isEnabled", 0, is_enabled);
168    host::method(g, obj, "enable", 0, enable);
169    host::method(g, obj, "disable", 0, disable);
170    host::method(g, obj, "open", 0, open);
171    host::method(g, obj, "info", 0, info_js);
172    host::method(g, obj, "onChange", 1, on_change);
173}
174
175#[cfg(test)]
176mod tests {
177    use std::cell::Cell;
178    use std::rc::Rc;
179
180    use super::*;
181    use crate::testing::on_js_thread;
182    use crate::JsRuntime;
183
184    #[derive(Default)]
185    struct Fake {
186        enabled: Cell<bool>,
187        locked: Cell<bool>,
188        opens: Cell<u32>,
189    }
190
191    struct Shared(Rc<Fake>);
192
193    impl DevtoolsHost for Shared {
194        fn info(&self) -> DevtoolsInfo {
195            let enabled = self.0.enabled.get();
196            DevtoolsInfo {
197                enabled,
198                locked: self.0.locked.get(),
199                port: enabled.then_some(49221),
200                ..DevtoolsInfo::default()
201            }
202        }
203        fn set_enabled(&self, on: bool) -> Result<bool, String> {
204            if !on && self.0.locked.get() {
205                return Err("SK_DEVTOOLS=1 holds the devtools on".into());
206            }
207            self.0.enabled.set(on);
208            Ok(on)
209        }
210        fn open(&self) -> Result<bool, String> {
211            if !self.0.enabled.get() {
212                return Err("the devtools are disabled".into());
213            }
214            self.0.opens.set(self.0.opens.get() + 1);
215            Ok(true)
216        }
217    }
218
219    fn eval(src: &str) -> String {
220        JsRuntime::with(|rt| {
221            let v = rt.ctx().eval(src).expect(src);
222            rt.ctx().to_rust_string(v).unwrap_or_default()
223        })
224    }
225
226    #[test]
227    fn changes_reach_listeners_once_and_refusals_do_not() {
228        on_js_thread(|| {
229            let fake = Rc::new(Fake::default());
230            fake.enabled.set(true);
231            JsRuntime::with(|rt| unsafe {
232                install(rt.raw(), Some(Box::new(Shared(fake.clone()))))
233            });
234            assert_eq!(
235                eval(
236                    "globalThis.seen = []; globalThis.dt = __sk_appDevtools; \
237                     dt.onChange(() => { throw new Error('boom'); }); \
238                     const watch = (on) => seen.push(on); \
239                     globalThis.offWatch = dt.onChange(watch); dt.onChange(watch); \
240                     [dt.disable(), dt.disable(), dt.info().port, dt.enable(), dt.info().port, seen.join(',')].join('|')"
241                ),
242                "false|false||true|49221|false,true"
243            );
244            fake.locked.set(true);
245            assert_eq!(
246                eval("[dt.disable(), dt.isEnabled(), seen.length].join('|')"),
247                "true|true|2"
248            );
249            fake.locked.set(false);
250            assert_eq!(
251                eval("[dt.open(), offWatch(), dt.disable(), seen.length, dt.open()].join('|')"),
252                "true||false|2|false"
253            );
254            assert_eq!(fake.opens.get(), 1);
255        });
256    }
257
258    #[test]
259    fn without_a_host_it_answers_inertly() {
260        on_js_thread(|| {
261            JsRuntime::with(|rt| unsafe { install(rt.raw(), None) });
262            assert_eq!(
263                eval(
264                    "(() => { const dt = __sk_appDevtools; \
265                     return [dt.available, dt.isEnabled(), dt.disable(), dt.enable(), dt.open(), dt.info().port, \
266                      typeof dt.onChange(() => {})].join('|'); })()"
267                ),
268                "false|false|false|false|false||function"
269            );
270        });
271    }
272}