omena-resolver 0.2.0

Omena resolver boundary over CME source-resolution producer contracts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
use super::*;
use std::fs;

mod package_resolution;
mod path_mappings;

use package_resolution::{
    PackageStyleCandidateResolution, is_package_import_style_source,
    package_import_style_module_base_candidates, package_manifest_style_module_base_candidates,
    package_style_module_base_candidates, parse_package_style_source,
};
use path_mappings::{
    bundler_style_module_base_candidates, source_matches_bundler_path_mapping,
    source_matches_tsconfig_path_mapping, tsconfig_style_module_base_candidates,
};

pub fn resolve_omena_resolver_style_module_source(
    from_style_path: &str,
    source: &str,
    available_style_paths: &BTreeSet<&str>,
    package_manifests: &[OmenaResolverStylePackageManifestV0],
) -> Option<String> {
    summarize_omena_resolver_style_module_resolution(
        from_style_path,
        source,
        available_style_paths,
        package_manifests,
    )
    .resolved_style_path
}

pub fn resolve_omena_resolver_style_module_source_with_tsconfig_paths(
    from_style_path: &str,
    source: &str,
    available_style_paths: &BTreeSet<&str>,
    package_manifests: &[OmenaResolverStylePackageManifestV0],
    tsconfig_path_mappings: &[OmenaResolverTsconfigPathMappingV0],
) -> Option<String> {
    summarize_omena_resolver_style_module_resolution_with_tsconfig_paths(
        from_style_path,
        source,
        available_style_paths,
        package_manifests,
        tsconfig_path_mappings,
    )
    .resolved_style_path
}

pub fn resolve_omena_resolver_style_module_source_with_path_mappings(
    from_style_path: &str,
    source: &str,
    available_style_paths: &BTreeSet<&str>,
    package_manifests: &[OmenaResolverStylePackageManifestV0],
    bundler_path_mappings: &[OmenaResolverBundlerPathAliasMappingV0],
    tsconfig_path_mappings: &[OmenaResolverTsconfigPathMappingV0],
) -> Option<String> {
    summarize_omena_resolver_style_module_resolution_with_path_mappings(
        from_style_path,
        source,
        available_style_paths,
        package_manifests,
        bundler_path_mappings,
        tsconfig_path_mappings,
    )
    .resolved_style_path
}

pub fn summarize_omena_resolver_style_module_resolution(
    from_style_path: &str,
    source: &str,
    available_style_paths: &BTreeSet<&str>,
    package_manifests: &[OmenaResolverStylePackageManifestV0],
) -> OmenaResolverStyleModuleResolutionV0 {
    summarize_omena_resolver_style_module_resolution_with_tsconfig_paths(
        from_style_path,
        source,
        available_style_paths,
        package_manifests,
        &[],
    )
}

pub fn summarize_omena_resolver_style_module_resolution_with_tsconfig_paths(
    from_style_path: &str,
    source: &str,
    available_style_paths: &BTreeSet<&str>,
    package_manifests: &[OmenaResolverStylePackageManifestV0],
    tsconfig_path_mappings: &[OmenaResolverTsconfigPathMappingV0],
) -> OmenaResolverStyleModuleResolutionV0 {
    summarize_omena_resolver_style_module_resolution_with_path_mappings(
        from_style_path,
        source,
        available_style_paths,
        package_manifests,
        &[],
        tsconfig_path_mappings,
    )
}

pub fn summarize_omena_resolver_style_module_resolution_with_path_mappings(
    from_style_path: &str,
    source: &str,
    available_style_paths: &BTreeSet<&str>,
    package_manifests: &[OmenaResolverStylePackageManifestV0],
    bundler_path_mappings: &[OmenaResolverBundlerPathAliasMappingV0],
    tsconfig_path_mappings: &[OmenaResolverTsconfigPathMappingV0],
) -> OmenaResolverStyleModuleResolutionV0 {
    summarize_omena_resolver_style_module_resolution_with_load_path_roots(
        from_style_path,
        source,
        available_style_paths,
        package_manifests,
        bundler_path_mappings,
        tsconfig_path_mappings,
        &[],
    )
}

/// Resolve a style-module specifier, additionally trying each `load_path_roots` entry as a
/// load-path root for **path-shaped, non-`./`-relative, non-package** specifiers (the dart-sass
/// `--load-path` behavior). File-relative, alias, and bare-package routing are unchanged: the
/// load-path candidates are appended last and only accepted when they exist in
/// `available_style_paths`, so a genuinely missing module still flags and a real external package
/// import still routes through the package resolver. (RFC-0007-I, #49)
pub fn summarize_omena_resolver_style_module_resolution_with_load_path_roots(
    from_style_path: &str,
    source: &str,
    available_style_paths: &BTreeSet<&str>,
    package_manifests: &[OmenaResolverStylePackageManifestV0],
    bundler_path_mappings: &[OmenaResolverBundlerPathAliasMappingV0],
    tsconfig_path_mappings: &[OmenaResolverTsconfigPathMappingV0],
    load_path_roots: &[&str],
) -> OmenaResolverStyleModuleResolutionV0 {
    let candidates = collect_omena_resolver_style_module_source_candidates_with_load_path_roots(
        from_style_path,
        source,
        package_manifests,
        bundler_path_mappings,
        tsconfig_path_mappings,
        load_path_roots,
    );
    let resolved_style_path =
        resolve_style_module_candidate_from_available_paths(&candidates, available_style_paths);
    let resolution_kind = if let Some(resolved_style_path) = resolved_style_path.as_deref() {
        if source_matches_bundler_path_mapping(source, bundler_path_mappings) {
            "bundlerPathStyleModule"
        } else if source_matches_tsconfig_path_mapping(source, tsconfig_path_mappings) {
            "tsconfigPathStyleModule"
        } else if is_package_import_style_source(source) {
            "packageImportStyleModule"
        } else if resolved_via_load_path_root_candidate(
            from_style_path,
            source,
            resolved_style_path,
            load_path_roots,
        ) {
            // A load-path-rooted resolution can `parse_package_style_source` (a path-shaped
            // specifier like `src/scss/design-system.scss` reads as package `src`), so this
            // probe must precede the bare-package classification to avoid mislabeling. (#49)
            "loadPathStyleModule"
        } else if parse_package_style_source(source).is_some() {
            "packageStyleModule"
        } else {
            "relativeStyleModule"
        }
    } else if is_external_style_module_source(source) {
        "externalIgnored"
    } else {
        "unresolved"
    };

    OmenaResolverStyleModuleResolutionV0 {
        schema_version: "0",
        product: "omena-resolver.style-module-resolution",
        from_style_path: from_style_path.to_string(),
        source: source.to_string(),
        resolved_style_path,
        candidate_count: candidates.len(),
        candidates,
        resolution_kind,
    }
}

pub fn collect_omena_resolver_style_module_source_candidates(
    from_style_path: &str,
    source: &str,
    package_manifests: &[OmenaResolverStylePackageManifestV0],
) -> Vec<String> {
    collect_omena_resolver_style_module_source_candidates_with_tsconfig_paths(
        from_style_path,
        source,
        package_manifests,
        &[],
    )
}

pub fn collect_omena_resolver_style_module_source_candidates_with_tsconfig_paths(
    from_style_path: &str,
    source: &str,
    package_manifests: &[OmenaResolverStylePackageManifestV0],
    tsconfig_path_mappings: &[OmenaResolverTsconfigPathMappingV0],
) -> Vec<String> {
    collect_omena_resolver_style_module_source_candidates_with_path_mappings(
        from_style_path,
        source,
        package_manifests,
        &[],
        tsconfig_path_mappings,
    )
}

pub fn collect_omena_resolver_style_module_source_candidates_with_path_mappings(
    from_style_path: &str,
    source: &str,
    package_manifests: &[OmenaResolverStylePackageManifestV0],
    bundler_path_mappings: &[OmenaResolverBundlerPathAliasMappingV0],
    tsconfig_path_mappings: &[OmenaResolverTsconfigPathMappingV0],
) -> Vec<String> {
    collect_omena_resolver_style_module_source_candidates_with_load_path_roots(
        from_style_path,
        source,
        package_manifests,
        bundler_path_mappings,
        tsconfig_path_mappings,
        &[],
    )
}

pub fn collect_omena_resolver_style_module_source_candidates_with_load_path_roots(
    from_style_path: &str,
    source: &str,
    package_manifests: &[OmenaResolverStylePackageManifestV0],
    bundler_path_mappings: &[OmenaResolverBundlerPathAliasMappingV0],
    tsconfig_path_mappings: &[OmenaResolverTsconfigPathMappingV0],
    load_path_roots: &[&str],
) -> Vec<String> {
    if is_external_style_module_source(source) {
        return Vec::new();
    }

    let mut candidates = Vec::new();
    for base_path in bundler_style_module_base_candidates(source, bundler_path_mappings) {
        push_style_module_path_candidates(&mut candidates, base_path, true);
    }
    for base_path in tsconfig_style_module_base_candidates(source, tsconfig_path_mappings) {
        push_style_module_path_candidates(&mut candidates, base_path, true);
    }

    if is_package_import_style_source(source) {
        match package_import_style_module_base_candidates(
            from_style_path,
            source,
            package_manifests,
        ) {
            PackageStyleCandidateResolution::Candidates(base_paths) => {
                for base_path in base_paths {
                    push_style_module_path_candidates(&mut candidates, base_path, true);
                }
            }
            PackageStyleCandidateResolution::Blocked => {}
        }
        return candidates;
    }

    let source_path = Path::new(source);
    let base_path = if source_path.is_absolute() {
        PathBuf::from(source)
    } else {
        Path::new(from_style_path)
            .parent()
            .map(|parent| parent.join(source))
            .unwrap_or_else(|| PathBuf::from(source))
    };
    push_style_module_path_candidates(
        &mut candidates,
        base_path,
        source_path.extension().is_none(),
    );
    match package_manifest_style_module_base_candidates(from_style_path, source, package_manifests)
    {
        PackageStyleCandidateResolution::Candidates(base_paths) => {
            for package_manifest_base_path in base_paths {
                push_style_module_path_candidates(
                    &mut candidates,
                    package_manifest_base_path,
                    true,
                );
            }
        }
        PackageStyleCandidateResolution::Blocked => {
            // Append load-path candidates even when package-manifest resolution is blocked: a
            // path-shaped specifier whose leading segment is misread as a package (`src/...`)
            // is exactly the load-path case, and the file-relative candidate above is the only
            // other route. Load-path candidates are appended last so file-relative wins. (#49)
            push_load_path_rooted_candidates(&mut candidates, source, load_path_roots);
            return candidates;
        }
    }
    for package_base_path in package_style_module_base_candidates(from_style_path, source) {
        push_style_module_path_candidates(&mut candidates, package_base_path, true);
    }
    push_load_path_rooted_candidates(&mut candidates, source, load_path_roots);

    candidates
}

/// True iff a non-`./`-relative, non-package-import specifier is path-shaped, i.e. eligible for
/// load-path rooting (dart-sass `--load-path`). Bare-package specifiers (`pkg`, `@scope/pkg`)
/// and explicit relative/absolute specifiers are excluded so the package and file-relative
/// routes are never shadowed. A specifier qualifies when it carries a recognized style
/// extension (`.scss`/`.sass`/`.css`/`.less`) — that is the dart-sass load-path form that the
/// design-system corpus uses (`'src/scss/design-system.scss'`). (#49)
fn is_load_path_shaped_style_specifier(source: &str) -> bool {
    if source.starts_with("./")
        || source.starts_with("../")
        || source.starts_with('/')
        || source.starts_with('#')
        || source.starts_with('@')
        || source.starts_with("pkg:")
        || is_external_style_module_source(source)
    {
        return false;
    }
    // Require a directory segment so a single bare filename never reroutes through load paths.
    if !source.contains('/') {
        return false;
    }
    let extension = Path::new(source)
        .extension()
        .and_then(|extension| extension.to_str())
        .map(str::to_ascii_lowercase);
    matches!(extension.as_deref(), Some("scss" | "sass" | "css" | "less"))
}

fn push_load_path_rooted_candidates(
    candidates: &mut Vec<String>,
    source: &str,
    load_path_roots: &[&str],
) {
    if load_path_roots.is_empty() || !is_load_path_shaped_style_specifier(source) {
        return;
    }
    for root in load_path_roots {
        let base_path = Path::new(root).join(source);
        // The specifier already carries an explicit style extension, so emit exactly that path
        // (plus its `_partial` sibling) without re-appending extension variants.
        push_style_module_path_candidates(candidates, base_path, false);
    }
}

/// Determine whether `resolved_style_path` was reached through a load-path root rather than the
/// file-relative or bare-package routes, used only to classify `resolution_kind`. (#49)
fn resolved_via_load_path_root_candidate(
    from_style_path: &str,
    source: &str,
    resolved_style_path: &str,
    load_path_roots: &[&str],
) -> bool {
    if load_path_roots.is_empty() || !is_load_path_shaped_style_specifier(source) {
        return false;
    }
    // If the file-relative candidate already produced this path, it is not a load-path resolution.
    let relative_base = Path::new(from_style_path)
        .parent()
        .map(|parent| parent.join(source))
        .unwrap_or_else(|| PathBuf::from(source));
    let mut relative_candidates = Vec::new();
    push_style_module_path_candidates(&mut relative_candidates, relative_base, false);
    if relative_candidates
        .iter()
        .any(|candidate| style_paths_share_identity(candidate, resolved_style_path))
    {
        return false;
    }
    let mut load_path_candidates = Vec::new();
    push_load_path_rooted_candidates(&mut load_path_candidates, source, load_path_roots);
    load_path_candidates
        .iter()
        .any(|candidate| style_paths_share_identity(candidate, resolved_style_path))
}

fn style_paths_share_identity(left: &str, right: &str) -> bool {
    left == right
        || canonicalize_omena_resolver_style_identity_path(left)
            == canonicalize_omena_resolver_style_identity_path(right)
}

pub fn summarize_omena_resolver_specifier_resolution_runtime(
    from_style_path: &str,
    sources: &[String],
    available_style_paths: &BTreeSet<&str>,
    package_manifests: &[OmenaResolverStylePackageManifestV0],
    tsconfig_path_mappings: &[OmenaResolverTsconfigPathMappingV0],
) -> OmenaResolverSpecifierResolutionRuntimeV0 {
    summarize_omena_resolver_specifier_resolution_runtime_with_path_mappings(
        from_style_path,
        sources,
        available_style_paths,
        package_manifests,
        &[],
        tsconfig_path_mappings,
    )
}

pub fn summarize_omena_resolver_specifier_resolution_runtime_with_path_mappings(
    from_style_path: &str,
    sources: &[String],
    available_style_paths: &BTreeSet<&str>,
    package_manifests: &[OmenaResolverStylePackageManifestV0],
    bundler_path_mappings: &[OmenaResolverBundlerPathAliasMappingV0],
    tsconfig_path_mappings: &[OmenaResolverTsconfigPathMappingV0],
) -> OmenaResolverSpecifierResolutionRuntimeV0 {
    let mut entries = sources
        .iter()
        .map(|source| {
            let resolution = summarize_omena_resolver_style_module_resolution_with_path_mappings(
                from_style_path,
                source,
                available_style_paths,
                package_manifests,
                bundler_path_mappings,
                tsconfig_path_mappings,
            );
            let status = if resolution.resolution_kind == "externalIgnored" {
                "external"
            } else if resolution.resolved_style_path.is_some() {
                "resolved"
            } else {
                "unresolved"
            };
            OmenaResolverSpecifierResolutionRuntimeEntryV0 {
                source: source.clone(),
                resolved_style_path: resolution.resolved_style_path,
                candidate_count: resolution.candidate_count,
                resolution_kind: resolution.resolution_kind,
                status,
            }
        })
        .collect::<Vec<_>>();
    entries.sort_by_key(|entry| (entry.status, entry.source.clone()));

    let resolved_specifier_count = entries
        .iter()
        .filter(|entry| entry.status == "resolved")
        .count();
    let external_specifier_count = entries
        .iter()
        .filter(|entry| entry.status == "external")
        .count();
    let unresolved_specifier_count = entries
        .len()
        .saturating_sub(resolved_specifier_count + external_specifier_count);

    OmenaResolverSpecifierResolutionRuntimeV0 {
        schema_version: "0",
        product: "omena-resolver.specifier-resolution-runtime",
        from_style_path: from_style_path.to_string(),
        specifier_count: entries.len(),
        resolved_specifier_count,
        external_specifier_count,
        unresolved_specifier_count,
        entries,
        ready_surfaces: vec![
            "specifierResolutionRuntime",
            "batchStyleModuleResolution",
            "bundlerPathAliasMapping",
            "tsconfigPathMapping",
            "packageManifestResolution",
            "externalSpecifierFiltering",
        ],
    }
}

/// True iff a specifier is a fully-qualified external module URL — one the resolver must NOT
/// attempt to canonicalize against the in-graph `available_style_paths` and must route through the
/// external-SIF branch (`externalIgnored` -> `status == "external"`) instead. (#33/#34)
///
/// The `sass:` builtin and `http(s)://` remote schemes were always external. `file://` joins them
/// because it is the canonical-URL form that a bridge-generated SIF carries
/// (`generate_omena_bridge_sif_for_resolved_style_path` returns `canonical_url = file://<abs>`):
/// an `@use "file:///…"` edge is a fully-resolved on-disk URL, so it is matched 1:1 against an
/// in-scope SIF's `canonical_url` rather than re-joined as a workspace-relative candidate. A
/// `file://` edge with NO SIF in scope stays in the external lane and surfaces as
/// `missingExternalSif` (the #34 boundary state) — it is never silently demoted to `unresolved`.
/// `file://` is never an in-graph `@use` source (style files are referenced relatively), so no
/// in-graph resolution is shadowed by this classification.
fn is_external_style_module_source(source: &str) -> bool {
    source.starts_with("sass:")
        || source.starts_with("http://")
        || source.starts_with("https://")
        || source.starts_with("file://")
}

pub fn canonicalize_omena_resolver_style_identity_path(path: &str) -> String {
    fs::canonicalize(path)
        .map(normalize_style_path)
        .unwrap_or_else(|_| normalize_style_path(PathBuf::from(path)))
}

fn resolve_style_module_candidate_from_available_paths(
    candidates: &[String],
    available_style_paths: &BTreeSet<&str>,
) -> Option<String> {
    for candidate in candidates {
        if available_style_paths.contains(candidate.as_str()) {
            return Some(candidate.clone());
        }
    }

    let available_by_identity = available_style_paths
        .iter()
        .map(|path| {
            (
                canonicalize_omena_resolver_style_identity_path(path),
                (*path).to_string(),
            )
        })
        .collect::<BTreeMap<_, _>>();

    candidates.iter().find_map(|candidate| {
        available_by_identity
            .get(canonicalize_omena_resolver_style_identity_path(candidate).as_str())
            .cloned()
    })
}

fn push_style_module_path_candidates(
    candidates: &mut Vec<String>,
    base_path: PathBuf,
    include_extension_variants: bool,
) {
    push_style_path_candidate(candidates, base_path.clone());
    push_partial_style_path_candidate(candidates, &base_path);

    if !include_extension_variants {
        return;
    }

    for extension in [
        ".module.scss",
        ".module.sass",
        ".module.css",
        ".module.less",
        ".scss",
        ".sass",
        ".css",
        ".less",
    ] {
        let candidate = PathBuf::from(format!("{}{}", base_path.display(), extension));
        push_style_path_candidate(candidates, candidate.clone());
        push_partial_style_path_candidate(candidates, &candidate);
    }
}

fn push_unique_pathbuf(candidates: &mut Vec<PathBuf>, value: PathBuf) {
    if !candidates.contains(&value) {
        candidates.push(value);
    }
}

fn push_partial_style_path_candidate(candidates: &mut Vec<String>, path: &Path) {
    let Some(file_name) = path.file_name().and_then(|file_name| file_name.to_str()) else {
        return;
    };
    if file_name.starts_with('_') {
        return;
    }
    let mut partial_path = path.to_path_buf();
    partial_path.set_file_name(format!("_{file_name}"));
    push_style_path_candidate(candidates, partial_path);
}

fn push_style_path_candidate(candidates: &mut Vec<String>, path: PathBuf) {
    let candidate = normalize_style_path(path);
    if !candidates.contains(&candidate) {
        candidates.push(candidate);
    }
}

pub(crate) fn normalize_style_path(path: PathBuf) -> String {
    let mut normalized = PathBuf::new();
    for component in path.components() {
        match component {
            Component::CurDir => {}
            Component::ParentDir => {
                normalized.pop();
            }
            Component::Normal(part) => normalized.push(part),
            Component::RootDir | Component::Prefix(_) => normalized.push(component.as_os_str()),
        }
    }
    percent_decode_style_path(&normalized.to_string_lossy().replace('\\', "/"))
}

fn percent_decode_style_path(path: &str) -> String {
    let bytes = path.as_bytes();
    let mut output = Vec::with_capacity(bytes.len());
    let mut index = 0;
    let mut changed = false;

    while index < bytes.len() {
        if bytes[index] == b'%'
            && index + 2 < bytes.len()
            && let (Some(high), Some(low)) = (
                decode_hex_byte(bytes[index + 1]),
                decode_hex_byte(bytes[index + 2]),
            )
        {
            output.push((high << 4) | low);
            index += 3;
            changed = true;
            continue;
        }
        output.push(bytes[index]);
        index += 1;
    }

    if !changed {
        return path.to_string();
    }
    String::from_utf8(output).unwrap_or_else(|_| path.to_string())
}

fn decode_hex_byte(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}