microsoft-webui-node 0.0.25

Node.js native addon for WebUI framework via napi-rs
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
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
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT license.

//! Node.js native addon for the WebUI framework via napi-rs.
//!
//! Provides high-performance server-side rendering by compiling the Rust
//! WebUI handler directly into a `.node` native addon — no C ABI intermediary.
//!
//! The `Protocol` class decodes pre-compiled protobuf data from `webui build`
//! once and provides buffered and streaming render methods.
//!
//! ## Usage (from Node.js)
//!
//! ```js
//! import fs from 'node:fs';
//!
//! // Load the native addon
//! const mod = { exports: {} };
//! process.dlopen(mod, './target/release/libwebui_node.dylib');
//! const { Protocol } = mod.exports;
//!
//! // Read pre-compiled protocol (from `webui build`)
//! const protocol = new Protocol(fs.readFileSync('./dist/protocol.bin'), 'webui');
//! const state = '{"name": "WebUI"}';
//!
//! // Stream rendered fragments
//! protocol.renderStream(state, 'index.html', '/', (chunk) => process.stdout.write(chunk));
//! ```

use std::sync::Arc;

use napi::bindgen_prelude::{Buffer, Function};
use napi::Error as NapiError;
use napi_derive::napi;
use serde_json::Value;
use webui_handler::plugin::fast_v2::FastV2HydrationPlugin;
use webui_handler::plugin::fast_v3::FastV3HydrationPlugin;
use webui_handler::plugin::webui::WebUIHydrationPlugin;
use webui_handler::{
    BoundaryId, BoundaryMode, HandlerError, Protocol as HandlerProtocol, RenderOptions,
    ResponseWriter, SessionOptions, StreamingSession as HandlerStreamingSession, WebUIHandler,
};
#[cfg(test)]
use webui_protocol::WebUIProtocol;

const STREAM_CHUNK_SIZE: usize = 16 * 1024;

/// Build statistics returned from the build function.
#[napi(object)]
pub struct JsBuildStats {
    /// Build duration in milliseconds.
    pub duration_ms: f64,
    /// Total number of protocol fragments.
    pub fragment_count: u32,
    /// Number of registered components.
    pub component_count: u32,
    /// Number of CSS files produced.
    pub css_file_count: u32,
    /// Size of the serialized protocol in bytes.
    pub protocol_size_bytes: u32,
    /// Number of unique CSS tokens discovered.
    pub token_count: u32,
}

/// Result of a successful build operation.
#[napi(object)]
pub struct JsBuildResult {
    /// Serialized protocol (protobuf binary).
    pub protocol: Buffer,
    /// CSS files as alternating [filename, content, filename, content, ...].
    pub css_files: Vec<String>,
    /// Static component asset files as alternating [filename, content, filename, content, ...].
    pub component_asset_files: Vec<String>,
    /// Esbuild-compatible component asset metafile JSON when requested.
    pub metafile: Option<String>,
    /// Non-fatal build advisories (plain text), e.g. CSS tokens used only with a
    /// literal `var()` fallback and absent from every theme.
    pub warnings: Vec<String>,
    /// Build statistics.
    pub stats: JsBuildStats,
}

/// Inline projection manifest transported through N-API.
#[napi(object)]
pub struct JsProjectionManifest {
    /// Logical manifest path used to resolve `root` and stale file checks.
    pub path: String,
    /// Canonical manifest JSON.
    pub json: String,
}

/// Build options for the webui build API.
#[napi(object)]
pub struct JsBuildOptions {
    /// Path to the application folder containing templates.
    pub app_dir: String,
    /// Entry HTML file name (defaults to "index.html").
    pub entry: Option<String>,
    /// CSS mode: "link" (default) or "style".
    pub css: Option<String>,
    /// DOM strategy for component rendering: "shadow" (default) or "light".
    pub dom: Option<String>,
    /// Plugin identifier (see crate documentation for available identifiers).
    pub plugin: Option<String>,
    /// Additional component sources (npm packages or local paths).
    pub components: Option<Vec<String>>,
    /// Root component tags emitted as static `.webui.js` ESM assets.
    pub component_asset_roots: Option<Vec<String>>,
    /// Generate and return an esbuild-compatible component asset metafile.
    pub metafile: Option<bool>,
    /// Link-mode CSS filename template using [name], [hash], [ext].
    pub css_file_name_template: Option<String>,
    /// Optional base URL/path prefix for Link-mode css hrefs.
    pub css_public_base: Option<String>,
    /// Legal comment handling: "inline" (default) or "none".
    pub legal_comments: Option<String>,
    /// Design token theme: a JSON file path or npm package name.
    pub theme: Option<String>,
    /// Projection manifest paths.
    pub projection_manifests: Option<Vec<String>>,
    /// Inline manifest objects with their logical paths.
    pub projection_manifest_objects: Option<Vec<JsProjectionManifest>>,
}

/// Build a WebUI application from an app directory.
///
/// Returns the compiled protocol bytes, CSS files, and build statistics.
#[napi]
#[allow(clippy::cast_possible_truncation)] // stats are bounded by component/file counts
pub fn build(options: JsBuildOptions) -> napi::Result<JsBuildResult> {
    let css = options
        .css
        .map(|s| s.parse::<webui::CssStrategy>())
        .transpose()
        .map_err(NapiError::from_reason)?
        .unwrap_or_default();

    let dom = options
        .dom
        .map(|s| s.parse::<webui::DomStrategy>())
        .transpose()
        .map_err(NapiError::from_reason)?
        .unwrap_or_default();

    let plugin = options
        .plugin
        .map(|s| s.parse::<webui::Plugin>())
        .transpose()
        .map_err(NapiError::from_reason)?;

    let legal_comments = options
        .legal_comments
        .map(|s| s.parse::<webui::LegalComments>())
        .transpose()
        .map_err(NapiError::from_reason)?
        .unwrap_or_default();

    let app_dir = std::path::PathBuf::from(&options.app_dir);
    let theme = options
        .theme
        .as_deref()
        .map(|theme| load_theme(theme, &app_dir))
        .transpose()?;
    let mut projection_manifests: Vec<webui::ProjectionManifestSource> = options
        .projection_manifests
        .unwrap_or_default()
        .into_iter()
        .map(std::path::PathBuf::from)
        .map(Into::into)
        .collect();
    projection_manifests.extend(
        options
            .projection_manifest_objects
            .unwrap_or_default()
            .into_iter()
            .map(|manifest| webui::ProjectionManifestSource::Inline {
                manifest_path: std::path::PathBuf::from(manifest.path),
                json: manifest.json,
            }),
    );

    let build_options = webui::BuildOptions {
        app_dir,
        entry: options.entry.unwrap_or_else(|| "index.html".to_string()),
        css,
        dom,
        plugin,
        components: options.components.unwrap_or_default(),
        component_asset_roots: options.component_asset_roots.unwrap_or_default(),
        metafile: options.metafile.unwrap_or(false),
        css_file_name_template: options
            .css_file_name_template
            .unwrap_or_else(|| webui::DEFAULT_CSS_FILE_NAME_TEMPLATE.to_string()),
        css_public_base: options.css_public_base,
        legal_comments,
        theme,
        projection_manifests,
    };

    let result = webui::build(build_options)
        .map_err(|e| NapiError::from_reason(format!("Build error: {}", e.chain_message())))?;

    // Flatten css_files into alternating [filename, content, ...] for JS interop
    let css_files: Vec<String> = result
        .css_files
        .into_iter()
        .flat_map(|(name, content)| [name, content])
        .collect();
    let component_asset_files: Vec<String> = result
        .component_asset_files
        .into_iter()
        .flat_map(|file| [file.name, file.content])
        .collect();
    let warnings: Vec<String> = result.warnings.iter().map(|d| d.to_string()).collect();

    Ok(JsBuildResult {
        protocol: Buffer::from(result.protocol_bytes),
        css_files,
        component_asset_files,
        metafile: result.metafile,
        warnings,
        stats: JsBuildStats {
            duration_ms: result.stats.duration.as_secs_f64() * 1000.0,
            fragment_count: result.stats.fragment_count as u32,
            component_count: result.stats.component_count as u32,
            css_file_count: result.stats.css_file_count as u32,
            protocol_size_bytes: result.stats.protocol_size_bytes as u32,
            token_count: result.stats.token_count as u32,
        },
    })
}

fn load_theme(theme: &str, search_root: &std::path::Path) -> napi::Result<webui::TokenFile> {
    let resolved = webui::resolve_theme_path(theme, search_root)
        .map_err(|e| NapiError::from_reason(format!("Theme resolution error: {e}")))?;
    webui::load_token_file(&resolved).map_err(|e| {
        NapiError::from_reason(format!("Theme load error for {}: {e}", resolved.display()))
    })
}

/// Inspect protocol bytes and return a JSON representation.
#[napi]
pub fn inspect(protocol_data: Buffer) -> napi::Result<String> {
    webui::inspect_bytes(&protocol_data)
        .map_err(|e| NapiError::from_reason(format!("Inspect error: {e}")))
}

/// A decoded protocol and its reusable deterministic indices.
///
/// Create this once when a Node server loads `protocol.bin`, then reuse it for
/// full renders, partial navigation, component loading, and token queries. The
/// selected hydration plugin is bound once at construction.
#[napi]
pub struct Protocol {
    inner: Arc<HandlerProtocol>,
    handler: Arc<WebUIHandler>,
}

#[napi]
impl Protocol {
    /// Decode a protocol and bind its render plugin for repeated rendering.
    #[napi(constructor)]
    pub fn new(protocol_data: Buffer, plugin: Option<String>) -> napi::Result<Self> {
        let inner = Arc::new(decode_protocol(&protocol_data)?);
        let handler = Arc::new(create_handler(plugin)?);
        Ok(Self { inner, handler })
    }

    /// Render from an existing JSON string into a UTF-8 Node.js buffer.
    #[napi]
    pub fn render(
        &self,
        state_json: String,
        entry: String,
        request_path: String,
    ) -> napi::Result<Buffer> {
        let state = parse_state_json(&state_json)?;
        let options = RenderOptions::new(&entry, &request_path);
        let html = render_to_string(&self.handler, &self.inner, &state, &options)?;
        // napi-rs can expose the existing Vec as an external Buffer on Node.
        Ok(Buffer::from(html.into_bytes()))
    }

    /// Stream an existing JSON string in bounded chunks.
    #[napi]
    pub fn render_stream(
        &self,
        state_json: String,
        entry: String,
        request_path: String,
        on_chunk: Function<String>,
    ) -> napi::Result<()> {
        let state = parse_state_json(&state_json)?;
        let options = RenderOptions::new(&entry, &request_path);
        render_to_callback(&self.handler, &self.inner, &state, &options, &on_chunk)
    }

    /// Produce a complete partial-navigation response.
    #[napi]
    pub fn render_partial(
        &self,
        state_json: String,
        entry_id: String,
        request_path: String,
        inventory_hex: String,
    ) -> napi::Result<String> {
        self.inner
            .render_partial(&state_json, &entry_id, &request_path, &inventory_hex)
            .map_err(|e| NapiError::from_reason(format!("render_partial failed: {e}")))
    }

    /// Render component templates and styles for on-demand loading.
    #[napi]
    pub fn render_component_templates(
        &self,
        component_tags: Vec<String>,
        inventory_hex: String,
    ) -> napi::Result<String> {
        let tag_refs: Vec<&str> = component_tags.iter().map(String::as_str).collect();
        let result = self
            .inner
            .render_component_templates(&tag_refs, &inventory_hex)
            .map_err(|e| {
                NapiError::from_reason(format!("render_component_templates failed: {e}"))
            })?;
        serde_json::to_string(&result)
            .map_err(|e| NapiError::from_reason(format!("JSON serialize error: {e}")))
    }

    /// Return CSS token names in build order.
    #[napi]
    pub fn tokens(&self) -> Vec<String> {
        self.inner.tokens().to_vec()
    }

    /// Open a host-driven progressive response for a streaming entry.
    ///
    /// Unlike `renderStream`, which pushes every chunk during one synchronous
    /// call, the returned session hands each chunk back so the Node server
    /// owns the socket, the write order, and backpressure.
    #[napi]
    pub fn stream_response(
        &self,
        entry: String,
        request_path: String,
        options: Option<JsStreamOptions>,
    ) -> napi::Result<StreamingSession> {
        let options = options.unwrap_or_default();
        let mut session_options = SessionOptions::new(entry, request_path);
        session_options.nonce = options.nonce;
        session_options.head_inject = options.head_inject;
        session_options.body_inject = options.body_inject;
        let inner = HandlerStreamingSession::new(
            Arc::clone(&self.handler),
            Arc::clone(&self.inner),
            session_options,
        )
        .map_err(streaming_error)?;
        Ok(StreamingSession { inner })
    }
}

/// Optional per-response streaming settings.
#[napi(object)]
#[derive(Default)]
pub struct JsStreamOptions {
    /// CSP nonce applied to generated inline `<script>` tags.
    pub nonce: Option<String>,
    /// HTML injected at the structural `head_end` boundary.
    pub head_inject: Option<String>,
    /// HTML injected at the structural `body_end` boundary.
    pub body_inject: Option<String>,
}

/// A progressive HTML response driven one chunk at a time from Node.
///
/// Every method returns the bytes it produced. Write them to the response and
/// await `drain` whenever `write()` returns `false`; the session holds no
/// transport and never blocks on one.
///
/// ```js
/// const session = protocol.streamResponse('index.html', '/');
/// const weather = session.boundary('weather-shell');
/// res.write(session.writeShell(shellState));
/// res.write(session.writeBoundary(weather, weatherState, 'updatable'));
/// res.write(session.update(weather, forecast));
/// res.end(session.finish(tailState));
/// ```
#[napi]
pub struct StreamingSession {
    inner: HandlerStreamingSession,
}

#[napi]
impl StreamingSession {
    /// Resolve an authored boundary name to a stable integer handle.
    ///
    /// Resolve once outside the write loop; the handle costs nothing to reuse.
    #[napi]
    pub fn boundary(&self, name: String) -> napi::Result<u32> {
        self.inner
            .boundary(&name)
            .map(BoundaryId::raw)
            .map_err(streaming_error)
    }

    /// Number of compile-time boundaries declared by this entry.
    #[napi(getter)]
    pub fn boundary_count(&self) -> u32 {
        // Boundary counts are bounded by the compiled entry, so this cannot
        // exceed u32 in any protocol the build can produce.
        u32::try_from(self.inner.boundary_count()).unwrap_or(u32::MAX)
    }

    /// Whether the terminal record has been written.
    #[napi(getter)]
    pub fn finished(&self) -> bool {
        self.inner.is_finished()
    }

    /// Render everything before the first boundary.
    #[napi]
    pub fn write_shell(&mut self, state_json: String) -> napi::Result<Buffer> {
        let state = parse_state_json(&state_json)?;
        self.inner
            .write_shell(&state)
            .map(Buffer::from)
            .map_err(streaming_error)
    }

    /// Render and commit the next boundary in declaration order.
    ///
    /// `mode` is `"final"` (default) or `"updatable"`. Only updatable
    /// boundaries accept later `update()` calls.
    #[napi]
    pub fn write_boundary(
        &mut self,
        boundary: u32,
        state_json: String,
        mode: Option<String>,
    ) -> napi::Result<Buffer> {
        let state = parse_state_json(&state_json)?;
        let mode = parse_boundary_mode(mode.as_deref())?;
        self.inner
            .write_boundary(BoundaryId::from_raw(boundary), &state, mode)
            .map(Buffer::from)
            .map_err(streaming_error)
    }

    /// Push a projected state patch to a committed updatable boundary.
    #[napi]
    pub fn update(&mut self, boundary: u32, state_json: String) -> napi::Result<Buffer> {
        let state = parse_state_json(&state_json)?;
        self.inner
            .update(BoundaryId::from_raw(boundary), &state)
            .map(Buffer::from)
            .map_err(streaming_error)
    }

    /// Render the document tail and emit the terminal record.
    #[napi]
    pub fn finish(&mut self, state_json: String) -> napi::Result<Buffer> {
        let state = parse_state_json(&state_json)?;
        self.inner
            .finish(&state)
            .map(Buffer::from)
            .map_err(streaming_error)
    }
}

fn parse_boundary_mode(mode: Option<&str>) -> napi::Result<BoundaryMode> {
    match mode {
        None | Some("final") => Ok(BoundaryMode::Final),
        Some("updatable") => Ok(BoundaryMode::Updatable),
        Some(other) => Err(NapiError::from_reason(format!(
            "unknown boundary mode '{other}'; expected 'final' or 'updatable'"
        ))),
    }
}

fn streaming_error(error: HandlerError) -> NapiError {
    NapiError::from_reason(error.to_string())
}

fn decode_protocol(protocol_data: &[u8]) -> napi::Result<HandlerProtocol> {
    HandlerProtocol::from_protobuf(protocol_data)
        .map_err(|e| NapiError::from_reason(format!("Protocol decode error: {e}")))
}

fn parse_state_json(state_json: &str) -> napi::Result<Value> {
    serde_json::from_str(state_json)
        .map_err(|e| NapiError::from_reason(format!("State JSON error: {e}")))
}

fn create_handler(plugin: Option<String>) -> napi::Result<WebUIHandler> {
    let plugin = plugin
        .map(|value| value.parse::<webui::Plugin>())
        .transpose()
        .map_err(NapiError::from_reason)?;
    Ok(match plugin {
        Some(webui::Plugin::Fast | webui::Plugin::FastV2) => {
            WebUIHandler::with_plugin(|| Box::new(FastV2HydrationPlugin::new()))
        }
        Some(webui::Plugin::FastV3) => {
            WebUIHandler::with_plugin(|| Box::new(FastV3HydrationPlugin::new()))
        }
        Some(webui::Plugin::WebUI) => {
            WebUIHandler::with_plugin(|| Box::new(WebUIHydrationPlugin::new()))
        }
        None => WebUIHandler::new(),
    })
}

struct BufferedWriter {
    output: String,
}

impl BufferedWriter {
    fn new() -> Self {
        Self {
            output: String::with_capacity(4096),
        }
    }
}

impl ResponseWriter for BufferedWriter {
    fn write(&mut self, content: &str) -> webui_handler::Result<()> {
        self.output.push_str(content);
        Ok(())
    }

    fn end(&mut self) -> webui_handler::Result<()> {
        Ok(())
    }
}

fn render_to_string(
    handler: &WebUIHandler,
    protocol: &HandlerProtocol,
    state: &Value,
    options: &RenderOptions<'_>,
) -> napi::Result<String> {
    let mut writer = BufferedWriter::new();
    handler
        .render(protocol, state, options, &mut writer)
        .map_err(|e| NapiError::from_reason(format!("Render error: {e}")))?;
    Ok(writer.output)
}

/// A writer that batches rendered fragments before crossing into JavaScript.
struct CallbackWriter<F> {
    callback: F,
    buffer: String,
    error: Option<NapiError>,
}

impl<F> CallbackWriter<F>
where
    F: FnMut(String) -> napi::Result<()>,
{
    fn new(callback: F) -> Self {
        Self {
            callback,
            buffer: String::with_capacity(STREAM_CHUNK_SIZE),
            error: None,
        }
    }

    fn flush(&mut self) -> webui_handler::Result<()> {
        if self.error.is_some() {
            return Err(callback_writer_error());
        }
        if self.buffer.is_empty() {
            return Ok(());
        }

        let chunk = std::mem::replace(&mut self.buffer, String::with_capacity(STREAM_CHUNK_SIZE));
        if let Err(error) = (self.callback)(chunk) {
            self.error = Some(error);
            return Err(callback_writer_error());
        }
        Ok(())
    }
}

impl<F> ResponseWriter for CallbackWriter<F>
where
    F: FnMut(String) -> napi::Result<()>,
{
    fn write(&mut self, content: &str) -> webui_handler::Result<()> {
        if self.error.is_some() {
            return Err(callback_writer_error());
        }
        self.buffer.push_str(content);
        if self.buffer.len() >= STREAM_CHUNK_SIZE {
            self.flush()?;
        }
        Ok(())
    }

    fn end(&mut self) -> webui_handler::Result<()> {
        self.flush()
    }
}

#[cold]
#[inline(never)]
fn callback_writer_error() -> HandlerError {
    HandlerError::Writer("Node chunk callback failed".to_owned())
}

fn render_to_callback(
    handler: &WebUIHandler,
    protocol: &HandlerProtocol,
    state: &Value,
    options: &RenderOptions<'_>,
    on_chunk: &Function<String>,
) -> napi::Result<()> {
    let mut writer = CallbackWriter::new(|chunk| on_chunk.call(chunk).map(drop));
    let render_result = handler.render(protocol, state, options, &mut writer);
    if let Some(error) = writer.error {
        return Err(error);
    }
    render_result.map_err(|e| NapiError::from_reason(format!("Render error: {e}")))
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::collections::BTreeMap;
    use webui_parser::HtmlParser;
    use webui_protocol::projection_manifest::{
        ProjectionAdapter, ProjectionComponent, ProjectionManifest, ProjectionProducer,
        PRODUCER_NAME, SCHEMA_ID,
    };

    /// Helper: parse HTML into protobuf bytes for testing.
    fn build_protocol(html: &str) -> Vec<u8> {
        let mut parser = HtmlParser::new();
        parser.parse("index.html", html).expect("parse failed");
        let tokens = parser.take_tokens();
        let protocol = WebUIProtocol::with_tokens(parser.into_fragment_records(), tokens);
        protocol.to_protobuf().expect("protobuf encode failed")
    }

    /// Helper: render protocol bytes + state, collecting output into a String.
    fn render_to_string(protocol_bytes: &[u8], state_json: &str) -> Result<String, String> {
        let protocol = HandlerProtocol::from_protobuf(protocol_bytes).map_err(|e| e.to_string())?;
        let state: Value = serde_json::from_str(state_json).map_err(|e| e.to_string())?;

        let mut output = String::with_capacity(1024);
        let handler = WebUIHandler::new();

        struct StringWriter<'a> {
            output: &'a mut String,
        }
        impl ResponseWriter for StringWriter<'_> {
            fn write(&mut self, content: &str) -> webui_handler::Result<()> {
                self.output.push_str(content);
                Ok(())
            }
            fn end(&mut self) -> webui_handler::Result<()> {
                Ok(())
            }
        }

        let mut writer = StringWriter {
            output: &mut output,
        };
        handler
            .render(
                &protocol,
                &state,
                &RenderOptions::new("index.html", "/"),
                &mut writer,
            )
            .map_err(|e| e.to_string())?;
        Ok(output)
    }

    #[test]
    fn test_simple_passthrough() {
        let proto = build_protocol("<p>Hello</p>");
        let result = render_to_string(&proto, "{}");
        assert_eq!(result.as_deref(), Ok("<p>Hello</p>"));
    }

    #[test]
    fn test_signal_substitution() {
        let proto = build_protocol("Hello, {{name}}!");
        let result = render_to_string(&proto, r#"{"name": "WebUI"}"#);
        assert_eq!(result.as_deref(), Ok("Hello, WebUI!"));
    }

    #[test]
    fn protocol_reuses_decoded_protocol_for_json_state() {
        let proto = build_protocol("Hello, {{name}}!");
        let protocol = Protocol::new(Buffer::from(proto), None).expect("protocol should load");

        let first = protocol
            .render(
                r#"{"name":"First"}"#.to_string(),
                "index.html".to_string(),
                "/".to_string(),
            )
            .expect("first render should succeed");
        let second = protocol
            .render(
                r#"{"name":"世界"}"#.to_string(),
                "index.html".to_string(),
                "/".to_string(),
            )
            .expect("second render should succeed");

        assert_eq!(first.as_ref(), b"Hello, First!");
        assert_eq!(second.as_ref(), "Hello, 世界!".as_bytes());
    }

    #[test]
    fn test_for_loop() {
        let proto = build_protocol("<ul><for each=\"item in items\"><li>{{item}}</li></for></ul>");
        let result = render_to_string(&proto, r#"{"items": ["a", "b", "c"]}"#);
        assert_eq!(
            result.as_deref(),
            Ok("<ul><li>a</li><li>b</li><li>c</li></ul>")
        );
    }

    #[test]
    fn test_if_condition_true() {
        let proto = build_protocol("<if condition=\"show\"><p>Visible</p></if>");
        let result = render_to_string(&proto, r#"{"show": true}"#);
        assert_eq!(result.as_deref(), Ok("<p>Visible</p>"));
    }

    #[test]
    fn test_if_condition_false() {
        let proto = build_protocol("<if condition=\"show\"><p>Hidden</p></if>");
        let result = render_to_string(&proto, r#"{"show": false}"#);
        assert_eq!(result.as_deref(), Ok(""));
    }

    #[test]
    fn test_html_escaping() {
        let proto = build_protocol("<div>{{content}}</div>");
        let state = r#"{"content": "<script>alert('xss')</script>"}"#;
        let result = render_to_string(&proto, state).expect("render should succeed");
        assert!(!result.contains("<script>"));
        assert!(result.contains("&lt;script&gt;"));
    }

    #[test]
    fn test_raw_signal() {
        let proto = build_protocol("<div>{{{content}}}</div>");
        let result = render_to_string(&proto, r#"{"content": "<b>bold</b>"}"#);
        assert_eq!(result.as_deref(), Ok("<div><b>bold</b></div>"));
    }

    #[test]
    fn test_invalid_json() {
        let proto = build_protocol("<p>hi</p>");
        let result = render_to_string(&proto, "NOT JSON");
        assert!(result.is_err());
    }

    #[test]
    fn test_empty_state() {
        let proto = build_protocol("<p>static</p>");
        let result = render_to_string(&proto, "{}");
        assert_eq!(result.as_deref(), Ok("<p>static</p>"));
    }

    #[test]
    fn test_nested_object_signal() {
        let proto = build_protocol("{{user.name}}");
        let result = render_to_string(&proto, r#"{"user": {"name": "Alice"}}"#);
        assert_eq!(result.as_deref(), Ok("Alice"));
    }

    #[test]
    fn test_invalid_protobuf() {
        let result = render_to_string(&[0xFF, 0xFF, 0xFF], "{}");
        assert!(result.is_err());
    }

    /// Parse `html`, attach a sorted hydration `schema`, and encode to protobuf.
    fn build_projected_protocol(html: &str, schema: &[&str]) -> Vec<u8> {
        let mut parser = HtmlParser::new();
        parser.parse("index.html", html).expect("parse failed");
        let tokens = parser.take_tokens();
        let mut protocol = WebUIProtocol::with_tokens(parser.into_fragment_records(), tokens);
        protocol.fragments.insert(
            "client-card".to_string(),
            webui_protocol::FragmentList {
                fragments: vec![webui_protocol::WebUIFragment::raw("<p>client</p>")],
            },
        );
        protocol
            .fragments
            .get_mut("index.html")
            .expect("index fragment should exist")
            .fragments
            .insert(1, webui_protocol::WebUIFragment::component("client-card"));
        protocol.initial_state_strategy = webui_protocol::InitialStateStrategy::Components as i32;
        protocol.components.insert(
            "client-card".to_string(),
            webui_protocol::ComponentData {
                hydration_mode: webui_protocol::StateProjectionMode::Keys as i32,
                hydration_keys: schema.iter().map(|key| (*key).to_string()).collect(),
                ..Default::default()
            },
        );
        protocol.to_protobuf().expect("protobuf encode failed")
    }

    /// Render protocol bytes with the WebUI hydration plugin so the `#webui-data`
    /// bootstrap block (and its projected state) is emitted — this mirrors the
    /// production `render(..., plugin = "webui")` path.
    fn render_with_webui_plugin(protocol_bytes: &[u8], state_json: &str) -> Result<String, String> {
        let protocol = HandlerProtocol::from_protobuf(protocol_bytes).map_err(|e| e.to_string())?;
        let state: Value = serde_json::from_str(state_json).map_err(|e| e.to_string())?;

        let mut output = String::with_capacity(1024);
        struct StringWriter<'a> {
            output: &'a mut String,
        }
        impl ResponseWriter for StringWriter<'_> {
            fn write(&mut self, content: &str) -> webui_handler::Result<()> {
                self.output.push_str(content);
                Ok(())
            }
            fn end(&mut self) -> webui_handler::Result<()> {
                Ok(())
            }
        }
        let mut writer = StringWriter {
            output: &mut output,
        };
        let handler = WebUIHandler::with_plugin(|| Box::new(WebUIHydrationPlugin::new()));
        handler
            .render(
                &protocol,
                &state,
                &RenderOptions::new("index.html", "/"),
                &mut writer,
            )
            .map_err(|e| e.to_string())?;
        Ok(output)
    }

    #[test]
    fn render_projects_state_to_component_hydration_keys() {
        // Full document so the parser emits a `body_end` signal, which makes the
        // WebUI plugin emit the #webui-data bootstrap block.
        let bytes =
            build_projected_protocol("<html><body><p>{{kept}}</p></body></html>", &["kept"]);
        let out =
            render_with_webui_plugin(&bytes, r#"{"kept":"KEPT_VALUE","dropped":"DROPPED_VALUE"}"#)
                .expect("render should succeed");

        // Only the hydratable key reaches the bootstrap state block...
        assert!(
            out.contains(r#""kept":"KEPT_VALUE""#),
            "hydratable key missing from bootstrap state: {out}"
        );
        // ...the non-hydratable key is projected out entirely.
        assert!(
            !out.contains("DROPPED_VALUE"),
            "server-only value leaked: {out}"
        );
        assert!(
            !out.contains("dropped"),
            "server-only key name leaked: {out}"
        );
    }

    // ── Tests for build() and inspect() napi exports ─────────────────

    fn projection_manifest_json() -> String {
        const EMPTY_SHA256: &str =
            "sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855";
        let mut manifest = ProjectionManifest {
            schema: SCHEMA_ID.to_string(),
            producer: ProjectionProducer {
                name: PRODUCER_NAME.to_string(),
                version: "0.0.18".to_string(),
            },
            adapter: ProjectionAdapter {
                name: "test".to_string(),
                bundler: "test@1.0.0".to_string(),
            },
            root: ".".to_string(),
            analysis_hash: format!("sha256:{}", "1".repeat(64)),
            build_id: String::new(),
            inputs: BTreeMap::from([("demo-card.ts".to_string(), EMPTY_SHA256.to_string())]),
            outputs: BTreeMap::from([("bundle.js".to_string(), EMPTY_SHA256.to_string())]),
            components: BTreeMap::from([(
                "demo-card".to_string(),
                ProjectionComponent {
                    module: "demo-card.ts".to_string(),
                    outputs: vec!["bundle.js".to_string()],
                    hydration_keys: vec!["name".to_string()],
                    navigation_keys: vec!["label".to_string(), "name".to_string()],
                },
            )]),
            entry_closures: BTreeMap::new(),
        };
        manifest.build_id = manifest.compute_build_id();
        serde_json::to_string(&manifest).unwrap()
    }

    fn projection_build_options(app_dir: &std::path::Path) -> JsBuildOptions {
        JsBuildOptions {
            app_dir: app_dir.to_string_lossy().to_string(),
            entry: None,
            css: None,
            dom: None,
            plugin: Some("webui".to_string()),
            components: None,
            component_asset_roots: None,
            metafile: None,
            css_file_name_template: None,
            css_public_base: None,
            legal_comments: None,
            theme: None,
            projection_manifests: None,
            projection_manifest_objects: None,
        }
    }

    #[test]
    fn test_build_accepts_projection_paths_and_inline_objects() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("index.html"), "<demo-card></demo-card>").unwrap();
        std::fs::write(dir.path().join("demo-card.html"), "<p>{{name}}</p>").unwrap();
        std::fs::write(dir.path().join("demo-card.ts"), "").unwrap();
        std::fs::write(dir.path().join("bundle.js"), "").unwrap();
        let manifest_path = dir.path().join("projection.json");
        let json = projection_manifest_json();
        std::fs::write(&manifest_path, &json).unwrap();

        let mut path_options = projection_build_options(dir.path());
        path_options.projection_manifests = Some(vec![manifest_path.to_string_lossy().to_string()]);
        let path_result = build(path_options).unwrap();
        let path_protocol = WebUIProtocol::from_protobuf(&path_result.protocol).unwrap();
        assert_eq!(
            path_protocol.components["demo-card"].hydration_keys,
            ["name"]
        );

        std::fs::remove_file(&manifest_path).unwrap();
        let mut inline_options = projection_build_options(dir.path());
        inline_options.projection_manifest_objects = Some(vec![JsProjectionManifest {
            path: manifest_path.to_string_lossy().to_string(),
            json,
        }]);
        let inline_result = build(inline_options).unwrap();
        let inline_protocol = WebUIProtocol::from_protobuf(&inline_result.protocol).unwrap();
        assert_eq!(
            inline_protocol.components["demo-card"].navigation_keys,
            ["label", "name"]
        );
    }

    #[test]
    fn test_build_simple_app() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("index.html"), "<h1>Hello</h1>").unwrap();

        let options = JsBuildOptions {
            app_dir: dir.path().to_string_lossy().to_string(),
            entry: None,
            css: None,
            dom: None,
            plugin: None,
            components: None,
            component_asset_roots: None,
            metafile: None,
            css_file_name_template: None,
            css_public_base: None,
            legal_comments: None,
            theme: None,
            projection_manifests: None,
            projection_manifest_objects: None,
        };

        let result = build(options).unwrap();
        assert!(!result.protocol.is_empty());
        assert!(result.stats.fragment_count > 0);
        assert!(result.stats.protocol_size_bytes > 0);
        assert!(result.stats.duration_ms >= 0.0);
    }

    #[test]
    fn test_build_with_custom_entry() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("page.html"), "<p>Custom</p>").unwrap();

        let options = JsBuildOptions {
            app_dir: dir.path().to_string_lossy().to_string(),
            entry: Some("page.html".to_string()),
            css: None,
            dom: None,
            plugin: None,
            components: None,
            component_asset_roots: None,
            metafile: None,
            css_file_name_template: None,
            css_public_base: None,
            legal_comments: None,
            theme: None,
            projection_manifests: None,
            projection_manifest_objects: None,
        };

        let result = build(options).unwrap();
        assert!(!result.protocol.is_empty());
    }

    #[test]
    fn test_build_missing_app_dir() {
        let options = JsBuildOptions {
            app_dir: "/nonexistent/path".to_string(),
            entry: None,
            css: None,
            dom: None,
            plugin: None,
            components: None,
            component_asset_roots: None,
            metafile: None,
            css_file_name_template: None,
            css_public_base: None,
            legal_comments: None,
            theme: None,
            projection_manifests: None,
            projection_manifest_objects: None,
        };

        let result = build(options);
        assert!(result.is_err());
    }

    #[test]
    fn test_build_invalid_css() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("index.html"), "<h1>Hello</h1>").unwrap();

        let options = JsBuildOptions {
            app_dir: dir.path().to_string_lossy().to_string(),
            entry: None,
            css: Some("bogus".to_string()),
            dom: None,
            plugin: None,
            components: None,
            component_asset_roots: None,
            metafile: None,
            css_file_name_template: None,
            css_public_base: None,
            legal_comments: None,
            theme: None,
            projection_manifests: None,
            projection_manifest_objects: None,
        };

        let result = build(options);
        assert!(result.is_err());
    }

    #[test]
    fn test_build_with_components_css() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("index.html"), "<my-card>Hello</my-card>").unwrap();
        std::fs::write(dir.path().join("my-card.html"), "<div><slot></slot></div>").unwrap();
        std::fs::write(dir.path().join("my-card.css"), ".card { color: red; }").unwrap();

        let options = JsBuildOptions {
            app_dir: dir.path().to_string_lossy().to_string(),
            entry: None,
            css: Some("link".to_string()),
            dom: None,
            plugin: None,
            components: None,
            component_asset_roots: None,
            metafile: None,
            css_file_name_template: None,
            css_public_base: None,
            legal_comments: None,
            theme: None,
            projection_manifests: None,
            projection_manifest_objects: None,
        };

        let result = build(options).unwrap();
        // css_files is flattened: [filename, content, filename, content, ...]
        assert_eq!(result.css_files.len(), 2);
        assert_eq!(result.css_files[0], "my-card.css");
        assert!(result.css_files[1].contains("color: red"));
        assert_eq!(result.stats.css_file_count, 1);
    }

    #[test]
    fn test_build_with_theme_missing_token_errors() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("index.html"), "<my-card></my-card>").unwrap();
        std::fs::write(dir.path().join("my-card.html"), "<div>Card</div>").unwrap();
        std::fs::write(
            dir.path().join("my-card.css"),
            ":host { --token-a: red; --foo-bar: var(--token-a, var(--token-b, var(--token-c))); }",
        )
        .unwrap();
        let theme_path = dir.path().join("theme.json");
        std::fs::write(&theme_path, r#"{"themes":{"light":{"token-b":"green"}}}"#).unwrap();

        let options = JsBuildOptions {
            app_dir: dir.path().to_string_lossy().to_string(),
            entry: None,
            css: Some("link".to_string()),
            dom: None,
            plugin: None,
            components: None,
            component_asset_roots: None,
            metafile: None,
            css_file_name_template: None,
            css_public_base: None,
            legal_comments: None,
            theme: Some(theme_path.to_string_lossy().to_string()),
            projection_manifests: None,
            projection_manifest_objects: None,
        };

        let Err(err) = build(options) else {
            panic!("missing theme token must fail");
        };
        let message = err.to_string();
        assert!(message.contains("missing-theme-token"), "msg: {message}");
        assert!(message.contains("--token-c"), "msg: {message}");
    }

    #[test]
    fn test_build_returns_component_asset_files() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("index.html"), "<app-shell></app-shell>").unwrap();
        std::fs::write(dir.path().join("app-shell.html"), "<div></div>").unwrap();
        std::fs::write(dir.path().join("lazy-panel.html"), "<p>{{title}}</p>").unwrap();
        std::fs::write(dir.path().join("lazy-panel.ts"), "export {};").unwrap();

        let options = JsBuildOptions {
            app_dir: dir.path().to_string_lossy().to_string(),
            entry: None,
            css: Some("link".to_string()),
            dom: None,
            plugin: Some("webui".to_string()),
            components: None,
            component_asset_roots: Some(vec!["lazy-panel".to_string()]),
            metafile: Some(true),
            css_file_name_template: None,
            css_public_base: None,
            legal_comments: None,
            theme: None,
            projection_manifests: None,
            projection_manifest_objects: None,
        };

        let result = build(options).unwrap();

        assert_eq!(result.component_asset_files.len(), 2);
        assert_eq!(result.component_asset_files[0], "lazy-panel.webui.js");
        assert!(result.component_asset_files[1].contains("webui-component-asset"));
        assert!(result.component_asset_files[1].contains("export default asset;"));
        let metafile = result
            .metafile
            .as_deref()
            .expect("requested metafile must be returned");
        let parsed: serde_json::Value = serde_json::from_str(metafile).unwrap();
        assert!(parsed["inputs"].get("webui:component/lazy-panel").is_some());
        assert!(parsed["outputs"].get("lazy-panel.webui.js").is_some());
    }

    #[test]
    fn test_build_legal_comments_none_strips_legal_css() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("index.html"), "<my-card>Hello</my-card>").unwrap();
        std::fs::write(dir.path().join("my-card.html"), "<div><slot></slot></div>").unwrap();
        std::fs::write(
            dir.path().join("my-card.css"),
            "/*! @license MIT */ .card { color: red; }",
        )
        .unwrap();

        let options = JsBuildOptions {
            app_dir: dir.path().to_string_lossy().to_string(),
            entry: None,
            css: Some("link".to_string()),
            dom: None,
            plugin: None,
            components: None,
            component_asset_roots: None,
            metafile: None,
            css_file_name_template: None,
            css_public_base: None,
            legal_comments: Some("none".to_string()),
            theme: None,
            projection_manifests: None,
            projection_manifest_objects: None,
        };

        let result = build(options).unwrap();
        assert_eq!(result.css_files[1], " .card { color: red; }");
    }

    #[test]
    fn test_build_invalid_legal_comments() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("index.html"), "<h1>Hello</h1>").unwrap();

        let options = JsBuildOptions {
            app_dir: dir.path().to_string_lossy().to_string(),
            entry: None,
            css: None,
            dom: None,
            plugin: None,
            components: None,
            component_asset_roots: None,
            metafile: None,
            css_file_name_template: None,
            css_public_base: None,
            legal_comments: Some("linked".to_string()),
            theme: None,
            projection_manifests: None,
            projection_manifest_objects: None,
        };

        let result = build(options);
        assert!(result.is_err());
    }

    #[test]
    fn test_build_with_light_dom_omits_shadow_root_template() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("index.html"), "<my-card>Hi</my-card>").unwrap();
        std::fs::write(dir.path().join("my-card.html"), "<div><slot></slot></div>").unwrap();

        let options = JsBuildOptions {
            app_dir: dir.path().to_string_lossy().to_string(),
            entry: None,
            css: None,
            dom: Some("light".to_string()),
            plugin: None,
            components: None,
            component_asset_roots: None,
            metafile: None,
            css_file_name_template: None,
            css_public_base: None,
            legal_comments: None,
            theme: None,
            projection_manifests: None,
            projection_manifest_objects: None,
        };

        let result = build(options).unwrap();
        let json = inspect(result.protocol).unwrap();
        assert!(
            !json.contains("shadowrootmode"),
            "light DOM build should not emit shadowrootmode wrappers, got: {json}"
        );
    }

    #[test]
    fn test_build_with_shadow_dom_emits_shadow_root_template() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("index.html"), "<my-card>Hi</my-card>").unwrap();
        std::fs::write(dir.path().join("my-card.html"), "<div><slot></slot></div>").unwrap();

        let options = JsBuildOptions {
            app_dir: dir.path().to_string_lossy().to_string(),
            entry: None,
            css: None,
            dom: Some("shadow".to_string()),
            plugin: None,
            components: None,
            component_asset_roots: None,
            metafile: None,
            css_file_name_template: None,
            css_public_base: None,
            legal_comments: None,
            theme: None,
            projection_manifests: None,
            projection_manifest_objects: None,
        };

        let result = build(options).unwrap();
        let json = inspect(result.protocol).unwrap();
        assert!(
            json.contains("shadowrootmode"),
            "shadow DOM build should emit shadowrootmode wrappers, got: {json}"
        );
    }

    #[test]
    fn test_build_invalid_dom() {
        let dir = tempfile::TempDir::new().unwrap();
        std::fs::write(dir.path().join("index.html"), "<h1>Hello</h1>").unwrap();

        let options = JsBuildOptions {
            app_dir: dir.path().to_string_lossy().to_string(),
            entry: None,
            css: None,
            dom: Some("bogus".to_string()),
            plugin: None,
            components: None,
            component_asset_roots: None,
            metafile: None,
            css_file_name_template: None,
            css_public_base: None,
            legal_comments: None,
            theme: None,
            projection_manifests: None,
            projection_manifest_objects: None,
        };

        let result = build(options);
        assert!(result.is_err());
    }

    #[test]
    fn test_inspect_valid_protocol() {
        let proto = build_protocol("<h1>Hello {{name}}</h1>");
        let json = inspect(napi::bindgen_prelude::Buffer::from(proto)).unwrap();
        let parsed: serde_json::Value = serde_json::from_str(&json).unwrap();
        assert!(parsed.get("fragments").is_some());
    }

    #[test]
    fn test_inspect_invalid_protocol() {
        let result = inspect(napi::bindgen_prelude::Buffer::from(vec![0xFF, 0xFF]));
        assert!(result.is_err());
    }

    #[test]
    fn test_protocol_tokens_empty() {
        let proto = build_protocol("<p>Hello</p>");
        let protocol = Protocol::new(Buffer::from(proto), None).unwrap();
        let tokens = protocol.tokens();
        assert!(tokens.is_empty());
    }

    #[test]
    fn test_protocol_tokens_returns_parsed_tokens() {
        // Build from a protocol that has CSS tokens via with_tokens constructor.
        let mut parser = HtmlParser::new();
        parser.parse("index.html", "<p>Hi</p>").expect("parse");
        let protocol = WebUIProtocol::with_tokens(
            parser.into_fragment_records(),
            vec![
                "colorBrandBackground".to_string(),
                "fontSizeBase300".to_string(),
            ],
        );
        let proto = protocol.to_protobuf().expect("encode");
        let protocol = Protocol::new(Buffer::from(proto), None).unwrap();
        let tokens = protocol.tokens();
        assert_eq!(tokens, vec!["colorBrandBackground", "fontSizeBase300"]);
    }

    #[test]
    fn test_protocol_tokens_invalid_protobuf() {
        let result = Protocol::new(Buffer::from(vec![0xFF, 0xFF]), None);
        assert!(result.is_err());
    }
}