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
pub mod fs;
mod util;

use fancy_regex::Regex;
use lazy_static::lazy_static;
use serde::Deserialize;
use serde_with::{serde_as, DefaultOnNull};
use std::{path::{Path, PathBuf}, collections::{HashSet, HashMap, hash_map::Entry}};
use util::RegexDef;

#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("Bad specifier")]
    BadSpecifier,

    #[error("Bad specifier")]
    FailedResolution,

    #[error("Assertion failed: Regular expression failed to run")]
    Disconnect(#[from] fancy_regex::Error),

    #[error(transparent)]
    JsonError(#[from] serde_json::Error),

    #[error(transparent)]
    IOError(#[from] std::io::Error),
}

#[derive(Debug)]
pub enum Resolution {
    Specifier(String),
    Package(PathBuf, Option<String>),
}

pub struct ResolutionHost {
    pub find_pnp_manifest: Box<dyn Fn(&Path) -> Result<Option<Manifest>, Error>>,
}

impl Default for ResolutionHost {
    fn default() -> ResolutionHost {
        ResolutionHost {
            find_pnp_manifest: Box::new(find_pnp_manifest),
        }
    }
}

#[derive(Default)]
pub struct ResolutionConfig {
    pub builtins: HashSet<String>,
    pub host: ResolutionHost,
}

#[derive(Clone)]
#[derive(Debug)]
#[derive(Default)]
#[derive(Deserialize)]
pub struct PackageLocator {
    name: String,
    reference: String,
}

#[derive(Clone)]
#[derive(Deserialize)]
#[serde(untagged)]
enum PackageDependency {
    Reference(String),
    Alias(String, String),
}

#[serde_as]
#[derive(Clone)]
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PackageInformation {
    package_location: PathBuf,

    #[serde(default)]
    discard_from_lookup: bool,

    #[serde_as(as = "Vec<(_, Option<_>)>")]
    package_dependencies: HashMap<String, Option<PackageDependency>>,
}

#[serde_as]
#[derive(Clone)]
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Manifest {
    #[serde(skip_deserializing)]
    pub manifest_dir: PathBuf,

    #[serde(skip_deserializing)]
    pub manifest_path: PathBuf,

    #[serde(skip_deserializing)]
    location_trie: arca::path::Trie<PackageLocator>,

    enable_top_level_fallback: bool,
    ignore_pattern_data: Option<RegexDef>,

    // fallbackPool: [[
    //   "@app/monorepo",
    //   "workspace:.",
    // ]]
    #[serde_as(as = "Vec<(_, _)>")]
    fallback_pool: HashMap<String, Option<PackageDependency>>,

    // fallbackExclusionList: [[
    //   "@app/server",
    //  ["workspace:sources/server"],
    // ]]
    #[serde_as(as = "Vec<(_, _)>")]
    fallback_exclusion_list: HashMap<String, HashSet<String>>,

    // packageRegistryData: [
    //   [null, [
    //     [null, {
    //       ...
    //     }]
    //   }]
    // ]
    #[serde_as(as = "Vec<(DefaultOnNull<_>, Vec<(DefaultOnNull<_>, _)>)>")]
    package_registry_data: HashMap<String, HashMap<String, PackageInformation>>,
}

pub fn parse_bare_identifier(specifier: &str) -> Result<(String, Option<String>), Error> {
    let mut segments = specifier.splitn(3, '/');
    let mut ident_option: Option<String> = None;

    if let Some(first) = segments.next() {
        if first.starts_with('@') {
            if let Some(second) = segments.next() {
                ident_option = Some(format!("{}/{}", first, second));
            }
        } else {
            ident_option = Some(first.to_string());
        }
    }

    if let Some(ident) = ident_option {
        Ok((ident, segments.next().map(|v| v.to_string())))
    } else {
        Err(Error::BadSpecifier)
    }
}

pub fn find_closest_pnp_manifest_path<P: AsRef<Path>>(p: P) -> Option<PathBuf> {
    let pnp_path = p.as_ref().join(".pnp.cjs");

    if pnp_path.exists() {
        Some(pnp_path)
    } else if let Some(directory_path) = p.as_ref().parent() {
        find_closest_pnp_manifest_path(directory_path)
    } else {
        None
    }
}

pub fn load_pnp_manifest<P: AsRef<Path>>(p: P) -> Result<Manifest, Error> {
    let manifest_content = std::fs::read_to_string(p.as_ref())?;

    lazy_static! {
        static ref RE: Regex = Regex::new("(const\\s+RAW_RUNTIME_STATE\\s*=\\s*|hydrateRuntimeState\\(JSON\\.parse\\()'").unwrap();
    }

    let manifest_match = RE.find(&manifest_content)?
        .expect("Should have been able to locate the runtime state payload offset");

    let iter = manifest_content.chars().skip(manifest_match.end());
    let mut json_string = String::default();
    let mut escaped = false;

    for c in iter {
        match c {
            '\'' if !escaped => {
                break;
            }
            '\\' if !escaped => {
                escaped = true;
            }
            _ => {
                escaped = false;
                json_string.push(c);
            }
        }
    }

    let mut manifest: Manifest = serde_json::from_str(&json_string.to_owned())?;
    init_pnp_manifest(&mut manifest, p.as_ref());

    Ok(manifest)
}

pub fn init_pnp_manifest<P: AsRef<Path>>(manifest: &mut Manifest, p: P) {
    manifest.manifest_path = p.as_ref()
        .to_path_buf();

    manifest.manifest_dir = p.as_ref().parent()
        .expect("Should have a parent directory")
        .to_owned();

    for (name, ranges) in manifest.package_registry_data.iter_mut() {
        for (reference, info) in ranges.iter_mut() {
            let package_location = manifest.manifest_dir
                .join(info.package_location.clone());

            let normalized_location = arca::path::normalize_path(
                &package_location.to_string_lossy(),
            );

            info.package_location = PathBuf::from(normalized_location);

            if !info.discard_from_lookup {
                manifest.location_trie.insert(&info.package_location, PackageLocator {
                    name: name.clone(),
                    reference: reference.clone(),
                });
            }
        }
    }

    let top_level_pkg = manifest.package_registry_data
        .get("").expect("Assertion failed: Should have a top-level name key")
        .get("").expect("Assertion failed: Should have a top-level range key");

    for (name, dependency) in &top_level_pkg.package_dependencies {
        if let Entry::Vacant(entry) = manifest.fallback_pool.entry(name.clone()) {
            entry.insert(dependency.clone());
        }
    }
}

pub fn find_pnp_manifest(parent: &Path) -> Result<Option<Manifest>, Error> {
    find_closest_pnp_manifest_path(parent).map_or(Ok(None), |p| Ok(Some(load_pnp_manifest(p)?)))
}

pub fn find_locator<'a, P: AsRef<Path>>(manifest: &'a Manifest, path: &P) -> Option<&'a PackageLocator> {
    let rel_path = pathdiff::diff_paths(path, &manifest.manifest_dir)
        .expect("Assertion failed: Provided path should be absolute");

    if let Some(regex) = &manifest.ignore_pattern_data {
        if regex.0.is_match(&arca::path::normalize_path(rel_path.to_string_lossy())).unwrap() {
            return None
        }
    }

    manifest.location_trie.get_ancestor_value(&path)
}

pub fn get_package<'a>(manifest: &'a Manifest, locator: &PackageLocator) -> Result<&'a PackageInformation, Error> {
    let references = manifest.package_registry_data.get(&locator.name)
        .expect("Should have an entry in the package registry");

    let info = references.get(&locator.reference)
        .expect("Should have an entry in the package registry");

    Ok(info)
}

pub fn is_excluded_from_fallback(manifest: &Manifest, locator: &PackageLocator) -> bool {
    if let Some(references) = manifest.fallback_exclusion_list.get(&locator.name) {
        references.contains(&locator.reference)
    } else {
        false
    }
}

pub fn resolve_to_unqualified_via_manifest<P: AsRef<Path>>(manifest: &Manifest, specifier: &str, parent: P) -> Result<Resolution, Error> {
    let (ident, module_path) = parse_bare_identifier(specifier)?;

    if let Some(parent_locator) = find_locator(manifest, &parent) {
        let parent_pkg = get_package(manifest, parent_locator)?;

        let mut reference_or_alias: Option<PackageDependency> = None;
        let mut is_set = false;
        
        if !is_set {
            if let Some(Some(binding)) = parent_pkg.package_dependencies.get(&ident) {
                reference_or_alias = Some(binding.clone());
                is_set = true;
            }
        }

        if !is_set && manifest.enable_top_level_fallback && !is_excluded_from_fallback(manifest, parent_locator) {
            if let Some(fallback_resolution) = manifest.fallback_pool.get(&ident) {
                reference_or_alias = fallback_resolution.clone();
                is_set = true;
            }
        }

        if !is_set {
            return Err(Error::FailedResolution);
        }

        if let Some(resolution) = reference_or_alias {
            let dependency_pkg = match resolution {
                PackageDependency::Reference(reference) => get_package(manifest, &PackageLocator { name: ident, reference }),
                PackageDependency::Alias(name, reference) => get_package(manifest, &PackageLocator { name, reference }),
            }?;

            Ok(Resolution::Package(dependency_pkg.package_location.clone(), module_path))
        } else {
            Err(Error::FailedResolution)
        }
    } else {
        Ok(Resolution::Specifier(specifier.to_string()))
    }
}

pub fn resolve_to_unqualified<P: AsRef<Path>>(specifier: &str, parent: P, config: &ResolutionConfig) -> Result<Resolution, Error> {
    if let Some(manifest) = (config.host.find_pnp_manifest)(parent.as_ref())? {
        resolve_to_unqualified_via_manifest(&manifest, specifier, &parent)
    } else {
        Ok(Resolution::Specifier(specifier.to_string()))
    }
}

#[cfg(test)]
mod lib_tests;