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
use anyhow::{Context, Result};
use notify_debouncer_full::{new_debouncer, notify::RecursiveMode};
use std::{
fs,
path::{Path, PathBuf},
time::Duration,
};
use crate::cache::{
CacheEntry, collect_watch_files, compute_config_hash, content_hash, expand_for_cache,
init_cache, is_watchable_ts_file, normalized_content_hash, warm_cache, write_cache_file,
};
// =========================================================================
// Macro source watching: discover, detect build system, rebuild
// =========================================================================
#[derive(Debug)]
struct MacroSourceInfo {
name: String,
package_dir: PathBuf,
source_dirs: Vec<PathBuf>,
kind: MacroSourceKind,
}
#[derive(Debug)]
enum MacroSourceKind {
/// Rust NAPI macro (has Cargo.toml with macroforge_ts dependency)
RustNapi,
/// JavaScript/TypeScript macro package
JsTs,
}
#[derive(Debug, Clone, Copy)]
enum BuildSystem {
Npm,
Pnpm,
Yarn,
}
fn detect_build_system(root: &Path) -> BuildSystem {
if root.join("pnpm-lock.yaml").exists() {
BuildSystem::Pnpm
} else if root.join("yarn.lock").exists() {
BuildSystem::Yarn
} else {
BuildSystem::Npm
}
}
/// Discover macro source packages from workspace configuration.
fn discover_macro_sources(root: &Path) -> Vec<MacroSourceInfo> {
let pkg_json_path = root.join("package.json");
let pkg_json = match fs::read_to_string(&pkg_json_path) {
Ok(s) => s,
Err(_) => return Vec::new(),
};
let pkg: serde_json::Value = match serde_json::from_str(&pkg_json) {
Ok(v) => v,
Err(_) => return Vec::new(),
};
// Collect workspace patterns
let workspace_patterns: Vec<String> = match &pkg["workspaces"] {
serde_json::Value::Array(arr) => arr
.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect(),
serde_json::Value::Object(obj) => obj
.get("packages")
.and_then(|v| v.as_array())
.map(|arr| {
arr.iter()
.filter_map(|v| v.as_str().map(String::from))
.collect()
})
.unwrap_or_default(),
_ => Vec::new(),
};
// Expand workspace patterns into actual directories
let mut workspace_dirs: Vec<PathBuf> = Vec::new();
for pattern in &workspace_patterns {
if pattern.contains('*') {
// Simple glob: "packages/*" -> list subdirs of "packages/"
let prefix = pattern.trim_end_matches("/*").trim_end_matches("/**");
let base = root.join(prefix);
if let Ok(entries) = fs::read_dir(&base) {
for entry in entries.flatten() {
if entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
workspace_dirs.push(entry.path());
}
}
}
} else {
let dir = root.join(pattern);
if dir.is_dir() {
workspace_dirs.push(dir);
}
}
}
let mut sources = Vec::new();
for dir in &workspace_dirs {
let cargo_toml = dir.join("Cargo.toml");
let child_pkg_json = dir.join("package.json");
// Check if it's a Rust NAPI macro crate
if cargo_toml.exists()
&& let Ok(content) = fs::read_to_string(&cargo_toml)
&& content.contains("macroforge_ts")
{
let src_dir = dir.join("src");
let name = dir
.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string();
sources.push(MacroSourceInfo {
name,
package_dir: dir.clone(),
source_dirs: if src_dir.is_dir() {
vec![src_dir]
} else {
vec![dir.clone()]
},
kind: MacroSourceKind::RustNapi,
});
continue;
}
// Check if it's a JS/TS macro package
if child_pkg_json.exists()
&& let Ok(content) = fs::read_to_string(&child_pkg_json)
&& let Ok(child_pkg) = serde_json::from_str::<serde_json::Value>(&content)
{
let has_macroforge_dep = ["dependencies", "devDependencies", "peerDependencies"]
.iter()
.any(|key| {
child_pkg[key]
.as_object()
.is_some_and(|deps| deps.contains_key("macroforge"))
});
if has_macroforge_dep {
let src_dir = dir.join("src");
let name = child_pkg["name"].as_str().unwrap_or_default().to_string();
sources.push(MacroSourceInfo {
name: if name.is_empty() {
dir.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string()
} else {
name
},
package_dir: dir.clone(),
source_dirs: if src_dir.is_dir() {
vec![src_dir]
} else {
vec![dir.clone()]
},
kind: MacroSourceKind::JsTs,
});
}
}
}
sources
}
/// Rebuild a macro package. Returns Ok(()) on success.
fn rebuild_macro(info: &MacroSourceInfo, build_system: BuildSystem, _root: &Path) -> Result<()> {
let (cmd, args) = match build_system {
BuildSystem::Pnpm => ("pnpm", vec!["run", "build"]),
BuildSystem::Yarn => ("yarn", vec!["build"]),
BuildSystem::Npm => ("npm", vec!["run", "build"]),
};
eprintln!(
"[macroforge watch] Running `{} {}` in {}",
cmd,
args.join(" "),
info.package_dir.display()
);
let output = std::process::Command::new(cmd)
.args(&args)
.current_dir(&info.package_dir)
.env("NAPI_BUILD_SKIP_WATCHER", "1")
.output()
.with_context(|| format!("failed to run `{cmd}` for macro package '{}'", info.name))?;
if !output.status.success() {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
anyhow::bail!(
"macro rebuild failed for '{}' (exit {}):\n{}\n{}",
info.name,
output.status,
stdout,
stderr
);
}
Ok(())
}
/// Main watch loop: warm cache then watch for changes.
pub fn run_watch(root: Option<PathBuf>, debounce_ms: u64) -> Result<()> {
let (root, cache_dir, mut manifest) = init_cache(root, "watch")?;
warm_cache("watch", &root, &cache_dir, &mut manifest)?;
// Discover macro source packages and watch them
let macro_sources = discover_macro_sources(&root);
let build_system = detect_build_system(&root);
if !macro_sources.is_empty() {
eprintln!(
"[macroforge watch] Discovered {} macro source package(s):",
macro_sources.len()
);
for src in ¯o_sources {
eprintln!(" - {} ({:?})", src.name, src.kind);
}
}
eprintln!("[macroforge watch] Watching for changes... (Ctrl+C to stop)");
// --- Watch loop ---
let (tx, rx) = std::sync::mpsc::channel();
let mut debouncer = new_debouncer(Duration::from_millis(debounce_ms), None, tx)
.context("failed to create file watcher")?;
debouncer
.watch(&root, RecursiveMode::Recursive)
.context("failed to start watching")?;
// Watch macro source directories that are outside root
for src in ¯o_sources {
for dir in &src.source_dirs {
if dir.exists() && !dir.starts_with(&root) {
debouncer
.watch(dir, RecursiveMode::Recursive)
.with_context(|| format!("failed to watch macro source: {}", dir.display()))?;
}
}
}
for result in rx {
match result {
Ok(events) => {
let mut config_changed = false;
let mut macro_source_changed: Option<&MacroSourceInfo> = None;
let mut changed_files: Vec<PathBuf> = Vec::new();
for event in &events {
for event_path in &event.paths {
// Check for config file changes
if let Some(name) = event_path.file_name() {
let name_str = name.to_string_lossy();
if name_str.starts_with("macroforge.config.") {
config_changed = true;
continue;
}
}
// Check if path belongs to a macro source package
let is_macro_src = macro_sources
.iter()
.find(|ms| ms.source_dirs.iter().any(|d| event_path.starts_with(d)));
if let Some(ms) = is_macro_src {
macro_source_changed = Some(ms);
continue;
}
if is_watchable_ts_file(event_path, &root) {
changed_files.push(event_path.clone());
}
}
}
changed_files.sort();
changed_files.dedup();
// Macro source change: rebuild then full re-expand
if let Some(macro_info) = macro_source_changed {
eprintln!(
"[macroforge watch] Macro source changed in '{}', rebuilding...",
macro_info.name
);
match rebuild_macro(macro_info, build_system, &root) {
Ok(()) => {
eprintln!(
"[macroforge watch] Macro '{}' rebuilt, re-expanding all files...",
macro_info.name
);
manifest.entries.clear();
macroforge_ts::host::clear_config_cache();
warm_cache("watch", &root, &cache_dir, &mut manifest)?;
}
Err(e) => {
eprintln!("[macroforge watch] Macro rebuild failed: {}", e);
}
}
} else if config_changed {
use rayon::prelude::*;
let new_config_hash = compute_config_hash(&root);
manifest.config_hash = new_config_hash;
manifest.entries.clear();
eprintln!("[macroforge watch] Config changed, re-expanding all files...");
let all_files = collect_watch_files(&root);
// Read and hash all files (sequential)
let files_with_source: Vec<_> = all_files
.iter()
.filter_map(|file_path| {
let rel_path = file_path
.strip_prefix(&root)
.unwrap_or(file_path)
.to_string_lossy()
.to_string();
let source = fs::read_to_string(file_path).ok()?;
let source_hash = content_hash(source.as_bytes());
let norm_hash = normalized_content_hash(&source);
Some((file_path.clone(), rel_path, source, source_hash, norm_hash))
})
.collect();
// Expand in parallel
let results: Vec<_> = files_with_source
.par_iter()
.map(|(file_path, rel_path, source, source_hash, norm_hash)| {
let result = expand_for_cache(file_path, source);
(
rel_path.clone(),
source_hash.clone(),
norm_hash.clone(),
result,
)
})
.collect();
// Apply results (sequential)
let mut count = 0u32;
for (rel_path, source_hash, norm_hash, result) in results {
match result {
Ok(Some(expanded)) => {
let _ = write_cache_file(&cache_dir, &rel_path, &expanded);
manifest.entries.insert(
rel_path.clone(),
CacheEntry {
source_hash,
has_macros: true,
normalized_hash: norm_hash,
},
);
count += 1;
eprintln!(" [~] {}", rel_path);
}
Ok(None) => {
manifest.entries.insert(
rel_path,
CacheEntry {
source_hash,
has_macros: false,
normalized_hash: norm_hash,
},
);
}
Err(e) => eprintln!(" [!] {} — {}", rel_path, e),
}
}
manifest.save(&cache_dir)?;
eprintln!("[macroforge watch] Re-expanded {} files", count);
} else if !changed_files.is_empty() {
for file_path in &changed_files {
let rel_path = file_path
.strip_prefix(&root)
.unwrap_or(file_path)
.to_string_lossy()
.to_string();
let source = match fs::read_to_string(file_path) {
Ok(s) => s,
Err(_) => {
// File was deleted
manifest.entries.remove(&rel_path);
// Remove cached file too
let cache_path = cache_dir.join(format!("{rel_path}.cache"));
let _ = fs::remove_file(&cache_path);
eprintln!(" [-] {} (removed)", rel_path);
continue;
}
};
let source_hash = content_hash(source.as_bytes());
// Fast path: file is byte-identical to cached version
if let Some(entry) = manifest.entries.get(&rel_path)
&& entry.source_hash == source_hash
{
continue;
}
// Check if only whitespace changed
let norm_hash = normalized_content_hash(&source);
if let Some(entry) = manifest.entries.get(&rel_path)
&& !entry.normalized_hash.is_empty()
&& entry.normalized_hash == norm_hash
{
// Update raw hash but skip re-expansion
manifest.entries.insert(
rel_path.clone(),
CacheEntry {
source_hash,
has_macros: entry.has_macros,
normalized_hash: norm_hash,
},
);
eprintln!(" [·] {} (whitespace only)", rel_path);
continue;
}
let file_start = std::time::Instant::now();
match expand_for_cache(file_path, &source) {
Ok(Some(expanded)) => {
let _ = write_cache_file(&cache_dir, &rel_path, &expanded);
manifest.entries.insert(
rel_path.clone(),
CacheEntry {
source_hash,
has_macros: true,
normalized_hash: norm_hash,
},
);
let elapsed = file_start.elapsed();
eprintln!(" [~] {} ({}ms)", rel_path, elapsed.as_millis());
}
Ok(None) => {
manifest.entries.insert(
rel_path.clone(),
CacheEntry {
source_hash,
has_macros: false,
normalized_hash: norm_hash,
},
);
eprintln!(" [.] {} (no macros)", rel_path);
}
Err(e) => {
eprintln!(" [!] {} — {}", rel_path, e);
}
}
}
manifest.save(&cache_dir)?;
}
}
Err(errors) => {
for e in errors {
eprintln!("[macroforge watch] Watch error: {}", e);
}
}
}
}
Ok(())
}