Skip to main content

fresh/
init_script.rs

1//! User init.ts support.
2//!
3//! At startup Fresh reads `~/.config/fresh/init.ts` (if present) and feeds it
4//! through the existing plugin pipeline as a plugin named `init.ts`. This is
5//! the same code path as "Load Plugin from Buffer", so reload, unload, and
6//! per-plugin registration tagging are free.
7//!
8//! Recovery: a lightweight crash fuse at
9//! `~/.config/fresh/logs/init.crashes` counts consecutive init.ts failures
10//! within a rolling window. After N failures the next launch auto-skips
11//! init.ts until the user fixes or removes it. A successful evaluation
12//! clears the counter.
13
14use std::path::{Path, PathBuf};
15
16/// How many consecutive failed attempts trigger auto-skip.
17const CRASH_FUSE_THRESHOLD: u32 = 3;
18/// Rolling window (seconds) beyond which stale failures are ignored.
19const CRASH_FUSE_WINDOW_SECS: u64 = 300;
20/// Plugin name Fresh uses when loading init.ts — stable so hot-reload works.
21pub const INIT_PLUGIN_NAME: &str = "init.ts";
22
23/// Starter content written by `init: Edit init.ts` when the file doesn't
24/// exist yet. Every example is commented out — an empty init() body is
25/// valid and users un-comment what they want.
26///
27/// The comments establish what init.ts is *not* for (static preferences,
28/// keybindings, themes, reusable features) so users don't reach for this
29/// file when another surface is the right tool.
30pub const STARTER_TEMPLATE: &str = r#"/// <reference path="./types/fresh.d.ts" />
31/// <reference path="./types/plugins.d.ts" />
32const editor = getEditor();
33
34// Fresh init.ts — decisions that depend on the environment at startup.
35//
36// init.ts is NOT for:
37//   - Static preferences (tab size, line numbers, ...)  -> Settings UI
38//   - Key bindings                                      -> Keybindings editor
39//   - Themes you always want                            -> Theme selector
40//   - Reusable features                                 -> A plugin package
41//
42// init.ts IS for things that:
43//   - Register code handlers, commands, etc.
44//   - Depend on where/how Fresh is starting (host, SSH, $TERM, project, ...)
45//   - Would differ across machines or launches
46//   - Can't live in a shared config.json without lying to teammates
47//
48// API reference: ~/.config/fresh/types/fresh.d.ts (same as plugins)
49// Commands:  Ctrl+P -> "init: Reload", "init: Check"
50// CLI:       fresh --cmd init check | fresh --safe | fresh --no-init
51
52// Example: enable vi mode at startup (otherwise off until toggled).
53//
54// editor.on("plugins_loaded", () => {
55//     editor.getPluginApi("vi-mode")?.enable();
56// });
57
58// Example: Add a command to select (mark) from current cursor to target line.
59//
60// registerHandler("select_to_line_handler", async function start_review_range() {
61//   editor.executeActions([
62//     { action: "set_mark", count: 1 },
63//     { action: "goto_line", count: 1 },
64//   ]);
65// });
66//
67// editor.registerCommand(
68//   "select_to_line",
69//   "Select from current position to target line",
70//   "select_to_line_handler",
71// );
72//
73
74// Example: fade the editor in from black to the target theme. Uses
75// `overrideThemeColors` (in-memory, no disk I/O) for each frame, then
76// calls `applyTheme` at the end to drop the overrides and land cleanly
77// on the saved theme. `editor.delay(ms)` returns a Promise, so an async
78// for-loop is all the timing machinery we need — no setInterval.
79// (async () => {
80//     const target = "one-dark";
81//     const data = editor.getThemeData(target) as
82//         | { editor?: Record<string, [number, number, number]> }
83//         | null;
84//     const bg = data?.editor?.bg ?? [30, 30, 30];
85//     const fg = data?.editor?.fg ?? [220, 220, 220];
86//     const frames = 18;
87//     const stepMs = 16;
88//     const lerp = (a: number, b: number, t: number) =>
89//         Math.round(a + (b - a) * t);
90//     for (let i = 1; i <= frames; i++) {
91//         const t = i / frames;
92//         editor.overrideThemeColors({
93//             "editor.bg": [lerp(0, bg[0], t), lerp(0, bg[1], t), lerp(0, bg[2], t)],
94//             "editor.fg": [lerp(0, fg[0], t), lerp(0, fg[1], t), lerp(0, fg[2], t)],
95//         });
96//         await editor.delay(stepMs);
97//     }
98//     editor.applyTheme(target); // drop overrides, settle on the real theme
99// })();
100
101// Example: calmer UI over SSH. setSetting writes to the runtime layer —
102// nothing is persisted to disk, and removing this file is a complete undo.
103// if (editor.getEnv("SSH_TTY")) {
104//     editor.setSetting("editor.diagnostics_inline_text", false);
105//     editor.setSetting("terminal.mouse", false);
106// }
107
108// Example: host-specific rust-analyzer path.
109// if (editor.getEnv("HOSTNAME") === "my-mac") {
110//     editor.registerLspServer("rust", {
111//         command: "/opt/homebrew/bin/rust-analyzer",
112//         args: [],
113//         autoStart: true,
114//         initializationOptions: null,
115//         processLimits: null,
116//     });
117// }
118
119// Example: env-driven profile (fresh invoked as FRESH_PROFILE=writing fresh).
120// if (editor.getEnv("FRESH_PROFILE") === "writing") {
121//     editor.setSetting("editor.line_wrap", true);
122//     editor.setSetting("editor.wrap_column", 80);
123// }
124
125// Example: configure a plugin once it loads. `plugins_loaded` fires after
126// every registry plugin and init.ts top-level code has run.
127// editor.on("plugins_loaded", () => {
128//     const api = editor.getPluginApi("my-plugin");
129//     if (api) api.configure({ option: "value" });
130// });
131
132// Example: enable the opt-in Dashboard widgets (weather, GitHub).
133// Both hit the network on every refresh, so the plugin ships with
134// only `git` and `disk` registered by default. The handlers live
135// on the exported plugin API as `builtinHandlers` — pass them to
136// `registerSection` with whatever name you like.
137//
138// editor.on("plugins_loaded", () => {
139//     const dash = editor.getPluginApi("dashboard");
140//     if (!dash) return;
141//     dash.registerSection("weather", dash.builtinHandlers.weather);
142//     dash.registerSection("github", dash.builtinHandlers.github);
143// });
144
145// Example: disable the Dashboard's auto-open behaviour on this
146// machine (it will still be available via the "Show Dashboard"
147// command). The same toggle can also be set persistently in
148// config.json at `plugins.dashboard.auto-open`.
149//
150// editor.on("plugins_loaded", () => {
151//     const dash = editor.getPluginApi("dashboard");
152//     if (dash) dash.setAutoOpen(false);
153// });
154
155// Example: add a custom section to the Dashboard plugin.
156//
157// `editor.getPluginApi("dashboard")` is typed automatically via
158// `types/plugins.d.ts` — no `as` cast needed. Hover over `dash` or
159// `ctx` in your editor to see the full API.
160//
161// editor.on("plugins_loaded", () => {
162//     const dash = editor.getPluginApi("dashboard");
163//     if (!dash) return;
164//     dash.registerSection("todo", async (ctx) => {
165//         // Pretend we read a TODO count from somewhere async.
166//         const count = 3;
167//         if (count === 0) {
168//             ctx.kv("status", "inbox zero", "ok");
169//             return;
170//         }
171//         ctx.kv("open", String(count), count > 5 ? "warn" : "value");
172//         ctx.text("    " + "see all".padEnd(10), { color: "muted" });
173//         ctx.text("open inbox", {
174//             color: "accent",
175//             bold: true,
176//             onClick: () => editor.executeAction("open_inbox"),
177//         });
178//         ctx.newline();
179//     });
180// });
181
182// Example: register a custom Live Grep search backend.
183//
184// The bundled providers (ripgrep → git grep → grep) are picked by
185// priority on each invocation. Higher-priority registrations win;
186// register from init.ts to use a custom indexer or wrapper script.
187//
188// editor.on("plugins_loaded", () => {
189//     const liveGrep = editor.getPluginApi("live-grep");
190//     if (!liveGrep) return;
191//     liveGrep.registerProvider({
192//         name: "fff",
193//         priority: 100,
194//         isAvailable: async () => {
195//             try {
196//                 const r = await editor.spawnProcess("fff", ["--version"], editor.getCwd());
197//                 return r.exit_code === 0;
198//             } catch {
199//                 return false;
200//             }
201//         },
202//         search: async (query, { cwd, maxResults }) => {
203//             const r = await editor.spawnProcess("fff", [query], cwd);
204//             // Return GrepMatch[]: { file, line, column, content }
205//             return r.stdout.split("\n").filter(Boolean).map((line) => {
206//                 const [file, lineStr, ...rest] = line.split(":");
207//                 return {
208//                     file,
209//                     line: parseInt(lineStr, 10) || 1,
210//                     column: 1,
211//                     content: rest.join(":"),
212//                 };
213//             }).slice(0, maxResults);
214//         },
215//     });
216// });
217"#;
218
219/// `tsconfig.json` for the user's init.ts. Matches the plugin-dev
220/// workspace (no DOM, no ambient types) so LSP behaviour is consistent
221/// with plugins.
222const INIT_TSCONFIG: &str = r#"{
223  "compilerOptions": {
224    "target": "ES2020",
225    "module": "ES2020",
226    "moduleResolution": "node",
227    "strict": true,
228    "noEmit": true,
229    "skipLibCheck": true,
230    "lib": ["ES2020"],
231    "types": []
232  },
233  "files": ["init.ts", "types/fresh.d.ts", "types/plugins.d.ts"]
234}
235"#;
236
237/// Resolve the path to `fresh.d.ts` inside the embedded-plugins cache.
238/// Only embedded content is used — never an on-disk copy that isn't
239/// guaranteed to match this binary — so the types always track the
240/// running build.
241#[cfg(feature = "embed-plugins")]
242fn embedded_fresh_dts_path() -> Option<PathBuf> {
243    let embedded = crate::services::plugins::embedded::get_embedded_plugins_dir()?;
244    let p = embedded.join("lib").join("fresh.d.ts");
245    p.exists().then_some(p)
246}
247
248#[cfg(not(feature = "embed-plugins"))]
249fn embedded_fresh_dts_path() -> Option<PathBuf> {
250    None
251}
252
253/// Refresh `~/.config/fresh/types/fresh.d.ts` from the embedded copy and
254/// write `tsconfig.json` if it isn't already present.
255///
256/// `fresh.d.ts` is **always overwritten** — it's an auto-generated API
257/// mirror that must track the running binary. Keeping a stale copy in
258/// `~/.config/fresh/types/` would silently hide drift between the API
259/// the user's `init.ts` was written against and the one the running
260/// binary actually exposes. `tsconfig.json` is treated as user-editable
261/// and only written on first run.
262///
263/// Errors are logged but not returned: type scaffolding is best-effort
264/// and must not block opening or loading init.ts.
265pub fn refresh_types_scaffolding(config_dir: &Path) {
266    let Some(source) = embedded_fresh_dts_path() else {
267        tracing::warn!(
268            "init.ts: embedded fresh.d.ts unavailable; \
269             LSP completions in init.ts will be unavailable"
270        );
271        return;
272    };
273
274    let types_dir = config_dir.join("types");
275    if let Err(e) = std::fs::create_dir_all(&types_dir) {
276        tracing::warn!("init.ts: failed to create {}: {e}", types_dir.display());
277        return;
278    }
279    let dest_dts = types_dir.join("fresh.d.ts");
280    if let Err(e) = std::fs::copy(&source, &dest_dts) {
281        tracing::warn!(
282            "init.ts: failed to copy fresh.d.ts from {} to {}: {e}",
283            source.display(),
284            dest_dts.display()
285        );
286    }
287
288    let tsconfig = config_dir.join("tsconfig.json");
289    if !tsconfig.exists() {
290        if let Err(e) = std::fs::write(&tsconfig, INIT_TSCONFIG) {
291            tracing::warn!("init.ts: failed to write {}: {e}", tsconfig.display());
292        }
293    }
294}
295
296/// Write `<config_dir>/types/plugins.d.ts` from the `.d.ts` emit of
297/// each loaded plugin. The editor calls this after scanning every
298/// plugin directory, so by the time `init.ts` is evaluated the
299/// ambient `FreshPluginRegistry` is fully populated and
300/// `editor.getPluginApi("dashboard")` resolves to the typed overload.
301///
302/// Errors are logged but not returned: an empty or stale
303/// `plugins.d.ts` must not block startup.
304pub fn write_plugin_declarations(config_dir: &Path, declarations: &[(String, String)]) {
305    let types_dir = config_dir.join("types");
306    if let Err(e) = std::fs::create_dir_all(&types_dir) {
307        tracing::warn!("init.ts: failed to create {}: {e}", types_dir.display());
308        return;
309    }
310    let dest = types_dir.join("plugins.d.ts");
311
312    // Stable order so a re-scan doesn't produce a needlessly
313    // different file (and a noisy diff for users who version-control
314    // their config dir).
315    let mut sorted: Vec<&(String, String)> = declarations.iter().collect();
316    sorted.sort_by(|a, b| a.0.cmp(&b.0));
317
318    let mut body = String::new();
319    body.push_str(
320        "// AUTO-GENERATED by fresh — do not edit.\n\
321         //\n\
322         // Aggregate of every loaded plugin's isolated-declarations\n\
323         // emit (oxc). This is what makes `editor.getPluginApi(\"foo\")`\n\
324         // return a typed result in init.ts / downstream plugins —\n\
325         // each plugin that declares `FreshPluginRegistry` here\n\
326         // contributes its augmentation.\n\n",
327    );
328    for (name, dts) in sorted {
329        let trimmed = dts.trim();
330        // Script-style plugins with no exports get `export {};` appended
331        // in the parser to force module mode. After isolated-declarations
332        // strips internals, that's all that remains — a per-plugin
333        // section with just `export {};` is pure noise in the aggregate.
334        if trimmed.is_empty() || trimmed == "export {};" {
335            continue;
336        }
337        body.push_str(&format!("// ── {name} ─────────────────────\n"));
338        body.push_str(dts.trim_end());
339        body.push_str("\n\n");
340    }
341
342    if let Err(e) = std::fs::write(&dest, &body) {
343        tracing::warn!("init.ts: failed to write {}: {e}", dest.display());
344    }
345}
346
347/// Ensure `~/.config/fresh/init.ts` exists. If absent, writes the starter
348/// template. Also refreshes `types/fresh.d.ts` + `tsconfig.json` so the
349/// template's `/// <reference path=...` directive resolves and
350/// `getEditor()` type-checks in any TS-aware editor.
351/// Returns the (possibly newly-created) `init.ts` path.
352pub fn ensure_starter(config_dir: &Path) -> std::io::Result<PathBuf> {
353    let path = init_ts_path(config_dir);
354    if !path.exists() {
355        if let Some(parent) = path.parent() {
356            std::fs::create_dir_all(parent)?;
357        }
358        std::fs::write(&path, STARTER_TEMPLATE)?;
359    }
360    refresh_types_scaffolding(config_dir);
361    Ok(path)
362}
363
364/// Outcome of [`autoload`].
365#[derive(Debug)]
366pub enum InitOutcome {
367    /// init.ts did not exist; nothing to do.
368    NotFound,
369    /// Skipped because `--no-init` / `--safe` was passed.
370    Disabled,
371    /// Skipped because the crash fuse engaged.
372    CrashFused { failures: u32 },
373    /// Loaded and evaluated successfully.
374    Loaded,
375    /// Evaluation produced an error; the status message has been set.
376    Failed { message: String },
377}
378
379/// Resolve `~/.config/fresh/init.ts`.
380pub fn init_ts_path(config_dir: &Path) -> PathBuf {
381    config_dir.join("init.ts")
382}
383
384/// Resolve the crash-fuse counter file path.
385fn crashes_path(config_dir: &Path) -> PathBuf {
386    config_dir.join("logs").join("init.crashes")
387}
388
389#[derive(Debug, Default)]
390struct CrashState {
391    count: u32,
392    last_increment_epoch: u64,
393}
394
395impl CrashState {
396    fn load(config_dir: &Path) -> Self {
397        let path = crashes_path(config_dir);
398        let Ok(text) = std::fs::read_to_string(&path) else {
399            return Self::default();
400        };
401        let mut count = 0u32;
402        let mut last = 0u64;
403        for (i, line) in text.lines().enumerate() {
404            let trimmed = line.trim();
405            if trimmed.is_empty() {
406                continue;
407            }
408            match i {
409                0 => count = trimmed.parse().unwrap_or(0),
410                1 => last = trimmed.parse().unwrap_or(0),
411                _ => break,
412            }
413        }
414        Self {
415            count,
416            last_increment_epoch: last,
417        }
418    }
419
420    fn save(&self, config_dir: &Path) -> std::io::Result<()> {
421        let path = crashes_path(config_dir);
422        if let Some(parent) = path.parent() {
423            std::fs::create_dir_all(parent)?;
424        }
425        std::fs::write(
426            &path,
427            format!("{}\n{}\n", self.count, self.last_increment_epoch),
428        )
429    }
430
431    fn clear(config_dir: &Path) {
432        let path = crashes_path(config_dir);
433        if let Err(e) = std::fs::remove_file(&path) {
434            if e.kind() != std::io::ErrorKind::NotFound {
435                tracing::debug!(
436                    "init.ts crash-fuse: failed to clear {}: {e}",
437                    path.display()
438                );
439            }
440        }
441    }
442}
443
444fn now_epoch_secs() -> u64 {
445    std::time::SystemTime::now()
446        .duration_since(std::time::UNIX_EPOCH)
447        .map(|d| d.as_secs())
448        .unwrap_or(0)
449}
450
451/// Called before loading init.ts. Returns `Some(failures)` if the fuse has
452/// tripped and init.ts should be skipped; `None` if loading may proceed.
453///
454/// Also increments the counter — if init.ts evaluation succeeds, the caller
455/// must invoke [`record_success`] to reset it.
456fn check_and_increment_fuse(config_dir: &Path) -> Option<u32> {
457    let now = now_epoch_secs();
458    let mut state = CrashState::load(config_dir);
459
460    // Stale entries outside the rolling window: treat as a clean slate.
461    if state.last_increment_epoch == 0
462        || now.saturating_sub(state.last_increment_epoch) > CRASH_FUSE_WINDOW_SECS
463    {
464        state.count = 0;
465    }
466
467    if state.count >= CRASH_FUSE_THRESHOLD {
468        return Some(state.count);
469    }
470
471    state.count += 1;
472    state.last_increment_epoch = now;
473    if let Err(e) = state.save(config_dir) {
474        tracing::debug!("init.ts crash-fuse: failed to persist counter: {e}");
475    }
476
477    None
478}
479
480/// Called after init.ts finishes cleanly. Resets the crash-fuse counter so
481/// the next launch starts from zero.
482pub fn record_success(config_dir: &Path) {
483    CrashState::clear(config_dir);
484}
485
486/// Read init.ts from disk. Returns `Ok(None)` when the file simply doesn't
487/// exist.
488pub fn read_init_script(config_dir: &Path) -> std::io::Result<Option<String>> {
489    let path = init_ts_path(config_dir);
490    match std::fs::read_to_string(&path) {
491        Ok(s) => Ok(Some(s)),
492        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None),
493        Err(e) => Err(e),
494    }
495}
496
497/// Decide, without touching disk for the source, whether init.ts loading
498/// should run at all.
499pub fn should_skip(enabled: bool) -> bool {
500    !enabled
501}
502
503/// Human-readable summary for the status bar / logs.
504pub fn describe(outcome: &InitOutcome) -> String {
505    match outcome {
506        InitOutcome::NotFound => String::from("init.ts: not present"),
507        InitOutcome::Disabled => String::from("init.ts: skipped (--no-init / --safe)"),
508        InitOutcome::CrashFused { failures } => format!(
509            "init.ts: skipped after {failures} consecutive failures — fix ~/.config/fresh/init.ts or remove it"
510        ),
511        InitOutcome::Loaded => String::from("init.ts: loaded"),
512        InitOutcome::Failed { message } => format!("init.ts: {message}"),
513    }
514}
515
516/// Pre-flight for the caller: check fuse, return either the source to load
517/// or an outcome explaining why we're not loading.
518pub enum LoadDecision {
519    Skip(InitOutcome),
520    Load { source: String },
521}
522
523pub fn decide_load(config_dir: &Path, enabled: bool) -> LoadDecision {
524    if should_skip(enabled) {
525        return LoadDecision::Skip(InitOutcome::Disabled);
526    }
527    match read_init_script(config_dir) {
528        Ok(None) => LoadDecision::Skip(InitOutcome::NotFound),
529        Err(e) => LoadDecision::Skip(InitOutcome::Failed {
530            message: format!("read failed: {e}"),
531        }),
532        Ok(Some(source)) => {
533            if let Some(failures) = check_and_increment_fuse(config_dir) {
534                LoadDecision::Skip(InitOutcome::CrashFused { failures })
535            } else {
536                LoadDecision::Load { source }
537            }
538        }
539    }
540}
541
542/// Result of `fresh --cmd init check`.
543#[derive(Debug)]
544pub struct CheckReport {
545    pub ok: bool,
546    pub diagnostics: Vec<CheckDiagnostic>,
547    pub path: PathBuf,
548}
549
550#[derive(Debug)]
551pub struct CheckDiagnostic {
552    pub severity: CheckSeverity,
553    pub message: String,
554    /// Best-effort: 1-based line number. `0` if the parser didn't surface one.
555    pub line: u32,
556    pub column: u32,
557}
558
559#[derive(Debug, Clone, Copy, PartialEq, Eq)]
560pub enum CheckSeverity {
561    Error,
562    Warning,
563}
564
565/// Parse `~/.config/fresh/init.ts` via oxc and report syntax errors.
566///
567/// This is the "parse mode" from the design (§5.1): always-on, low-latency,
568/// catches the mistakes that would otherwise blow up at startup. The
569/// deeper type-check (`tsc --noEmit`) and the scope-discipline lints
570/// (`init/unconditional-preference`, `init/unconditional-plugin-load`)
571/// are deliberately not implemented here — they're strict-mode concerns
572/// that can grow on top of this foundation.
573pub fn check(config_dir: &Path) -> CheckReport {
574    use oxc_allocator::Allocator;
575    use oxc_parser::Parser;
576    use oxc_span::SourceType;
577
578    let path = init_ts_path(config_dir);
579
580    let source = match std::fs::read_to_string(&path) {
581        Ok(s) => s,
582        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
583            return CheckReport {
584                ok: true,
585                diagnostics: Vec::new(),
586                path,
587            };
588        }
589        Err(e) => {
590            return CheckReport {
591                ok: false,
592                diagnostics: vec![CheckDiagnostic {
593                    severity: CheckSeverity::Error,
594                    message: format!("read failed: {e}"),
595                    line: 0,
596                    column: 0,
597                }],
598                path,
599            };
600        }
601    };
602
603    let allocator = Allocator::default();
604    let source_type = SourceType::from_path(&path).unwrap_or_default();
605    let parser_ret = Parser::new(&allocator, &source, source_type).parse();
606
607    let mut diagnostics = Vec::new();
608    for err in &parser_ret.errors {
609        // oxc errors carry labels/spans but the formatting is embedded in
610        // the miette-style Display impl. Pull the primary message + try to
611        // recover line/column from the start of the first label.
612        let (line, column) = err
613            .labels
614            .as_ref()
615            .and_then(|v| v.first())
616            .map(|l| line_col(&source, l.offset()))
617            .unwrap_or((0, 0));
618        diagnostics.push(CheckDiagnostic {
619            severity: CheckSeverity::Error,
620            message: err.message.to_string(),
621            line,
622            column,
623        });
624    }
625
626    CheckReport {
627        ok: parser_ret.errors.is_empty(),
628        diagnostics,
629        path,
630    }
631}
632
633/// Convert a byte offset into a (line, column) pair, 1-based, for display.
634fn line_col(source: &str, offset: usize) -> (u32, u32) {
635    let clipped = source.get(..offset).unwrap_or(source);
636    let line = 1 + clipped.bytes().filter(|&b| b == b'\n').count();
637    let col = 1 + clipped
638        .rsplit('\n')
639        .next()
640        .map(|s| s.chars().count())
641        .unwrap_or(0);
642    (line as u32, col as u32)
643}
644
645#[cfg(test)]
646mod tests {
647    use super::*;
648    use tempfile::TempDir;
649
650    #[test]
651    fn init_ts_path_is_under_config_dir() {
652        let p = init_ts_path(Path::new("/tmp/fresh"));
653        assert_eq!(p, PathBuf::from("/tmp/fresh/init.ts"));
654    }
655
656    #[test]
657    fn crash_fuse_trips_after_threshold_consecutive_failures() {
658        let tmp = TempDir::new().unwrap();
659        let dir = tmp.path();
660
661        // Three attempts that never record success — each returns None
662        // (proceed) and bumps the counter.
663        for _ in 0..CRASH_FUSE_THRESHOLD {
664            assert!(check_and_increment_fuse(dir).is_none());
665        }
666
667        // Fourth attempt should be short-circuited.
668        let tripped = check_and_increment_fuse(dir);
669        assert!(tripped.is_some());
670        assert_eq!(tripped.unwrap(), CRASH_FUSE_THRESHOLD);
671    }
672
673    #[test]
674    fn record_success_resets_the_fuse() {
675        let tmp = TempDir::new().unwrap();
676        let dir = tmp.path();
677
678        for _ in 0..CRASH_FUSE_THRESHOLD {
679            check_and_increment_fuse(dir);
680        }
681        record_success(dir);
682
683        // After success, we should have room for another full cycle.
684        assert!(check_and_increment_fuse(dir).is_none());
685    }
686
687    #[test]
688    fn stale_failures_outside_window_are_ignored() {
689        let tmp = TempDir::new().unwrap();
690        let dir = tmp.path();
691
692        // Manually plant an old, tripped counter.
693        let state = CrashState {
694            count: CRASH_FUSE_THRESHOLD + 5,
695            last_increment_epoch: now_epoch_secs().saturating_sub(CRASH_FUSE_WINDOW_SECS + 1),
696        };
697        state.save(dir).unwrap();
698
699        // Next attempt should treat it as fresh: proceed, counter back to 1.
700        assert!(check_and_increment_fuse(dir).is_none());
701    }
702
703    #[test]
704    fn decide_load_reports_not_found_when_missing() {
705        let tmp = TempDir::new().unwrap();
706        match decide_load(tmp.path(), true) {
707            LoadDecision::Skip(InitOutcome::NotFound) => {}
708            other => panic!("expected NotFound, got {other:?}"),
709        }
710    }
711
712    #[test]
713    fn decide_load_reports_disabled_when_flag_says_so() {
714        let tmp = TempDir::new().unwrap();
715        std::fs::write(init_ts_path(tmp.path()), "// hi").unwrap();
716        match decide_load(tmp.path(), false) {
717            LoadDecision::Skip(InitOutcome::Disabled) => {}
718            other => panic!("expected Disabled, got {other:?}"),
719        }
720    }
721
722    #[test]
723    fn decide_load_returns_source_when_file_present_and_enabled() {
724        let tmp = TempDir::new().unwrap();
725        std::fs::write(init_ts_path(tmp.path()), "const x = 1;").unwrap();
726        match decide_load(tmp.path(), true) {
727            LoadDecision::Load { source } => assert_eq!(source, "const x = 1;"),
728            other => panic!("expected Load, got {other:?}"),
729        }
730    }
731
732    // Minor: LoadDecision/InitOutcome must be Debug to use in assertions.
733    impl std::fmt::Debug for LoadDecision {
734        fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
735            match self {
736                LoadDecision::Skip(o) => write!(f, "Skip({o:?})"),
737                LoadDecision::Load { source } => write!(f, "Load({} chars)", source.len()),
738            }
739        }
740    }
741
742    #[test]
743    fn check_no_file_is_ok() {
744        let tmp = TempDir::new().unwrap();
745        let report = check(tmp.path());
746        assert!(report.ok);
747        assert!(report.diagnostics.is_empty());
748    }
749
750    #[test]
751    fn check_clean_source_is_ok() {
752        let tmp = TempDir::new().unwrap();
753        std::fs::write(
754            init_ts_path(tmp.path()),
755            "const editor = getEditor();\neditor.setStatus('hi');\n",
756        )
757        .unwrap();
758        let report = check(tmp.path());
759        assert!(report.ok, "diagnostics: {:?}", report.diagnostics);
760    }
761
762    #[test]
763    fn check_syntax_error_reports_a_diagnostic() {
764        let tmp = TempDir::new().unwrap();
765        // Missing closing paren — unambiguous parse error.
766        std::fs::write(init_ts_path(tmp.path()), "function broken(\n").unwrap();
767        let report = check(tmp.path());
768        assert!(!report.ok);
769        assert!(!report.diagnostics.is_empty());
770        assert_eq!(report.diagnostics[0].severity, CheckSeverity::Error);
771    }
772
773    #[test]
774    fn starter_template_references_both_dts_files() {
775        assert!(
776            STARTER_TEMPLATE.contains(r#"/// <reference path="./types/fresh.d.ts" />"#),
777            "starter template must reference fresh.d.ts"
778        );
779        assert!(
780            STARTER_TEMPLATE.contains(r#"/// <reference path="./types/plugins.d.ts" />"#),
781            "starter template must reference plugins.d.ts so plugin APIs are typed"
782        );
783    }
784
785    #[test]
786    fn write_plugin_declarations_skips_empty_export_plugins() {
787        let tmp = TempDir::new().unwrap();
788        let decls = vec![
789            ("noop".to_string(), "export {};\n".to_string()),
790            ("blank".to_string(), "".to_string()),
791            (
792                "dashboard".to_string(),
793                "export type DashboardApi = { foo(): void; };\n\
794                 declare global { interface FreshPluginRegistry { dashboard: DashboardApi; } }\n\
795                 export {};\n"
796                    .to_string(),
797            ),
798        ];
799        write_plugin_declarations(tmp.path(), &decls);
800        let body = std::fs::read_to_string(tmp.path().join("types/plugins.d.ts")).unwrap();
801        assert!(
802            body.contains("// ── dashboard ─"),
803            "dashboard section missing: {body}"
804        );
805        assert!(
806            body.contains("DashboardApi"),
807            "dashboard API missing: {body}"
808        );
809        assert!(
810            !body.contains("// ── noop ─"),
811            "empty-export plugin should not get a section header: {body}"
812        );
813        assert!(
814            !body.contains("// ── blank ─"),
815            "blank-emit plugin should not get a section header: {body}"
816        );
817    }
818}