Skip to main content

satteri_plugin_api/
js_commands.rs

1//! Binary command buffer parser and mutation applicator.
2//!
3//! Reads a command buffer produced by the JS `CommandBuffer` class, converts
4//! commands into arena mutations, and returns the rebuilt arena.
5//!
6//! ## Wire format
7//!
8//! All multi-byte integers are **little-endian**.
9//!
10//! Commands (first byte):
11//!   0x01  REMOVE           [nodeId: u32]
12//!   0x05  INSERT_BEFORE    [nodeId: u32][payloadType: u8][payload...]
13//!   0x06  INSERT_AFTER     [nodeId: u32][payloadType: u8][payload...]
14//!   0x07  PREPEND_CHILD    [nodeId: u32][payloadType: u8][payload...]
15//!   0x08  APPEND_CHILD     [nodeId: u32][payloadType: u8][payload...]
16//!   0x09  WRAP             [nodeId: u32][payloadType: u8][payload...]
17//!   0x0B  REPLACE          [nodeId: u32][payloadType: u8][payload...]
18//!   0x0C  SET_PROPERTY     [nodeId: u32][valueType: u8][nameLen: u32][name...][valueLen: u32][value...]
19//!
20//! Value types for SET_PROPERTY:
21//!   0  STRING     : UTF-8 value
22//!   1  BOOL_TRUE  : no value bytes
23//!   2  BOOL_FALSE : no value bytes
24//!   3  SPACE_SEP  : space-separated list (UTF-8)
25//!   4  INT        : value is decimal string, parsed to i64
26//!   5  NULL       : no value bytes
27//!
28//! Payload types:
29//!   0x10  RAW_MARKDOWN     [len: u32][utf8...]
30//!   0x11  RAW_HTML         [len: u32][utf8...]
31//!   0x12  SERDE_JSON       [len: u32][utf8...]
32
33use satteri_arena::{Arena, ArenaBuilder, StringRef};
34use satteri_ast::commands::{CommandError, JsNode};
35use satteri_ast::hast::HastNodeType;
36use satteri_ast::mdast::codec::*;
37use satteri_ast::mdast::MdastNodeType;
38use satteri_ast::rebuild::Patch;
39use satteri_ast::shared::{
40    encode_js_jsx_attrs, PROP_BOOL_FALSE, PROP_BOOL_TRUE, PROP_INT, PROP_NULL, PROP_SPACE_SEP,
41    PROP_STRING,
42};
43
44// Must match packages/satteri/src/command-buffer.ts
45const CMD_REMOVE: u8 = 0x01;
46const CMD_INSERT_BEFORE: u8 = 0x05;
47const CMD_INSERT_AFTER: u8 = 0x06;
48const CMD_PREPEND_CHILD: u8 = 0x07;
49const CMD_APPEND_CHILD: u8 = 0x08;
50const CMD_WRAP: u8 = 0x09;
51const CMD_REPLACE: u8 = 0x0B;
52const CMD_SET_PROPERTY: u8 = 0x0C;
53
54const PAYLOAD_RAW_MARKDOWN: u8 = 0x10;
55const PAYLOAD_RAW_HTML: u8 = 0x11;
56const PAYLOAD_SERDE_JSON: u8 = 0x12;
57
58// MDAST field IDs: internal to the set_string_ref / resolve_mdast_field dispatch
59const FIELD_DEPTH: u16 = 0x0001;
60const FIELD_URL: u16 = 0x0010;
61const FIELD_TITLE: u16 = 0x0011;
62const FIELD_LANG: u16 = 0x0020;
63const FIELD_META: u16 = 0x0021;
64const FIELD_VALUE: u16 = 0x0022;
65const FIELD_ALT: u16 = 0x0030;
66const FIELD_ORDERED: u16 = 0x0040;
67const FIELD_START: u16 = 0x0041;
68const FIELD_SPREAD: u16 = 0x0042;
69const FIELD_CHECKED: u16 = 0x0050;
70const FIELD_IDENTIFIER: u16 = 0x0060;
71const FIELD_LABEL: u16 = 0x0061;
72const FIELD_REFERENCE_TYPE: u16 = 0x0062;
73const FIELD_NAME: u16 = 0x0070;
74
75struct BufReader<'a> {
76    data: &'a [u8],
77    pos: usize,
78}
79
80impl<'a> BufReader<'a> {
81    fn new(data: &'a [u8]) -> Self {
82        Self { data, pos: 0 }
83    }
84
85    fn remaining(&self) -> usize {
86        self.data.len() - self.pos
87    }
88
89    fn read_u8(&mut self) -> Result<u8, CommandError> {
90        if self.remaining() < 1 {
91            return Err(CommandError::UnexpectedEof);
92        }
93        let v = self.data[self.pos];
94        self.pos += 1;
95        Ok(v)
96    }
97
98    fn read_u32(&mut self) -> Result<u32, CommandError> {
99        if self.remaining() < 4 {
100            return Err(CommandError::UnexpectedEof);
101        }
102        let v = u32::from_le_bytes([
103            self.data[self.pos],
104            self.data[self.pos + 1],
105            self.data[self.pos + 2],
106            self.data[self.pos + 3],
107        ]);
108        self.pos += 4;
109        Ok(v)
110    }
111
112    fn read_bytes(&mut self, len: usize) -> Result<&'a [u8], CommandError> {
113        if self.remaining() < len {
114            return Err(CommandError::UnexpectedEof);
115        }
116        let slice = &self.data[self.pos..self.pos + len];
117        self.pos += len;
118        Ok(slice)
119    }
120
121    fn read_str(&mut self, len: usize) -> Result<&'a str, CommandError> {
122        let bytes = self.read_bytes(len)?;
123        std::str::from_utf8(bytes).map_err(|_| CommandError::InvalidUtf8)
124    }
125}
126
127/// Resolve an MDAST property name to its field ID for a given node type.
128fn resolve_mdast_field(node_type: u8, name: &str) -> Option<u16> {
129    match (node_type, name) {
130        (2, "depth") => Some(FIELD_DEPTH),
131        (15, "url") | (16, "url") | (9, "url") => Some(FIELD_URL),
132        (15, "title") | (16, "title") | (9, "title") => Some(FIELD_TITLE),
133        (8, "lang") => Some(FIELD_LANG),
134        (8, "meta") | (27, "meta") => Some(FIELD_META),
135        (10 | 13 | 7 | 25 | 26 | 28, "value")
136        | (8, "value")
137        | (27, "value")
138        | (102..=104, "value") => Some(FIELD_VALUE),
139        (16, "alt") => Some(FIELD_ALT),
140        (5, "ordered") => Some(FIELD_ORDERED),
141        (5, "start") => Some(FIELD_START),
142        (5 | 6, "spread") => Some(FIELD_SPREAD),
143        (6, "checked") => Some(FIELD_CHECKED),
144        (9 | 17 | 18 | 19 | 20, "identifier") => Some(FIELD_IDENTIFIER),
145        (9 | 17 | 18 | 19 | 20, "label") => Some(FIELD_LABEL),
146        (17 | 18 | 20, "referenceType") => Some(FIELD_REFERENCE_TYPE),
147        (100 | 101, "name") => Some(FIELD_NAME),
148        _ => None,
149    }
150}
151
152/// Unified set-property for both MDAST and HAST nodes.
153///
154/// For HAST elements: adds/updates a property in the element's property array.
155/// For MDAST nodes: resolves the property name to a field ID and modifies type_data.
156fn apply_set_property(
157    arena: &mut Arena,
158    node_id: u32,
159    prop_name: &str,
160    value_type: u8,
161    value_str: &str,
162) -> Result<(), CommandError> {
163    // "data" is stored as JSON bytes in the arena's node_data map, not as a
164    // typed field — handle it before the HAST path. Numeric node-type values
165    // overlap between MDAST and HAST (e.g. mdast Paragraph=1 collides with
166    // HastNodeType::Element=1), so dispatching by type alone misroutes
167    // mdast nodes into the HAST element-properties writer and fails on the
168    // empty type_data buffer.
169    if prop_name == "data" {
170        if value_type == PROP_NULL {
171            arena.set_node_data(node_id, Vec::new());
172        } else {
173            arena.set_node_data(node_id, value_str.as_bytes().to_vec());
174        }
175        return Ok(());
176    }
177
178    if let Some(result) = apply_hast_set_property(arena, node_id, prop_name, value_type, value_str)
179    {
180        return result;
181    }
182
183    // MDAST node, resolve name to field and apply
184    let node_type = arena.get_node(node_id).node_type;
185    let field_id =
186        resolve_mdast_field(node_type, prop_name).ok_or(CommandError::UnknownField(0))?;
187
188    match value_type {
189        PROP_STRING | PROP_SPACE_SEP => {
190            let sref = arena.alloc_string(value_str);
191            set_string_ref(arena, node_id, field_id, sref)
192        }
193        PROP_BOOL_TRUE => apply_mdast_bool(arena, node_id, node_type, field_id, true),
194        PROP_BOOL_FALSE => apply_mdast_bool(arena, node_id, node_type, field_id, false),
195        PROP_INT => {
196            let value: i64 = value_str.parse().unwrap_or(0);
197            apply_mdast_int(arena, node_id, node_type, field_id, value)
198        }
199        PROP_NULL => apply_mdast_null(arena, node_id, node_type, field_id),
200        _ => Err(CommandError::UnknownCommand(value_type)),
201    }
202}
203
204fn apply_mdast_int(
205    arena: &mut Arena,
206    node_id: u32,
207    node_type: u8,
208    field_id: u16,
209    value: i64,
210) -> Result<(), CommandError> {
211    let data_offset = arena.get_node(node_id).data_offset as usize;
212    let data_len = arena.get_node(node_id).data_len as usize;
213    match (node_type, field_id) {
214        (2, FIELD_DEPTH) => {
215            if data_len >= 1 {
216                arena.type_data[data_offset] = value as u8;
217            }
218        }
219        (5, FIELD_START) => {
220            if data_len >= 4 {
221                arena.type_data[data_offset..data_offset + 4]
222                    .copy_from_slice(&(value as u32).to_ne_bytes());
223            }
224        }
225        (6, FIELD_CHECKED) => {
226            if data_len >= 1 {
227                arena.type_data[data_offset] = value as u8;
228            }
229        }
230        _ => return Err(CommandError::UnknownField(field_id)),
231    }
232    Ok(())
233}
234
235fn apply_mdast_bool(
236    arena: &mut Arena,
237    node_id: u32,
238    node_type: u8,
239    field_id: u16,
240    value: bool,
241) -> Result<(), CommandError> {
242    let data_offset = arena.get_node(node_id).data_offset as usize;
243    let data_len = arena.get_node(node_id).data_len as usize;
244    match (node_type, field_id) {
245        (5, FIELD_ORDERED) => {
246            if data_len >= 5 {
247                arena.type_data[data_offset + 4] = value as u8;
248            }
249        }
250        (5, FIELD_SPREAD) => {
251            if data_len >= 6 {
252                arena.type_data[data_offset + 5] = value as u8;
253            }
254        }
255        (6, FIELD_SPREAD) => {
256            if data_len >= 2 {
257                arena.type_data[data_offset + 1] = value as u8;
258            }
259        }
260        _ => return Err(CommandError::UnknownField(field_id)),
261    }
262    Ok(())
263}
264
265fn apply_mdast_null(
266    arena: &mut Arena,
267    node_id: u32,
268    node_type: u8,
269    field_id: u16,
270) -> Result<(), CommandError> {
271    match (node_type, field_id) {
272        (6, FIELD_CHECKED) => {
273            let data_offset = arena.get_node(node_id).data_offset as usize;
274            let data_len = arena.get_node(node_id).data_len as usize;
275            if data_len >= 1 {
276                arena.type_data[data_offset] = 2;
277            }
278            Ok(())
279        }
280        _ => set_string_ref(arena, node_id, field_id, StringRef::empty()),
281    }
282}
283
284fn set_string_ref(
285    arena: &mut Arena,
286    node_id: u32,
287    field_id: u16,
288    sref: StringRef,
289) -> Result<(), CommandError> {
290    let node = arena.get_node(node_id);
291    let node_type = node.node_type;
292    let data_offset = node.data_offset as usize;
293
294    let ref_offset = match (node_type, field_id) {
295        // Text/InlineCode/Html/Yaml/Toml/InlineMath: StringRef at 0
296        (10 | 13 | 7 | 25 | 26 | 28, FIELD_VALUE) => 0,
297        // Link: LinkData { url: 0, title: 8 }
298        (15, FIELD_URL) => 0,
299        (15, FIELD_TITLE) => 8,
300        // Image: ImageData { url: 0, alt: 8, title: 16 }
301        (16, FIELD_URL) => 0,
302        (16, FIELD_ALT) => 8,
303        (16, FIELD_TITLE) => 16,
304        // Code: CodeData { lang: 0, meta: 8, value: 16 }
305        (8, FIELD_LANG) => 0,
306        (8, FIELD_META) => 8,
307        (8, FIELD_VALUE) => 16,
308        // Math: MathData { meta: 0, value: 8 }
309        (27, FIELD_META) => 0,
310        (27, FIELD_VALUE) => 8,
311        // Definition: DefinitionData { url: 0, title: 8, identifier: 16, label: 24 }
312        (9, FIELD_URL) => 0,
313        (9, FIELD_TITLE) => 8,
314        (9, FIELD_IDENTIFIER) => 16,
315        (9, FIELD_LABEL) => 24,
316        // LinkReference/ImageReference/FootnoteReference: ReferenceData { identifier: 0, label: 8 }
317        (17 | 18 | 20, FIELD_IDENTIFIER) => 0,
318        (17 | 18 | 20, FIELD_LABEL) => 8,
319        // FootnoteDefinition: FootnoteDefinitionData { identifier: 0, label: 8 }
320        (19, FIELD_IDENTIFIER) => 0,
321        (19, FIELD_LABEL) => 8,
322        // MdxJsxElement: MdxJsxElementData { name: 0 }
323        (100 | 101, FIELD_NAME) => 0,
324        // MdxExpression/MdxjsEsm: ExpressionData { value: 0 }
325        (102..=104, FIELD_VALUE) => 0,
326        _ => return Err(CommandError::UnknownField(field_id)),
327    };
328
329    let abs_offset = data_offset + ref_offset;
330    let bytes_offset = sref.offset.to_ne_bytes();
331    let bytes_len = sref.len.to_ne_bytes();
332    arena.type_data[abs_offset..abs_offset + 4].copy_from_slice(&bytes_offset);
333    arena.type_data[abs_offset + 4..abs_offset + 8].copy_from_slice(&bytes_len);
334
335    Ok(())
336}
337
338fn parse_raw_markdown(markdown: &str, parse_markdown: &dyn Fn(&str) -> Arena) -> Arena {
339    parse_markdown(markdown)
340}
341
342/// Escape `{` and `}` in HTML text content so they are not interpreted as MDX
343/// expressions when the HTML is re-parsed through the MDX parser.
344///
345/// Only braces in **text content** (outside of HTML tags) are escaped; braces
346/// inside quoted attribute values are left untouched. The escape form `{'{'}` /
347/// `{'}'}` produces a valid MDX expression that evaluates to the literal brace
348/// character.
349fn escape_braces_in_html_text(html: &str) -> String {
350    let mut result = String::with_capacity(html.len());
351    let mut in_tag = false;
352    let mut in_quote: Option<char> = None;
353
354    for ch in html.chars() {
355        if in_tag {
356            match ch {
357                '"' | '\'' if in_quote == Some(ch) => {
358                    in_quote = None;
359                    result.push(ch);
360                }
361                '"' | '\'' if in_quote.is_none() => {
362                    in_quote = Some(ch);
363                    result.push(ch);
364                }
365                '>' if in_quote.is_none() => {
366                    in_tag = false;
367                    result.push(ch);
368                }
369                _ => result.push(ch),
370            }
371        } else {
372            match ch {
373                '<' => {
374                    in_tag = true;
375                    result.push(ch);
376                }
377                '{' => result.push_str("{'{'}"),
378                '}' => result.push_str("{'}'}"),
379                _ => result.push(ch),
380            }
381        }
382    }
383    result
384}
385
386fn js_node_to_arena(js_node: &JsNode) -> Result<(Arena, bool), CommandError> {
387    let mut builder = ArenaBuilder::new(String::new());
388    emit_js_node(js_node, &mut builder)?;
389    Ok((builder.finish(), js_node.keep_children))
390}
391
392fn emit_js_node(js_node: &JsNode, builder: &mut ArenaBuilder) -> Result<(), CommandError> {
393    if js_node.is_hast {
394        return emit_hast_js_node(js_node, builder);
395    }
396
397    let node_type = name_to_node_type(&js_node.node_type)?;
398    builder.open_node(node_type as u8);
399
400    let type_data = encode_js_node_data(js_node, node_type, builder);
401    if !type_data.is_empty() {
402        builder.set_data_current(&type_data);
403    }
404
405    write_js_node_data(js_node, builder)?;
406
407    if let Some(children) = &js_node.children {
408        for child in children {
409            emit_js_node(child, builder)?;
410        }
411    }
412
413    builder.close_node();
414    Ok(())
415}
416
417fn write_js_node_data(js_node: &JsNode, builder: &mut ArenaBuilder) -> Result<(), CommandError> {
418    let Some(data) = &js_node.data else {
419        return Ok(());
420    };
421    let id = builder.current_node_id();
422    let json = serde_json::to_vec(data).map_err(|e| CommandError::InvalidJson(e.to_string()))?;
423    builder.arena_mut().set_node_data(id, json);
424    Ok(())
425}
426
427fn encode_js_node_data(
428    js_node: &JsNode,
429    node_type: MdastNodeType,
430    builder: &mut ArenaBuilder,
431) -> Vec<u8> {
432    match node_type {
433        MdastNodeType::Heading => {
434            let depth = js_node.depth.unwrap_or(1);
435            encode_heading_data(depth)
436        }
437        MdastNodeType::Text
438        | MdastNodeType::InlineCode
439        | MdastNodeType::Html
440        | MdastNodeType::Yaml
441        | MdastNodeType::Toml
442        | MdastNodeType::InlineMath => {
443            let value = js_node.value.as_deref().unwrap_or("");
444            let sref = builder.alloc_string(value);
445            encode_string_ref_data(sref)
446        }
447        MdastNodeType::Code => {
448            let lang_ref = alloc_opt_str(builder, js_node.lang.as_deref());
449            let meta_ref = alloc_opt_str(builder, js_node.meta.as_deref());
450            let value_ref = alloc_opt_str(builder, js_node.value.as_deref());
451            encode_code_data(lang_ref, meta_ref, value_ref, b'`')
452        }
453        MdastNodeType::Math => {
454            let meta_ref = alloc_opt_str(builder, js_node.meta.as_deref());
455            let value_ref = alloc_opt_str(builder, js_node.value.as_deref());
456            encode_math_data(meta_ref, value_ref)
457        }
458        MdastNodeType::Link => {
459            let url_ref = alloc_opt_str(builder, js_node.url.as_deref());
460            let title_ref = alloc_opt_str(builder, js_node.title.as_deref());
461            encode_link_data(url_ref, title_ref)
462        }
463        MdastNodeType::Image => {
464            let url_ref = alloc_opt_str(builder, js_node.url.as_deref());
465            let alt_ref = alloc_opt_str(builder, js_node.alt.as_deref());
466            let title_ref = alloc_opt_str(builder, js_node.title.as_deref());
467            encode_image_data(url_ref, alt_ref, title_ref)
468        }
469        MdastNodeType::Definition => {
470            let url_ref = alloc_opt_str(builder, js_node.url.as_deref());
471            let title_ref = alloc_opt_str(builder, js_node.title.as_deref());
472            let id_ref = alloc_opt_str(builder, js_node.identifier.as_deref());
473            let label_ref = alloc_opt_str(builder, js_node.label.as_deref());
474            encode_definition_data(url_ref, title_ref, id_ref, label_ref)
475        }
476        MdastNodeType::List => {
477            let ordered = js_node.ordered.unwrap_or(false);
478            let start = js_node.start.unwrap_or(1);
479            let spread = js_node.spread.unwrap_or(false);
480            encode_list_data(ordered, start, spread)
481        }
482        MdastNodeType::ListItem => {
483            let checked = match js_node.checked {
484                Some(true) => 1u8,
485                Some(false) => 0u8,
486                None => 2u8, // not a task item
487            };
488            let spread = js_node.spread.unwrap_or(false);
489            encode_list_item_data(checked, spread)
490        }
491        MdastNodeType::LinkReference
492        | MdastNodeType::ImageReference
493        | MdastNodeType::FootnoteReference => {
494            let id_ref = alloc_opt_str(builder, js_node.identifier.as_deref());
495            let label_ref = alloc_opt_str(builder, js_node.label.as_deref());
496            let kind = match js_node.reference_type.as_deref() {
497                Some("collapsed") => 1u8,
498                Some("full") => 2u8,
499                _ => 0u8, // shortcut
500            };
501            encode_reference_data(id_ref, label_ref, kind)
502        }
503        MdastNodeType::FootnoteDefinition => {
504            let id_ref = alloc_opt_str(builder, js_node.identifier.as_deref());
505            let label_ref = alloc_opt_str(builder, js_node.label.as_deref());
506            encode_footnote_definition_data(id_ref, label_ref)
507        }
508        MdastNodeType::MdxJsxFlowElement | MdastNodeType::MdxJsxTextElement => {
509            let name_ref = alloc_opt_str(builder, js_node.name.as_deref());
510            let attr_tuples = encode_js_jsx_attrs(builder, js_node.attributes.as_deref());
511            encode_mdx_jsx_element_data(name_ref, &attr_tuples)
512        }
513        MdastNodeType::MdxFlowExpression
514        | MdastNodeType::MdxTextExpression
515        | MdastNodeType::MdxjsEsm => {
516            let value_ref = alloc_opt_str(builder, js_node.value.as_deref());
517            encode_expression_data(value_ref)
518        }
519        // Nodes with no type-specific data
520        _ => Vec::new(),
521    }
522}
523
524fn alloc_opt_str(builder: &mut ArenaBuilder, s: Option<&str>) -> StringRef {
525    match s {
526        Some(v) if !v.is_empty() => builder.alloc_string(v),
527        _ => StringRef::empty(),
528    }
529}
530
531fn name_to_node_type(name: &str) -> Result<MdastNodeType, CommandError> {
532    match name {
533        "root" => Ok(MdastNodeType::Root),
534        "paragraph" => Ok(MdastNodeType::Paragraph),
535        "heading" => Ok(MdastNodeType::Heading),
536        "thematicBreak" => Ok(MdastNodeType::ThematicBreak),
537        "blockquote" => Ok(MdastNodeType::Blockquote),
538        "list" => Ok(MdastNodeType::List),
539        "listItem" => Ok(MdastNodeType::ListItem),
540        "html" => Ok(MdastNodeType::Html),
541        "code" => Ok(MdastNodeType::Code),
542        "definition" => Ok(MdastNodeType::Definition),
543        "text" => Ok(MdastNodeType::Text),
544        "emphasis" => Ok(MdastNodeType::Emphasis),
545        "strong" => Ok(MdastNodeType::Strong),
546        "inlineCode" => Ok(MdastNodeType::InlineCode),
547        "break" => Ok(MdastNodeType::Break),
548        "link" => Ok(MdastNodeType::Link),
549        "image" => Ok(MdastNodeType::Image),
550        "linkReference" => Ok(MdastNodeType::LinkReference),
551        "imageReference" => Ok(MdastNodeType::ImageReference),
552        "footnoteDefinition" => Ok(MdastNodeType::FootnoteDefinition),
553        "footnoteReference" => Ok(MdastNodeType::FootnoteReference),
554        "table" => Ok(MdastNodeType::Table),
555        "tableRow" => Ok(MdastNodeType::TableRow),
556        "tableCell" => Ok(MdastNodeType::TableCell),
557        "delete" => Ok(MdastNodeType::Delete),
558        "yaml" => Ok(MdastNodeType::Yaml),
559        "toml" => Ok(MdastNodeType::Toml),
560        "math" => Ok(MdastNodeType::Math),
561        "inlineMath" => Ok(MdastNodeType::InlineMath),
562        "mdxJsxFlowElement" => Ok(MdastNodeType::MdxJsxFlowElement),
563        "mdxJsxTextElement" => Ok(MdastNodeType::MdxJsxTextElement),
564        "mdxFlowExpression" => Ok(MdastNodeType::MdxFlowExpression),
565        "mdxTextExpression" => Ok(MdastNodeType::MdxTextExpression),
566        "mdxjsEsm" => Ok(MdastNodeType::MdxjsEsm),
567        other => Err(CommandError::UnknownNodeType(other.to_string())),
568    }
569}
570
571// HAST command handlers
572
573/// Try to handle a set-property command for a HAST node.
574///
575/// Returns `Some(Ok(()))` if the node was a known HAST type and the property
576/// was applied.  Returns `Some(Err(...))` on error.  Returns `None` if the
577/// node type is not a HAST type (caller should fall through to MDAST handling).
578fn apply_hast_set_property(
579    arena: &mut Arena,
580    node_id: u32,
581    prop_name: &str,
582    value_type: u8,
583    value_str: &str,
584) -> Option<Result<(), CommandError>> {
585    let node_type = HastNodeType::from_u8(arena.get_node(node_id).node_type)?;
586
587    match node_type {
588        HastNodeType::Element => Some(apply_hast_element_property(
589            arena, node_id, prop_name, value_type, value_str,
590        )),
591
592        HastNodeType::Text
593        | HastNodeType::Comment
594        | HastNodeType::Raw
595        | HastNodeType::MdxFlowExpression
596        | HastNodeType::MdxTextExpression
597        | HastNodeType::MdxEsm
598            if prop_name == "value" =>
599        {
600            let sref = arena.alloc_string(value_str);
601            let data = arena.get_type_data(node_id);
602            if data.len() >= 8 {
603                let data_offset = arena.get_node(node_id).data_offset as usize;
604                arena.type_data[data_offset..data_offset + 4]
605                    .copy_from_slice(&sref.offset.to_le_bytes());
606                arena.type_data[data_offset + 4..data_offset + 8]
607                    .copy_from_slice(&sref.len.to_le_bytes());
608                Some(Ok(()))
609            } else {
610                Some(Err(CommandError::UnknownField(0)))
611            }
612        }
613
614        _ => None,
615    }
616}
617
618/// Set or add a single property on a HAST element node.
619fn apply_hast_element_property(
620    arena: &mut Arena,
621    node_id: u32,
622    prop_name: &str,
623    value_type: u8,
624    value_str: &str,
625) -> Result<(), CommandError> {
626    let old_data = arena.get_type_data(node_id).to_vec();
627    if old_data.len() < 16 {
628        return Err(CommandError::UnexpectedEof);
629    }
630
631    let old_prop_count = u32::from_le_bytes(old_data[8..12].try_into().unwrap()) as usize;
632
633    let mut found_index: Option<usize> = None;
634    for i in 0..old_prop_count {
635        let base = 16 + i * 20;
636        let name_off = u32::from_le_bytes(old_data[base..base + 4].try_into().unwrap());
637        let name_len = u32::from_le_bytes(old_data[base + 4..base + 8].try_into().unwrap());
638        let existing_name = arena.get_str(StringRef::new(name_off, name_len));
639        if existing_name == prop_name {
640            found_index = Some(i);
641            break;
642        }
643    }
644
645    let name_ref = arena.alloc_string(prop_name);
646    let val_ref = if value_str.is_empty() {
647        StringRef::empty()
648    } else {
649        arena.alloc_string(value_str)
650    };
651
652    if let Some(idx) = found_index {
653        let mut new_data = old_data;
654        let base = 16 + idx * 20;
655        new_data[base..base + 4].copy_from_slice(&name_ref.offset.to_le_bytes());
656        new_data[base + 4..base + 8].copy_from_slice(&name_ref.len.to_le_bytes());
657        new_data[base + 8] = value_type;
658        new_data[base + 9..base + 12].copy_from_slice(&[0u8; 3]);
659        new_data[base + 12..base + 16].copy_from_slice(&val_ref.offset.to_le_bytes());
660        new_data[base + 16..base + 20].copy_from_slice(&val_ref.len.to_le_bytes());
661        arena.set_type_data(node_id, &new_data);
662    } else {
663        let new_prop_count = (old_prop_count + 1) as u32;
664        let mut new_data = Vec::with_capacity(16 + new_prop_count as usize * 20);
665        new_data.extend_from_slice(&old_data[0..8]);
666        new_data.extend_from_slice(&new_prop_count.to_le_bytes());
667        new_data.extend_from_slice(&0u32.to_le_bytes());
668        if old_prop_count > 0 {
669            new_data.extend_from_slice(&old_data[16..16 + old_prop_count * 20]);
670        }
671        new_data.extend_from_slice(&name_ref.offset.to_le_bytes());
672        new_data.extend_from_slice(&name_ref.len.to_le_bytes());
673        new_data.push(value_type);
674        new_data.extend_from_slice(&[0u8; 3]);
675        new_data.extend_from_slice(&val_ref.offset.to_le_bytes());
676        new_data.extend_from_slice(&val_ref.len.to_le_bytes());
677        arena.set_type_data(node_id, &new_data);
678    }
679
680    Ok(())
681}
682
683/// Emit a HAST JS node (from plugin JSON) into an ArenaBuilder.
684fn emit_hast_js_node(js_node: &JsNode, builder: &mut ArenaBuilder) -> Result<(), CommandError> {
685    let raw_type = name_to_hast_type(&js_node.node_type)
686        .ok_or_else(|| CommandError::UnknownNodeType(js_node.node_type.clone()))?;
687    builder.open_node_raw(raw_type as u8);
688
689    let type_data = encode_hast_js_node_data(js_node, raw_type, builder);
690    if !type_data.is_empty() {
691        builder.set_data_current(&type_data);
692    }
693
694    write_js_node_data(js_node, builder)?;
695
696    if let Some(children) = &js_node.children {
697        for child in children {
698            emit_hast_js_node(child, builder)?;
699        }
700    }
701
702    builder.close_node();
703    Ok(())
704}
705
706fn name_to_hast_type(name: &str) -> Option<HastNodeType> {
707    match name {
708        "root" => Some(HastNodeType::Root),
709        "element" => Some(HastNodeType::Element),
710        "text" => Some(HastNodeType::Text),
711        "comment" => Some(HastNodeType::Comment),
712        "doctype" => Some(HastNodeType::Doctype),
713        "raw" => Some(HastNodeType::Raw),
714        "mdxJsxFlowElement" => Some(HastNodeType::MdxJsxElement),
715        "mdxJsxTextElement" => Some(HastNodeType::MdxJsxTextElement),
716        "mdxFlowExpression" => Some(HastNodeType::MdxFlowExpression),
717        "mdxTextExpression" => Some(HastNodeType::MdxTextExpression),
718        "mdxjsEsm" => Some(HastNodeType::MdxEsm),
719        _ => None,
720    }
721}
722
723fn encode_hast_js_node_data(
724    js_node: &JsNode,
725    node_type: HastNodeType,
726    builder: &mut ArenaBuilder,
727) -> Vec<u8> {
728    match node_type {
729        HastNodeType::Element => {
730            let tag = js_node.tag_name.as_deref().unwrap_or("div");
731            let tag_ref = builder.alloc_string(tag);
732
733            let mut props: Vec<(StringRef, u8, StringRef)> = Vec::new();
734            if let Some(properties) = &js_node.properties {
735                for (key, value) in properties {
736                    let name_ref = builder.alloc_string(key);
737                    match value {
738                        serde_json::Value::Bool(true) => {
739                            props.push((name_ref, PROP_BOOL_TRUE, StringRef::empty()));
740                        }
741                        serde_json::Value::Bool(false) => {
742                            props.push((name_ref, PROP_BOOL_FALSE, StringRef::empty()));
743                        }
744                        serde_json::Value::String(s) => {
745                            let val_ref = builder.alloc_string(s);
746                            props.push((name_ref, PROP_STRING, val_ref));
747                        }
748                        serde_json::Value::Array(arr) => {
749                            let joined: String = arr
750                                .iter()
751                                .filter_map(|v| v.as_str())
752                                .collect::<Vec<_>>()
753                                .join(" ");
754                            let val_ref = builder.alloc_string(&joined);
755                            props.push((name_ref, PROP_SPACE_SEP, val_ref));
756                        }
757                        _ => {}
758                    }
759                }
760            }
761
762            let mut out = Vec::with_capacity(16 + props.len() * 20);
763            out.extend_from_slice(&tag_ref.offset.to_le_bytes());
764            out.extend_from_slice(&tag_ref.len.to_le_bytes());
765            out.extend_from_slice(&(props.len() as u32).to_le_bytes());
766            out.extend_from_slice(&0u32.to_le_bytes());
767            for (name_ref, kind, val_ref) in &props {
768                out.extend_from_slice(&name_ref.offset.to_le_bytes());
769                out.extend_from_slice(&name_ref.len.to_le_bytes());
770                out.push(*kind);
771                out.extend_from_slice(&[0u8; 3]);
772                out.extend_from_slice(&val_ref.offset.to_le_bytes());
773                out.extend_from_slice(&val_ref.len.to_le_bytes());
774            }
775            out
776        }
777
778        HastNodeType::Text | HastNodeType::Comment | HastNodeType::Raw => {
779            let value = js_node.value.as_deref().unwrap_or("");
780            let sref = builder.alloc_string(value);
781            let mut out = [0u8; 8];
782            out[0..4].copy_from_slice(&sref.offset.to_le_bytes());
783            out[4..8].copy_from_slice(&sref.len.to_le_bytes());
784            out.to_vec()
785        }
786
787        HastNodeType::MdxJsxElement | HastNodeType::MdxJsxTextElement => {
788            let name = js_node
789                .name
790                .as_deref()
791                .or(js_node.tag_name.as_deref())
792                .unwrap_or("");
793            let name_ref = builder.alloc_string(name);
794            let attr_tuples = encode_js_jsx_attrs(builder, js_node.attributes.as_deref());
795            encode_mdx_jsx_element_data(name_ref, &attr_tuples)
796        }
797
798        HastNodeType::MdxFlowExpression
799        | HastNodeType::MdxTextExpression
800        | HastNodeType::MdxEsm => {
801            let value = js_node.value.as_deref().unwrap_or("");
802            let sref = builder.alloc_string(value);
803            let mut out = [0u8; 8];
804            out[0..4].copy_from_slice(&sref.offset.to_le_bytes());
805            out[4..8].copy_from_slice(&sref.len.to_le_bytes());
806            out.to_vec()
807        }
808
809        _ => Vec::new(),
810    }
811}
812
813/// Returns (arena, keep_children).
814fn read_payload(
815    reader: &mut BufReader<'_>,
816    parse_markdown: &dyn Fn(&str) -> Arena,
817) -> Result<(Arena, bool), CommandError> {
818    let payload_type = reader.read_u8()?;
819    let len = reader.read_u32()? as usize;
820
821    match payload_type {
822        PAYLOAD_RAW_MARKDOWN => {
823            let md = reader.read_str(len)?;
824            Ok((parse_raw_markdown(md, parse_markdown), false))
825        }
826        PAYLOAD_RAW_HTML => {
827            let html = reader.read_str(len)?;
828            let escaped = escape_braces_in_html_text(html);
829            Ok((parse_raw_markdown(&escaped, parse_markdown), false))
830        }
831        PAYLOAD_SERDE_JSON => {
832            let json_str = reader.read_str(len)?;
833            let js_node: JsNode = serde_json::from_str(json_str)
834                .map_err(|e| CommandError::InvalidJson(e.to_string()))?;
835            js_node_to_arena(&js_node)
836        }
837        other => Err(CommandError::UnknownPayloadType(other)),
838    }
839}
840
841/// The `parse_markdown` callback avoids a circular dependency on the `parser`
842/// crate. Set-property mutations are applied in-place on the arena;
843/// structural mutations are collected as `Patch` objects and applied via `rebuild()`.
844///
845/// Takes ownership of the arena to avoid unnecessary cloning.
846pub fn apply_commands(
847    mut arena: Arena,
848    command_buf: &[u8],
849    parse_markdown: &dyn Fn(&str) -> Arena,
850) -> Result<Arena, CommandError> {
851    if command_buf.is_empty() {
852        return Ok(arena);
853    }
854
855    let mut patches: Vec<Patch> = Vec::new();
856    let mut reader = BufReader::new(command_buf);
857
858    while reader.remaining() > 0 {
859        let cmd = reader.read_u8()?;
860
861        match cmd {
862            CMD_REMOVE => {
863                let node_id = reader.read_u32()?;
864                patches.push(Patch::Remove { node_id });
865            }
866
867            CMD_SET_PROPERTY => {
868                let node_id = reader.read_u32()?;
869                let value_type = reader.read_u8()?;
870                let name_len = reader.read_u32()? as usize;
871                let name = reader.read_str(name_len)?;
872                let value_len = reader.read_u32()? as usize;
873                let value = reader.read_str(value_len)?;
874                apply_set_property(&mut arena, node_id, name, value_type, value)?;
875            }
876
877            CMD_INSERT_BEFORE => {
878                let node_id = reader.read_u32()?;
879                let (new_tree, _) = read_payload(&mut reader, parse_markdown)?;
880                patches.push(Patch::InsertBefore { node_id, new_tree });
881            }
882
883            CMD_INSERT_AFTER => {
884                let node_id = reader.read_u32()?;
885                let (new_tree, _) = read_payload(&mut reader, parse_markdown)?;
886                patches.push(Patch::InsertAfter { node_id, new_tree });
887            }
888
889            CMD_PREPEND_CHILD => {
890                let node_id = reader.read_u32()?;
891                let (child_tree, _) = read_payload(&mut reader, parse_markdown)?;
892                patches.push(Patch::PrependChild {
893                    node_id,
894                    child_tree,
895                });
896            }
897
898            CMD_APPEND_CHILD => {
899                let node_id = reader.read_u32()?;
900                let (child_tree, _) = read_payload(&mut reader, parse_markdown)?;
901                patches.push(Patch::AppendChild {
902                    node_id,
903                    child_tree,
904                });
905            }
906
907            CMD_WRAP => {
908                let node_id = reader.read_u32()?;
909                let (parent_tree, _) = read_payload(&mut reader, parse_markdown)?;
910                patches.push(Patch::Wrap {
911                    node_id,
912                    parent_tree,
913                });
914            }
915
916            CMD_REPLACE => {
917                let node_id = reader.read_u32()?;
918                let (new_tree, keep_children) = read_payload(&mut reader, parse_markdown)?;
919                patches.push(Patch::Replace {
920                    node_id,
921                    new_tree,
922                    keep_children,
923                });
924            }
925
926            other => return Err(CommandError::UnknownCommand(other)),
927        }
928    }
929
930    if patches.is_empty() {
931        Ok(arena)
932    } else {
933        satteri_ast::rebuild::rebuild(&arena, &patches)
934    }
935}
936
937#[cfg(test)]
938mod tests {
939    use super::*;
940    use satteri_ast::shared::PROP_INT;
941
942    fn test_parse_markdown(source: &str) -> Arena {
943        let mut b = ArenaBuilder::new(String::new());
944        b.open_node(MdastNodeType::Root as u8);
945        b.open_node(MdastNodeType::Paragraph as u8);
946        b.open_node(MdastNodeType::Text as u8);
947        let sref = b.alloc_string(source);
948        b.set_data_current(&satteri_arena::encode_string_ref_data(sref));
949        b.close_node();
950        b.close_node();
951        b.close_node();
952        b.finish()
953    }
954
955    fn push_u32(buf: &mut Vec<u8>, v: u32) {
956        buf.extend_from_slice(&v.to_le_bytes());
957    }
958
959    /// Encode a CMD_SET_PROPERTY command into a buffer.
960    fn push_set_property(buf: &mut Vec<u8>, node_id: u32, value_type: u8, name: &str, value: &str) {
961        buf.push(CMD_SET_PROPERTY);
962        push_u32(buf, node_id);
963        buf.push(value_type);
964        push_u32(buf, name.len() as u32);
965        buf.extend_from_slice(name.as_bytes());
966        push_u32(buf, value.len() as u32);
967        buf.extend_from_slice(value.as_bytes());
968    }
969
970    fn build_hello_world() -> Arena {
971        use satteri_ast::mdast::codec::{encode_heading_data, encode_string_ref_data};
972
973        let source = "# Hello\n\nWorld".to_string();
974        let mut b = ArenaBuilder::new(source);
975
976        b.open_node(MdastNodeType::Root as u8);
977        b.set_position_current(0, 14, 1, 1, 2, 6);
978
979        b.open_node(MdastNodeType::Heading as u8);
980        b.set_position_current(0, 7, 1, 1, 1, 8);
981        b.set_data_current(&encode_heading_data(1));
982
983        b.open_node(MdastNodeType::Text as u8);
984        b.set_position_current(2, 7, 1, 3, 1, 8);
985        b.set_data_current(&encode_string_ref_data(StringRef::new(2, 5)));
986        b.close_node();
987
988        b.close_node();
989
990        b.open_node(MdastNodeType::Paragraph as u8);
991        b.set_position_current(9, 14, 2, 1, 2, 6);
992
993        b.open_node(MdastNodeType::Text as u8);
994        b.set_position_current(9, 14, 2, 1, 2, 6);
995        b.set_data_current(&encode_string_ref_data(StringRef::new(9, 5)));
996        b.close_node();
997
998        b.close_node();
999        b.close_node();
1000
1001        b.finish()
1002    }
1003
1004    #[test]
1005    fn empty_command_buffer() {
1006        let arena = build_hello_world();
1007        let result = apply_commands(arena.clone(), &[], &test_parse_markdown).unwrap();
1008        assert_eq!(result.len(), arena.len());
1009    }
1010
1011    #[test]
1012    fn remove_command() {
1013        let arena = build_hello_world();
1014        let heading_id = arena.get_children(0)[0];
1015        let mut buf = Vec::new();
1016        buf.push(CMD_REMOVE);
1017        push_u32(&mut buf, heading_id);
1018
1019        let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1020        assert_eq!(result.get_children(0).len(), 1);
1021        assert_eq!(
1022            result.get_node(result.get_children(0)[0]).node_type,
1023            MdastNodeType::Paragraph as u8
1024        );
1025    }
1026
1027    #[test]
1028    fn set_property_heading_depth() {
1029        let arena = build_hello_world();
1030        let heading_id = arena.get_children(0)[0];
1031
1032        let mut buf = Vec::new();
1033        push_set_property(&mut buf, heading_id, PROP_INT, "depth", "3");
1034
1035        let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1036        let heading_data = result.get_type_data(heading_id);
1037        let heading = decode_heading_data(heading_data);
1038        assert_eq!(heading.depth, 3);
1039    }
1040
1041    #[test]
1042    fn set_property_text_value() {
1043        let arena = build_hello_world();
1044        let heading_id = arena.get_children(0)[0];
1045        let text_id = arena.get_children(heading_id)[0];
1046
1047        let mut buf = Vec::new();
1048        push_set_property(&mut buf, text_id, PROP_STRING, "value", "Goodbye");
1049
1050        let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1051        let text_data = result.get_type_data(text_id);
1052        let sref = decode_string_ref_data(text_data);
1053        assert_eq!(result.get_str(sref), "Goodbye");
1054    }
1055
1056    #[test]
1057    fn replace_with_raw_markdown() {
1058        let arena = build_hello_world();
1059        let heading_id = arena.get_children(0)[0];
1060
1061        let raw_md = "## New Heading";
1062        let mut buf = Vec::new();
1063        buf.push(CMD_REPLACE);
1064        push_u32(&mut buf, heading_id);
1065        buf.push(PAYLOAD_RAW_MARKDOWN);
1066        push_u32(&mut buf, raw_md.len() as u32);
1067        buf.extend_from_slice(raw_md.as_bytes());
1068
1069        let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1070        let root_children = result.get_children(0);
1071        assert!(root_children.len() >= 2);
1072    }
1073
1074    #[test]
1075    fn replace_with_serde_json() {
1076        let arena = build_hello_world();
1077        let heading_id = arena.get_children(0)[0];
1078
1079        let json =
1080            r#"{"type":"heading","depth":2,"children":[{"type":"text","value":"Replaced"}]}"#;
1081        let mut buf = Vec::new();
1082        buf.push(CMD_REPLACE);
1083        push_u32(&mut buf, heading_id);
1084        buf.push(PAYLOAD_SERDE_JSON);
1085        push_u32(&mut buf, json.len() as u32);
1086        buf.extend_from_slice(json.as_bytes());
1087
1088        let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1089        let root_children = result.get_children(0);
1090        assert_eq!(root_children.len(), 2);
1091        let new_heading = root_children[0];
1092        assert_eq!(
1093            result.get_node(new_heading).node_type,
1094            MdastNodeType::Heading as u8
1095        );
1096        let heading_data = result.get_type_data(new_heading);
1097        assert_eq!(decode_heading_data(heading_data).depth, 2);
1098    }
1099
1100    #[test]
1101    fn multiple_commands() {
1102        let arena = build_hello_world();
1103        let heading_id = arena.get_children(0)[0];
1104        let text_id = arena.get_children(heading_id)[0];
1105
1106        let mut buf = Vec::new();
1107        push_set_property(&mut buf, heading_id, PROP_INT, "depth", "3");
1108        push_set_property(&mut buf, text_id, PROP_STRING, "value", "Hi");
1109
1110        let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1111
1112        let heading_data = result.get_type_data(heading_id);
1113        assert_eq!(decode_heading_data(heading_data).depth, 3);
1114
1115        let text_data = result.get_type_data(text_id);
1116        let sref = decode_string_ref_data(text_data);
1117        assert_eq!(result.get_str(sref), "Hi");
1118    }
1119
1120    #[test]
1121    fn set_property_null() {
1122        let arena = build_hello_world();
1123        let heading_id = arena.get_children(0)[0];
1124        let text_id = arena.get_children(heading_id)[0];
1125
1126        let mut buf = Vec::new();
1127        push_set_property(&mut buf, text_id, PROP_NULL, "value", "");
1128
1129        let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1130        let text_data = result.get_type_data(text_id);
1131        let sref = decode_string_ref_data(text_data);
1132        assert_eq!(sref.len, 0);
1133    }
1134
1135    #[test]
1136    fn js_node_to_arena_basic() {
1137        let js = JsNode {
1138            node_type: "heading".to_string(),
1139            children: Some(vec![JsNode {
1140                node_type: "text".to_string(),
1141                children: None,
1142                value: Some("Hello".to_string()),
1143                depth: None,
1144                url: None,
1145                title: None,
1146                alt: None,
1147                lang: None,
1148                meta: None,
1149                ordered: None,
1150                start: None,
1151                spread: None,
1152                checked: None,
1153                identifier: None,
1154                label: None,
1155                reference_type: None,
1156                name: None,
1157                attributes: None,
1158                tag_name: None,
1159                properties: None,
1160                is_hast: false,
1161                keep_children: false,
1162                data: None,
1163            }]),
1164            depth: Some(2),
1165            value: None,
1166            url: None,
1167            title: None,
1168            alt: None,
1169            lang: None,
1170            meta: None,
1171            ordered: None,
1172            start: None,
1173            spread: None,
1174            checked: None,
1175            identifier: None,
1176            label: None,
1177            reference_type: None,
1178            name: None,
1179            attributes: None,
1180            tag_name: None,
1181            properties: None,
1182            is_hast: false,
1183            keep_children: false,
1184            data: None,
1185        };
1186
1187        let (arena, _keep) = js_node_to_arena(&js).unwrap();
1188        assert_eq!(arena.len(), 2);
1189        assert_eq!(arena.get_node(0).node_type, MdastNodeType::Heading as u8);
1190        assert_eq!(arena.get_children(0).len(), 1);
1191        let text_id = arena.get_children(0)[0];
1192        assert_eq!(arena.get_node(text_id).node_type, MdastNodeType::Text as u8);
1193    }
1194
1195    #[test]
1196    fn escape_braces_in_html_text_basic() {
1197        assert_eq!(
1198            escape_braces_in_html_text("<span>{foo: 1}</span>"),
1199            "<span>{'{'}foo: 1{'}'}</span>"
1200        );
1201    }
1202
1203    #[test]
1204    fn escape_braces_preserves_attributes() {
1205        let result = escape_braces_in_html_text(r#"<span data-x="{a}">{b}</span>"#);
1206        assert!(
1207            result.contains(r#"data-x="{a}""#),
1208            "attribute braces preserved"
1209        );
1210        assert!(result.contains("{'{'}"), "text braces escaped");
1211    }
1212
1213    #[test]
1214    fn escape_braces_no_braces() {
1215        let html = r#"<pre class="shiki"><code><span style="color:red">hello</span></code></pre>"#;
1216        assert_eq!(escape_braces_in_html_text(html), html);
1217    }
1218
1219    #[test]
1220    fn escape_braces_shiki_output() {
1221        let html = r#"<pre class="shiki"><code><span style="color:#E1E4E8">const x = </span><span style="color:#B392F0">{</span><span style="color:#E1E4E8">foo: 1</span><span style="color:#B392F0">}</span></code></pre>"#;
1222        let escaped = escape_braces_in_html_text(html);
1223        assert!(
1224            !escaped.contains(">{<"),
1225            "bare braces in text should be escaped"
1226        );
1227        assert!(
1228            !escaped.contains(">}<"),
1229            "bare braces in text should be escaped"
1230        );
1231        assert!(escaped.contains(r#"class="shiki""#));
1232        assert!(escaped.contains(r#"style="color:#E1E4E8""#));
1233    }
1234
1235    #[test]
1236    fn hast_set_property_add_new() {
1237        let arena = build_hast_element(&[]);
1238        let element_id = arena.get_children(0)[0];
1239
1240        let mut buf = Vec::new();
1241        push_set_property(&mut buf, element_id, PROP_STRING, "class", "test");
1242
1243        let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1244        let data = result.get_type_data(element_id);
1245        let prop_count = u32::from_le_bytes(data[8..12].try_into().unwrap());
1246        assert_eq!(prop_count, 1);
1247        let name_ref = StringRef::new(
1248            u32::from_le_bytes(data[16..20].try_into().unwrap()),
1249            u32::from_le_bytes(data[20..24].try_into().unwrap()),
1250        );
1251        assert_eq!(result.get_str(name_ref), "class");
1252        let val_ref = StringRef::new(
1253            u32::from_le_bytes(data[28..32].try_into().unwrap()),
1254            u32::from_le_bytes(data[32..36].try_into().unwrap()),
1255        );
1256        assert_eq!(result.get_str(val_ref), "test");
1257        assert_eq!(data[24], PROP_STRING);
1258    }
1259
1260    #[test]
1261    fn hast_set_property_overwrite_existing() {
1262        let arena = build_hast_element(&[("class", PROP_STRING, "old")]);
1263        let element_id = arena.get_children(0)[0];
1264
1265        let mut buf = Vec::new();
1266        push_set_property(&mut buf, element_id, PROP_STRING, "class", "new-value");
1267
1268        let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1269        let data = result.get_type_data(element_id);
1270        let prop_count = u32::from_le_bytes(data[8..12].try_into().unwrap());
1271        assert_eq!(prop_count, 1);
1272        let val_ref = StringRef::new(
1273            u32::from_le_bytes(data[28..32].try_into().unwrap()),
1274            u32::from_le_bytes(data[32..36].try_into().unwrap()),
1275        );
1276        assert_eq!(result.get_str(val_ref), "new-value");
1277    }
1278
1279    #[test]
1280    fn hast_set_property_bool_true() {
1281        let arena = build_hast_element(&[]);
1282        let element_id = arena.get_children(0)[0];
1283
1284        let mut buf = Vec::new();
1285        push_set_property(&mut buf, element_id, PROP_BOOL_TRUE, "disabled", "");
1286
1287        let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1288        let data = result.get_type_data(element_id);
1289        let prop_count = u32::from_le_bytes(data[8..12].try_into().unwrap());
1290        assert_eq!(prop_count, 1);
1291        assert_eq!(data[24], PROP_BOOL_TRUE);
1292    }
1293
1294    #[test]
1295    fn hast_set_property_multiple_on_same_node() {
1296        let arena = build_hast_element(&[]);
1297        let element_id = arena.get_children(0)[0];
1298
1299        let mut buf = Vec::new();
1300        push_set_property(&mut buf, element_id, PROP_STRING, "class", "foo");
1301        push_set_property(&mut buf, element_id, PROP_STRING, "id", "bar");
1302
1303        let result = apply_commands(arena.clone(), &buf, &test_parse_markdown).unwrap();
1304        let data = result.get_type_data(element_id);
1305        let prop_count = u32::from_le_bytes(data[8..12].try_into().unwrap());
1306        assert_eq!(prop_count, 2);
1307    }
1308
1309    /// Build a minimal HAST element arena: root(type 0) → element(type 1, tag "div")
1310    fn build_hast_element(props: &[(&str, u8, &str)]) -> Arena {
1311        use satteri_ast::hast::node::HastNodeType;
1312
1313        let mut b = ArenaBuilder::new(String::new());
1314        b.open_node_raw(HastNodeType::Root as u8);
1315        b.open_node_raw(HastNodeType::Element as u8);
1316        let tag_ref = b.alloc_string("div");
1317        let prop_tuples: Vec<(StringRef, u8, StringRef)> = props
1318            .iter()
1319            .map(|(name, kind, value)| {
1320                let n = b.alloc_string(name);
1321                let v = if value.is_empty() {
1322                    StringRef::empty()
1323                } else {
1324                    b.alloc_string(value)
1325                };
1326                (n, *kind, v)
1327            })
1328            .collect();
1329        let mut type_data = Vec::with_capacity(16 + prop_tuples.len() * 20);
1330        type_data.extend_from_slice(&tag_ref.offset.to_le_bytes());
1331        type_data.extend_from_slice(&tag_ref.len.to_le_bytes());
1332        type_data.extend_from_slice(&(prop_tuples.len() as u32).to_le_bytes());
1333        type_data.extend_from_slice(&0u32.to_le_bytes());
1334        for (n, kind, v) in &prop_tuples {
1335            type_data.extend_from_slice(&n.offset.to_le_bytes());
1336            type_data.extend_from_slice(&n.len.to_le_bytes());
1337            type_data.push(*kind);
1338            type_data.extend_from_slice(&[0u8; 3]);
1339            type_data.extend_from_slice(&v.offset.to_le_bytes());
1340            type_data.extend_from_slice(&v.len.to_le_bytes());
1341        }
1342        b.set_data_current(&type_data);
1343        b.close_node();
1344        b.close_node();
1345        b.finish()
1346    }
1347}