fresh-editor 0.3.0

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
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
//! Unified Plugin Manager
//!
//! This module provides a unified interface for the plugin system that works
//! regardless of whether the `plugins` feature is enabled. When plugins are
//! disabled, all methods are no-ops, avoiding the need for cfg attributes
//! scattered throughout the codebase.

use crate::config_io::DirectoryContext;
use crate::input::command_registry::CommandRegistry;
use fresh_core::config::PluginConfig;
use std::collections::HashMap;
use std::path::Path;
use std::sync::{Arc, RwLock};

#[cfg(feature = "plugins")]
use super::bridge::EditorServiceBridge;
#[cfg(feature = "plugins")]
use fresh_plugin_runtime::PluginThreadHandle;

/// Unified plugin manager that abstracts over the plugin system.
///
/// When the `plugins` feature is enabled, this wraps `PluginThreadHandle`.
/// When disabled, all methods are no-ops.
pub struct PluginManager {
    #[cfg(feature = "plugins")]
    inner: Option<PluginThreadHandle>,
    #[cfg(not(feature = "plugins"))]
    _phantom: std::marker::PhantomData<()>,
}

impl PluginManager {
    /// Create a new plugin manager.
    ///
    /// When `plugins` feature is enabled and `enable` is true, spawns the plugin thread.
    /// Otherwise, creates a no-op manager.
    pub fn new(
        enable: bool,
        command_registry: Arc<RwLock<CommandRegistry>>,
        dir_context: DirectoryContext,
        theme_cache: Arc<RwLock<HashMap<String, serde_json::Value>>>,
    ) -> Self {
        #[cfg(feature = "plugins")]
        {
            if enable {
                let services = Arc::new(EditorServiceBridge {
                    command_registry: command_registry.clone(),
                    dir_context,
                    theme_cache,
                });
                match PluginThreadHandle::spawn(services) {
                    Ok(handle) => {
                        return Self {
                            inner: Some(handle),
                        }
                    }
                    Err(e) => {
                        tracing::error!("Failed to spawn TypeScript plugin thread: {}", e);
                        #[cfg(debug_assertions)]
                        panic!("TypeScript plugin thread creation failed: {}", e);
                    }
                }
            } else {
                tracing::info!("Plugins disabled via --no-plugins flag");
            }
            Self { inner: None }
        }

        #[cfg(not(feature = "plugins"))]
        {
            let _ = command_registry; // Suppress unused warning
            let _ = dir_context; // Suppress unused warning
            let _ = theme_cache; // Suppress unused warning
            if enable {
                tracing::warn!("Plugins requested but compiled without plugin support");
            }
            Self {
                _phantom: std::marker::PhantomData,
            }
        }
    }

    /// Check if the plugin system is active (has a running plugin thread).
    pub fn is_active(&self) -> bool {
        #[cfg(feature = "plugins")]
        {
            self.inner.is_some()
        }
        #[cfg(not(feature = "plugins"))]
        {
            false
        }
    }

    /// Check if the plugin thread is still alive
    pub fn is_alive(&self) -> bool {
        #[cfg(feature = "plugins")]
        {
            self.inner.as_ref().map(|h| h.is_alive()).unwrap_or(false)
        }
        #[cfg(not(feature = "plugins"))]
        {
            false
        }
    }

    /// Check thread health and panic if the plugin thread died due to a panic.
    /// This propagates plugin thread panics to the calling thread.
    /// Call this periodically (e.g., in wait loops) to fail fast on plugin errors.
    pub fn check_thread_health(&mut self) {
        #[cfg(feature = "plugins")]
        {
            if let Some(ref mut handle) = self.inner {
                handle.check_thread_health();
            }
        }
    }

    /// Load plugins from a directory.
    pub fn load_plugins_from_dir(&self, dir: &Path) -> Vec<String> {
        #[cfg(feature = "plugins")]
        {
            if let Some(ref manager) = self.inner {
                return manager.load_plugins_from_dir(dir);
            }
            Vec::new()
        }
        #[cfg(not(feature = "plugins"))]
        {
            let _ = dir;
            Vec::new()
        }
    }

    /// Load plugins from a directory with config support.
    /// Returns (errors, discovered_plugins) where discovered_plugins is a map of
    /// plugin name -> PluginConfig with paths populated.
    #[cfg(feature = "plugins")]
    pub fn load_plugins_from_dir_with_config(
        &self,
        dir: &Path,
        plugin_configs: &HashMap<String, PluginConfig>,
    ) -> (Vec<String>, HashMap<String, PluginConfig>) {
        if let Some(ref manager) = self.inner {
            return manager.load_plugins_from_dir_with_config(dir, plugin_configs);
        }
        (Vec::new(), HashMap::new())
    }

    /// Load plugins from a directory with config support (no-op when plugins disabled).
    #[cfg(not(feature = "plugins"))]
    pub fn load_plugins_from_dir_with_config(
        &self,
        dir: &Path,
        plugin_configs: &HashMap<String, PluginConfig>,
    ) -> (Vec<String>, HashMap<String, PluginConfig>) {
        let _ = (dir, plugin_configs);
        (Vec::new(), HashMap::new())
    }

    /// Unload a plugin by name.
    pub fn unload_plugin(&self, name: &str) -> anyhow::Result<()> {
        #[cfg(feature = "plugins")]
        {
            self.inner
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("Plugin system not active"))?
                .unload_plugin(name)
        }
        #[cfg(not(feature = "plugins"))]
        {
            let _ = name;
            Ok(())
        }
    }

    /// Load a single plugin by path.
    pub fn load_plugin(&self, path: &Path) -> anyhow::Result<()> {
        #[cfg(feature = "plugins")]
        {
            self.inner
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("Plugin system not active"))?
                .load_plugin(path)
        }
        #[cfg(not(feature = "plugins"))]
        {
            let _ = path;
            Ok(())
        }
    }

    /// Load a plugin from source code directly (no file I/O).
    ///
    /// If a plugin with the same name is already loaded, it will be unloaded first
    /// (hot-reload semantics). This is used for "Load Plugin from Buffer".
    pub fn load_plugin_from_source(
        &self,
        source: &str,
        name: &str,
        is_typescript: bool,
    ) -> anyhow::Result<()> {
        #[cfg(feature = "plugins")]
        {
            self.inner
                .as_ref()
                .ok_or_else(|| anyhow::anyhow!("Plugin system not active"))?
                .load_plugin_from_source(source, name, is_typescript)
        }
        #[cfg(not(feature = "plugins"))]
        {
            let _ = (source, name, is_typescript);
            Ok(())
        }
    }

    /// Run a hook (fire-and-forget).
    pub fn run_hook(&self, hook_name: &str, args: super::hooks::HookArgs) {
        #[cfg(feature = "plugins")]
        {
            if let Some(ref manager) = self.inner {
                manager.run_hook(hook_name, args);
            }
        }
        #[cfg(not(feature = "plugins"))]
        {
            let _ = (hook_name, args);
        }
    }

    /// Deliver a response to a pending async plugin operation.
    pub fn deliver_response(&self, response: super::api::PluginResponse) {
        #[cfg(feature = "plugins")]
        {
            if let Some(ref manager) = self.inner {
                manager.deliver_response(response);
            }
        }
        #[cfg(not(feature = "plugins"))]
        {
            let _ = response;
        }
    }

    /// Process pending plugin commands (non-blocking).
    pub fn process_commands(&mut self) -> Vec<super::api::PluginCommand> {
        #[cfg(feature = "plugins")]
        {
            if let Some(ref mut manager) = self.inner {
                return manager.process_commands();
            }
            Vec::new()
        }
        #[cfg(not(feature = "plugins"))]
        {
            Vec::new()
        }
    }

    /// Process commands, blocking until `HookCompleted` for the given hook arrives.
    /// See [`PluginThreadHandle::process_commands_until_hook_completed`] for details.
    ///
    // TODO: This method is currently unused (dead code). Either wire it into the
    // render path to synchronously wait for plugin responses (e.g. conceals from
    // lines_changed), or remove it along with PluginThreadHandle's implementation
    // and the HookCompleted sentinel if the non-blocking drain approach is sufficient.
    pub fn process_commands_until_hook_completed(
        &mut self,
        hook_name: &str,
        timeout: std::time::Duration,
    ) -> Vec<super::api::PluginCommand> {
        #[cfg(feature = "plugins")]
        {
            if let Some(ref mut manager) = self.inner {
                return manager.process_commands_until_hook_completed(hook_name, timeout);
            }
            Vec::new()
        }
        #[cfg(not(feature = "plugins"))]
        {
            let _ = (hook_name, timeout);
            Vec::new()
        }
    }

    /// Get the state snapshot handle for updating editor state.
    #[cfg(feature = "plugins")]
    pub fn state_snapshot_handle(&self) -> Option<Arc<RwLock<super::api::EditorStateSnapshot>>> {
        self.inner.as_ref().map(|m| m.state_snapshot_handle())
    }

    /// Execute a plugin action asynchronously.
    #[cfg(feature = "plugins")]
    pub fn execute_action_async(
        &self,
        action_name: &str,
    ) -> Option<anyhow::Result<fresh_plugin_runtime::thread::oneshot::Receiver<anyhow::Result<()>>>>
    {
        self.inner
            .as_ref()
            .map(|m| m.execute_action_async(action_name))
    }

    /// List all loaded plugins.
    #[cfg(feature = "plugins")]
    pub fn list_plugins(
        &self,
    ) -> Vec<fresh_plugin_runtime::backend::quickjs_backend::TsPluginInfo> {
        self.inner
            .as_ref()
            .map(|m| m.list_plugins())
            .unwrap_or_default()
    }

    /// Collect the isolated-declarations `.d.ts` emit of every loaded
    /// plugin that produced one. Returns `(plugin_name, d_ts_source)`
    /// pairs — callers use this to assemble `plugins.d.ts`.
    ///
    /// Available in all builds: without the `plugins` feature it
    /// returns an empty vec, letting `editor_init` call this
    /// unconditionally.
    pub fn plugin_declarations(&self) -> Vec<(String, String)> {
        #[cfg(feature = "plugins")]
        {
            self.list_plugins()
                .into_iter()
                .filter_map(|info| info.declarations.map(|d| (info.name, d)))
                .collect()
        }
        #[cfg(not(feature = "plugins"))]
        {
            Vec::new()
        }
    }

    /// Reload a plugin by name.
    #[cfg(feature = "plugins")]
    pub fn reload_plugin(&self, name: &str) -> anyhow::Result<()> {
        self.inner
            .as_ref()
            .ok_or_else(|| anyhow::anyhow!("Plugin system not active"))?
            .reload_plugin(name)
    }

    /// Check if any handlers are registered for a hook.
    pub fn has_hook_handlers(&self, hook_name: &str) -> bool {
        #[cfg(feature = "plugins")]
        {
            self.inner
                .as_ref()
                .map(|m| m.has_hook_handlers(hook_name))
                .unwrap_or(false)
        }
        #[cfg(not(feature = "plugins"))]
        {
            let _ = hook_name;
            false
        }
    }

    /// Resolve an async callback in the plugin runtime
    #[cfg(feature = "plugins")]
    pub fn resolve_callback(&self, callback_id: super::api::JsCallbackId, result_json: String) {
        if let Some(inner) = &self.inner {
            inner.resolve_callback(callback_id, result_json);
        }
    }

    /// Resolve an async callback in the plugin runtime (no-op when plugins disabled)
    #[cfg(not(feature = "plugins"))]
    pub fn resolve_callback(
        &self,
        callback_id: fresh_core::api::JsCallbackId,
        result_json: String,
    ) {
        let _ = (callback_id, result_json);
    }

    /// Reject an async callback in the plugin runtime
    #[cfg(feature = "plugins")]
    pub fn reject_callback(&self, callback_id: super::api::JsCallbackId, error: String) {
        if let Some(inner) = &self.inner {
            inner.reject_callback(callback_id, error);
        }
    }

    /// Reject an async callback in the plugin runtime (no-op when plugins disabled)
    #[cfg(not(feature = "plugins"))]
    pub fn reject_callback(&self, callback_id: fresh_core::api::JsCallbackId, error: String) {
        let _ = (callback_id, error);
    }

    /// Call a streaming callback with partial data (does not consume the callback).
    /// When `done` is true, the JS side cleans up.
    #[cfg(feature = "plugins")]
    pub fn call_streaming_callback(
        &self,
        callback_id: fresh_core::api::JsCallbackId,
        result_json: String,
        done: bool,
    ) {
        if let Some(inner) = &self.inner {
            inner.call_streaming_callback(callback_id, result_json, done);
        }
    }

    /// Call a streaming callback (no-op when plugins disabled)
    #[cfg(not(feature = "plugins"))]
    pub fn call_streaming_callback(
        &self,
        callback_id: fresh_core::api::JsCallbackId,
        result_json: String,
        done: bool,
    ) {
        let _ = (callback_id, result_json, done);
    }
}