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
1195
1196
use std::{
    collections::{BTreeMap, HashMap},
    path::{Path, PathBuf},
};

use crate::{indexmap::IndexMap, metadata::AtomSignature};
use semver::VersionReq;
use serde_cbor::Value;
use sha2::Digest;
use shared_buffer::{MmapError, OwnedBuffer};
use url::Url;
use wasmer_config::package::Manifest as WasmerManifest;

use crate::{
    metadata::{
        annotations::{
            Atom as AtomAnnotation, Emscripten, FileSystemMapping, FileSystemMappings,
            VolumeSpecificPath, Wapm, Wasi,
        },
        Atom, Binding, Command, Manifest as WebcManifest, UrlOrManifest, WaiBindings, WitBindings,
    },
    wasmer_package::{strictness::Strictness, Volume},
};

const METADATA_VOLUME: &str = Volume::METADATA;

/// Errors that may occur when converting from a [`wasmer_config::package::Manifest`] to
/// a [`crate::metadata::Manifest`].
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum ManifestError {
    /// A dependency specification had a syntax error.
    #[error("The dependency, \"{_0}\", isn't in the \"namespace/name\" format")]
    InvalidDependency(String),
    /// Unable to serialize an annotation.
    #[error("Unable to serialize the \"{key}\" annotation")]
    SerializeCborAnnotation {
        /// Which annotation was being serialized?
        key: String,
        /// The underlying error.
        #[source]
        error: serde_cbor::Error,
    },
    /// Specified an unknown atom kind.
    #[error("Unknown atom kind, \"{_0}\"")]
    UnknownAtomKind(String),
    /// A module was specified more than once.
    #[error("Duplicate module, \"{_0}\"")]
    DuplicateModule(String),
    /// Unable to read a module's `source`.
    #[error("Unable to read the \"{module}\" module's file from \"{}\"", path.display())]
    ReadAtomFile {
        /// The name of the module.
        module: String,
        /// The path that was read.
        path: PathBuf,
        /// The underlying error.
        #[source]
        error: std::io::Error,
    },
    /// A command was specified more than once.
    #[error("Duplicate command, \"{_0}\"")]
    DuplicateCommand(String),
    /// An unknown runner kind was specified.
    #[error("Unknown runner kind, \"{_0}\"")]
    UnknownRunnerKind(String),
    /// An error occurred while merging user-defined annotations in with
    /// automatically generated ones.
    #[error("Unable to merge in user-defined \"{key}\" annotations for the \"{command}\" command")]
    #[non_exhaustive]
    MergeAnnotations {
        /// The command annotations were being merged for.
        command: String,
        /// The annotation that was being merged.
        key: String,
    },
    /// A command uses a non-existent module.
    #[error("The \"{command}\" command uses a non-existent module, \"{module}\"")]
    InvalidModuleReference {
        /// The command name.
        command: String,
        /// The module name.
        module: String,
    },
    /// Unable to deserialize custom annotations from the `wasmer.toml`
    /// manifest.
    #[error("Unable to deserialize custom annotations from the wasmer.toml manifest")]
    WasmerTomlAnnotations {
        /// The underlying error.
        #[source]
        error: Box<dyn std::error::Error + Send + Sync>,
    },
    /// The `wasmer.toml` file references a file outside of its base directory.
    #[error("\"{}\" is outside of \"{}\"", path.display(), base_dir.display())]
    OutsideBaseDirectory {
        /// The file that was referenced.
        path: PathBuf,
        /// The base directory.
        base_dir: PathBuf,
    },
    /// The manifest references a file that doesn't exist.
    #[error("The \"{}\" doesn't exist (base dir: {})", path.display(), base_dir.display())]
    MissingFile {
        /// The file that was referenced.
        path: PathBuf,
        /// The base directory.
        base_dir: PathBuf,
    },
}

/// take a `wasmer.toml` manifest and convert it to the `*.webc` equivalent.
pub(crate) fn wasmer_manifest_to_webc(
    manifest: &WasmerManifest,
    base_dir: &Path,
    strictness: Strictness,
) -> Result<(WebcManifest, BTreeMap<String, OwnedBuffer>), ManifestError> {
    let use_map = transform_dependencies(&manifest.dependencies)?;

    // Note: We need to clone the [fs] table because the wasmer-toml crate has
    // already upgraded to indexmap v2.0, but the webc crate needs to stay at
    // 1.9.2 for backwards compatibility reasons.
    let fs: IndexMap<String, PathBuf> = manifest.fs.clone().into_iter().collect();

    let package =
        transform_package_annotations(manifest.package.as_ref(), &fs, base_dir, strictness)?;
    let (atoms, atom_files) = transform_atoms(manifest, base_dir)?;
    let commands = transform_commands(manifest, base_dir)?;
    let bindings = transform_bindings(manifest, base_dir)?;

    let manifest = WebcManifest {
        origin: None,
        use_map,
        package,
        atoms,
        commands,
        bindings,
        entrypoint: entrypoint(manifest),
    };

    Ok((manifest, atom_files))
}

fn transform_dependencies(
    original_dependencies: &HashMap<String, VersionReq>,
) -> Result<IndexMap<String, UrlOrManifest>, ManifestError> {
    let mut dependencies = IndexMap::new();

    for (dep, version) in original_dependencies {
        let (namespace, package_name) = extract_dependency_parts(dep)
            .ok_or_else(|| ManifestError::InvalidDependency(dep.clone()))?;

        // Note: the wasmer.toml format forces you to go through a registry for
        // all dependencies. There's no way to specify a URL-based dependency.
        let dependency_specifier =
            UrlOrManifest::RegistryDependentUrl(format!("{namespace}/{package_name}@{version}"));

        dependencies.insert(dep.clone(), dependency_specifier);
    }

    Ok(dependencies)
}

fn extract_dependency_parts(dep: &str) -> Option<(&str, &str)> {
    let (namespace, package_name) = dep.split_once('/')?;

    fn invalid_char(c: char) -> bool {
        !matches!(c, 'a'..='z' | 'A'..='Z' | '_' | '-' | '0'..='9')
    }

    if namespace.contains(invalid_char) || package_name.contains(invalid_char) {
        None
    } else {
        Some((namespace, package_name))
    }
}

type Atoms = BTreeMap<String, OwnedBuffer>;

fn transform_atoms(
    manifest: &WasmerManifest,
    base_dir: &Path,
) -> Result<(IndexMap<String, Atom>, Atoms), ManifestError> {
    let mut atom_files = BTreeMap::new();
    let mut metadata = IndexMap::new();

    for module in &manifest.modules {
        let name = &module.name;
        let path = base_dir.join(&module.source);
        let file = open_file(&path).map_err(|error| ManifestError::ReadAtomFile {
            module: name.clone(),
            path,
            error,
        })?;

        let atom = Atom {
            kind: atom_kind(module.kind.as_deref())?,
            signature: atom_signature(&file),
        };

        if metadata.contains_key(name) {
            return Err(ManifestError::DuplicateModule(name.clone()));
        }

        metadata.insert(name.clone(), atom);
        atom_files.insert(name.clone(), file);
    }

    Ok((metadata, atom_files))
}

fn atom_signature(atom: &[u8]) -> String {
    let hash: [u8; 32] = sha2::Sha256::digest(atom).into();
    AtomSignature::Sha256(hash).to_string()
}

/// Map the "kind" field in a `[module]` to the corresponding URI.
fn atom_kind(kind: Option<&str>) -> Result<Url, ManifestError> {
    const WASM_ATOM_KIND: &str = "https://webc.org/kind/wasm";
    const TENSORFLOW_SAVED_MODEL_KIND: &str = "https://webc.org/kind/tensorflow-SavedModel";

    let url = match kind {
        Some("wasm") | None => WASM_ATOM_KIND.parse().expect("Should never fail"),
        Some("tensorflow-SavedModel") => TENSORFLOW_SAVED_MODEL_KIND
            .parse()
            .expect("Should never fail"),
        Some(other) => {
            if let Ok(url) = Url::parse(other) {
                // if it is a valid URL, pass that through as-is
                url
            } else {
                return Err(ManifestError::UnknownAtomKind(other.to_string()));
            }
        }
    };

    Ok(url)
}

/// Try to open a file, preferring mmap and falling back to [`std::fs::read()`]
/// if mapping fails.
fn open_file(path: &Path) -> Result<OwnedBuffer, std::io::Error> {
    match OwnedBuffer::mmap(path) {
        Ok(b) => return Ok(b),
        Err(MmapError::Map(_)) => {
            // Unable to mmap the atom file. Falling back to std::fs::read()
        }
        Err(MmapError::FileOpen { error, .. }) => {
            return Err(error);
        }
    }

    let bytes = std::fs::read(path)?;

    Ok(OwnedBuffer::from_bytes(bytes))
}

fn transform_package_annotations(
    package: Option<&wasmer_config::package::Package>,
    fs: &IndexMap<String, PathBuf>,
    base_dir: &Path,
    strictness: Strictness,
) -> Result<IndexMap<String, Value>, ManifestError> {
    let mut annotations = IndexMap::new();

    if let Some(wasmer_package) = package {
        let wapm = transform_package_meta_to_annotations(wasmer_package, base_dir, strictness)?;
        insert_annotation(&mut annotations, Wapm::KEY, wapm)?;
    }

    let fs = get_fs_table(fs);

    if !fs.is_empty() {
        insert_annotation(&mut annotations, FileSystemMappings::KEY, fs)?;
    }

    Ok(annotations)
}

fn insert_annotation(
    annotations: &mut IndexMap<String, serde_cbor::Value>,
    key: impl Into<String>,
    value: impl serde::Serialize,
) -> Result<(), ManifestError> {
    let key = key.into();

    match serde_cbor::value::to_value(value) {
        Ok(value) => {
            annotations.insert(key, value);
            Ok(())
        }
        Err(error) => Err(ManifestError::SerializeCborAnnotation { key, error }),
    }
}

fn get_fs_table(fs: &IndexMap<String, PathBuf>) -> FileSystemMappings {
    if fs.is_empty() {
        return FileSystemMappings::default();
    }

    // When wapm-targz-to-pirita creates the final webc all files will be
    // merged into one "atom" volume, but we want to map each directory
    // separately.
    let mut entries = Vec::new();
    for (guest, host) in fs {
        let volume_name = host
            .to_str()
            .expect("failed to convert path to string")
            .to_string();

        let volume_name = sanitize_path(volume_name);

        let mapping = FileSystemMapping {
            from: None,
            volume_name,
            host_path: None,
            mount_path: sanitize_path(guest),
        };
        entries.push(mapping);
    }

    FileSystemMappings(entries)
}

/// Turn any path that gets passed in into something WASI can use.
///
/// In general, this means...
///
/// - Use "/" everywhere
/// - Remove "." or ".." components
/// - Make the path absolute because when loaded it'll be absolute with respect
///   to the volume
/// - Get rid of any UNC path stuff
pub(crate) fn sanitize_path(path: impl AsRef<Path>) -> String {
    let path = path.as_ref();

    let mut segments = Vec::new();

    for component in path.components() {
        match component {
            std::path::Component::Prefix(_) | std::path::Component::RootDir => {}
            std::path::Component::CurDir => {}
            std::path::Component::ParentDir => {
                segments.pop();
            }
            std::path::Component::Normal(segment) => {
                segments.push(segment.to_string_lossy());
            }
        }
    }

    let mut sanitized = String::new();

    for segment in segments {
        sanitized.push('/');
        sanitized.push_str(&segment);
    }

    if sanitized.is_empty() {
        sanitized.push('/');
    }

    sanitized
}

fn transform_package_meta_to_annotations(
    package: &wasmer_config::package::Package,
    base_dir: &Path,
    strictness: Strictness,
) -> Result<Wapm, ManifestError> {
    let mut wapm = Wapm::new(
        package.name.clone(),
        package.version.clone().map(|v| v.to_string()),
        package.description.clone(),
    );

    fn metadata_file(
        path: Option<&Path>,
        base_dir: &Path,
        strictness: Strictness,
    ) -> Result<Option<VolumeSpecificPath>, ManifestError> {
        let path = match path {
            Some(p) => p,
            None => return Ok(None),
        };

        let absolute_path = base_dir.join(path);

        // Touch the file to make sure it actually exists
        if !absolute_path.exists() {
            match strictness.missing_file(path, base_dir) {
                Ok(_) => return Ok(None),
                Err(e) => {
                    return Err(e);
                }
            }
        }

        match base_dir.join(path).strip_prefix(base_dir) {
            Ok(without_prefix) => Ok(Some(VolumeSpecificPath {
                volume: METADATA_VOLUME.to_string(),
                path: sanitize_path(without_prefix),
            })),
            Err(_) => match strictness.outside_base_directory(path, base_dir) {
                Ok(_) => Ok(None),
                Err(e) => Err(e),
            },
        }
    }

    wapm.license = package.license.clone();
    wapm.license_file = metadata_file(package.license_file.as_deref(), base_dir, strictness)?;
    wapm.readme = metadata_file(package.readme.as_deref(), base_dir, strictness)?;
    wapm.repository = package.repository.clone();
    wapm.homepage = package.homepage.clone();
    wapm.private = package.private;

    Ok(wapm)
}

fn transform_commands(
    manifest: &WasmerManifest,
    base_dir: &Path,
) -> Result<IndexMap<String, Command>, ManifestError> {
    let mut commands = IndexMap::new();

    for command in &manifest.commands {
        let cmd = match command {
            wasmer_config::package::Command::V1(cmd) => transform_command_v1(cmd, manifest)?,
            wasmer_config::package::Command::V2(cmd) => transform_command_v2(cmd, base_dir)?,
        };

        match commands.entry(command.get_name().to_string()) {
            indexmap::map::Entry::Occupied(_) => {
                return Err(ManifestError::DuplicateCommand(
                    command.get_name().to_string(),
                ));
            }
            indexmap::map::Entry::Vacant(entry) => {
                entry.insert(cmd);
            }
        }
    }

    Ok(commands)
}

#[allow(deprecated)]
fn transform_command_v1(
    cmd: &wasmer_config::package::CommandV1,
    manifest: &WasmerManifest,
) -> Result<Command, ManifestError> {
    // Note: a key difference between CommandV1 and CommandV2 is that v1 uses
    // a module's "abi" field to figure out which runner to use, whereas v2 has
    // a dedicated "runner" field and ignores module.abi.
    let runner = match &cmd.module {
        wasmer_config::package::ModuleReference::CurrentPackage { module } => {
            let module = manifest
                .modules
                .iter()
                .find(|m| m.name == module.as_str())
                .ok_or_else(|| ManifestError::InvalidModuleReference {
                    command: cmd.name.clone(),
                    module: cmd.module.to_string(),
                })?;

            RunnerKind::from_name(module.abi.to_str())?
        }
        wasmer_config::package::ModuleReference::Dependency { .. } => {
            // Note: We don't have any visibility into dependencies (this code
            // doesn't do resolution), so we blindly assume it's a WASI command.
            // That should be fine because people shouldn't use the CommandV1
            // syntax any more.
            RunnerKind::Wasi
        }
    };

    let mut annotations = IndexMap::new();
    // Splitting by whitespace isn't really correct, but proper shell splitting
    // would require a dependency and CommandV1 won't be used any more, anyway.
    let main_args = cmd
        .main_args
        .as_deref()
        .map(|args| args.split_whitespace().map(String::from).collect());
    runner.runner_specific_annotations(
        &mut annotations,
        &cmd.module,
        cmd.package.clone(),
        main_args,
    )?;

    Ok(Command {
        runner: runner.uri().to_string(),
        annotations,
    })
}

fn transform_command_v2(
    cmd: &wasmer_config::package::CommandV2,
    base_dir: &Path,
) -> Result<Command, ManifestError> {
    let runner = RunnerKind::from_name(&cmd.runner)?;
    let mut annotations = IndexMap::new();

    runner.runner_specific_annotations(&mut annotations, &cmd.module, None, None)?;

    // Now add the custom annotations
    let custom_annotations =
        cmd.get_annotations(base_dir)
            .map_err(|error| ManifestError::WasmerTomlAnnotations {
                error: error.into(),
            })?;

    if let Some(serde_cbor::Value::Map(custom_annotations)) = custom_annotations {
        for (key, value) in custom_annotations {
            if let serde_cbor::Value::Text(key) = key {
                match annotations.entry(key) {
                    indexmap::map::Entry::Occupied(mut entry) => {
                        merge_cbor(entry.get_mut(), value).map_err(|_| {
                            ManifestError::MergeAnnotations {
                                command: cmd.name.clone(),
                                key: entry.key().clone(),
                            }
                        })?;
                    }
                    indexmap::map::Entry::Vacant(entry) => {
                        entry.insert(value);
                    }
                }
            }
        }
    }

    Ok(Command {
        runner: runner.uri().to_string(),
        annotations,
    })
}

fn merge_cbor(original: &mut Value, addition: Value) -> Result<(), ()> {
    match (original, addition) {
        (Value::Map(left), Value::Map(right)) => {
            for (k, v) in right {
                match left.entry(k) {
                    std::collections::btree_map::Entry::Vacant(entry) => {
                        entry.insert(v);
                    }
                    std::collections::btree_map::Entry::Occupied(mut entry) => {
                        merge_cbor(entry.get_mut(), v)?;
                    }
                }
            }
        }
        (Value::Array(left), Value::Array(right)) => {
            left.extend(right);
        }
        // Primitives that have the same values are fine
        (Value::Bool(left), Value::Bool(right)) if *left == right => {}
        (Value::Bytes(left), Value::Bytes(right)) if *left == right => {}
        (Value::Float(left), Value::Float(right)) if *left == right => {}
        (Value::Integer(left), Value::Integer(right)) if *left == right => {}
        (Value::Text(left), Value::Text(right)) if *left == right => {}
        // null can be overwritten
        (original @ Value::Null, value) => {
            *original = value;
        }
        (_original, Value::Null) => {}
        // Oh well, we tried...
        (_left, _right) => {
            return Err(());
        }
    }

    Ok(())
}

#[derive(Debug, Clone, PartialEq)]
enum RunnerKind {
    Wasi,
    Wcgi,
    Emscripten,
    Wasm4,
    Other(Url),
}

impl RunnerKind {
    fn from_name(name: &str) -> Result<Self, ManifestError> {
        match name {
            "wasi" | "wasi@unstable_" | crate::metadata::annotations::WASI_RUNNER_URI => {
                Ok(RunnerKind::Wasi)
            }
            "generic" => {
                // This is what you get with a CommandV1 and abi = "none"
                Ok(RunnerKind::Wasi)
            }
            "wcgi" | crate::metadata::annotations::WCGI_RUNNER_URI => Ok(RunnerKind::Wcgi),
            "emscripten" | crate::metadata::annotations::EMSCRIPTEN_RUNNER_URI => {
                Ok(RunnerKind::Emscripten)
            }
            "wasm4" | crate::metadata::annotations::WASM4_RUNNER_URI => Ok(RunnerKind::Wasm4),
            other => {
                if let Ok(other) = Url::parse(other) {
                    Ok(RunnerKind::Other(other))
                } else if let Ok(other) = format!("https://webc.org/runner/{other}").parse() {
                    // fall back to something under webc.org
                    Ok(RunnerKind::Other(other))
                } else {
                    Err(ManifestError::UnknownRunnerKind(other.to_string()))
                }
            }
        }
    }

    fn uri(&self) -> &str {
        match self {
            RunnerKind::Wasi => crate::metadata::annotations::WASI_RUNNER_URI,
            RunnerKind::Wcgi => crate::metadata::annotations::WCGI_RUNNER_URI,
            RunnerKind::Emscripten => crate::metadata::annotations::EMSCRIPTEN_RUNNER_URI,
            RunnerKind::Wasm4 => crate::metadata::annotations::WASM4_RUNNER_URI,
            RunnerKind::Other(other) => other.as_str(),
        }
    }

    #[allow(deprecated)]
    fn runner_specific_annotations(
        &self,
        annotations: &mut IndexMap<String, Value>,
        module: &wasmer_config::package::ModuleReference,
        package: Option<String>,
        main_args: Option<Vec<String>>,
    ) -> Result<(), ManifestError> {
        let atom_annotation = match module {
            wasmer_config::package::ModuleReference::CurrentPackage { module } => {
                AtomAnnotation::new(module, None)
            }
            wasmer_config::package::ModuleReference::Dependency { dependency, module } => {
                AtomAnnotation::new(module, dependency.to_string())
            }
        };
        insert_annotation(annotations, AtomAnnotation::KEY, atom_annotation)?;

        match self {
            RunnerKind::Wasi | RunnerKind::Wcgi => {
                let mut wasi = Wasi::new(module.to_string());
                wasi.main_args = main_args;
                wasi.package = package;
                insert_annotation(annotations, Wasi::KEY, wasi)?;
            }
            RunnerKind::Emscripten => {
                let emscripten = Emscripten {
                    atom: Some(module.to_string()),
                    package,
                    env: None,
                    main_args,
                    mount_atom_in_volume: None,
                };
                insert_annotation(annotations, Emscripten::KEY, emscripten)?;
            }
            RunnerKind::Wasm4 | RunnerKind::Other(_) => {
                // No extra annotations to add
            }
        }

        Ok(())
    }
}

/// Infer the package's entrypoint.
fn entrypoint(manifest: &WasmerManifest) -> Option<String> {
    // check if manifest.package is none
    if let Some(package) = &manifest.package {
        if let Some(entrypoint) = &package.entrypoint {
            return Some(entrypoint.clone());
        }
    }

    if let [only_command] = manifest.commands.as_slice() {
        // For convenience (and to stay compatible with old docs), if there is
        // only one command we'll use that as the entrypoint
        return Some(only_command.get_name().to_string());
    }

    None
}

fn transform_bindings(
    manifest: &WasmerManifest,
    base_dir: &Path,
) -> Result<Vec<Binding>, ManifestError> {
    let mut bindings = Vec::new();

    for module in &manifest.modules {
        let b = match &module.bindings {
            Some(wasmer_config::package::Bindings::Wit(wit)) => {
                transform_wit_bindings(wit, module, base_dir)?
            }
            Some(wasmer_config::package::Bindings::Wai(wai)) => {
                transform_wai_bindings(wai, module, base_dir)?
            }
            None => continue,
        };
        bindings.push(b);
    }

    Ok(bindings)
}

fn transform_wai_bindings(
    wai: &wasmer_config::package::WaiBindings,
    module: &wasmer_config::package::Module,
    base_dir: &Path,
) -> Result<Binding, ManifestError> {
    let wasmer_config::package::WaiBindings {
        wai_version,
        exports,
        imports,
    } = wai;

    let bindings = WaiBindings {
        exports: exports
            .as_deref()
            .map(|path| metadata_volume_uri(path, base_dir))
            .transpose()?,
        module: module.name.clone(),
        imports: imports
            .iter()
            .map(|path| metadata_volume_uri(path, base_dir))
            .collect::<Result<Vec<_>, ManifestError>>()?,
    };
    let mut annotations = IndexMap::new();
    insert_annotation(&mut annotations, "wai", bindings)?;

    Ok(Binding {
        name: "library-bindings".to_string(),
        kind: format!("wai@{wai_version}"),
        annotations: Value::Map(
            annotations
                .into_iter()
                .map(|(k, v)| (Value::Text(k), v))
                .collect(),
        ),
    })
}

fn metadata_volume_uri(path: &Path, base_dir: &Path) -> Result<String, ManifestError> {
    make_relative_path(path, base_dir)
        .map(sanitize_path)
        .map(|p| format!("{METADATA_VOLUME}:/{p}"))
}

fn transform_wit_bindings(
    wit: &wasmer_config::package::WitBindings,
    module: &wasmer_config::package::Module,
    base_dir: &Path,
) -> Result<Binding, ManifestError> {
    let wasmer_config::package::WitBindings {
        wit_bindgen,
        wit_exports,
    } = wit;

    let bindings = WitBindings {
        exports: make_relative_path(wit_exports, base_dir)
            .and_then(|path| metadata_volume_uri(&path, base_dir))?,
        module: module.name.clone(),
    };
    let mut annotations = IndexMap::new();
    insert_annotation(&mut annotations, "wit", bindings)?;

    Ok(Binding {
        name: "library-bindings".to_string(),
        kind: format!("wit@{wit_bindgen}"),
        annotations: Value::Map(
            annotations
                .into_iter()
                .map(|(k, v)| (Value::Text(k), v))
                .collect(),
        ),
    })
}

/// Resolve an item relative to the base directory, returning an error if the
/// file lies outside of it.
fn make_relative_path(path: &Path, base_dir: &Path) -> Result<PathBuf, ManifestError> {
    let absolute_path = base_dir.join(path);

    match absolute_path.strip_prefix(base_dir) {
        Ok(p) => Ok(p.into()),
        Err(_) => Err(ManifestError::OutsideBaseDirectory {
            path: absolute_path,
            base_dir: base_dir.to_path_buf(),
        }),
    }
}

#[cfg(test)]
mod tests {
    use crate::metadata::annotations::Wasi;
    use tempfile::TempDir;

    use super::*;

    #[test]
    fn custom_annotations_are_copied_across_verbatim() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
        [package]
        name = "test"
        version = "0.0.0"
        description = "asdf"

        [[module]]
        name = "module"
        source = "file.wasm"
        abi = "wasi"

        [[command]]
        name = "command"
        module = "module"
        runner = "asdf"
        annotations = { first = 42, second = ["a", "b"] }
        "#;
        let manifest: WasmerManifest = toml::from_str(wasmer_toml).unwrap();
        std::fs::write(temp.path().join("file.wasm"), b"\0asm...").unwrap();

        let (transformed, _) =
            wasmer_manifest_to_webc(&manifest, temp.path(), Strictness::Strict).unwrap();

        let command = &transformed.commands["command"];
        assert_eq!(command.annotation::<u32>("first").unwrap(), Some(42));
        assert_eq!(command.annotation::<String>("non-existent").unwrap(), None);
        insta::with_settings! {
            { description => wasmer_toml },
            { insta::assert_yaml_snapshot!(&transformed); }
        }
    }

    #[test]
    fn transform_empty_manifest() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
            [package]
            name = "some/package"
            version = "0.0.0"
            description = "My awesome package"
        "#;
        let manifest: WasmerManifest = toml::from_str(wasmer_toml).unwrap();

        let (transformed, atoms) =
            wasmer_manifest_to_webc(&manifest, temp.path(), Strictness::Strict).unwrap();

        assert!(atoms.is_empty());
        insta::with_settings! {
            { description => wasmer_toml },
            { insta::assert_yaml_snapshot!(&transformed); }
        }
    }

    #[test]
    fn transform_manifest_with_single_atom() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
            [package]
            name = "some/package"
            version = "0.0.0"
            description = "My awesome package"

            [[module]]
            name = "first"
            source = "./path/to/file.wasm"
            abi = "wasi"
        "#;
        let manifest: WasmerManifest = toml::from_str(wasmer_toml).unwrap();
        let dir = temp.path().join("path").join("to");
        std::fs::create_dir_all(&dir).unwrap();
        std::fs::write(dir.join("file.wasm"), b"\0asm...").unwrap();

        let (transformed, atoms) =
            wasmer_manifest_to_webc(&manifest, temp.path(), Strictness::Strict).unwrap();

        assert_eq!(atoms.len(), 1);
        assert_eq!(atoms["first"].as_slice(), b"\0asm...");
        insta::with_settings! {
            { description => wasmer_toml },
            { insta::assert_yaml_snapshot!(&transformed); }
        }
    }

    #[test]
    fn transform_manifest_with_atom_and_command() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
            [package]
            name = "some/package"
            version = "0.0.0"
            description = "My awesome package"

            [[module]]
            name = "cpython"
            source = "python.wasm"
            abi = "wasi"

            [[command]]
            name = "python"
            module = "cpython"
            runner = "wasi"
        "#;
        let manifest: WasmerManifest = toml::from_str(wasmer_toml).unwrap();
        std::fs::write(temp.path().join("python.wasm"), b"\0asm...").unwrap();

        let (transformed, _) =
            wasmer_manifest_to_webc(&manifest, temp.path(), Strictness::Strict).unwrap();

        assert_eq!(transformed.commands.len(), 1);
        let python = &transformed.commands["python"];
        assert_eq!(
            &python.runner,
            crate::metadata::annotations::WASI_RUNNER_URI
        );
        assert_eq!(python.wasi().unwrap().unwrap(), Wasi::new("cpython"));
        insta::with_settings! {
            { description => wasmer_toml },
            { insta::assert_yaml_snapshot!(&transformed); }
        }
    }

    #[test]
    fn transform_manifest_with_multiple_commands() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
            [package]
            name = "some/package"
            version = "0.0.0"
            description = "My awesome package"

            [[module]]
            name = "cpython"
            source = "python.wasm"
            abi = "wasi"

            [[command]]
            name = "first"
            module = "cpython"
            runner = "wasi"

            [[command]]
            name = "second"
            module = "cpython"
            runner = "wasi"

            [[command]]
            name = "third"
            module = "cpython"
            runner = "wasi"
        "#;
        let manifest: WasmerManifest = toml::from_str(wasmer_toml).unwrap();
        std::fs::write(temp.path().join("python.wasm"), b"\0asm...").unwrap();

        let (transformed, _) =
            wasmer_manifest_to_webc(&manifest, temp.path(), Strictness::Strict).unwrap();

        assert_eq!(transformed.commands.len(), 3);
        assert!(transformed.commands.contains_key("first"));
        assert!(transformed.commands.contains_key("second"));
        assert!(transformed.commands.contains_key("third"));
        insta::with_settings! {
            { description => wasmer_toml },
            { insta::assert_yaml_snapshot!(&transformed); }
        }
    }

    #[test]
    fn merge_custom_attributes_with_builtin_ones() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
            [package]
            name = "some/package"
            version = "0.0.0"
            description = "My awesome package"

            [[module]]
            name = "cpython"
            source = "python.wasm"
            abi = "wasi"

            [[command]]
            name = "python"
            module = "cpython"
            runner = "wasi"
            annotations = { wasi = { env = ["KEY=val"]} }
        "#;
        let manifest: WasmerManifest = toml::from_str(wasmer_toml).unwrap();
        std::fs::write(temp.path().join("python.wasm"), b"\0asm...").unwrap();

        let (transformed, _) =
            wasmer_manifest_to_webc(&manifest, temp.path(), Strictness::Strict).unwrap();

        assert_eq!(transformed.commands.len(), 1);
        let cmd = &transformed.commands["python"];
        assert_eq!(
            &cmd.wasi().unwrap().unwrap(),
            Wasi::new("cpython").with_env("KEY", "val")
        );
        insta::with_settings! {
            { description => wasmer_toml },
            { insta::assert_yaml_snapshot!(&transformed); }
        }
    }

    #[test]
    fn transform_bash_manifest() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
            [package]
            name = "sharrattj/bash"
            version = "1.0.17"
            description = "Bash is a modern POSIX-compliant implementation of /bin/sh."
            license = "GNU"
            wasmer-extra-flags = "--enable-threads --enable-bulk-memory"

            [dependencies]
            "sharrattj/coreutils" = "1.0.16"

            [[module]]
            name = "bash"
            source = "bash.wasm"
            abi = "wasi"

            [[command]]
            name = "bash"
            module = "bash"
            runner = "wasi@unstable_"
        "#;
        let manifest: WasmerManifest = toml::from_str(wasmer_toml).unwrap();
        std::fs::write(temp.path().join("bash.wasm"), b"\0asm...").unwrap();

        let (transformed, _) =
            wasmer_manifest_to_webc(&manifest, temp.path(), Strictness::Strict).unwrap();

        insta::with_settings! {
            { description => wasmer_toml },
            { insta::assert_yaml_snapshot!(&transformed); }
        }
    }

    #[test]
    fn transform_wasmer_pack_manifest() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
            [package]
            name = "wasmer/wasmer-pack"
            version = "0.7.0"
            description = "The WebAssembly interface to wasmer-pack."
            license = "MIT"
            readme = "README.md"
            repository = "https://github.com/wasmerio/wasmer-pack"
            homepage = "https://wasmer.io/"

            [[module]]
            name = "wasmer-pack-wasm"
            source = "wasmer_pack_wasm.wasm"

            [module.bindings]
            wai-version = "0.2.0"
            exports = "wasmer-pack.exports.wai"
            imports = []
        "#;
        let manifest: WasmerManifest = toml::from_str(wasmer_toml).unwrap();
        std::fs::write(temp.path().join("wasmer_pack_wasm.wasm"), b"\0asm...").unwrap();
        std::fs::write(temp.path().join("wasmer-pack.exports.wai"), b"").unwrap();
        std::fs::write(temp.path().join("README.md"), b"").unwrap();

        let (transformed, _) =
            wasmer_manifest_to_webc(&manifest, temp.path(), Strictness::Strict).unwrap();

        insta::with_settings! {
            { description => wasmer_toml },
            { insta::assert_yaml_snapshot!(&transformed); }
        }
    }

    #[test]
    fn transform_python_manifest() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
            [package]
            name = "python"
            version = "0.1.0"
            description = "Python is an interpreted, high-level, general-purpose programming language"
            license = "ISC"
            repository = "https://github.com/wapm-packages/python"

            [[module]]
            name = "python"
            source = "bin/python.wasm"
            abi = "wasi"

            [module.interfaces]
            wasi = "0.0.0-unstable"

            [[command]]
            name = "python"
            module = "python"

            [fs]
            lib = "lib"
        "#;
        let manifest: WasmerManifest = toml::from_str(wasmer_toml).unwrap();
        let bin = temp.path().join("bin");
        std::fs::create_dir_all(&bin).unwrap();
        std::fs::write(bin.join("python.wasm"), b"\0asm...").unwrap();

        let (transformed, _) =
            wasmer_manifest_to_webc(&manifest, temp.path(), Strictness::Strict).unwrap();

        insta::with_settings! {
            { description => wasmer_toml },
            { insta::assert_yaml_snapshot!(&transformed); }
        }
    }

    #[test]
    fn transform_manifest_with_fs_table() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
            [package]
            name = "some/package"
            version = "0.0.0"
            description = "This is a package"

            [fs]
            lib = "lib"
            "/public" = "out"
        "#;
        let manifest: WasmerManifest = toml::from_str(wasmer_toml).unwrap();
        std::fs::write(temp.path().join("python.wasm"), b"\0asm...").unwrap();

        let (transformed, _) =
            wasmer_manifest_to_webc(&manifest, temp.path(), Strictness::Strict).unwrap();

        let fs = transformed.filesystem().unwrap().unwrap();
        assert_eq!(
            fs,
            [
                FileSystemMapping {
                    from: None,
                    volume_name: "/lib".to_string(),
                    host_path: None,
                    mount_path: "/lib".to_string(),
                },
                FileSystemMapping {
                    from: None,
                    volume_name: "/out".to_string(),
                    host_path: None,
                    mount_path: "/public".to_string(),
                }
            ]
        );
        insta::with_settings! {
            { description => wasmer_toml },
            { insta::assert_yaml_snapshot!(&transformed); }
        }
    }

    #[test]
    fn issue_124_command_runner_is_swallowed() {
        let temp = TempDir::new().unwrap();
        let wasmer_toml = r#"
            [package]
            name = "wasmer-tests/wcgi-always-panic"
            version = "0.1.0"
            description = "wasmer-tests/wcgi-always-panic website"

            [[module]]
            name = "wcgi-always-panic"
            source = "./wcgi-always-panic.wasm"
            abi = "wasi"

            [[command]]
            name = "wcgi"
            module = "wcgi-always-panic"
            runner = "https://webc.org/runner/wcgi"
        "#;
        let manifest: WasmerManifest = toml::from_str(wasmer_toml).unwrap();
        std::fs::write(temp.path().join("wcgi-always-panic.wasm"), b"\0asm...").unwrap();

        let (transformed, _) =
            wasmer_manifest_to_webc(&manifest, temp.path(), Strictness::Strict).unwrap();

        let cmd = &transformed.commands["wcgi"];
        assert_eq!(cmd.runner, crate::metadata::annotations::WCGI_RUNNER_URI);
        assert_eq!(cmd.wasi().unwrap().unwrap(), Wasi::new("wcgi-always-panic"));
        insta::with_settings! {
            { description => wasmer_toml },
            { insta::assert_yaml_snapshot!(&transformed); }
        }
    }
}