Skip to main content

Library/Fn/SWC/
Watch.rs

1//! SWC-compatible file watching module (using OXC backend)
2//!
3//! This module provides file watching functionality for the compiler.
4
5pub mod Compile;
6
7#[tracing::instrument]
8pub async fn Fn(path:std::path::PathBuf, options:crate::Struct::SWC::Option) -> anyhow::Result<()> {
9	let (tx, mut rx) = tokio::sync::mpsc::unbounded_channel();
10
11	let mut watcher = notify::RecommendedWatcher::new(
12		move |res| {
13			let _ = futures::executor::block_on(async {
14				tx.send(res).unwrap();
15			});
16		},
17		notify::Config::default(),
18	)?;
19
20	use notify::Watcher; // trait import
21	watcher.watch(path.as_ref(), notify::RecursiveMode::Recursive)?;
22
23	while let Some(result) = rx.recv().await {
24		match result {
25			Ok(event) => {
26				if let notify::Event {
27					kind: notify::EventKind::Modify(notify::event::ModifyKind::Data(_)),
28					paths,
29					..
30				} = event
31				{
32					for path in paths {
33						if path.extension().map_or(false, |ext| ext == "ts") {
34							let options = options.clone();
35							tokio::task::spawn_blocking(move || {
36								let rt = tokio::runtime::Handle::current();
37								rt.block_on(async {
38									if let Err(e) = Compile::Fn(crate::Struct::SWC::Option {
39										entry:vec![vec![path.to_string_lossy().to_string()]],
40										..options
41									})
42									.await
43									{
44										error!("Compilation error: {}", e);
45									}
46								})
47							});
48						}
49					}
50				}
51			},
52			Err(e) => error!("Watch error: {:?}", e),
53		}
54	}
55
56	Ok(())
57}
58
59use tracing::error;