plumb-config 0.0.6

Config loading and JSON Schema emission for Plumb.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
//! Tailwind config adapter.
//!
//! Reads a user's `tailwind.config.{js,ts,mjs,cjs}` and merges the
//! resolved `theme` into a Plumb [`Config`]. JavaScript / TypeScript
//! evaluation happens in a Node subprocess; Plumb itself ships zero
//! JS-runtime code at runtime.
//!
//! The pipeline is:
//!
//! 1. Validate the user-supplied path: must be a regular file with one
//!    of the supported extensions, and (when [`TailwindOptions::cwd_root`]
//!    is `Some`) live under that root or one of its ancestors.
//! 2. Look up `node` on `PATH` (or honour an explicit override) — if
//!    missing, surface [`ConfigError::TailwindUnavailable`].
//! 3. Consult the mtime cache. On hit, skip the spawn entirely.
//! 4. Spawn `node <embedded-loader.js> <config-path>` with stdin closed,
//!    stdout/stderr captured, and a configurable timeout (default 30 s).
//! 5. Parse stdout as JSON. The loader emits a small object whose top-
//!    level keys are a strict subset of the Tailwind theme keys Plumb
//!    cares about.
//! 6. Merge the parsed theme into the supplied [`Config`].
//!
//! ## Determinism
//!
//! - Cache reads return byte-identical themes to a fresh spawn.
//! - Cache writes happen only after a fresh spawn produced a parseable
//!   theme. A cache file is never the *first* witness of a theme.
//! - Merging is deterministic: tokens are inserted into [`IndexMap`]s in
//!   the order Tailwind emitted them, and scales are sorted ascending
//!   with duplicates removed.
//!
//! ## Hard rules upheld here
//!
//! - `#![forbid(unsafe_code)]` on the parent crate covers this module.
//! - No `unwrap`/`expect`/`panic!`. Errors surface as
//!   [`ConfigError::TailwindUnavailable`] or
//!   [`ConfigError::TailwindEval`].
//! - No `println!`/`eprintln!`. Diagnostic noise routes through `tracing`.
//! - Subprocess hygiene: arguments pass through `Command::arg`, no
//!   shell concatenation; stderr stays separate from stdout; the spawn
//!   is bounded by a `try_wait` polling loop that counts ticks instead
//!   of measuring wall-clock time (`std::time::Instant::now` is on the
//!   workspace's `clippy::disallowed_methods` list).

use std::ffi::OsStr;
use std::io::Read;
use std::path::{Path, PathBuf};
use std::process::{Command, ExitStatus, Stdio};
use std::thread;
use std::time::Duration;

use indexmap::IndexMap;
use plumb_core::Config;
use plumb_core::config::{ColorSpec, RadiusSpec, SpacingSpec, TypeScaleSpec};
use serde::Deserialize;
use serde_json::Value;

use crate::ConfigError;

mod cache;

/// Embedded Node loader script. Read at compile time so Plumb has no
/// runtime dependency on the script's location on disk.
const LOADER_JS: &str = include_str!("loader.js");

/// Default subprocess timeout. Tailwind themes resolve in well under a
/// second; 60 s is loud-failure territory.
const DEFAULT_TIMEOUT_SECS: u64 = 60;

/// Polling cadence for the `try_wait` loop. We can't use
/// `std::time::Instant::now` (banned by `clippy::disallowed_methods`) so
/// the timeout budget is expressed as a tick count rather than a wall-
/// clock deadline. 50 ms balances responsiveness against the cost of
/// repeatedly polling the OS.
const POLL_INTERVAL: Duration = Duration::from_millis(50);

/// Supported config file extensions. Anything else is rejected before
/// we spawn Node — keeps the failure mode predictable.
const SUPPORTED_EXTENSIONS: &[&str] = &["js", "mjs", "cjs", "ts", "mts", "cts"];

/// Options for [`merge_tailwind`]. All fields are optional; defaults
/// match the issue contract.
#[derive(Debug, Clone, Default)]
pub struct TailwindOptions {
    /// Override the discovered `node` executable. Useful in tests and
    /// in Nix-style build environments where `which` would fail.
    pub node_path: Option<PathBuf>,
    /// Cache directory for resolved themes.
    ///
    /// When `None`, the cache is disabled — every call spawns Node
    /// fresh. The library never reads `TMPDIR` / `TEMP` / `TMP`; the
    /// caller (typically `plumb-cli`) decides where to cache.
    pub cache_dir: Option<PathBuf>,
    /// Skip the cache entirely. Defaults to `false`. When `cache_dir`
    /// is `None` the cache is already disabled, so this flag is only
    /// meaningful alongside an explicit `cache_dir`.
    pub no_cache: bool,
    /// Subprocess timeout. Defaults to 60 seconds.
    pub timeout: Option<Duration>,
    /// CWD root used for the path-traversal guard.
    ///
    /// When `Some(root)`, the validated config path must be `root`
    /// itself, a descendant of `root`, or a sibling under any
    /// ancestor of `root` (so `--config /repo/tailwind.config.js`
    /// works from `/repo/sub/`).
    ///
    /// When `None`, the path-traversal guard is skipped entirely.
    /// Callers that need the guard MUST populate this with a canonical
    /// project root; `plumb-cli` reads `current_dir()` itself before
    /// invoking the adapter. The library never reads
    /// [`std::env::current_dir`].
    pub cwd_root: Option<PathBuf>,
}

/// Merge the resolved Tailwind theme at `tailwind_config_path` into
/// `config` and return the merged config.
///
/// # Errors
///
/// - [`ConfigError::TailwindUnavailable`] when `node` cannot be found
///   on PATH and no override is supplied.
/// - [`ConfigError::TailwindEval`] when the subprocess exits non-zero,
///   times out, or emits unparseable JSON.
/// - [`ConfigError::TailwindBadPath`] when the config path doesn't
///   exist, has the wrong extension, or escapes the CWD ancestor tree.
pub fn merge_tailwind(
    config: Config,
    tailwind_config_path: &Path,
    options: &TailwindOptions,
) -> Result<Config, ConfigError> {
    let theme = resolve_theme(tailwind_config_path, options)?;
    Ok(merge_theme_into_config(config, &theme))
}

/// Resolve the Tailwind theme for the given config file. Wraps the
/// cache lookup → Node spawn → cache write pipeline.
///
/// The cache is consulted only when [`TailwindOptions::cache_dir`] is
/// `Some(_)` and [`TailwindOptions::no_cache`] is `false`. When
/// `cache_dir` is `None` the library never reads or writes a cache
/// file; the caller is responsible for choosing a directory.
fn resolve_theme(config_path: &Path, options: &TailwindOptions) -> Result<Value, ConfigError> {
    let validated = validate_config_path(config_path, options.cwd_root.as_deref())?;
    let cache_dir = options.cache_dir.as_deref().filter(|_| !options.no_cache);

    if let Some(dir) = cache_dir
        && let Some(entry) = cache::read(&validated, dir)
    {
        tracing::debug!(
            target: "plumb_config::tailwind",
            path = %config_path.display(),
            "tailwind cache hit"
        );
        return Ok(entry.theme);
    }

    let node = find_node(options)?;
    let theme = spawn_loader(&node, &validated, options)?;

    if let Some(dir) = cache_dir {
        // Best-effort write. If the cache directory is read-only or full,
        // we still return a valid theme; subsequent runs will re-spawn.
        if let Err(err) = cache::write(&validated, &theme, dir) {
            tracing::debug!(
                target: "plumb_config::tailwind",
                path = %config_path.display(),
                error = %err,
                "tailwind cache write failed"
            );
        }
    }

    Ok(theme)
}

/// Validate the user-supplied config path. We require:
///
/// 1. A supported extension (`.js`, `.mjs`, `.cjs`, `.ts`, `.mts`, `.cts`).
/// 2. The file exists and is a regular file.
/// 3. When `cwd_override` is `Some`, after canonicalization the path
///    must be under at least one of:
///    - `cwd_override` itself,
///    - any of `cwd_override`'s ancestors (so users can pass
///      `--config /abs/path` pointing at a parent monorepo root),
///    - the path itself if it was already absolute and exists on disk
///      (covered by the ancestor check via the canonical form).
///
/// When `cwd_override` is `None`, the path-traversal guard is skipped.
/// The library never reads [`std::env::current_dir`]; callers that
/// want the guard MUST supply a canonical project root.
///
/// We return the canonical absolute path so downstream callers don't
/// re-resolve it.
fn validate_config_path(path: &Path, cwd_override: Option<&Path>) -> Result<PathBuf, ConfigError> {
    let ext = path
        .extension()
        .and_then(OsStr::to_str)
        .map(str::to_ascii_lowercase)
        .unwrap_or_default();
    if !SUPPORTED_EXTENSIONS.iter().any(|e| *e == ext) {
        return Err(ConfigError::TailwindBadPath {
            path: path.display().to_string(),
            reason: format!(
                "unsupported extension `.{ext}`; expected one of {SUPPORTED_EXTENSIONS:?}"
            ),
        });
    }
    let canonical = dunce::canonicalize(path).map_err(|err| ConfigError::TailwindBadPath {
        path: path.display().to_string(),
        reason: format!("could not resolve path: {err}"),
    })?;
    if !canonical.is_file() {
        return Err(ConfigError::TailwindBadPath {
            path: path.display().to_string(),
            reason: "not a regular file".to_owned(),
        });
    }

    if let Some(cwd) = cwd_override {
        let cwd_canonical =
            dunce::canonicalize(cwd).map_err(|err| ConfigError::TailwindBadPath {
                path: path.display().to_string(),
                reason: format!("could not resolve cwd root: {err}"),
            })?;

        if !is_under_or_ancestor(&canonical, &cwd_canonical) {
            return Err(ConfigError::TailwindBadPath {
                path: path.display().to_string(),
                reason: "config path resolves outside the current working directory tree"
                    .to_owned(),
            });
        }
    }

    Ok(canonical)
}

/// Returns `true` when `candidate` is `cwd`, a descendant of `cwd`, or a
/// file whose parent directory is `cwd` or any non-root ancestor of
/// `cwd`.
///
/// This covers the "pass `--config` pointing at a monorepo root" case
/// while rejecting `..`-traversal attacks that escape the user's
/// project tree. Crucially, the ancestor branch refuses to match when
/// the candidate's parent is just the filesystem root (e.g.
/// `/tailwind.config.js` on Unix); `cwd.starts_with("/")` is trivially
/// true on Unix and would otherwise let any root-level file slip past
/// the guard.
fn is_under_or_ancestor(candidate: &Path, cwd: &Path) -> bool {
    if candidate.starts_with(cwd) {
        return true;
    }
    // The candidate's *parent* must be `cwd` or a non-root ancestor of
    // `cwd`. Equivalently: `cwd` must start with the candidate's
    // parent, AND that parent must contain at least one named
    // component (so it's not just `/` or a Windows prefix).
    let Some(candidate_parent) = candidate.parent() else {
        return false;
    };
    let parent_has_named_component = candidate_parent
        .components()
        .any(|c| matches!(c, std::path::Component::Normal(_)));
    if !parent_has_named_component {
        return false;
    }
    cwd.starts_with(candidate_parent)
}

/// Find the `node` executable.
fn find_node(options: &TailwindOptions) -> Result<PathBuf, ConfigError> {
    if let Some(explicit) = &options.node_path {
        if explicit.is_file() {
            return Ok(explicit.clone());
        }
        return Err(ConfigError::TailwindUnavailable {
            reason: format!(
                "configured node executable `{}` does not exist",
                explicit.display()
            ),
        });
    }
    which::which("node").map_err(|err| ConfigError::TailwindUnavailable {
        reason: format!("`node` not found on PATH: {err}. Install Node.js (https://nodejs.org)"),
    })
}

/// Drain a stdout/stderr reader thread, returning an empty buffer on
/// any failure. Reader-thread errors are intentionally swallowed; the
/// caller surfaces a higher-level `TailwindEval` error and a partial
/// or empty buffer is fine for diagnostic context.
fn drain_reader(handle: Option<thread::JoinHandle<std::io::Result<Vec<u8>>>>) -> Vec<u8> {
    match handle {
        None => Vec::new(),
        Some(h) => match h.join() {
            Ok(Ok(buf)) => buf,
            Ok(Err(_)) | Err(_) => Vec::new(),
        },
    }
}

/// Outcome of polling a child process for completion.
enum WaitOutcome {
    /// The child exited with a final status before the budget expired.
    Exited(ExitStatus),
    /// `try_wait` returned an I/O error.
    Errored(std::io::Error),
    /// The poll budget elapsed without a final status.
    TimedOut,
}

/// Poll `try_wait` on a tick cadence until either the child exits or
/// the tick budget expires. We can't use `Instant::now` (workspace
/// `clippy::disallowed_methods`), so the deadline is expressed as a
/// tick count.
fn wait_with_timeout(child: &mut std::process::Child, timeout: Duration) -> WaitOutcome {
    let max_ticks = (timeout.as_millis() / POLL_INTERVAL.as_millis()).max(1);
    for _ in 0..max_ticks {
        match child.try_wait() {
            Ok(Some(status)) => return WaitOutcome::Exited(status),
            Ok(None) => thread::sleep(POLL_INTERVAL),
            Err(err) => return WaitOutcome::Errored(err),
        }
    }
    WaitOutcome::TimedOut
}

/// Drive the Node loader subprocess and parse its JSON output.
fn spawn_loader(
    node: &Path,
    config_path: &Path,
    options: &TailwindOptions,
) -> Result<Value, ConfigError> {
    let timeout = options
        .timeout
        .unwrap_or_else(|| Duration::from_secs(DEFAULT_TIMEOUT_SECS));

    let mut child = Command::new(node)
        // `-e` evaluates the embedded loader; the `--` separates Node's
        // own argv from the script argv. We rely on `Command::arg` for
        // shell-safe escaping — the user-supplied path is never
        // concatenated into a shell string.
        .arg("-e")
        .arg(LOADER_JS)
        .arg("--")
        .arg(config_path.as_os_str())
        .stdin(Stdio::null())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .map_err(|err| ConfigError::TailwindUnavailable {
            reason: format!("failed to spawn `node`: {err}"),
        })?;

    // Reader threads MUST be spawned before we wait. Node can write
    // more than one OS pipe buffer (~64 KiB on Linux) of stdout or
    // stderr; without concurrent drainers the child blocks on `write`
    // and we deadlock on the wait below.
    let stdout = child.stdout.take();
    let stderr = child.stderr.take();
    let stdout_handle = stdout.map(|mut s| {
        thread::spawn(move || -> std::io::Result<Vec<u8>> {
            let mut buf = Vec::new();
            s.read_to_end(&mut buf)?;
            Ok(buf)
        })
    });
    let stderr_handle = stderr.map(|mut s| {
        thread::spawn(move || -> std::io::Result<Vec<u8>> {
            let mut buf = Vec::new();
            s.read_to_end(&mut buf)?;
            Ok(buf)
        })
    });

    let status = match wait_with_timeout(&mut child, timeout) {
        WaitOutcome::Exited(status) => status,
        WaitOutcome::TimedOut => {
            // Kill the child, reap it with `wait` to release the OS
            // resources, then surface a structured error.
            let _ = child.kill();
            let _ = child.wait();
            let stderr_bytes = drain_reader(stderr_handle);
            let _ = drain_reader(stdout_handle);
            return Err(ConfigError::TailwindEval {
                path: config_path.display().to_string(),
                reason: format!("node subprocess timed out after {timeout:?}"),
                stderr: String::from_utf8_lossy(&stderr_bytes).into_owned(),
            });
        }
        WaitOutcome::Errored(err) => {
            let stderr_bytes = drain_reader(stderr_handle);
            let _ = drain_reader(stdout_handle);
            return Err(ConfigError::TailwindEval {
                path: config_path.display().to_string(),
                reason: format!("failed to wait for node subprocess: {err}"),
                stderr: String::from_utf8_lossy(&stderr_bytes).into_owned(),
            });
        }
    };

    let stdout_bytes = drain_reader(stdout_handle);
    let stderr_bytes = drain_reader(stderr_handle);

    if !status.success() {
        // The loader emits a structured JSON error to stdout when it
        // exits with code 2. Surface that structured form when present;
        // otherwise fall back to whatever stderr captured.
        let reason = parse_loader_error(&stdout_bytes).unwrap_or_else(|| {
            format!(
                "node exited with {} (stdout was {} bytes)",
                status,
                stdout_bytes.len()
            )
        });
        return Err(ConfigError::TailwindEval {
            path: config_path.display().to_string(),
            reason,
            stderr: String::from_utf8_lossy(&stderr_bytes).into_owned(),
        });
    }

    let stdout = String::from_utf8(stdout_bytes).map_err(|err| ConfigError::TailwindEval {
        path: config_path.display().to_string(),
        reason: format!("node stdout was not valid UTF-8: {err}"),
        stderr: String::from_utf8_lossy(&stderr_bytes).into_owned(),
    })?;

    let value: Value =
        serde_json::from_str(stdout.trim()).map_err(|err| ConfigError::TailwindEval {
            path: config_path.display().to_string(),
            reason: format!("could not parse loader output as JSON: {err}"),
            stderr: String::from_utf8_lossy(&stderr_bytes).into_owned(),
        })?;

    Ok(value)
}

/// Pull the structured `plumbTailwindError` payload out of the loader
/// stdout, if present.
fn parse_loader_error(stdout: &[u8]) -> Option<String> {
    #[derive(Deserialize)]
    struct Wrapper {
        #[serde(rename = "plumbTailwindError")]
        plumb_tailwind_error: Inner,
    }
    #[derive(Deserialize)]
    struct Inner {
        code: String,
        message: String,
    }
    let s = std::str::from_utf8(stdout).ok()?.trim();
    let parsed: Wrapper = serde_json::from_str(s).ok()?;
    Some(format!(
        "{} ({})",
        parsed.plumb_tailwind_error.message, parsed.plumb_tailwind_error.code
    ))
}

/// Apply a resolved Tailwind theme to a [`Config`]. Pure function — no
/// I/O, no side effects.
fn merge_theme_into_config(mut config: Config, theme: &Value) -> Config {
    if let Some(colors) = theme.get("colors").and_then(Value::as_object) {
        merge_colors(&mut config.color, colors);
    }
    if let Some(spacing) = theme.get("spacing").and_then(Value::as_object) {
        merge_spacing(&mut config.spacing, spacing);
    }
    if let Some(font_size) = theme.get("fontSize").and_then(Value::as_object) {
        merge_font_size(&mut config.type_scale, font_size);
    }
    if let Some(font_weight) = theme.get("fontWeight").and_then(Value::as_object) {
        merge_font_weight(&mut config.type_scale, font_weight);
    }
    if let Some(font_family) = theme.get("fontFamily").and_then(Value::as_object) {
        merge_font_family(&mut config.type_scale, font_family);
    }
    if let Some(radius) = theme.get("borderRadius").and_then(Value::as_object) {
        merge_radius(&mut config.radius, radius);
    }
    config
}

/// Merge `theme.colors`. Nested groups become slash-namespaced tokens
/// (`"red/500"`, `"bg/canvas"`, …). Non-string leaves are coerced to
/// hex via [`css_color_to_hex`]; anything we can't normalize is
/// dropped after a `tracing::debug` event.
fn merge_colors(spec: &mut ColorSpec, colors: &serde_json::Map<String, Value>) {
    for (name, value) in colors {
        match value {
            Value::String(s) => insert_color_token(spec, name, s),
            Value::Object(group) => {
                for (shade, leaf) in group {
                    if let Value::String(s) = leaf {
                        let key = format!("{name}/{shade}");
                        insert_color_token(spec, &key, s);
                    }
                }
            }
            _ => {
                tracing::debug!(
                    target: "plumb_config::tailwind",
                    name = %name,
                    "skipping non-string colour leaf"
                );
            }
        }
    }
}

fn insert_color_token(spec: &mut ColorSpec, name: &str, css_value: &str) {
    if let Some(hex) = css_color_to_hex(css_value) {
        spec.tokens.insert(name.to_owned(), hex);
    } else {
        tracing::debug!(
            target: "plumb_config::tailwind",
            name = %name,
            value = %css_value,
            "skipping unrecognized colour"
        );
    }
}

/// Convert a Tailwind colour value to a six-digit hex string.
///
/// Accepts `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, and `rgb(...)` /
/// `rgba(...)` in either comma- or whitespace-separated form. Alpha is
/// parsed but not preserved — Plumb's `[color].tokens` stores only the
/// opaque hex.
///
/// Other CSS colour forms (`hsl()`, `hsla()`, `oklch()`, named CSS
/// colours like `transparent` or `rebeccapurple`) return `None`.
/// Callers log the dropped token at `tracing::debug` and continue.
fn css_color_to_hex(value: &str) -> Option<String> {
    let v = value.trim().to_ascii_lowercase();
    if let Some(body) = v.strip_prefix('#') {
        return normalize_hex_body(body);
    }
    if let Some(rest) = v.strip_prefix("rgb(").and_then(|r| r.strip_suffix(')')) {
        return parse_rgb(rest);
    }
    if let Some(rest) = v.strip_prefix("rgba(").and_then(|r| r.strip_suffix(')')) {
        return parse_rgb(rest);
    }
    None
}

fn normalize_hex_body(body: &str) -> Option<String> {
    let body = body.trim();
    if !body.bytes().all(|b| b.is_ascii_hexdigit()) {
        return None;
    }
    match body.len() {
        3 => {
            // #rgb → #rrggbb
            let mut out = String::from("#");
            for ch in body.chars() {
                out.push(ch);
                out.push(ch);
            }
            Some(out)
        }
        4 => {
            // #rgba → #rrggbb (drop alpha)
            let mut out = String::from("#");
            for ch in body.chars().take(3) {
                out.push(ch);
                out.push(ch);
            }
            Some(out)
        }
        6 => Some(format!("#{body}")),
        8 => Some(format!("#{}", &body[..6])),
        _ => None,
    }
}

fn parse_rgb(body: &str) -> Option<String> {
    // Tailwind sometimes emits `rgb(255 0 0 / 0.5)` (modern syntax) or
    // `rgb(255, 0, 0)`. Accept both.
    let cleaned = body.replace([',', '/'], " ");
    let mut parts = cleaned.split_ascii_whitespace();
    let r = parts.next()?.parse::<u32>().ok()?;
    let g = parts.next()?.parse::<u32>().ok()?;
    let b = parts.next()?.parse::<u32>().ok()?;
    if r > 255 || g > 255 || b > 255 {
        return None;
    }
    Some(format!("#{r:02x}{g:02x}{b:02x}"))
}

/// Merge `theme.spacing`. Tailwind values are commonly `rem` strings;
/// we convert at the standard 16 px = 1 rem ratio. Tokens that round
/// to a non-positive integer are dropped.
fn merge_spacing(spec: &mut SpacingSpec, spacing: &serde_json::Map<String, Value>) {
    for (name, value) in spacing {
        let Some(px) = css_length_to_px(value) else {
            continue;
        };
        spec.tokens.insert(name.clone(), px);
    }
    rebuild_scale_from_tokens(&mut spec.scale, &spec.tokens);
}

/// Merge `theme.fontSize`. Tailwind entries are either a string (the
/// size only) or a `[size, options]` tuple; either way we extract the
/// size and convert to pixels.
fn merge_font_size(spec: &mut TypeScaleSpec, font_size: &serde_json::Map<String, Value>) {
    for (name, value) in font_size {
        let raw = match value {
            Value::String(_) | Value::Number(_) => Some(value.clone()),
            Value::Array(arr) => arr.first().cloned(),
            _ => None,
        };
        let Some(size) = raw else {
            continue;
        };
        let Some(px) = css_length_to_px(&size) else {
            continue;
        };
        spec.tokens.insert(name.clone(), px);
    }
    rebuild_scale_from_tokens(&mut spec.scale, &spec.tokens);
}

/// Merge `theme.fontWeight`. Values are numeric (string or number) per
/// CSS. We dedupe and sort ascending to keep output deterministic.
fn merge_font_weight(spec: &mut TypeScaleSpec, font_weight: &serde_json::Map<String, Value>) {
    let mut existing: Vec<u16> = spec.weights.clone();
    for value in font_weight.values() {
        let parsed = match value {
            Value::String(s) => s.parse::<u16>().ok(),
            Value::Number(n) => n.as_u64().and_then(|u| u16::try_from(u).ok()),
            _ => None,
        };
        if let Some(w) = parsed {
            existing.push(w);
        }
    }
    existing.sort_unstable();
    existing.dedup();
    spec.weights = existing;
}

/// Merge `theme.fontFamily`. Each value is typically a `[primary,
/// fallback...]` array; we keep only the primary family per name and
/// dedupe in insertion order.
fn merge_font_family(spec: &mut TypeScaleSpec, font_family: &serde_json::Map<String, Value>) {
    let mut seen: IndexMap<String, ()> = IndexMap::new();
    for family in &spec.families {
        seen.insert(family.clone(), ());
    }
    for value in font_family.values() {
        let primary = match value {
            Value::String(s) => Some(s.trim().trim_matches(['\'', '"']).to_owned()),
            Value::Array(arr) => arr
                .first()
                .and_then(Value::as_str)
                .map(|s| s.trim().trim_matches(['\'', '"']).to_owned()),
            _ => None,
        };
        if let Some(family) = primary
            && !family.is_empty()
        {
            seen.insert(family, ());
        }
    }
    spec.families = seen.into_keys().collect();
}

/// Merge `theme.borderRadius` into [`RadiusSpec`].
fn merge_radius(spec: &mut RadiusSpec, radius: &serde_json::Map<String, Value>) {
    let mut values: Vec<u32> = spec.scale.clone();
    for value in radius.values() {
        if let Some(px) = css_length_to_px(value) {
            values.push(px);
        }
    }
    values.sort_unstable();
    values.dedup();
    spec.scale = values;
}

/// Convert a CSS length JSON value to integer pixels.
///
/// Supported units: `px` (rounds), `rem` and `em` (×16). Bare numbers
/// are treated as pixels. Anything else returns `None`.
fn css_length_to_px(value: &Value) -> Option<u32> {
    let raw = match value {
        Value::String(s) => s.trim().to_ascii_lowercase(),
        Value::Number(n) => return n.as_f64().and_then(u32_from_f64_round),
        _ => return None,
    };
    if raw.is_empty() || raw == "0" {
        return Some(0);
    }
    if let Some(stripped) = raw.strip_suffix("px") {
        return stripped
            .trim()
            .parse::<f64>()
            .ok()
            .and_then(u32_from_f64_round);
    }
    if let Some(stripped) = raw.strip_suffix("rem").or_else(|| raw.strip_suffix("em")) {
        return stripped
            .trim()
            .parse::<f64>()
            .ok()
            .and_then(|f| u32_from_f64_round(f * 16.0));
    }
    raw.parse::<f64>().ok().and_then(u32_from_f64_round)
}

fn u32_from_f64_round(f: f64) -> Option<u32> {
    if !f.is_finite() || f < 0.0 {
        return None;
    }
    let rounded = f.round();
    if rounded > f64::from(u32::MAX) {
        return None;
    }
    // `as u32` is well-defined for non-negative finite floats below
    // `u32::MAX`. We avoid `clippy::cast_possible_truncation` noise by
    // doing the bound check above.
    #[allow(clippy::cast_sign_loss, clippy::cast_possible_truncation)]
    Some(rounded as u32)
}

fn rebuild_scale_from_tokens(scale: &mut Vec<u32>, tokens: &IndexMap<String, u32>) {
    let mut combined: Vec<u32> = scale.clone();
    combined.extend(tokens.values().copied());
    combined.sort_unstable();
    combined.dedup();
    *scale = combined;
}

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

    #[test]
    fn css_color_normalizes_short_hex() {
        assert_eq!(css_color_to_hex("#fff"), Some("#ffffff".to_owned()));
        assert_eq!(css_color_to_hex("#FFF"), Some("#ffffff".to_owned()));
        assert_eq!(css_color_to_hex("#0b7285"), Some("#0b7285".to_owned()));
    }

    #[test]
    fn css_color_drops_alpha() {
        assert_eq!(css_color_to_hex("#0b728580"), Some("#0b7285".to_owned()));
        assert_eq!(css_color_to_hex("#abcd"), Some("#aabbcc".to_owned()));
    }

    #[test]
    fn css_color_parses_rgb() {
        assert_eq!(
            css_color_to_hex("rgb(255, 0, 0)"),
            Some("#ff0000".to_owned())
        );
        assert_eq!(
            css_color_to_hex("rgb(11 114 133)"),
            Some("#0b7285".to_owned())
        );
        assert_eq!(
            css_color_to_hex("rgba(11, 114, 133, 0.5)"),
            Some("#0b7285".to_owned())
        );
    }

    #[test]
    fn css_color_rejects_unknown() {
        assert!(css_color_to_hex("transparent").is_none());
        assert!(css_color_to_hex("hsl(0, 100%, 50%)").is_none());
    }

    #[test]
    fn css_length_handles_rem_and_px() {
        assert_eq!(css_length_to_px(&Value::String("1rem".into())), Some(16));
        assert_eq!(css_length_to_px(&Value::String("1.5rem".into())), Some(24));
        assert_eq!(css_length_to_px(&Value::String("12px".into())), Some(12));
        assert_eq!(css_length_to_px(&Value::String("0".into())), Some(0));
        assert_eq!(css_length_to_px(&Value::Number(8.into())), Some(8));
    }

    #[test]
    fn merge_colors_supports_groups() {
        let mut spec = ColorSpec::default();
        let theme = serde_json::json!({
            "white": "#ffffff",
            "red": {
                "500": "#ef4444",
                "600": "#dc2626"
            }
        });
        let map = theme.as_object().expect("object");
        merge_colors(&mut spec, map);
        assert_eq!(spec.tokens["white"], "#ffffff");
        assert_eq!(spec.tokens["red/500"], "#ef4444");
        assert_eq!(spec.tokens["red/600"], "#dc2626");
    }

    #[test]
    fn merge_spacing_dedupes_scale() {
        let mut spec = SpacingSpec {
            scale: vec![0, 4],
            ..SpacingSpec::default()
        };
        let theme = serde_json::json!({
            "1": "0.25rem",
            "2": "0.5rem",
            "4": "1rem"
        });
        let map = theme.as_object().expect("object");
        merge_spacing(&mut spec, map);
        assert_eq!(spec.tokens["1"], 4);
        assert_eq!(spec.tokens["2"], 8);
        assert_eq!(spec.tokens["4"], 16);
        // Scale combines existing 0/4 with 4/8/16 → sorted/deduped.
        assert_eq!(spec.scale, vec![0, 4, 8, 16]);
    }

    #[test]
    fn merge_font_size_supports_tuple_form() {
        let mut spec = TypeScaleSpec::default();
        let theme = serde_json::json!({
            "sm": ["0.875rem", { "lineHeight": "1.25rem" }],
            "base": "1rem"
        });
        let map = theme.as_object().expect("object");
        merge_font_size(&mut spec, map);
        assert_eq!(spec.tokens["sm"], 14);
        assert_eq!(spec.tokens["base"], 16);
        assert_eq!(spec.scale, vec![14, 16]);
    }

    #[test]
    fn merge_font_weight_dedupes_and_sorts() {
        let mut spec = TypeScaleSpec {
            weights: vec![400],
            ..TypeScaleSpec::default()
        };
        let theme = serde_json::json!({
            "regular": "400",
            "medium": 500,
            "bold": 700
        });
        let map = theme.as_object().expect("object");
        merge_font_weight(&mut spec, map);
        assert_eq!(spec.weights, vec![400, 500, 700]);
    }

    #[test]
    fn merge_font_family_keeps_primary() {
        let mut spec = TypeScaleSpec::default();
        let theme = serde_json::json!({
            "sans": ["Inter", "ui-sans-serif", "system-ui"],
            "mono": ["JetBrains Mono", "monospace"]
        });
        let map = theme.as_object().expect("object");
        merge_font_family(&mut spec, map);
        assert_eq!(spec.families, vec!["Inter", "JetBrains Mono"]);
    }

    #[test]
    fn merge_radius_sorts_and_dedupes() {
        let mut spec = RadiusSpec { scale: vec![4] };
        let theme = serde_json::json!({
            "sm": "0.125rem",
            "md": "0.375rem",
            "DEFAULT": "0.25rem"
        });
        let map = theme.as_object().expect("object");
        merge_radius(&mut spec, map);
        // 0.125rem→2, 0.25rem→4 (dup), 0.375rem→6 → [2, 4, 6]
        assert_eq!(spec.scale, vec![2, 4, 6]);
    }

    #[test]
    fn validate_rejects_unknown_extension() {
        let dir = tempfile::tempdir().expect("tempdir");
        let path = dir.path().join("tailwind.config.toml");
        std::fs::write(&path, "x = 1").expect("write");
        let err = validate_config_path(&path, Some(dir.path())).unwrap_err();
        assert!(matches!(err, ConfigError::TailwindBadPath { .. }));
    }

    #[test]
    fn validate_rejects_path_outside_cwd_root() {
        let outside = tempfile::tempdir().expect("outside");
        let outside_cfg = outside.path().join("tailwind.config.js");
        std::fs::write(&outside_cfg, "module.exports = {};").expect("write");
        let inside = tempfile::tempdir().expect("inside");
        let err = validate_config_path(&outside_cfg, Some(inside.path())).unwrap_err();
        assert!(matches!(err, ConfigError::TailwindBadPath { .. }));
    }

    #[test]
    fn validate_accepts_descendant_of_cwd_root() {
        let dir = tempfile::tempdir().expect("dir");
        let path = dir.path().join("tailwind.config.js");
        std::fs::write(&path, "module.exports = {};").expect("write");
        let canonical = validate_config_path(&path, Some(dir.path())).expect("ok");
        assert!(canonical.is_file());
    }

    #[test]
    fn is_under_or_ancestor_accepts_descendant() {
        assert!(is_under_or_ancestor(
            Path::new("/work/proj/tailwind.config.js"),
            Path::new("/work/proj")
        ));
    }

    #[test]
    fn is_under_or_ancestor_accepts_ancestor_sibling() {
        // cwd is /work/proj/sub; config lives at /work/proj/tailwind.config.js
        assert!(is_under_or_ancestor(
            Path::new("/work/proj/tailwind.config.js"),
            Path::new("/work/proj/sub")
        ));
    }

    #[test]
    fn is_under_or_ancestor_rejects_unrelated() {
        assert!(!is_under_or_ancestor(
            Path::new("/etc/passwd"),
            Path::new("/work/proj")
        ));
    }

    /// Security regression guard: a candidate at the filesystem root
    /// (parent is `/`) MUST NOT slip past the ancestor branch on Unix.
    /// `cwd.starts_with("/")` is trivially true for any absolute path,
    /// so without the named-component check `/tailwind.config.js`
    /// would be accepted as if it were a sibling under an ancestor.
    #[test]
    fn is_under_or_ancestor_rejects_filesystem_root() {
        assert!(!is_under_or_ancestor(
            Path::new("/tailwind.config.js"),
            Path::new("/work/proj")
        ));
    }
}