oj_server 0.2.16

Dev server: on-demand compile over HTTP, WebSocket HMR channel, file watcher
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
use super::*;

/// How the SSR pipeline resolved an import: a module it serves, or an external
/// the runner imports from node_modules with its own Node resolution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SsrResolution {
    Module(String),
    External(String),
}

/// Why an SSR module could not be served.
#[derive(Debug)]
pub enum SsrModuleError {
    Forbidden(String),
    NotFound(String),
    Failed(String),
}

impl std::fmt::Display for SsrModuleError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SsrModuleError::Forbidden(m)
            | SsrModuleError::NotFound(m)
            | SsrModuleError::Failed(m) => f.write_str(m),
        }
    }
}

/// In-process access to the `/@ssr-resolve` / `/@ssr-module` pipeline for the
/// embedded runner; HTTP endpoints and runner share one implementation.
#[derive(Clone)]
pub struct SsrBridge {
    pub(crate) state: Arc<ServerState>,
}

impl SsrBridge {
    /// The dev server's engine registry, for hosts on the other side of the
    /// bridge to register their engines in (SSR, Start).
    pub fn engine_registry(&self) -> oj_js::EngineRegistry {
        self.state.engine_registry.clone()
    }

    pub async fn resolve(&self, importer: &str, spec: &str) -> Result<SsrResolution, String> {
        ssr_resolve_inner(&self.state, importer, spec).await
    }

    /// The module's transformed code (plugins + dev-ssr compile), with its
    /// source map inline.
    pub async fn load_module(&self, id: &str) -> Result<String, SsrModuleError> {
        ssr_module_inner(&self.state, id, false).await
    }

    /// Like [`resolve`], but a node_modules hit keeps its RESOLVED path so the
    /// Start host uses the Vite-picked file, not a Node re-resolution.
    pub async fn resolve_start(
        &self,
        importer: &str,
        spec: &str,
    ) -> Result<StartResolution, String> {
        Ok(match ssr_resolve_raw(&self.state, importer, spec).await? {
            RawResolution::Path(p) if p.to_string_lossy().contains("/node_modules/") => {
                StartResolution::Dependency(p)
            }
            RawResolution::Path(p) => StartResolution::Module(p.to_string_lossy().into_owned()),
            RawResolution::PluginId(id) => StartResolution::Module(id),
            RawResolution::Bare => StartResolution::Bare(spec.to_string()),
        })
    }

    /// Plugin-transform + compile tail on a pre-read source; `run_plugins:
    /// false` skips the plugin chain and applies only the dev-ssr compile.
    pub async fn transform_module(
        &self,
        id: &str,
        source: String,
        from_plugin: bool,
        run_plugins: bool,
    ) -> Result<String, SsrModuleError> {
        if run_plugins {
            ssr_transform_source(&self.state, id, source, from_plugin, false).await
        } else {
            ssr_compile_source(&self.state, id, source, from_plugin, false)
        }
    }

    /// The lazily spawned ssr-environment plugin host, when the app has one.
    pub async fn plugin_host(&self) -> Option<std::sync::Arc<PluginHost>> {
        ssr_plugin_host(&self.state).await
    }

    /// Whether the SSR pipeline may serve this module path (root, allow-list,
    /// node_modules), the same rule `load_module` enforces.
    pub fn module_allowed(&self, path: &Path) -> bool {
        ssr_module_allowed(&self.state, path)
    }
}

/// Start host resolution: a served module (fs path or virtual id), a resolved
/// node_modules file, or a bare specifier left to Node semantics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum StartResolution {
    Module(String),
    Dependency(PathBuf),
    Bare(String),
}

/// What the SSR resolve ladder found, before each caller classifies it.
enum RawResolution {
    Path(PathBuf),
    PluginId(String),
    /// Unresolved bare specifier, left to the runtime's own resolution.
    Bare,
}

/// The ssr resolver, then the ssr plugin host's `resolveId`, then a bare
/// specifier passthrough.
async fn ssr_resolve_raw(
    state: &Arc<ServerState>,
    importer: &str,
    spec: &str,
) -> Result<RawResolution, String> {
    let importer_dir = Path::new(importer).parent().unwrap_or(&state.root);
    let err = match state.ssr_resolver.resolve(importer_dir, spec) {
        Ok(p) => return Ok(RawResolution::Path(p)),
        Err(e) => e,
    };
    if let Some(host) = ssr_plugin_host(state).await {
        if let Ok(Some(id)) = host.resolve_id(spec, importer).await {
            return Ok(RawResolution::PluginId(id));
        }
    }
    if !spec.starts_with('.') && !spec.starts_with('/') {
        return Ok(RawResolution::Bare);
    }
    Err(format!("cannot resolve {spec}: {}", err.reason))
}

pub(crate) async fn ssr_resolve_inner(
    state: &Arc<ServerState>,
    importer: &str,
    spec: &str,
) -> Result<SsrResolution, String> {
    Ok(match ssr_resolve_raw(state, importer, spec).await? {
        RawResolution::Path(p) => {
            let s = p.to_string_lossy();
            if s.contains("/node_modules/") {
                SsrResolution::External(spec.to_string())
            } else {
                SsrResolution::Module(s.into_owned())
            }
        }
        RawResolution::PluginId(id) => SsrResolution::Module(id),
        RawResolution::Bare => SsrResolution::External(spec.to_string()),
    })
}

pub(crate) async fn ssr_resolve(
    State(state): State<Arc<ServerState>>,
    Query(q): Query<HashMap<String, String>>,
) -> Response {
    let (Some(importer), Some(spec)) = (q.get("importer"), q.get("spec")) else {
        return (StatusCode::BAD_REQUEST, "importer and spec required").into_response();
    };
    match ssr_resolve_inner(&state, importer, spec).await {
        Ok(SsrResolution::Module(id)) => js_response_json(serde_json::json!({ "id": id })),
        Ok(SsrResolution::External(spec)) => {
            js_response_json(serde_json::json!({ "external": true, "spec": spec }))
        }
        Err(e) => (StatusCode::NOT_FOUND, e).into_response(),
    }
}

pub(crate) fn js_response_json(v: serde_json::Value) -> Response {
    ([(header::CONTENT_TYPE, "application/json")], v.to_string()).into_response()
}

pub(crate) fn module_read_allowed(
    root: &Path,
    allow: &std::collections::HashSet<PathBuf>,
    path: &Path,
) -> bool {
    let Ok(candidate) = std::fs::canonicalize(path) else {
        return true;
    };
    let real = |p: &Path| std::fs::canonicalize(p).unwrap_or_else(|_| p.to_path_buf());
    if candidate.starts_with(real(root)) {
        return true;
    }
    if candidate
        .components()
        .any(|c| c.as_os_str() == "node_modules")
    {
        return true;
    }
    allow
        .iter()
        .any(|allowed| candidate.starts_with(real(allowed)))
}

pub(crate) fn ssr_module_allowed(state: &ServerState, path: &Path) -> bool {
    let allow = state.fs_allow.lock().unwrap().clone();
    module_read_allowed(&state.root, &allow, path)
}

pub(crate) async fn ssr_module_inner(
    state: &Arc<ServerState>,
    id: &str,
    runner: bool,
) -> Result<String, SsrModuleError> {
    let path = PathBuf::from(id);
    if !ssr_module_allowed(state, &path) {
        return Err(SsrModuleError::Forbidden(
            "oj: module not allow-listed".into(),
        ));
    }
    let (source, from_plugin) = match std::fs::read(&path).and_then(bytes_to_string) {
        Ok(s) => (s, false),
        Err(read_err) => match ssr_plugin_host(state).await {
            Some(host) if host.hook_wants_load(id) => match host.load(id).await {
                Ok(Some(code)) => (code, true),
                _ => return Err(SsrModuleError::NotFound(format!("{id}: {read_err}"))),
            },
            Some(_) | None => return Err(SsrModuleError::NotFound(format!("{id}: {read_err}"))),
        },
    };
    let ext = path.extension().and_then(|e| e.to_str());
    if !from_plugin && ext.is_some_and(is_style_ext) {
        let source = if is_preprocessor(id) {
            run_preprocess_engine(state, id, &source, serde_json::Value::Null)
                .await
                .map_err(SsrModuleError::Failed)?
        } else {
            source
        };
        return ssr_css_module(&state.root, &path, &source).map_err(SsrModuleError::Failed);
    }
    if !from_plugin && ext == Some("json") {
        return oj_compiler::json::to_esm(&source, id)
            .map_err(|e| SsrModuleError::Failed(format!("{e}")));
    }
    ssr_transform_source(state, id, source, from_plugin, runner).await
}

/// Plugin-transform + dev-ssr-compile tail of the SSR module pipeline, on a
/// source the caller already has.
pub(crate) async fn ssr_transform_source(
    state: &Arc<ServerState>,
    id: &str,
    source: String,
    from_plugin: bool,
    runner: bool,
) -> Result<String, SsrModuleError> {
    let source = match ssr_plugin_host(state).await {
        // Same filter gate as the client path: an unclaimed module skips the
        // isolate RPC and the import pre-resolution that only feeds it.
        Some(host) if host.hook_wants_transform(id, &source) => {
            let resolved =
                resolved_imports_json(&state.resolver, &state.fs_allow, &source, Path::new(id));
            match host.transform(&source, id, &resolved).await {
                Ok((code, _, _, _)) => code,
                Err(e) => {
                    return Err(SsrModuleError::Failed(format!(
                        "oj: plugin transform error for {id}:\n{e}"
                    )));
                }
            }
        }
        Some(_) => {
            if plugins::hook_gate_debug() {
                eprintln!("oj: hook gate skipped ssr transform for {id}");
            }
            source
        }
        None => source,
    };
    ssr_compile_source(state, id, source, from_plugin, runner)
}

/// The dev-ssr compile alone (no plugin transforms): TS/JSX strip, define,
/// import.meta.env/glob, refresh off, SSR true.
pub(crate) fn ssr_compile_source(
    state: &Arc<ServerState>,
    id: &str,
    source: String,
    from_plugin: bool,
    runner: bool,
) -> Result<String, SsrModuleError> {
    let compile_path: PathBuf = if from_plugin {
        PathBuf::from("virtual.tsx")
    } else {
        PathBuf::from(id)
    };
    // Compile as dev + ssr so `import.meta.env.SSR` is true and `DEV`/`MODE`
    // match the client; Fast Refresh stays off on the server.
    let mut opts = dev_compile_opts(state);
    opts.refresh = false;
    opts.ssr = true;
    if runner {
        return match oj_compiler::ssr::ssr_transform_module_with_map(&compile_path, &source, &opts)
        {
            Ok((code, map)) => Ok(with_inline_map(code, map)),
            Err(e) => Err(SsrModuleError::Failed(format!("{e}"))),
        };
    }
    match oj_compiler::compile(&compile_path, &source, &opts) {
        Ok(out) => Ok(with_inline_map(out.code, out.map_json)),
        Err(e) => Err(SsrModuleError::Failed(format!("{e}"))),
    }
}

pub(crate) async fn ssr_module(
    State(state): State<Arc<ServerState>>,
    Query(q): Query<HashMap<String, String>>,
) -> Response {
    let Some(id) = q.get("id") else {
        return (StatusCode::BAD_REQUEST, "id required").into_response();
    };
    let runner = q.get("runner").map(|v| v == "1").unwrap_or(false);
    match ssr_module_inner(&state, id, runner).await {
        Ok(code) => js(code),
        Err(SsrModuleError::Forbidden(m)) => (StatusCode::FORBIDDEN, m).into_response(),
        Err(SsrModuleError::NotFound(m)) => (StatusCode::NOT_FOUND, m).into_response(),
        Err(SsrModuleError::Failed(m)) => (StatusCode::INTERNAL_SERVER_ERROR, m).into_response(),
    }
}

pub(crate) async fn ssr_plugin_host(
    state: &Arc<ServerState>,
) -> Option<std::sync::Arc<PluginHost>> {
    let host = state
        .plugins_ssr
        .get_or_init(|| async {
            let file = match plugins::plugin_source(&state.root, state.config_file.as_deref())? {
                plugins::PluginSource::OjPlugins(p) | plugins::PluginSource::ViteConfig(p) => p,
            };
            // Lazy spawn with the short init-wait policy: a wedged init must
            // not block watcher dispatch or SSR transforms.
            match PluginHost::spawn_lazy(
                &state.root,
                &file,
                &state.ssr_plugin_config,
                Some(state.engine_registry.clone()),
            )
            .await
            {
                Ok(host) => {
                    host.set_import_meta_env(Arc::clone(&state.import_meta_env));
                    eprintln!("oj ssr: plugins (ssr environment) from {}", file.display());
                    // Catch-up half of the watcher's pre-init fast-skip
                    // (see SsrWatchQueue).
                    spawn_ssr_watch_catch_up(
                        std::sync::Arc::clone(&host),
                        Arc::clone(&state.ssr_watch),
                    );
                    // `environments.ssr.define` (plus config()-hook deltas)
                    // layers over the shared define for SSR compiles.
                    let ssr_defines = host.config_defines().await;
                    if !ssr_defines.is_empty() {
                        state.import_meta_env.merge_ssr(ssr_defines);
                    }
                    Some(host)
                }
                Err(e) => {
                    eprintln!("oj ssr: plugin host failed to start: {e}");
                    None
                }
            }
        })
        .await
        .clone();
    // Every consumer acquires the host here, so prime the hook plan at this
    // one seam before any gated dispatch; a no-op once live.
    if let Some(h) = &host {
        h.prime_hook_plan().await;
    }
    host
}

/// Watcher events the pre-init lazy SSR host could not take yet: the watcher
/// fast-skips and queues them here for a watchChange replay at init. The
/// backlog dedups by file (latest change type wins). `order` serializes EVERY
/// watchChange dispatch toward the host, replay and live alike (live drains
/// the backlog first), so a stale queued event never lands after a newer live
/// event for the same file.
#[derive(Default)]
pub(crate) struct SsrWatchQueue {
    pub(crate) backlog: Mutex<Vec<(String, String)>>,
    order: tokio::sync::Mutex<()>,
    /// One line for the first skip, not one per save.
    logged: std::sync::atomic::AtomicBool,
}

/// Record a skipped watcher event (see [`SsrWatchQueue`]): deduped by file,
/// latest change type wins (a delete after an update must replay as delete).
pub(crate) fn note_ssr_watch_skip(queue: &SsrWatchQueue, file: &str, change_type: &str) {
    {
        let mut b = queue.backlog.lock().unwrap();
        if let Some(entry) = b.iter_mut().find(|(f, _)| f == file) {
            entry.1 = change_type.to_string();
        } else {
            b.push((file.to_string(), change_type.to_string()));
        }
    }
    if !queue.logged.swap(true, std::sync::atomic::Ordering::SeqCst) {
        println!(
            "oj: ssr plugin host still initializing; queuing file changes for a catch-up replay at its init"
        );
    }
}

/// Replay skipped events as `watchChange` to the initialized host; hotUpdate
/// is deliberately not replayed (client updates already went through oj's own
/// pipeline). Holds the order lock for the whole replay so queued (older)
/// events reach the host before live (newer) ones; the loop catches a skip
/// racing the drain.
pub(crate) async fn replay_ssr_watch_backlog(host: &PluginHost, queue: &SsrWatchQueue) {
    let _order = queue.order.lock().await;
    loop {
        let batch: Vec<(String, String)> = {
            let mut b = queue.backlog.lock().unwrap();
            b.drain(..).collect()
        };
        if batch.is_empty() {
            return;
        }
        println!(
            "oj: ssr plugin host caught up: replaying {} file change(s) missed during its init",
            batch.len()
        );
        for (file, ev) in batch {
            if let Err(e) = host.watch_change(&file, &ev).await {
                eprintln!("oj: watchChange (ssr catch-up) failed for {file}: {e}");
            }
        }
    }
}

/// Wait for the lazy host's init, then replay the watcher backlog. A pre-init
/// death keeps the wait alive while revivable; only permanent death releases it.
pub(crate) fn spawn_ssr_watch_catch_up(
    host: std::sync::Arc<PluginHost>,
    queue: Arc<SsrWatchQueue>,
) {
    tokio::spawn(async move {
        let mut init = host.initialized_updates();
        let mut gone = host.host_gone_updates();
        loop {
            if *init.borrow_and_update() {
                break;
            }
            if *gone.borrow_and_update() && !host.can_revive() {
                return;
            }
            tokio::select! {
                changed = init.changed() => { if changed.is_err() { return; } }
                changed = gone.changed() => { if changed.is_err() { return; } }
                // Permanent death makes no watch change of its own: re-check slowly.
                _ = tokio::time::sleep(std::time::Duration::from_secs(60)) => {}
            }
        }
        replay_ssr_watch_backlog(&host, &queue).await;
    });
}

pub(crate) fn sass_additional_data_for(state: &ServerState, url: &str) -> Option<String> {
    if !oj_css::is_sass(url) {
        return None;
    }
    let indented = url.split('?').next().unwrap_or(url).ends_with(".sass");
    if indented {
        state.sass_additional_data.clone()
    } else {
        state.scss_additional_data.clone()
    }
}

/// `css.preprocessorOptions.<scss|sass>.loadPaths` / `includePaths`, resolved
/// against the app root.
pub(crate) fn sass_load_paths_for(state: &ServerState, url: &str) -> Vec<PathBuf> {
    if !oj_css::is_sass(url) {
        return Vec::new();
    }
    let Some(css) = &state.css_config else {
        return Vec::new();
    };
    let cfg = oj_config::OjConfig {
        css: Some(css.clone()),
        ..Default::default()
    };
    let lang = if url.split('?').next().unwrap_or(url).ends_with(".sass") {
        "sass"
    } else {
        "scss"
    };
    oj_config::css_load_paths(&cfg, lang)
        .into_iter()
        .map(|p| state.root.join(p))
        .collect()
}

pub(crate) fn ssr_css_module(root: &Path, path: &Path, source: &str) -> Result<String, String> {
    let css_src = if oj_css::is_sass(&path.to_string_lossy()) {
        oj_css::compile_sass(source, path.parent())?
    } else {
        source.to_string()
    };
    let css_id = match path.strip_prefix(root) {
        Ok(rel) => format!("/{}", rel.display()),
        Err(_) => path.to_string_lossy().to_string(),
    };
    let output = oj_css::compile_css(&css_id, &css_src, true)?;
    Ok(match output.exports {
        Some(exports) => oj_css::css_modules_esm(&exports),
        None => "export default {};".to_string(),
    })
}

/// Vite's `css.modules` options as the CSS compiler applies them (dev and build).
pub fn css_modules_options(config: &oj_config::OjConfig) -> oj_css::CssModulesOptions {
    let m = oj_config::css_modules(config);
    oj_css::CssModulesOptions {
        locals_convention: m.locals_convention,
        generate_scoped_name: m.generate_scoped_name,
        global_scope: m.global_scope,
        global_module_paths: m.global_module_paths,
    }
}