1use napi::bindgen_prelude::{Buffer, Function};
32use napi::Error as NapiError;
33use napi_derive::napi;
34use serde_json::Value;
35use webui_handler::plugin::fast::FastHydrationPlugin;
36use webui_handler::plugin::webui::WebUIHydrationPlugin;
37use webui_handler::{RenderOptions, ResponseWriter, WebUIHandler};
38use webui_protocol::WebUIProtocol;
39
40#[napi(object)]
42pub struct JsBuildStats {
43 pub duration_ms: f64,
45 pub fragment_count: u32,
47 pub component_count: u32,
49 pub css_file_count: u32,
51 pub protocol_size_bytes: u32,
53 pub token_count: u32,
55}
56
57#[napi(object)]
59pub struct JsBuildResult {
60 pub protocol: Buffer,
62 pub css_files: Vec<String>,
64 pub stats: JsBuildStats,
66}
67
68#[napi(object)]
70pub struct JsBuildOptions {
71 pub app_dir: String,
73 pub entry: Option<String>,
75 pub css: Option<String>,
77 pub plugin: Option<String>,
79 pub components: Option<Vec<String>>,
81}
82
83#[napi]
87pub fn build(options: JsBuildOptions) -> napi::Result<JsBuildResult> {
88 let css = options
89 .css
90 .map(|s| s.parse::<webui::CssStrategy>())
91 .transpose()
92 .map_err(NapiError::from_reason)?
93 .unwrap_or_default();
94
95 let plugin = options
96 .plugin
97 .map(|s| s.parse::<webui::Plugin>())
98 .transpose()
99 .map_err(NapiError::from_reason)?;
100
101 let build_options = webui::BuildOptions {
102 app_dir: std::path::PathBuf::from(&options.app_dir),
103 entry: options.entry.unwrap_or_else(|| "index.html".to_string()),
104 css,
105 dom: webui::DomStrategy::Shadow,
106 plugin,
107 components: options.components.unwrap_or_default(),
108 };
109
110 let result = webui::build(build_options)
111 .map_err(|e| NapiError::from_reason(format!("Build error: {e}")))?;
112
113 let css_files: Vec<String> = result
115 .css_files
116 .into_iter()
117 .flat_map(|(name, content)| [name, content])
118 .collect();
119
120 Ok(JsBuildResult {
121 protocol: Buffer::from(result.protocol_bytes),
122 css_files,
123 stats: JsBuildStats {
124 duration_ms: result.stats.duration.as_secs_f64() * 1000.0,
125 fragment_count: result.stats.fragment_count as u32,
126 component_count: result.stats.component_count as u32,
127 css_file_count: result.stats.css_file_count as u32,
128 protocol_size_bytes: result.stats.protocol_size_bytes as u32,
129 token_count: result.stats.token_count as u32,
130 },
131 })
132}
133
134#[napi]
136pub fn inspect(protocol_data: Buffer) -> napi::Result<String> {
137 webui::inspect_bytes(&protocol_data)
138 .map_err(|e| NapiError::from_reason(format!("Inspect error: {e}")))
139}
140
141#[napi]
149pub fn render_partial(
150 protocol_data: Buffer,
151 state_json: String,
152 entry_id: String,
153 request_path: String,
154 inventory_hex: String,
155) -> napi::Result<String> {
156 let protocol = WebUIProtocol::from_protobuf(&protocol_data)
157 .map_err(|e| NapiError::from_reason(format!("Protocol decode error: {e}")))?;
158
159 let state: serde_json::Value = serde_json::from_str(&state_json)
160 .map_err(|e| NapiError::from_reason(format!("invalid state JSON: {e}")))?;
161
162 let result = webui_handler::route_handler::render_partial(
163 &protocol,
164 state,
165 &entry_id,
166 &request_path,
167 &inventory_hex,
168 );
169
170 serde_json::to_string(&result)
171 .map_err(|e| NapiError::from_reason(format!("JSON serialize error: {e}")))
172}
173
174struct CallbackWriter<'a, 'env> {
176 callback: &'a Function<'env, String, ()>,
177 error: Option<String>,
178}
179
180impl<'a, 'env> CallbackWriter<'a, 'env> {
181 fn new(callback: &'a Function<'env, String, ()>) -> Self {
182 Self {
183 callback,
184 error: None,
185 }
186 }
187}
188
189impl ResponseWriter for CallbackWriter<'_, '_> {
190 fn write(&mut self, content: &str) -> webui_handler::Result<()> {
191 if self.error.is_some() {
192 return Ok(());
193 }
194 if let Err(e) = self.callback.call(content.to_owned()) {
195 let msg = format!("{e}");
198 if !msg.contains("Value is not undefined") {
199 self.error = Some(msg);
200 }
201 }
202 Ok(())
203 }
204
205 fn end(&mut self) -> webui_handler::Result<()> {
206 Ok(())
207 }
208}
209
210#[napi]
220#[allow(clippy::too_many_arguments)]
221pub fn render(
222 protocol_data: Buffer,
223 state_json: String,
224 entry: String,
225 request_path: String,
226 on_chunk: Function<String, ()>,
227 plugin: Option<String>,
228) -> napi::Result<()> {
229 let protocol = WebUIProtocol::from_protobuf(&protocol_data)
230 .map_err(|e| NapiError::from_reason(format!("Protocol decode error: {e}")))?;
231
232 let state: Value = serde_json::from_str(&state_json)
233 .map_err(|e| NapiError::from_reason(format!("State JSON error: {e}")))?;
234
235 let mut writer = CallbackWriter::new(&on_chunk);
236 let plugin = plugin
237 .map(|s| s.parse::<webui::Plugin>())
238 .transpose()
239 .map_err(NapiError::from_reason)?;
240 let handler = match plugin {
241 Some(webui::Plugin::Fast) => {
242 WebUIHandler::with_plugin(|| Box::new(FastHydrationPlugin::new()))
243 }
244 Some(webui::Plugin::WebUI) => {
245 WebUIHandler::with_plugin(|| Box::new(WebUIHydrationPlugin::new()))
246 }
247 None => WebUIHandler::new(),
248 };
249 handler
250 .render(
251 &protocol,
252 &state,
253 &RenderOptions::new(&entry, &request_path),
254 &mut writer,
255 )
256 .map_err(|e| NapiError::from_reason(format!("Render error: {e}")))?;
257
258 if let Some(err) = writer.error {
259 return Err(NapiError::from_reason(format!("Callback error: {err}")));
260 }
261
262 Ok(())
263}
264
265#[cfg(test)]
266mod tests {
267 use super::*;
268 use webui_parser::HtmlParser;
269
270 fn build_protocol(html: &str) -> Vec<u8> {
272 let mut parser = HtmlParser::new();
273 parser.parse("index.html", html).expect("parse failed");
274 let tokens = parser.take_tokens();
275 let protocol = WebUIProtocol::with_tokens(parser.into_fragment_records(), tokens);
276 protocol.to_protobuf().expect("protobuf encode failed")
277 }
278
279 fn render_to_string(protocol_bytes: &[u8], state_json: &str) -> Result<String, String> {
281 let protocol = WebUIProtocol::from_protobuf(protocol_bytes).map_err(|e| e.to_string())?;
282 let state: Value = serde_json::from_str(state_json).map_err(|e| e.to_string())?;
283
284 let mut output = String::with_capacity(1024);
285 let handler = WebUIHandler::new();
286
287 struct StringWriter<'a> {
288 output: &'a mut String,
289 }
290 impl ResponseWriter for StringWriter<'_> {
291 fn write(&mut self, content: &str) -> webui_handler::Result<()> {
292 self.output.push_str(content);
293 Ok(())
294 }
295 fn end(&mut self) -> webui_handler::Result<()> {
296 Ok(())
297 }
298 }
299
300 let mut writer = StringWriter {
301 output: &mut output,
302 };
303 handler
304 .render(
305 &protocol,
306 &state,
307 &RenderOptions::new("index.html", "/"),
308 &mut writer,
309 )
310 .map_err(|e| e.to_string())?;
311 Ok(output)
312 }
313
314 #[test]
315 fn test_simple_passthrough() {
316 let proto = build_protocol("<p>Hello</p>");
317 let result = render_to_string(&proto, "{}");
318 assert_eq!(result.as_deref(), Ok("<p>Hello</p>"));
319 }
320
321 #[test]
322 fn test_signal_substitution() {
323 let proto = build_protocol("Hello, {{name}}!");
324 let result = render_to_string(&proto, r#"{"name": "WebUI"}"#);
325 assert_eq!(result.as_deref(), Ok("Hello, WebUI!"));
326 }
327
328 #[test]
329 fn test_for_loop() {
330 let proto = build_protocol("<ul><for each=\"item in items\"><li>{{item}}</li></for></ul>");
331 let result = render_to_string(&proto, r#"{"items": ["a", "b", "c"]}"#);
332 assert_eq!(
333 result.as_deref(),
334 Ok("<ul><li>a</li><li>b</li><li>c</li></ul>")
335 );
336 }
337
338 #[test]
339 fn test_if_condition_true() {
340 let proto = build_protocol("<if condition=\"show\"><p>Visible</p></if>");
341 let result = render_to_string(&proto, r#"{"show": true}"#);
342 assert_eq!(result.as_deref(), Ok("<p>Visible</p>"));
343 }
344
345 #[test]
346 fn test_if_condition_false() {
347 let proto = build_protocol("<if condition=\"show\"><p>Hidden</p></if>");
348 let result = render_to_string(&proto, r#"{"show": false}"#);
349 assert_eq!(result.as_deref(), Ok(""));
350 }
351
352 #[test]
353 fn test_html_escaping() {
354 let proto = build_protocol("<div>{{content}}</div>");
355 let state = r#"{"content": "<script>alert('xss')</script>"}"#;
356 let result = render_to_string(&proto, state).expect("render should succeed");
357 assert!(!result.contains("<script>"));
358 assert!(result.contains("<script>"));
359 }
360
361 #[test]
362 fn test_raw_signal() {
363 let proto = build_protocol("<div>{{{content}}}</div>");
364 let result = render_to_string(&proto, r#"{"content": "<b>bold</b>"}"#);
365 assert_eq!(result.as_deref(), Ok("<div><b>bold</b></div>"));
366 }
367
368 #[test]
369 fn test_invalid_json() {
370 let proto = build_protocol("<p>hi</p>");
371 let result = render_to_string(&proto, "NOT JSON");
372 assert!(result.is_err());
373 }
374
375 #[test]
376 fn test_empty_state() {
377 let proto = build_protocol("<p>static</p>");
378 let result = render_to_string(&proto, "{}");
379 assert_eq!(result.as_deref(), Ok("<p>static</p>"));
380 }
381
382 #[test]
383 fn test_nested_object_signal() {
384 let proto = build_protocol("{{user.name}}");
385 let result = render_to_string(&proto, r#"{"user": {"name": "Alice"}}"#);
386 assert_eq!(result.as_deref(), Ok("Alice"));
387 }
388
389 #[test]
390 fn test_invalid_protobuf() {
391 let result = render_to_string(&[0xFF, 0xFF, 0xFF], "{}");
392 assert!(result.is_err());
393 }
394
395 #[test]
398 fn test_build_simple_app() {
399 let dir = tempfile::TempDir::new().unwrap();
400 std::fs::write(dir.path().join("index.html"), "<h1>Hello</h1>").unwrap();
401
402 let options = JsBuildOptions {
403 app_dir: dir.path().to_string_lossy().to_string(),
404 entry: None,
405 css: None,
406 plugin: None,
407 components: None,
408 };
409
410 let result = build(options).unwrap();
411 assert!(!result.protocol.is_empty());
412 assert!(result.stats.fragment_count > 0);
413 assert!(result.stats.protocol_size_bytes > 0);
414 assert!(result.stats.duration_ms >= 0.0);
415 }
416
417 #[test]
418 fn test_build_with_custom_entry() {
419 let dir = tempfile::TempDir::new().unwrap();
420 std::fs::write(dir.path().join("page.html"), "<p>Custom</p>").unwrap();
421
422 let options = JsBuildOptions {
423 app_dir: dir.path().to_string_lossy().to_string(),
424 entry: Some("page.html".to_string()),
425 css: None,
426 plugin: None,
427 components: None,
428 };
429
430 let result = build(options).unwrap();
431 assert!(!result.protocol.is_empty());
432 }
433
434 #[test]
435 fn test_build_missing_app_dir() {
436 let options = JsBuildOptions {
437 app_dir: "/nonexistent/path".to_string(),
438 entry: None,
439 css: None,
440 plugin: None,
441 components: None,
442 };
443
444 let result = build(options);
445 assert!(result.is_err());
446 }
447
448 #[test]
449 fn test_build_invalid_css() {
450 let dir = tempfile::TempDir::new().unwrap();
451 std::fs::write(dir.path().join("index.html"), "<h1>Hello</h1>").unwrap();
452
453 let options = JsBuildOptions {
454 app_dir: dir.path().to_string_lossy().to_string(),
455 entry: None,
456 css: Some("bogus".to_string()),
457 plugin: None,
458 components: None,
459 };
460
461 let result = build(options);
462 assert!(result.is_err());
463 }
464
465 #[test]
466 fn test_build_with_components_css() {
467 let dir = tempfile::TempDir::new().unwrap();
468 std::fs::write(dir.path().join("index.html"), "<my-card>Hello</my-card>").unwrap();
469 std::fs::write(dir.path().join("my-card.html"), "<div><slot></slot></div>").unwrap();
470 std::fs::write(dir.path().join("my-card.css"), ".card { color: red; }").unwrap();
471
472 let options = JsBuildOptions {
473 app_dir: dir.path().to_string_lossy().to_string(),
474 entry: None,
475 css: Some("link".to_string()),
476 plugin: None,
477 components: None,
478 };
479
480 let result = build(options).unwrap();
481 assert_eq!(result.css_files.len(), 2);
483 assert_eq!(result.css_files[0], "my-card.css");
484 assert!(result.css_files[1].contains("color: red"));
485 assert_eq!(result.stats.css_file_count, 1);
486 }
487
488 #[test]
489 fn test_inspect_valid_protocol() {
490 let proto = build_protocol("<h1>Hello {{name}}</h1>");
491 let json = inspect(napi::bindgen_prelude::Buffer::from(proto)).unwrap();
492 let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
493 assert!(parsed.get("fragments").is_some());
494 }
495
496 #[test]
497 fn test_inspect_invalid_protocol() {
498 let result = inspect(napi::bindgen_prelude::Buffer::from(vec![0xFF, 0xFF]));
499 assert!(result.is_err());
500 }
501}