nsh-js 0.2.0

QuickJS host: runtime setup, host APIs, op decoding and bytecode.
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
//! The TypeScript declarations of what apps import (`.nsh/types`), made
//! from what serves it: the declaration ([`Ts`]) next to each export of
//! nsh's modules (`modules.rs` and the tables it lists), the modules' own
//! types, the specs of the registries' components and modules
//! (`nsh_core::ui::declarations`), and the core's tables (styles, host
//! props and events, easings, canvas operations: `nsh_core::js`). Nothing
//! is written twice: a test loads every module and checks that what it
//! exports is what its declarations say.
//!
//! Each file declares its own names; the `import type` lines between the
//! files are worked out from the names each one uses.

use std::{collections::BTreeMap, fmt::Write as _};

use nsh_core::ui::{Registry, description::SetDescription};

use crate::modules::{Item, MODULES, NativeModule, Ts};

/// The banner of every file.
const BANNER: &str = "// Generated by nsh from its Rust sources: do not edit.\n\n";

/// The element and JSX types (`types.d.ts`, all exported by `nsh`) that do
/// not come from a table: how the tables' interfaces make up the props of
/// each element.
const ELEMENT_TYPES: &str = r#"/** A list of styles, possibly nested: `[base, props.style]` where
 * `props.style` is itself a list. */
export type RecursiveArray<T> = readonly (T | RecursiveArray<T>)[];

/** A style, or a list of styles (nested lists included) merged left to
 * right; falsy entries are skipped. */
export type StyleProp<T> = T | RecursiveArray<T | false | null | undefined> | false | null | undefined;

/** Props every host element accepts. */
export interface CommonProps extends TouchProps, HostProps, StateStyleProps {
  ref?: YNode | ((node: YNode) => void);
  children?: JSX.Element;
  /** iOS-only props (ignored elsewhere). */
  ios?: IOSProps;
  /** Android-only props (ignored elsewhere). */
  android?: AndroidProps;
  /** Desktop-only props (macOS, Windows, Linux and desktop browsers;
   * ignored on mobile). */
  desktop?: DesktopProps;
  /** Web-only props (ignored elsewhere). */
  web?: WebProps;
}

/** Styles while the element is in a state, over its own `style` and
 * classes, applied natively (no JS runs): as the `<state>:` classes.
 * Later states win (checked, then hover, focus, active); `disabledStyle`
 * wins over all, and the others do not apply while disabled. */
export interface StateStyleProps {
  /** While pressed (`active:`). */
  activeStyle?: StyleProp<ViewStyle>;
  /** While a pointer is over it (`hover:`). */
  hoverStyle?: StyleProp<ViewStyle>;
  /** While it has focus (`focus:`). */
  focusStyle?: StyleProp<ViewStyle>;
  /** While `disabled` (`disabled:`). */
  disabledStyle?: StyleProp<ViewStyle>;
  /** While `accessibilityState.checked` is `true` (`checked:`; `"mixed"`
   * is not checked): a checkbox, a switch or a radio styled by its
   * value. */
  checkedStyle?: StyleProp<ViewStyle>;
  /** While `accessibilityState.checked` is `"mixed"` (`indeterminate:`):
   * a checkbox that is neither checked nor unchecked. */
  indeterminateStyle?: StyleProp<ViewStyle>;
}

/** iOS-only props of every element (`ios={{…}}`); elements add their own. */
export interface IOSProps {}

/** Desktop-only props of every element (`desktop={{…}}`); elements add their own. */
export interface DesktopProps {}

/** Web-only props of every element (`web={{…}}`). */
export interface WebProps {}

/** Android-only props of every element (`android={{…}}`). */
export interface AndroidProps extends AndroidHostProps {}

/** `<View>` */
export interface ViewProps extends CommonProps {
  style?: StyleProp<ViewStyle>;
}

/** `<Text>`: nested `<Text>` elements are spans of the same paragraph. */
export interface TextProps extends CommonProps, TextHostProps {
  style?: StyleProp<TextStyle>;
}

/** An image asset (`import logo from "./logo.png"`), sized in points. */
export interface ImageAsset {
  url: string;
  /** Its size in points. */
  size: Size;
  /** The pixel densities it ships in, 1 being the imported file:
   * `[1, 2, 3]` when `logo@2x.png` and `logo@3x.png` sit next to
   * `logo.png`. The image loads the one for the screen's pixel ratio.
   * Absent when the imported file is the only one. */
  scales?: number[];
}

/** `<Image>` */
export interface ImageProps extends CommonProps, ImageHostProps {
  style?: StyleProp<ImageStyle>;
}

/** `<Scroll>` */
export interface ScrollProps extends CommonProps, ScrollingHostProps, ScrollHostProps {
  style?: StyleProp<ViewStyle>;
  /** The style of a view around the content: it scrolls with the
   * content, `flexGrow: 1` makes it at least as tall as the viewport (a
   * centered empty state). Without it or `contentClass`, the children are
   * the scroll view's own. */
  contentStyle?: StyleProp<ViewStyle>;
  /** The classes of the content (`contentStyle`), e.g.
   * `"grow justify-center p-4"`. */
  contentClass?: string;
}

/** `<Input>` */
export interface InputProps extends CommonProps, InputHostProps {
  style?: StyleProp<TextStyle>;
  ios?: IOSInputProps;
}

/** iOS-only props of `<Input>`. */
export interface IOSInputProps extends IOSProps, IOSInputHostProps {}

/** `<Overlay>`: its children shown on top of the root view it is in (the
 * surface, or the dialog around it), outside its parent's layout and
 * clipping; laid out as a `position: fixed` box of that root view, or
 * placed against `anchor`. */
export interface OverlayProps extends CommonProps, OverlayHostProps {
  style?: StyleProp<ViewStyle>;
}

/** What JS sets on a Rust component's host itself: the app's classes
 * (appended to the component's own), its inline and state styles, its test id, its
 * tooltip, layout events and the ref (`ref.command(name, args)`). */
export type ComponentHostProps = Pick<ViewProps, "class" | "classList" | "style" | "activeStyle" | "hoverStyle" | "focusStyle" | "disabledStyle" | "testID" | "tooltip" | "onLayout" | "ref">;

/** An operating system (`platform.os`). */
export type OS = "ios" | "android" | "macos" | "windows" | "linux" | "web";

export declare namespace JSX {
  /** What components return and children accept. */
  type Element = YNode | ArrayElement | (() => Element) | string | number | boolean | null | undefined;
  interface ArrayElement extends Array<Element> {}
  interface ElementChildrenAttribute {
    children: {};
  }
  /** None: every tag is a component in scope (`View` from "nsh", ...), or
   * the global `If` / `Each`. */
  interface IntrinsicElements {}
}
"#;

/// `/** doc */` for `doc` (plain text, possibly several lines).
fn doc_comment(out: &mut String, doc: &str, indent: &str) {
    if doc.is_empty() {
        return;
    }
    let lines: Vec<&str> = doc.lines().collect();
    if lines.len() == 1 {
        let _ = writeln!(out, "{indent}/** {doc} */");
        return;
    }
    let _ = writeln!(out, "{indent}/**");
    for line in lines {
        if line.is_empty() {
            let _ = writeln!(out, "{indent} *");
        } else {
            let _ = writeln!(out, "{indent} * {line}");
        }
    }
    let _ = writeln!(out, "{indent} */");
}

/// The declaration of export `name`.
fn export(out: &mut String, name: &str, ts: Ts) {
    export_moved(out, name, ts, None);
}

/// The declaration of export `name`, `@deprecated` when it is imported
/// from module `moved_to` now.
fn export_moved(out: &mut String, name: &str, ts: Ts, moved_to: Option<&str>) {
    let doc = |doc: &str| match moved_to {
        Some(to) => format!("{doc}\n\n@deprecated Import from \"{to}\"."),
        None => doc.to_owned(),
    };
    match ts {
        Ts::Function(text, signatures) => {
            doc_comment(out, &doc(text), "");
            for signature in signatures {
                let _ = writeln!(out, "export declare function {name}{signature};");
            }
        }
        Ts::Const(text, ty) => {
            doc_comment(out, &doc(text), "");
            let _ = writeln!(out, "export declare const {name}: {ty};");
        }
        // One declaration for both modules (a class declared twice is two
        // types), which `nsh` re-exports: never deprecated.
        Ts::Class(text, body) => {
            doc_comment(out, text, "");
            let _ = writeln!(out, "export declare class {name}{body}");
        }
        Ts::Internal => return,
    }
    out.push('\n');
}

fn exports(out: &mut String, items: &[Item], moved_to: Option<&str>) {
    for &(name, _, ts) in items {
        export_moved(out, name, ts, moved_to);
    }
}

/// What module `m` serves of module `other` (`nsh` of `nsh/list`): its
/// values declared again, its classes and types re-exported from its file
/// (`other_body`, the names it declares).
fn also_part(out: &mut String, m: &NativeModule, other: &NativeModule, other_body: &str) {
    let from = relative(&path_of(m.name), &path_of(other.name));
    for &(name, _, ts) in other.exports {
        match ts {
            Ts::Class(..) => {
                let _ = writeln!(out, "export {{ {name} }} from \"{from}\";");
            }
            ts => export(out, name, ts),
        }
    }
    let values: Vec<&str> = other.exports.iter().map(|e| e.0).collect();
    let mut any = false;
    for name in exported_names(other_body) {
        if !values.contains(&name.as_str()) {
            let _ = writeln!(out, "export type {{ {name} }} from \"{from}\";");
            any = true;
        }
    }
    if any || other.exports.iter().any(|e| matches!(e.2, Ts::Class(..))) {
        out.push('\n');
    }
}

/// `types.d.ts`: the styles, the elements' props and events, the node and
/// JSX types.
fn element_types() -> String {
    let mut out = String::from(ELEMENT_TYPES);
    out.push('\n');
    out.push_str(&nsh_core::js::style::declarations());
    out.push('\n');
    out.push_str(&nsh_core::js::host::declarations());
    out.push('\n');
    out.push_str(crate::touch::TOUCH_TYPES);
    out.push_str("\n/** Raw touches and the gesture responder system (React Native semantics). */\nexport interface TouchProps {\n");
    for (name, handler, doc) in crate::touch::TOUCH_PROPS {
        doc_comment(&mut out, doc, "  ");
        let _ = writeln!(out, "  {name}?: {handler};");
    }
    out.push_str("}\n\n/** A native node: what `ref` receives. Its methods send commands to its\n * view, in order with the changes before them. */\nexport interface YNode {\n");
    for (name, _, signature, doc) in crate::dom::NODE_METHODS {
        doc_comment(&mut out, doc, "  ");
        let _ = writeln!(out, "  {name}{signature};");
    }
    out.push_str("}\n");
    out
}

/// The file of module `specifier` (`nsh/base` -> `nsh/base.d.ts`).
fn path_of(specifier: &str) -> String {
    match specifier {
        "nsh" => "nsh/index.d.ts".to_owned(),
        s => format!("{s}.d.ts"),
    }
}

/// What the core's tables add to one of nsh's modules.
fn generated(module: &str) -> String {
    match module {
        "nsh/animated" => nsh_core::js::animation::declarations(),
        "nsh/canvas" => nsh_core::js::canvas::declarations(),
        _ => String::new(),
    }
}

/// The declarations of a registry's exports, leaving out those `own`
/// declares.
fn registry_part(out: &mut String, registry: &Registry, own: &[Item]) {
    let omit: Vec<&str> = own.iter().map(|(n, ..)| *n).collect();
    out.push_str(&nsh_core::ui::declarations(registry, &omit));
    let (values, types) = registry.reexports();
    reexports_part(out, values, types, registry.native_value_names());
}

/// The declarations of a described UI set's exports.
fn set_part(out: &mut String, set: &SetDescription) {
    out.push_str(&set.declarations);
    fn strs(names: &[String]) -> Vec<&str> {
        names.iter().map(String::as_str).collect()
    }
    reexports_part(
        out,
        &strs(&set.reexported_values),
        &strs(&set.reexported_types),
        &strs(&set.native_values),
    );
}

/// The declarations of what a set exports as the runtime makes it: the
/// runtime's `values` and `types`, and the values nsh-js makes for it
/// (`natives`: navigation's).
fn reexports_part(out: &mut String, values: &[&str], types: &[&str], natives: &[&str]) {
    let made = crate::env::REEXPORTS
        .iter()
        .chain(crate::navigation::EXPORTS);
    let mut navigation = false;
    for item in made {
        if values.contains(&item.0) || natives.contains(&item.0) {
            navigation |= crate::navigation::EXPORTS.iter().any(|n| n.0 == item.0);
            export(out, item.0, item.2);
        }
    }
    if navigation {
        out.push_str(crate::navigation::TYPES);
        out.push('\n');
    }
    if !types.is_empty() {
        let _ = writeln!(out, "export type {{ {} }};", types.join(", "));
    }
}

/// The modules' files, before imports: (path, body).
fn bodies(ui_sets: &[SetDescription]) -> Vec<(String, String)> {
    let mut files = vec![("nsh/types.d.ts".to_owned(), element_types())];
    let registries = nsh_core::runtime::registries();
    let declared = |m: &&NativeModule| m.exports.iter().any(|e| !matches!(e.2, Ts::Internal));
    let body_of = |m: &NativeModule| {
        let mut body = String::from(m.types);
        if !body.is_empty() {
            body.push('\n');
        }
        body.push_str(&generated(m.name));
        for registry in registries.iter().filter(|r| r.specifier() == Some(m.name)) {
            registry_part(&mut body, registry, m.exports);
        }
        // A UI set is a module of its own (the command line refuses one
        // named as nsh's): nothing of nsh's to leave out.
        for set in ui_sets.iter().filter(|s| s.specifier == m.name) {
            set_part(&mut body, set);
        }
        exports(&mut body, m.exports, m.moved_to);
        body
    };
    for m in MODULES.iter().filter(declared) {
        let mut body = body_of(m);
        for other in m
            .also
            .iter()
            .filter_map(|a| MODULES.iter().find(|o| o.name == *a))
        {
            also_part(&mut body, m, other, &body_of(other));
        }
        files.push((path_of(m.name), body));
    }
    // The registries that are modules of their own (`nsh/base`, `nsh/image`).
    for registry in registries {
        let Some(specifier) = registry.specifier() else {
            continue;
        };
        if MODULES.iter().any(|m| m.name == specifier) {
            continue;
        }
        let mut body = String::new();
        registry_part(&mut body, registry, &[]);
        files.push((path_of(specifier), body));
    }
    // The UI sets (`nsh/base`, an app's own).
    for set in ui_sets {
        if MODULES.iter().any(|m| m.name == set.specifier) {
            continue;
        }
        let mut body = String::new();
        set_part(&mut body, set);
        files.push((path_of(&set.specifier), body));
    }
    files
}

/// Removes comments and string literals (their words are not references).
fn code_only(text: &str) -> String {
    let bytes = text.as_bytes();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    while i < bytes.len() {
        let rest = &text[i..];
        if rest.starts_with("/*") {
            i += rest.find("*/").map_or(rest.len(), |e| e + 2);
            out.push(' ');
        } else if rest.starts_with("//") {
            i += rest.find('\n').unwrap_or(rest.len());
        } else if bytes[i] == b'"' || bytes[i] == b'`' {
            let quote = bytes[i];
            i += 1;
            while i < bytes.len() && bytes[i] != quote {
                if bytes[i] == b'\\' {
                    i += 1;
                }
                i += 1;
            }
            i += 1;
            out.push_str("\"\"");
        } else {
            let c = rest.chars().next().unwrap_or(' ');
            out.push(c);
            i += c.len_utf8();
        }
    }
    out
}

fn is_ident_start(c: char) -> bool {
    c.is_ascii_alphabetic() || c == '_' || c == '$'
}

fn is_ident(c: char) -> bool {
    c.is_ascii_alphanumeric() || c == '_' || c == '$'
}

/// The identifiers of `code`, with what precedes each (to tell member
/// names and declarations from references).
fn words(code: &str) -> Vec<(&str, &str)> {
    let mut out = Vec::new();
    let mut start = None;
    for (i, c) in code.char_indices() {
        match start {
            None if is_ident_start(c) => start = Some(i),
            Some(s) if !is_ident(c) => {
                out.push((&code[..s], &code[s..i]));
                start = None;
            }
            _ => {}
        }
    }
    if let Some(s) = start {
        out.push((&code[..s], &code[s..]));
    }
    out
}

/// The keywords that declare a name.
const DECLARING: &[&str] = &[
    "interface",
    "type",
    "class",
    "const",
    "function",
    "enum",
    "namespace",
    "let",
    "var",
];

/// The names `body` declares at its top level and exports (`export
/// [declare] interface X` ...).
pub(crate) fn exported_names(body: &str) -> Vec<String> {
    let mut out = Vec::new();
    for line in code_only(body).lines() {
        let Some(rest) = line.strip_prefix("export ") else {
            continue;
        };
        let rest = rest.trim_start_matches("declare ");
        let rest = rest.trim_start_matches("abstract ");
        let mut parts = rest.split_whitespace();
        let (Some(keyword), Some(name)) = (parts.next(), parts.next()) else {
            continue;
        };
        if DECLARING.contains(&keyword) {
            let name: String = name.chars().take_while(|c| is_ident(*c)).collect();
            if !name.is_empty() {
                out.push(name);
            }
        }
    }
    out
}

/// The values `body` declares as exports (what a module's namespace must
/// hold).
#[cfg(test)]
pub(crate) fn exported_values(body: &str) -> Vec<String> {
    let mut out = Vec::new();
    for line in code_only(body).lines() {
        let Some(rest) = line.strip_prefix("export ") else {
            continue;
        };
        // The local binding is not the exported name: `export default x`
        // creates the namespace value `default`, not a named export `x`.
        if rest.split_whitespace().next() == Some("default") {
            if !out.iter().any(|name| name == "default") {
                out.push("default".to_owned());
            }
            continue;
        }
        // A value re-exported: `export { Path2D } from "./canvas";`.
        if let Some(names) = rest.strip_prefix('{').and_then(|r| r.split_once('}')) {
            for name in names.0.split(',').map(str::trim).filter(|n| !n.is_empty()) {
                let name = name.rsplit(" as ").next().unwrap_or(name).to_owned();
                if !out.contains(&name) {
                    out.push(name);
                }
            }
            continue;
        }
        let Some(rest) = rest.strip_prefix("declare ") else {
            continue;
        };
        let rest = rest.trim_start_matches("abstract ");
        let mut parts = rest.split_whitespace();
        let (Some(keyword), Some(name)) = (parts.next(), parts.next()) else {
            continue;
        };
        if matches!(keyword, "const" | "function" | "class" | "let" | "var") {
            let name: String = name.chars().take_while(|c| is_ident(*c)).collect();
            if !out.contains(&name) {
                out.push(name);
            }
        }
    }
    out
}

/// The names `body` uses, declares itself (at any depth, and type
/// parameters) or imports.
fn references(body: &str) -> (Vec<String>, Vec<String>) {
    let code = code_only(body);
    let mut used = Vec::new();
    let mut local = Vec::new();
    for (before, word) in words(&code) {
        let prev = before.trim_end();
        let prev_word = prev
            .rsplit(|c: char| !is_ident(c))
            .next()
            .unwrap_or_default();
        let after = &code[before.len() + word.len()..];
        if DECLARING.contains(&prev_word) && prev.ends_with(prev_word) {
            local.push(word.to_owned());
        } else if prev.ends_with('.') {
            // A member (`JSX.Element`, `Symbol.iterator`).
        } else if after.trim_start_matches('?').starts_with([':', '(']) {
            // A field's, method's or parameter's name (`signal?: string`,
            // `connect(url: string)`), not a type.
        } else {
            used.push(word.to_owned());
        }
    }
    // Imported by the body itself (`nsh`'s `JSX`).
    for line in body.lines() {
        if let Some(rest) = line.strip_prefix("import type {")
            && let Some(names) = rest.split('}').next()
        {
            local.extend(names.split(',').map(|n| n.trim().to_owned()));
        }
    }
    (used, local)
}

/// `to` relative to the directory of `from` (both under `.nsh/types`),
/// without the extension: `./types`, `../types`.
fn relative(from: &str, to: &str) -> String {
    let from_dir: Vec<&str> =
        from.split('/').collect::<Vec<_>>()[..from.split('/').count() - 1].to_vec();
    let to_parts: Vec<&str> = to.split('/').collect();
    let common = from_dir
        .iter()
        .zip(&to_parts)
        .take_while(|(a, b)| a == b)
        .count();
    let mut path = String::new();
    if from_dir.len() == common {
        path.push_str("./");
    } else {
        for _ in common..from_dir.len() {
            path.push_str("../");
        }
    }
    path.push_str(&to_parts[common..].join("/"));
    path.trim_end_matches(".d.ts").to_owned()
}

/// The files of `.nsh/types` for apps whose hosts serve `ui_sets`
/// (`nsh/base`, an app's own, as data: their declarations come with
/// them), as (path relative to it, contents): one per
/// module apps import, `nsh/types.d.ts` (the element types `nsh` exports),
/// `nsh/jsx-runtime.d.ts` (where TypeScript finds the JSX namespace:
/// `jsxImportSource: "nsh"`) and `nsh/globals.d.ts`.
pub fn type_definitions(ui_sets: &[SetDescription]) -> Vec<(String, String)> {
    let files = bodies(ui_sets);
    // Who declares each name.
    let mut owner: BTreeMap<String, &str> = BTreeMap::new();
    for (path, body) in &files {
        for name in exported_names(body) {
            owner.entry(name).or_insert(path);
        }
    }
    let mut out: Vec<(String, String)> = files
        .iter()
        .map(|(path, body)| {
            let (used, local) = references(body);
            let mut imports: BTreeMap<&str, Vec<&str>> = BTreeMap::new();
            for name in &used {
                if local.contains(name) {
                    continue;
                }
                if let Some(&from) = owner.get(name)
                    && from != path
                {
                    let names = imports.entry(from).or_default();
                    if !names.contains(&name.as_str()) {
                        names.push(name);
                    }
                }
            }
            let mut text = String::from(BANNER);
            let any = !imports.is_empty();
            for (from, mut names) in imports {
                names.sort_unstable();
                let _ = writeln!(
                    text,
                    "import type {{ {} }} from \"{}\";",
                    names.join(", "),
                    relative(path, from)
                );
            }
            if any {
                text.push('\n');
            }
            text.push_str(body);
            (path.clone(), text)
        })
        .collect();
    out.push((
        "nsh/jsx-runtime.d.ts".to_owned(),
        format!("{BANNER}export type {{ JSX }} from \"./types\";\n"),
    ));
    out.push(("nsh/globals.d.ts".to_owned(), globals()));
    out.extend(standard_types().iter().cloned());
    out
}

/// Standard export discovery evaluates trusted builtins once, without running
/// application code, privileged operations, or asynchronous jobs.
fn standard_types() -> &'static Vec<(String, String)> {
    static FILES: std::sync::OnceLock<Vec<(String, String)>> = std::sync::OnceLock::new();
    FILES.get_or_init(|| {
        let host = crate::Host::new().expect("create standard declaration discovery VM");
        let exports = host
            .standard_exports()
            .expect("discover actual standard module exports");
        let names: Vec<Vec<&str>> = exports
            .iter()
            .map(|(_, values)| values.iter().map(String::as_str).collect())
            .collect();
        let borrowed: Vec<(&str, &[&str])> = exports
            .iter()
            .zip(&names)
            .map(|((name, _), values)| (name.as_str(), values.as_slice()))
            .collect();
        crate::standard::declarations::type_definitions(&borrowed)
    })
}

/// A constant's value as TypeScript (`2`, not `2.0`).
fn number(v: f64) -> String {
    if v.fract() == 0.0 && v.abs() < 1e15 {
        format!("{}", v as i64)
    } else {
        format!("{v}")
    }
}

/// `globals.d.ts`: what an app can use besides the ECMAScript library: the
/// host's globals, the web classes (from their specs) and functions.
fn globals() -> String {
    let mut out = String::from(BANNER);
    out.push_str("// The globals of nsh's JS environment besides the ECMAScript library\n// (there is no DOM).\n\n");
    out.push_str("/// <reference path=\"../standard/index.d.ts\" />\n");
    out.push_str(crate::host::GLOBALS);
    out.push_str(&crate::standard::declarations::globals());
    for types in crate::web::TYPES {
        out.push('\n');
        out.push_str(types);
    }
    for spec in crate::web::declared_specs() {
        let ts = &spec.ts;
        out.push('\n');
        doc_comment(&mut out, ts.doc, "");
        let name = spec.name.to_str().unwrap_or_default();
        let _ = writeln!(out, "declare class {name}{} {{", ts.head);
        for (constant, value) in spec.constants {
            let constant = constant.to_str().unwrap_or_default();
            let value = number(*value);
            let _ = writeln!(out, "  static readonly {constant}: {value};");
            let _ = writeln!(out, "  readonly {constant}: {value};");
        }
        for line in ts.members.lines() {
            let _ = writeln!(out, "  {line}");
        }
        out.push_str("}\n");
    }
    for f in crate::web::functions() {
        out.push('\n');
        doc_comment(&mut out, f.doc, "");
        let name = f.name.to_str().unwrap_or_default();
        let _ = writeln!(out, "declare function {name}{};", f.signature);
    }
    out
}

/// The names of a class body's members (`static`, accessors and symbols
/// as `[Symbol.iterator]`), one per declaration (overloads repeat).
#[cfg(test)]
fn member_names(members: &str) -> Vec<String> {
    let mut out = Vec::new();
    for line in members.lines() {
        if line.starts_with([' ', ')', '}', '/', '*']) || line.trim().is_empty() {
            continue;
        }
        let mut rest = line;
        for prefix in ["static ", "readonly ", "get ", "set "] {
            rest = rest.strip_prefix(prefix).unwrap_or(rest);
        }
        let name = if rest.starts_with('[') {
            rest[..rest.find(']').map_or(rest.len(), |e| e + 1)].to_owned()
        } else {
            rest.chars().take_while(|c| is_ident(*c)).collect()
        };
        if !name.is_empty() && name != "constructor" && !out.contains(&name) {
            out.push(name);
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn variant_types_image_asset_lists_its_scales() {
        let files = type_definitions(&[]);
        let (_, types) = files
            .iter()
            .find(|(path, _)| path == "nsh/types.d.ts")
            .expect("nsh/types.d.ts");
        let at = types
            .find("export interface ImageAsset {")
            .expect("ImageAsset");
        let asset = &types[at..at + types[at..].find("\n}").unwrap()];
        assert!(asset.contains("  scales?: number[];"), "{asset}");
        assert!(asset.contains("The image loads the one for the screen's pixel ratio."));
    }

    #[test]
    fn default_export_statements_name_the_default_namespace_value() {
        assert_eq!(
            exported_values(
                r#"
declare const moduleValue: { value: number };
export default moduleValue;
export declare const EOL: string;
export interface Shape { default: string; }
// export default ignored;
declare const text: "export default ignored";
"#
            ),
            ["default", "EOL"]
        );
        for source in [
            "export default class Example {}",
            "export default function example(): void;",
            "export default\n  moduleValue;",
        ] {
            assert_eq!(exported_values(source), ["default"], "{source}");
        }
    }

    #[test]
    fn generated_os_declaration_really_exports_its_typed_default_object() {
        let files = bodies(&[]);
        let (_, os) = files.iter().find(|(path, _)| path == "os.d.ts").unwrap();
        assert!(os.contains("declare const defaultExport: {"), "{os}");
        assert!(os.contains("readonly EOL: string;"), "{os}");
        assert!(os.contains("export default defaultExport;"), "{os}");
        let mut values = exported_values(os);
        values.sort();
        assert_eq!(values, ["EOL", "arch", "default", "homedir", "platform"]);
    }

    #[test]
    fn paths_are_relative() {
        assert_eq!(relative("nsh/list.d.ts", "nsh/types.d.ts"), "./types");
        assert_eq!(relative("nsh/acme/ui.d.ts", "nsh/types.d.ts"), "../types");
        assert_eq!(relative("nsh/types.d.ts", "nsh/acme/ui.d.ts"), "./acme/ui");
    }

    #[test]
    fn references_skip_members_strings_and_declarations() {
        let (used, local) = references(
            "/** A `Foo` */\nexport interface Bar<T> { a: JSX.Element; b: \"Baz\"; c: Qux<T>; safeArea?: Quux }",
        );
        assert!(used.contains(&"Quux".to_owned()));
        assert!(!used.contains(&"safeArea".to_owned()));
        assert!(used.contains(&"JSX".to_owned()));
        assert!(used.contains(&"Qux".to_owned()));
        assert!(!used.contains(&"Element".to_owned()));
        assert!(!used.contains(&"Baz".to_owned()));
        assert!(!used.contains(&"Foo".to_owned()));
        assert!(local.contains(&"Bar".to_owned()));
    }

    /// A name a file imports is declared in one file only.
    #[test]
    fn imports_are_unambiguous() {
        let files = bodies(&[nsh_base::registry().into()]);
        let mut owners: BTreeMap<String, Vec<&str>> = BTreeMap::new();
        for (path, body) in &files {
            for name in exported_names(body) {
                let paths = owners.entry(name).or_default();
                if !paths.contains(&path.as_str()) {
                    paths.push(path);
                }
            }
        }
        for (path, body) in &files {
            let (used, local) = references(body);
            for name in used.iter().filter(|n| !local.contains(n)) {
                if let Some(paths) = owners.get(name) {
                    let others: Vec<_> = paths.iter().filter(|p| **p != path).collect();
                    assert!(
                        others.len() <= 1 || paths.contains(&path.as_str()),
                        "{path} uses `{name}`, declared in {others:?}"
                    );
                }
            }
        }
    }

    /// Each web class declares the members its spec defines, and no others.
    #[test]
    fn web_classes_declare_their_members() {
        use crate::web::Key;
        let mut wrong = Vec::new();
        for spec in crate::web::declared_specs() {
            let name = spec.name.to_str().unwrap();
            let mut declared = member_names(spec.ts.members);
            declared.sort();
            let mut defined: Vec<String> = spec
                .methods
                .iter()
                .map(|(key, ..)| match key {
                    Key::Name(n) => n.to_str().unwrap().to_owned(),
                    Key::Iterator => "[Symbol.iterator]".to_owned(),
                    Key::AsyncIterator => "[Symbol.asyncIterator]".to_owned(),
                })
                .chain(
                    spec.accessors
                        .iter()
                        .map(|(n, ..)| n.to_str().unwrap().to_owned()),
                )
                .chain(
                    spec.statics
                        .iter()
                        .map(|(n, ..)| n.to_str().unwrap().to_owned()),
                )
                .collect();
            defined.sort();
            defined.dedup();
            let missing: Vec<_> = defined.iter().filter(|n| !declared.contains(n)).collect();
            let extra: Vec<_> = declared.iter().filter(|n| !defined.contains(n)).collect();
            if !missing.is_empty() || !extra.is_empty() {
                wrong.push(format!(
                    "{name}: undeclared {missing:?}, not defined {extra:?}"
                ));
            }
            if let Some(parent) = spec.parent {
                let parent = crate::web::declared_specs()
                    .chain(crate::web::internal_specs())
                    .find(|s| s.class == parent)
                    .map(|s| s.name.to_str().unwrap())
                    .unwrap();
                if !spec.ts.head.contains(&format!("extends {parent}")) {
                    wrong.push(format!("{name} extends {parent}"));
                }
            }
        }
        assert!(wrong.is_empty(), "{}", wrong.join("\n"));
    }

    /// The declared globals exist, and every global the host adds is declared.
    #[test]
    fn globals_match_the_host() {
        let globals = globals();
        let mut declared: Vec<String> = Vec::new();
        for line in code_only(&globals).lines() {
            let Some(rest) = line.strip_prefix("declare ") else {
                continue;
            };
            let mut parts = rest.split_whitespace();
            if let (Some("var" | "function" | "class" | "const"), Some(name)) =
                (parts.next(), parts.next())
            {
                let name: String = name.chars().take_while(|c| is_ident(*c)).collect();
                if !declared.contains(&name) {
                    declared.push(name);
                }
            }
        }
        let names = |source: &str| -> Vec<String> {
            source
                .split(' ')
                .filter(|n| !n.is_empty())
                .map(str::to_owned)
                .collect()
        };
        let host = crate::Host::new().unwrap();
        host.eval_source(
            "import { text } from \"nsh:rt\";\ntext(Object.getOwnPropertyNames(globalThis).join(\" \"));",
        )
        .unwrap();
        let mut ops = Vec::new();
        host.take_ops(&mut ops);
        let on_host = ops
            .into_iter()
            .find_map(|op| match op {
                nsh_core::Op::CreateText { text, .. } => Some(names(&text)),
                _ => None,
            })
            .unwrap();
        let rt = rquickjs::Runtime::new().unwrap();
        let cx = rquickjs::Context::full(&rt).unwrap();
        let bare: Vec<String> = cx.with(|cx| {
            let list: String = cx
                .eval("Object.getOwnPropertyNames(globalThis).join(' ')")
                .unwrap();
            names(&list)
        });
        for name in &declared {
            assert!(
                on_host.contains(name),
                "`{name}` is declared but not a global"
            );
        }
        for name in on_host
            .iter()
            .filter(|n| !bare.contains(n) && !n.starts_with("__"))
            .filter(|n| !crate::web::ECMASCRIPT_GLOBALS.contains(&n.as_str()))
        {
            assert!(declared.contains(name), "global `{name}` is not declared");
        }
    }

    /// What each module exports at run time is what its declarations say
    /// (with a set of classes besides the UI sets).
    #[test]
    fn declarations_match_the_modules() {
        let sets = vec![nsh_base::registry(), crate::classes::tests::registry()];
        let host = crate::Host::with_options(crate::HostOptions {
            ui_sets: sets.clone(),
            ..crate::HostOptions::default()
        })
        .unwrap();
        let files = bodies(&sets.iter().cloned().map(Into::into).collect::<Vec<_>>());
        assert!(
            files.iter().any(|(path, body)| path == "test/classes.d.ts"
                && body.contains("export declare class Tally {")),
            "the classes are declared"
        );
        for (path, body) in files {
            if path == "nsh/types.d.ts" {
                continue;
            }
            let specifier = match path.trim_end_matches(".d.ts") {
                "nsh/index" => "nsh",
                s => s,
            }
            .to_owned();
            let mut declared = exported_values(&body);
            declared.sort();
            host.eval_source(&format!(
                "import {{ text }} from \"nsh:rt\";\nimport * as m from \"{specifier}\";\ntext(Object.keys(m).sort().join(\",\"));"
            ))
            .unwrap_or_else(|e| panic!("{specifier}: {e}"));
            let mut ops = Vec::new();
            host.take_ops(&mut ops);
            let actual = ops
                .into_iter()
                .find_map(|op| match op {
                    nsh_core::Op::CreateText { text, .. } => Some(text.to_string()),
                    _ => None,
                })
                .expect("the module's names");
            assert_eq!(actual, declared.join(","), "{specifier}");
        }
    }
}