nsh-engine 0.8.1

Engine thread that drives the JS host and the core and emits mount batches.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
//! `openUrl` of `nsh/device`: the platform opens what the embedding app's
//! URL handler does not take, what the handler takes never reaches the
//! platform, and refused URLs and capabilities reject; a `TextView` with
//! `links="open"` opens its links, and a `Link` its `href`. And
//! `nsh/mobile`'s `AppSettings.open`: sent to a platform that has the app's
//! settings page, rejected at once elsewhere.

use std::time::Duration;

use crossbeam_channel::Receiver;
use nsh_core::{
    ApproxTextEngine, Command, EventKind, EventPayload, MountBatch, MountItem, PayloadValue,
    ROOT_ID, Size, geometry::px,
};
use nsh_engine::{Bundle, Capabilities, Engine, EngineConfig, HostChannel};

use crate::ChannelSink;

fn bundle(app: &str) -> Bundle {
    static APPS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
    let dir = crate::temporary_root().join(format!(
        "nsh-open-url-{}-{}",
        std::process::id(),
        APPS.fetch_add(1, std::sync::atomic::Ordering::Relaxed)
    ));
    std::fs::create_dir_all(&dir).unwrap();
    let entry = dir.join("App.tsx");
    std::fs::write(&entry, app).unwrap();
    let ui_sets = [nsh_base::registry()];
    let bundle = nsh_bundler::bundle(&nsh_bundler::BundleOptions {
        entry,
        minify: false,
        split: false,
        ui_sets: ui_sets.iter().map(Into::into).collect(),
        ..Default::default()
    })
    .unwrap();
    let bytecode = nsh_js::compile_bytecode_with(
        &bundle.code,
        false,
        &ui_sets.iter().map(Into::into).collect::<Vec<_>>(),
    )
    .unwrap();
    // SAFETY: compiled just now by this runtime.
    unsafe { Bundle::bytecode(bytecode) }
}

fn start(bundle: Bundle, host: &HostChannel) -> (Engine, Receiver<MountBatch>) {
    let (tx, rx) = crossbeam_channel::unbounded();
    let config = EngineConfig {
        viewport: Size::new(px(400.0), px(600.0)),
        host: host.clone(),
        ui_sets: vec![nsh_base::registry()],
        ..EngineConfig::new(bundle)
    };
    (
        Engine::start(config, || ApproxTextEngine, ChannelSink(tx)).unwrap(),
        rx,
    )
}

/// Plays the platform until a shown text contains every one of `parts`:
/// each URL it is asked to open is recorded and answered with `opened`.
/// Returns the text and the URLs.
fn run(
    engine: &Engine,
    rx: &Receiver<MountBatch>,
    opened: bool,
    parts: &[&str],
) -> (String, Vec<String>) {
    let mut last = String::new();
    let mut urls = Vec::new();
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    while std::time::Instant::now() < deadline {
        let Ok(batch) = rx.recv_timeout(Duration::from_millis(100)) else {
            continue;
        };
        for item in batch.items {
            match item {
                MountItem::Text { text, .. } => last = text.text.to_string(),
                MountItem::Command {
                    id,
                    command: Command::OpenUrl { id: request, url },
                } => {
                    assert_eq!(id, ROOT_ID);
                    urls.push(url);
                    engine.control().dispatch_event(
                        ROOT_ID,
                        EventKind::OpenUrl,
                        EventPayload::Map(vec![
                            ("id", PayloadValue::Number(f64::from(request))),
                            ("opened", PayloadValue::Bool(opened)),
                        ]),
                    );
                }
                _ => {}
            }
        }
        if parts.iter().all(|p| last.contains(p)) {
            return (last, urls);
        }
    }
    panic!("no text with {parts:?}; last: {last}");
}

const APP: &str = r#"import { mount, signal, Text } from "nsh";
import { openUrl } from "nsh";

const log = signal<string[]>([]);
const say = (s: string) => log.set([...log(), s]);

openUrl("https://example.com/a?b=1").then(({ opened }) => say(`web ${opened}`));
openUrl("mailto:ada@example.com").then(({ opened }) => say(`mail ${opened}`));
for (const url of ["javascript:alert(1)", "example.com", "file:///etc/passwd"]) {
  openUrl(url).catch((e: Error) => say(`refused ${e.name}`));
}

mount(() => <Text>{log().join(" | ")}</Text>);
"#;

#[test]
fn the_platform_opens_urls() {
    let (engine, rx) = start(bundle(APP), &HostChannel::new());
    let (text, urls) = run(&engine, &rx, true, &["web true", "mail true"]);
    assert_eq!(text.matches("refused TypeError").count(), 3, "{text}");
    assert_eq!(
        urls,
        ["https://example.com/a?b=1", "mailto:ada@example.com"]
    );
    drop(engine);

    // No app for the scheme: false.
    let (engine, rx) = start(bundle(APP), &HostChannel::new());
    run(&engine, &rx, false, &["web false", "mail false"]);
    drop(engine);
}

#[test]
fn the_embedding_app_takes_urls_first() {
    let host = HostChannel::new();
    let (seen_tx, seen) = crossbeam_channel::unbounded();
    host.handle_open_url(move |request| {
        let _ = seen_tx.send(request.url().to_owned());
        // The host's router takes web pages and leaves the rest (answered
        // from another thread, or dropped) to the system.
        if request.url().starts_with("https:") {
            std::thread::spawn(move || request.handled());
        } else {
            drop(request);
        }
    });
    let (engine, rx) = start(bundle(APP), &host);
    let (_, urls) = run(&engine, &rx, true, &["web true", "mail true"]);
    assert_eq!(urls, ["mailto:ada@example.com"]);
    let seen: Vec<String> = seen.try_iter().collect();
    assert_eq!(
        seen,
        ["https://example.com/a?b=1", "mailto:ada@example.com"]
    );
    drop(engine);

    // Without the handler, the system opens both.
    host.remove_open_url_handler();
    let (engine, rx) = start(bundle(APP), &host);
    let (_, urls) = run(&engine, &rx, true, &["web true", "mail true"]);
    assert_eq!(urls.len(), 2);
    drop(engine);
}

const LINKS: &str = r#"import { mount, signal, Text, View } from "nsh";
import { TextView } from "nsh/base";

const pressed = signal<string[]>([]);
mount(() => (
  <View>
    <TextView
      markdown="See [the docs](https://example.com/docs) or [the top](#top)."
      links="open"
      onLinkPress={({ url, modifiers }) => pressed.set([...pressed(), modifiers.platform ? `cmd+${url}` : url])}
    />
    <Text>{`pressed ${pressed().join(" ")}`}</Text>
  </View>
));
"#;

#[test]
fn a_text_view_opens_its_links_when_asked() {
    let (engine, rx) = start(bundle(LINKS), &HostChannel::new());
    // The links of the paragraph's text, as the platform presses them.
    let mut links = Vec::new();
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    while links.len() < 2 && std::time::Instant::now() < deadline {
        if let Ok(batch) = rx.recv_timeout(Duration::from_millis(100)) {
            for item in batch.items {
                if let MountItem::Text { text, .. } = item
                    && text.links.len() == 2
                {
                    links = text.links.iter().map(|l| l.node).collect();
                }
            }
        }
    }
    assert_eq!(links.len(), 2, "no text with two links");
    // The page clicked with Command held, the anchor pressed from the
    // keyboard (no pointer, no modifiers).
    let cmd = nsh_core::PressEvent {
        modifiers: nsh_core::keymap::Modifiers {
            cmd: true,
            ..Default::default()
        },
        clicks: 1,
        ..Default::default()
    };
    engine
        .control()
        .dispatch_event(links[0], EventKind::Press, EventPayload::Press(cmd));
    engine
        .control()
        .dispatch_event(links[1], EventKind::Press, EventPayload::None);
    // The page opens; the anchor is only reported.
    let (_, urls) = run(
        &engine,
        &rx,
        true,
        &["pressed cmd+https://example.com/docs #top"],
    );
    assert_eq!(urls, ["https://example.com/docs"]);
    drop(engine);
}

const LINK: &str = r#"import { mount, signal, Text, View } from "nsh";
import { Link } from "nsh/base";

const log = signal<string[]>([]);
const say = (s: string) => log.set([...log(), s]);
mount(() => (
  <View>
    <Link testID="docs" href="https://example.com/docs" onOpen={({ href }) => say(`open ${href}`)} onPress={() => say("press")}>
      <Text>Docs</Text>
    </Link>
    <Link testID="order" href="/orders/42" openWith="app" accessibilityLabel="Order 42" onOpen={({ href }) => say(`route ${href}`)}>
      <Text>#42</Text>
    </Link>
    <Link testID="home" current disabled href="https://example.com" class="disabled:opacity-50">
      <Text>Home</Text>
    </Link>
    <Text>{`log ${log().join(" | ")}`}</Text>
  </View>
));
"#;

/// `nsh/base`'s `Link` through its JS face: the link role, its label and
/// the current page for screen readers, no style of its own; a press opens
/// a site through the system after `onOpen`, and `openWith="app"` leaves
/// the opening to the app.
#[test]
fn a_link_opens_its_href_through_the_system_or_the_app() {
    use nsh_core::{AccessibilityCurrent, AccessibilityRole, ViewProps};
    let (engine, rx) = start(bundle(LINK), &HostChannel::new());
    let first = rx
        .recv_timeout(Duration::from_secs(5))
        .expect("first frame");
    let props = |test_id: &str| -> (u32, ViewProps) {
        first
            .items
            .iter()
            .find_map(|i| match i {
                MountItem::ViewProps { id, props } if props.test_id.as_deref() == Some(test_id) => {
                    Some((*id, (**props).clone()))
                }
                _ => None,
            })
            .expect(test_id)
    };
    let (docs, docs_props) = props("docs");
    let (order, order_props) = props("order");
    let (home, home_props) = props("home");
    for p in [&docs_props, &order_props, &home_props] {
        assert_eq!(p.accessibility.role, AccessibilityRole::Link);
    }
    assert_eq!(order_props.accessibility.label.as_deref(), Some("Order 42"));
    assert_eq!(docs_props.accessibility.state.current, None);
    assert_eq!(
        home_props.accessibility.state.current,
        Some(AccessibilityCurrent::Page)
    );
    assert!(home_props.accessibility.state.disabled);
    // No look of its own beyond the pointer cursor: only the app's
    // `disabled:` class styles a link.
    for id in [docs, order] {
        for i in &first.items {
            if let MountItem::ViewStyle { id: v, style } = i
                && *v == id
            {
                assert_eq!(style.cursor, nsh_core::Cursor::Pointer);
                let mut rest = style.clone();
                rest.cursor = Default::default();
                assert_eq!(rest, Default::default(), "no style beyond the cursor");
            }
        }
    }
    // A disabled link takes no presses.
    assert!(!first.items.iter().any(|i| matches!(
        i,
        MountItem::Events { id, events } if *id == home && events.contains(EventKind::Press)
    )));

    engine
        .control()
        .dispatch_event(docs, EventKind::Press, EventPayload::None);
    let (_, urls) = run(
        &engine,
        &rx,
        true,
        &["open https://example.com/docs | press"],
    );
    assert_eq!(urls, ["https://example.com/docs"]);
    engine
        .control()
        .dispatch_event(order, EventKind::Press, EventPayload::None);
    let (_, urls) = run(&engine, &rx, true, &["route /orders/42"]);
    assert!(urls.is_empty(), "the app routes it: {urls:?}");
    drop(engine);
}

const GUARDED: &str = r#"import { mount, signal, Text } from "nsh";
import { openUrl } from "nsh";

const log = signal("start");
openUrl("https://example.com").catch((e: Error & { code?: string; permission?: string; resource?: string }) =>
  log.set(`denied ${e.name} ${e.code} ${e.permission} ${e.resource} ${e.message}`),
);
mount(() => <Text>{log()}</Text>);
"#;

#[test]
fn opening_urls_is_a_capability() {
    let mut app = bundle(GUARDED);
    app.policy.declared = Some(
        Capabilities::from_json(&serde_json::json!({ "network": { "hosts": ["*"] } })).unwrap(),
    );
    let (engine, rx) = start(app, &HostChannel::new());
    let (text, urls) = run(
        &engine,
        &rx,
        true,
        &["denied Error ERR_ACCESS_DENIED openUrl https://example.com "],
    );
    assert!(text.contains("\"openUrl\": true"), "{text}");
    assert!(urls.is_empty());
    drop(engine);

    let mut app = bundle(GUARDED);
    app.policy.declared =
        Some(Capabilities::from_json(&serde_json::json!({ "openUrl": true })).unwrap());
    let (engine, rx) = start(app, &HostChannel::new());
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    let mut urls = Vec::new();
    while urls.is_empty() && std::time::Instant::now() < deadline {
        if let Ok(batch) = rx.recv_timeout(Duration::from_millis(100)) {
            for item in batch.items {
                if let MountItem::Command {
                    command: Command::OpenUrl { url, .. },
                    ..
                } = item
                {
                    urls.push(url);
                }
            }
        }
    }
    assert_eq!(urls, ["https://example.com"]);
    drop(engine);
}

/// A Rust root that opens an `https:` URL, then an `smb:` one, and shows
/// the answers.
#[nsh_core::prelude::component]
fn Opener() -> impl nsh_core::prelude::IntoElement {
    use nsh_core::prelude::*;
    let answers = signal(String::new());
    spawn(async move {
        let web = open_url("https://example.com/a").await;
        let share = open_url("smb://server/share").await;
        answers.set(format!("web {web} share {share}"));
    });
    text(move || answers.get())
}

/// Runs `root` until it shows its answers: the text and the URLs it asked
/// the platform to open.
fn opened_by(root: nsh_core::element::Root) -> (String, Vec<String>) {
    let (tx, rx) = crossbeam_channel::unbounded();
    let config = EngineConfig {
        viewport: Size::new(px(400.0), px(600.0)),
        ..EngineConfig::new(root)
    };
    let engine = Engine::start(config, || ApproxTextEngine, ChannelSink(tx)).unwrap();
    run(&engine, &rx, true, &["web ", "share "])
}

#[test]
fn a_rust_root_opens_urls_under_its_declared_capabilities() {
    use nsh_core::element::Root;
    // `nsh.json` `capabilities` of a Rust root (`"root"`): only `https:`.
    let declared =
        Capabilities::from_json(&serde_json::json!({ "openUrl": { "schemes": ["https"] } }))
            .unwrap();
    let (text, urls) = opened_by(Root::of::<Opener>().capabilities(declared));
    assert_eq!(text, "web true share false");
    assert_eq!(urls, ["https://example.com/a"]);

    // No declaration: every URL the platform opens.
    let (text, urls) = opened_by(Root::of::<Opener>());
    assert_eq!(text, "web true share true");
    assert_eq!(urls, ["https://example.com/a", "smb://server/share"]);
}

const SETTINGS_APP: &str = r#"import { mount, signal, Text } from "nsh";
import { AppSettings } from "nsh/mobile";

const log = signal<string[]>([]);
const say = (s: string) => log.set([...log(), s]);

AppSettings.available().then((yes: boolean) => say(`available ${yes}`));
const pending = AppSettings.open();
say(`promise ${typeof pending.then}`);
pending.then(
  ({ opened }) => say(`opened ${opened}`),
  (e: Error & { code?: string }) => say(`rejected ${e.code}`),
);

mount(() => <Text>{log().join(" | ")}</Text>);
"#;

/// Runs [`SETTINGS_APP`] on a platform that has the app's settings page or
/// not, answering each request with `opened`, until it shows `last`.
/// Returns the text and how many requests reached the platform.
fn open_settings(app_settings: bool, opened: bool, last: &str) -> (String, usize) {
    let (tx, rx) = crossbeam_channel::unbounded();
    let config = EngineConfig {
        viewport: Size::new(px(400.0), px(600.0)),
        environment: nsh_engine::Environment {
            app_settings,
            ..Default::default()
        },
        ..EngineConfig::new(bundle(SETTINGS_APP))
    };
    let engine = Engine::start(config, || ApproxTextEngine, ChannelSink(tx)).unwrap();
    let mut text = String::new();
    let mut requests = 0;
    let deadline = std::time::Instant::now() + Duration::from_secs(5);
    while std::time::Instant::now() < deadline {
        let Ok(batch) = rx.recv_timeout(Duration::from_millis(100)) else {
            continue;
        };
        for item in batch.items {
            match item {
                MountItem::Text { text: shown, .. } => text = shown.text.to_string(),
                MountItem::Command {
                    id,
                    command: Command::OpenAppSettings { id: request },
                } => {
                    assert_eq!(id, ROOT_ID);
                    requests += 1;
                    engine.control().dispatch_event(
                        ROOT_ID,
                        EventKind::OpenAppSettings,
                        EventPayload::Map(vec![
                            ("id", PayloadValue::Number(f64::from(request))),
                            ("opened", PayloadValue::Bool(opened)),
                        ]),
                    );
                }
                _ => {}
            }
        }
        if text.contains(last) && text.contains("available") {
            return (text, requests);
        }
    }
    panic!("no text with {last:?}; last: {text}");
}

#[test]
fn the_platform_opens_the_apps_settings_page() {
    let (text, requests) = open_settings(true, true, "opened true");
    assert_eq!(requests, 1);
    assert!(text.contains("promise function"), "{text}");
    assert!(text.contains("available true"), "{text}");

    // The system did not open it: false, never a rejection.
    let (text, _) = open_settings(true, false, "opened false");
    assert!(!text.contains("rejected"), "{text}");
}

#[test]
fn the_apps_settings_page_rejects_at_once_where_the_platform_has_none() {
    let (text, requests) =
        open_settings(false, true, "rejected ERR_FEATURE_UNAVAILABLE_ON_PLATFORM");
    assert_eq!(requests, 0, "nothing reaches the platform");
    assert!(text.contains("promise function"), "{text}");
    assert!(text.contains("available false"), "{text}");
    assert!(!text.contains("opened"), "{text}");
}