Skip to main content

vibe_wasm/
lib.rs

1//! WASM bindings for VibeScript 0.1.
2//!
3//! Exposes parse, check, evaluate, and bytecode operations to JavaScript
4//! via `wasm-bindgen`.  The wrapper serialises results as plain JS objects
5//! (through `serde-wasm-bindgen`) so the playground can consume them
6//! without a custom ABI.
7
8use js_sys::{Array, Object, Reflect, Uint8Array};
9use wasm_bindgen::prelude::*;
10
11use vibe::{
12    bytecode::{self, compile, compile_expr, decode_chunk, encode_chunk, Vm},
13    check_cell, check_program, decode as decode_cbor_ast, diagnose, encode as encode_cbor_ast,
14    eval_cell, eval_function, load_program, parse_cell, parse_program, Budget, DiagCode,
15    Diagnostic, Engine, Env, Host, Item, LocalHost, Span, Value, HOST_VERSION, LANGUAGE_VERSION,
16    TAG_VIBE_AST,
17};
18
19// ── helpers ────────────────────────────────────────────────────────
20
21/// Convert a `Value` into a plain JS value.
22fn value_to_js(v: &Value) -> JsValue {
23    match v {
24        Value::Null => JsValue::NULL,
25        Value::Bool(b) => JsValue::from_bool(*b),
26        Value::I64(n) => JsValue::from_str(&n.to_string()),
27        Value::U64(n) => JsValue::from_str(&n.to_string()),
28        Value::F64(f) => JsValue::from_f64(*f),
29        Value::String(s) => JsValue::from_str(s),
30        Value::Iri(s) => {
31            let o = Object::new();
32            Reflect::set(&o, &"type".into(), &"iri".into()).ok();
33            Reflect::set(&o, &"value".into(), &JsValue::from_str(s)).ok();
34            o.into()
35        }
36        Value::Blank(s) => {
37            let o = Object::new();
38            Reflect::set(&o, &"type".into(), &"blank".into()).ok();
39            Reflect::set(&o, &"value".into(), &JsValue::from_str(s)).ok();
40            o.into()
41        }
42        Value::Prefixed(p, l) => {
43            let o = Object::new();
44            Reflect::set(&o, &"type".into(), &"prefixed".into()).ok();
45            Reflect::set(&o, &"prefix".into(), &JsValue::from_str(p)).ok();
46            Reflect::set(&o, &"local".into(), &JsValue::from_str(l)).ok();
47            o.into()
48        }
49        Value::Var(s) => {
50            let o = Object::new();
51            Reflect::set(&o, &"type".into(), &"var".into()).ok();
52            Reflect::set(&o, &"name".into(), &JsValue::from_str(s)).ok();
53            o.into()
54        }
55        Value::List(items) => {
56            let arr = Array::new();
57            for item in items {
58                arr.push(&value_to_js(item));
59            }
60            arr.into()
61        }
62        Value::Record(map) => {
63            let o = Object::new();
64            for (k, v) in map.iter() {
65                Reflect::set(&o, &JsValue::from_str(k), &value_to_js(v)).ok();
66            }
67            o.into()
68        }
69        Value::Ok(v) => {
70            let o = Object::new();
71            Reflect::set(&o, &"type".into(), &"ok".into()).ok();
72            Reflect::set(&o, &"value".into(), &value_to_js(v)).ok();
73            o.into()
74        }
75        Value::Err(inner) => {
76            let o = Object::new();
77            Reflect::set(&o, &"type".into(), &"error".into()).ok();
78            Reflect::set(&o, &"value".into(), &value_to_js(inner)).ok();
79            o.into()
80        }
81        Value::Receipt => {
82            let o = Object::new();
83            Reflect::set(&o, &"type".into(), &"receipt".into()).ok();
84            o.into()
85        }
86        // For complex domain values, serialise as a tagged record.
87        _ => {
88            let o = Object::new();
89            Reflect::set(&o, &"type".into(), &JsValue::from_str(&format!("{:?}", v))).ok();
90            Reflect::set(&o, &"repr".into(), &JsValue::from_str(&format!("{:?}", v))).ok();
91            o.into()
92        }
93    }
94}
95
96/// Convert a `Diagnostic` into a JS error object.
97fn diag_to_js(d: &vibe::Diagnostic) -> JsValue {
98    // Native parity with Diagnostic::to_json / DiagnoseReport (G-A).
99    js_sys::JSON::parse(&d.to_json()).unwrap_or_else(|_| JsValue::NULL)
100}
101
102// ── public API ─────────────────────────────────────────────────────
103
104/// Get the VibeScript language version string.
105#[wasm_bindgen]
106pub fn language_version() -> String {
107    LANGUAGE_VERSION.to_string()
108}
109
110/// Frozen host ABI stamp (`vibe-host-0.1`).
111#[wasm_bindgen]
112pub fn host_version() -> String {
113    HOST_VERSION.to_string()
114}
115
116/// Capability invoke — routes through `LocalHost` so Civics/stdlib kernels
117/// (`Econ.*`, `Statistics.ols`, `PhysicalUnits.convert`, …) work under WASM.
118/// Ungranted / unknown ids still fail closed with E300 / E100.
119#[wasm_bindgen]
120pub fn capability_invoke(id: &str, args_json: &str) -> JsValue {
121    let args = match serde_json::from_str::<serde_json::Value>(args_json) {
122        Ok(v) => json_to_vibe_value(&v),
123        Err(e) => {
124            let diag = Diagnostic::new(
125                DiagCode::E100,
126                Span { start: 0, end: 0 },
127                format!("capability.invoke args JSON: {e}"),
128            );
129            let o = Object::new();
130            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
131            Reflect::set(&o, &"error".into(), &diag_to_js(&diag)).ok();
132            return o.into();
133        }
134    };
135    let mut host = LocalHost::default();
136    match host.capability_invoke(id, &args, Span { start: 0, end: 0 }) {
137        Ok(v) => {
138            let o = Object::new();
139            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
140            Reflect::set(&o, &"value".into(), &value_to_js(&v)).ok();
141            o.into()
142        }
143        Err(d) => {
144            let o = Object::new();
145            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
146            Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
147            o.into()
148        }
149    }
150}
151
152fn json_to_vibe_value(v: &serde_json::Value) -> Value {
153    match v {
154        serde_json::Value::Null => Value::Null,
155        serde_json::Value::Bool(b) => Value::Bool(*b),
156        serde_json::Value::Number(n) => {
157            if let Some(i) = n.as_i64() {
158                Value::I64(i)
159            } else if let Some(u) = n.as_u64() {
160                Value::U64(u)
161            } else {
162                Value::F64(n.as_f64().unwrap_or(0.0))
163            }
164        }
165        serde_json::Value::String(s) => Value::String(s.clone()),
166        serde_json::Value::Array(items) => {
167            Value::List(items.iter().map(json_to_vibe_value).collect())
168        }
169        serde_json::Value::Object(map) => {
170            let mut rec = std::collections::BTreeMap::new();
171            for (k, val) in map {
172                rec.insert(k.clone(), json_to_vibe_value(val));
173            }
174            Value::Record(rec)
175        }
176    }
177}
178
179/// Parse a cell expression (`= expr`).
180/// Returns `{ ok: true, ast: ... }` or `{ ok: false, error: ... }`.
181#[wasm_bindgen]
182pub fn parse_cell_src(src: &str) -> JsValue {
183    match parse_cell(src) {
184        Ok(expr) => {
185            let o = Object::new();
186            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
187            Reflect::set(
188                &o,
189                &"kind".into(),
190                &JsValue::from_str(&format!("{:?}", expr.kind)),
191            )
192            .ok();
193            o.into()
194        }
195        Err(d) => {
196            let o = Object::new();
197            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
198            Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
199            o.into()
200        }
201    }
202}
203
204/// Check a cell expression.
205#[wasm_bindgen]
206pub fn check_cell_src(src: &str) -> JsValue {
207    match parse_cell(src) {
208        Ok(expr) => match check_cell(&expr) {
209            Ok(_) => {
210                let o = Object::new();
211                Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
212                o.into()
213            }
214            Err(d) => {
215                let o = Object::new();
216                Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
217                Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
218                o.into()
219            }
220        },
221        Err(d) => {
222            let o = Object::new();
223            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
224            Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
225            o.into()
226        }
227    }
228}
229
230/// Evaluate a cell expression (`= expr`) with the in-process local host.
231#[wasm_bindgen]
232pub fn eval_cell_src(src: &str) -> JsValue {
233    let mut host = LocalHost::default();
234    let mut env = Env::default();
235    match eval_cell(src, &mut host, &mut env) {
236        Ok(v) => {
237            let o = Object::new();
238            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
239            Reflect::set(&o, &"value".into(), &value_to_js(&v)).ok();
240            o.into()
241        }
242        Err(d) => {
243            let o = Object::new();
244            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
245            Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
246            o.into()
247        }
248    }
249}
250
251/// Parse a full VibeScript program (module).
252#[wasm_bindgen]
253pub fn parse_program_src(src: &str) -> JsValue {
254    match parse_program(src) {
255        Ok(prog) => {
256            let o = Object::new();
257            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
258            let items = Array::new();
259            for item in &prog.items {
260                let desc = format!("{:?}", item);
261                items.push(&JsValue::from_str(&desc));
262            }
263            Reflect::set(&o, &"items".into(), &items).ok();
264            let funcs = Array::new();
265            for item in &prog.items {
266                if let vibe::Item::Function(fd) = item {
267                    funcs.push(&JsValue::from_str(&fd.name));
268                }
269            }
270            Reflect::set(&o, &"functions".into(), &funcs).ok();
271            o.into()
272        }
273        Err(d) => {
274            let o = Object::new();
275            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
276            Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
277            o.into()
278        }
279    }
280}
281
282/// Check a full program.
283#[wasm_bindgen]
284pub fn check_program_src(src: &str) -> JsValue {
285    match load_program(src) {
286        Ok(prog) => {
287            let o = Object::new();
288            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
289            let funcs = Array::new();
290            for item in &prog.items {
291                if let vibe::Item::Function(fd) = item {
292                    funcs.push(&JsValue::from_str(&fd.name));
293                }
294            }
295            Reflect::set(&o, &"functions".into(), &funcs).ok();
296            o.into()
297        }
298        Err(d) => {
299            let o = Object::new();
300            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
301            Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
302            o.into()
303        }
304    }
305}
306
307/// Evaluate a cell and return the result as a JSON-compatible JS value.
308/// Playground Run uses `eval_program_src` (module + optional `main`), not this.
309#[wasm_bindgen]
310pub fn eval_cell_json(src: &str) -> JsValue {
311    eval_cell_src(src)
312}
313
314/// Parse + check a module; collect up to eight diagnostics.
315#[wasm_bindgen]
316pub fn diagnose_src(src: &str) -> JsValue {
317    // Byte-level JSON parity with native DiagnoseReport::to_json (G-A).
318    let report = diagnose(src);
319    js_sys::JSON::parse(&report.to_json()).unwrap_or_else(|_| JsValue::NULL)
320}
321
322/// Evaluate a full program on LocalHost (workshop dialect).
323///
324/// Runs preamble items, then `main` when present — same as `vibe eval FILE main`.
325#[wasm_bindgen]
326pub fn eval_program_src(src: &str) -> JsValue {
327    match parse_program(src).and_then(|p| check_program(&p).map(|_| p)) {
328        Ok(prog) => {
329            let mut host = LocalHost::default();
330            let mut env = Env::default();
331            let result = (|| {
332                let top_val = {
333                    let mut engine = Engine::with_program(&mut host, Budget::default(), &prog);
334                    engine.eval_program(&prog, &mut env)?
335                };
336                let has_main = prog
337                    .items
338                    .iter()
339                    .any(|item| matches!(item, Item::Function(f) if f.name == "main"));
340                if has_main {
341                    eval_function(&prog, "main", Vec::new(), &mut host, &mut env)
342                } else {
343                    Ok(top_val)
344                }
345            })();
346            match result {
347                Ok(v) => {
348                    let o = Object::new();
349                    Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
350                    Reflect::set(&o, &"value".into(), &value_to_js(&v)).ok();
351                    o.into()
352                }
353                Err(d) => {
354                    let o = Object::new();
355                    Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
356                    Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
357                    o.into()
358                }
359            }
360        }
361        Err(d) => {
362            let o = Object::new();
363            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
364            Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
365            o.into()
366        }
367    }
368}
369
370/// Persistent compiled cell for the browser binding.
371///
372/// Keeps the compiled [`bytecode::Chunk`] so timed / repeated runs can call
373/// [`CompiledCell::run`] without re-decoding VBC1 bytes. Prefer this over
374/// [`decode_and_run`] when the job is "run what we already compiled."
375#[wasm_bindgen]
376pub struct CompiledCell {
377    chunk: bytecode::Chunk,
378}
379
380#[wasm_bindgen]
381impl CompiledCell {
382    /// Compile a cell expression (`= expr`) into a handle. Does not run it.
383    pub fn compile(src: &str) -> Result<CompiledCell, JsValue> {
384        match parse_cell(src) {
385            Ok(expr) => match compile_expr(&expr) {
386                Ok(chunk) => Ok(CompiledCell { chunk }),
387                Err(e) => Err(JsValue::from_str(&format!("{:?}", e))),
388            },
389            Err(d) => Err(diag_to_js(&d)),
390        }
391    }
392
393    /// Decode a VBC1 byte buffer once into a handle. Later [`Self::run`] calls
394    /// do not decode again.
395    pub fn from_bytes(bytes: &[u8]) -> Result<CompiledCell, JsValue> {
396        match decode_chunk(bytes) {
397            Ok(chunk) => Ok(CompiledCell { chunk }),
398            Err(e) => Err(JsValue::from_str(&format!("{:?}", e))),
399        }
400    }
401
402    /// Run the held chunk on a fresh local VM. Does not decode.
403    pub fn run(&self) -> JsValue {
404        let mut host = LocalHost::default();
405        let mut vm = Vm::new(&self.chunk, &mut host, Budget::default());
406        match vm.run() {
407            Ok(v) => {
408                let o = Object::new();
409                Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
410                Reflect::set(&o, &"value".into(), &value_to_js(&v)).ok();
411                o.into()
412            }
413            Err(e) => {
414                let o = Object::new();
415                Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
416                Reflect::set(&o, &"error".into(), &JsValue::from_str(&format!("{:?}", e))).ok();
417                o.into()
418            }
419        }
420    }
421
422    #[wasm_bindgen(getter)]
423    /// `code` size.
424    pub fn code_size(&self) -> usize {
425        self.chunk.code.len()
426    }
427
428    #[wasm_bindgen(getter)]
429    /// Constants.
430    pub fn constants(&self) -> usize {
431        self.chunk.constants.len()
432    }
433
434    #[wasm_bindgen(getter)]
435    /// Functions.
436    pub fn functions(&self) -> usize {
437        self.chunk.functions.len()
438    }
439
440    #[wasm_bindgen(getter)]
441    /// Top-level locals.
442    pub fn top_locals(&self) -> u16 {
443        self.chunk.top_locals
444    }
445
446    /// Human-readable disassembly of the held chunk (inspect only).
447    pub fn disassembly(&self) -> String {
448        disassemble(&self.chunk)
449    }
450}
451
452/// Compile a cell expression to bytecode and return chunk metadata.
453///
454/// For repeated execution without re-decode, use [`CompiledCell::compile`] and
455/// [`CompiledCell::run`] instead. This export stays for playground inspect /
456/// size reporting.
457#[wasm_bindgen]
458pub fn compile_cell_bytecode(src: &str) -> JsValue {
459    match CompiledCell::compile(src) {
460        Ok(cell) => {
461            let o = Object::new();
462            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
463            Reflect::set(
464                &o,
465                &"code_size".into(),
466                &JsValue::from_f64(cell.code_size() as f64),
467            )
468            .ok();
469            Reflect::set(
470                &o,
471                &"constants".into(),
472                &JsValue::from_f64(cell.constants() as f64),
473            )
474            .ok();
475            Reflect::set(
476                &o,
477                &"functions".into(),
478                &JsValue::from_f64(cell.functions() as f64),
479            )
480            .ok();
481            Reflect::set(
482                &o,
483                &"top_locals".into(),
484                &JsValue::from_f64(cell.top_locals() as f64),
485            )
486            .ok();
487            Reflect::set(
488                &o,
489                &"disassembly".into(),
490                &JsValue::from_str(&cell.disassembly()),
491            )
492            .ok();
493            o.into()
494        }
495        Err(err) => {
496            let o = Object::new();
497            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
498            Reflect::set(&o, &"error".into(), &err).ok();
499            o.into()
500        }
501    }
502}
503
504/// Compile a cell to bytecode, run it on the VM, and return the result.
505#[wasm_bindgen]
506pub fn run_cell_bytecode(src: &str) -> JsValue {
507    match parse_cell(src) {
508        Ok(expr) => match compile_expr(&expr) {
509            Ok(chunk) => {
510                let mut host = LocalHost::default();
511                let mut vm = Vm::new(&chunk, &mut host, Budget::default());
512                match vm.run() {
513                    Ok(v) => {
514                        let o = Object::new();
515                        Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
516                        Reflect::set(&o, &"value".into(), &value_to_js(&v)).ok();
517                        o.into()
518                    }
519                    Err(e) => {
520                        let o = Object::new();
521                        Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
522                        Reflect::set(&o, &"error".into(), &JsValue::from_str(&format!("{:?}", e)))
523                            .ok();
524                        o.into()
525                    }
526                }
527            }
528            Err(e) => {
529                let o = Object::new();
530                Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
531                Reflect::set(&o, &"error".into(), &JsValue::from_str(&format!("{:?}", e))).ok();
532                o.into()
533            }
534        },
535        Err(d) => {
536            let o = Object::new();
537            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
538            Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
539            o.into()
540        }
541    }
542}
543
544/// Compile a program to bytecode, encode it to binary, decode it, and run
545/// a named function.  Demonstrates the full bytecode round-trip.
546#[wasm_bindgen]
547pub fn run_program_bytecode(src: &str, fn_name: &str, args: Vec<JsValue>) -> JsValue {
548    match load_program(src) {
549        Ok(prog) => match compile(&prog) {
550            Ok(chunk) => {
551                // Encode → decode round-trip.
552                let bytes = encode_chunk(&chunk);
553                let decoded = match decode_chunk(&bytes) {
554                    Ok(c) => c,
555                    Err(e) => {
556                        let o = Object::new();
557                        Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
558                        Reflect::set(&o, &"error".into(), &JsValue::from_str(&format!("{:?}", e)))
559                            .ok();
560                        return o.into();
561                    }
562                };
563
564                let idx = match decoded.find_function(fn_name) {
565                    Some(i) => i,
566                    None => {
567                        let o = Object::new();
568                        Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
569                        Reflect::set(
570                            &o,
571                            &"error".into(),
572                            &JsValue::from_str(&format!("function '{}' not found", fn_name)),
573                        )
574                        .ok();
575                        return o.into();
576                    }
577                };
578
579                // Convert JS args to Values.
580                let vibe_args: Vec<Value> = args.iter().map(js_to_value).collect();
581
582                let mut host = LocalHost::default();
583                let mut vm = Vm::new(&decoded, &mut host, Budget::default());
584                // Run the preamble first.
585                if let Err(e) = vm.run() {
586                    let o = Object::new();
587                    Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
588                    Reflect::set(
589                        &o,
590                        &"error".into(),
591                        &JsValue::from_str(&format!("preamble: {:?}", e)),
592                    )
593                    .ok();
594                    return o.into();
595                }
596
597                match vm.call_function(idx, &vibe_args) {
598                    Ok(v) => {
599                        let o = Object::new();
600                        Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
601                        Reflect::set(&o, &"value".into(), &value_to_js(&v)).ok();
602                        Reflect::set(
603                            &o,
604                            &"bytecode_size".into(),
605                            &JsValue::from_f64(bytes.len() as f64),
606                        )
607                        .ok();
608                        o.into()
609                    }
610                    Err(e) => {
611                        let o = Object::new();
612                        Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
613                        Reflect::set(&o, &"error".into(), &JsValue::from_str(&format!("{:?}", e)))
614                            .ok();
615                        o.into()
616                    }
617                }
618            }
619            Err(e) => {
620                let o = Object::new();
621                Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
622                Reflect::set(&o, &"error".into(), &JsValue::from_str(&format!("{:?}", e))).ok();
623                o.into()
624            }
625        },
626        Err(d) => {
627            let o = Object::new();
628            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
629            Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
630            o.into()
631        }
632    }
633}
634
635/// Encode a cell's bytecode to a binary Uint8Array.
636#[wasm_bindgen]
637pub fn encode_cell_bytecode(src: &str) -> JsValue {
638    match parse_cell(src) {
639        Ok(expr) => match compile_expr(&expr) {
640            Ok(chunk) => {
641                let bytes = encode_chunk(&chunk);
642                Uint8Array::from(&bytes[..]).into()
643            }
644            Err(e) => {
645                let o = Object::new();
646                Reflect::set(&o, &"error".into(), &JsValue::from_str(&format!("{:?}", e))).ok();
647                o.into()
648            }
649        },
650        Err(d) => {
651            let o = Object::new();
652            Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
653            o.into()
654        }
655    }
656}
657
658/// Decode a binary bytecode chunk and run it once.
659///
660/// Compat wrapper: each call decodes again. Prefer [`CompiledCell::from_bytes`]
661/// then [`CompiledCell::run`] when the same bytes will run more than once.
662#[wasm_bindgen]
663pub fn decode_and_run(bytes: &[u8]) -> JsValue {
664    match CompiledCell::from_bytes(bytes) {
665        Ok(cell) => cell.run(),
666        Err(err) => {
667            let o = Object::new();
668            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
669            Reflect::set(&o, &"error".into(), &err).ok();
670            o.into()
671        }
672    }
673}
674
675/// Get the EBNF grammar string.
676#[wasm_bindgen]
677pub fn ebnf_grammar() -> String {
678    vibe::EBNF.to_string()
679}
680
681/// Get the GBNF grammar (for LLM constrained decoding).
682#[wasm_bindgen]
683pub fn gbnf_grammar() -> String {
684    vibe::GBNF.to_string()
685}
686
687/// Get the JSON schema for the AST.
688#[wasm_bindgen]
689pub fn ast_schema_json() -> String {
690    vibe::SOURCE_SCHEMA_JSON.to_string()
691}
692
693/// Get the JSON schema for diagnostics.
694#[wasm_bindgen]
695pub fn diagnostic_schema_json() -> String {
696    vibe::DIAGNOSTIC_SCHEMA_JSON.to_string()
697}
698
699// ── internal helpers ───────────────────────────────────────────────
700
701/// Convert a JsValue to a VibeScript Value.
702fn js_to_value(v: &JsValue) -> Value {
703    if v.is_null() {
704        Value::Null
705    } else if let Some(b) = v.as_bool() {
706        Value::Bool(b)
707    } else if let Some(n) = v.as_f64() {
708        if n.fract() == 0.0 && n.abs() < 9.007e15 {
709            Value::I64(n as i64)
710        } else {
711            Value::F64(n)
712        }
713    } else if let Some(s) = v.as_string() {
714        Value::String(s)
715    } else {
716        Value::Null
717    }
718}
719
720/// Disassemble a chunk's bytecode into a human-readable string.
721fn disassemble(chunk: &bytecode::Chunk) -> String {
722    use bytecode::Op;
723    let mut out = String::new();
724    let mut pc = 0;
725    out.push_str(&format!(
726        "=== Chunk: {} ops, {} constants, {} functions ===\n",
727        chunk.code.len(),
728        chunk.constants.len(),
729        chunk.functions.len()
730    ));
731    while pc < chunk.code.len() {
732        let op_byte = chunk.code[pc];
733        let op = Op::from_byte(op_byte);
734        let offset = pc;
735        pc += 1;
736        match op {
737            Some(o) => {
738                let name = format!("{:?}", o);
739                // Read operands for ops that have them.
740                match o {
741                    Op::PushInt | Op::PushUInt => {
742                        if pc + 8 <= chunk.code.len() {
743                            let bytes: [u8; 8] =
744                                chunk.code[pc..pc + 8].try_into().unwrap_or([0; 8]);
745                            let val = i64::from_le_bytes(bytes);
746                            pc += 8;
747                            out.push_str(&format!("{:04}  {} {}\n", offset, name, val));
748                        } else {
749                            out.push_str(&format!("{:04}  {} <truncated>\n", offset, name));
750                        }
751                    }
752                    Op::PushFloat => {
753                        if pc + 8 <= chunk.code.len() {
754                            let bytes: [u8; 8] =
755                                chunk.code[pc..pc + 8].try_into().unwrap_or([0; 8]);
756                            let val = f64::from_le_bytes(bytes);
757                            pc += 8;
758                            out.push_str(&format!("{:04}  {} {}\n", offset, name, val));
759                        } else {
760                            out.push_str(&format!("{:04}  {} <truncated>\n", offset, name));
761                        }
762                    }
763                    Op::PushString | Op::PushIri => {
764                        if pc + 2 <= chunk.code.len() {
765                            let idx = u16::from_le_bytes([chunk.code[pc], chunk.code[pc + 1]]);
766                            pc += 2;
767                            let const_val = chunk
768                                .constants
769                                .get(idx as usize)
770                                .map(|c| format!("{:?}", c))
771                                .unwrap_or_else(|| "<invalid>".to_string());
772                            out.push_str(&format!(
773                                "{:04}  {} [{}] {}\n",
774                                offset, name, idx, const_val
775                            ));
776                        } else {
777                            out.push_str(&format!("{:04}  {} <truncated>\n", offset, name));
778                        }
779                    }
780                    Op::LoadVar
781                    | Op::StoreVar
782                    | Op::MakeList
783                    | Op::MakeRecord
784                    | Op::Jump
785                    | Op::JumpIfFalse
786                    | Op::JumpIfTrue
787                    | Op::CallHost
788                    | Op::CallUser => {
789                        if pc + 2 <= chunk.code.len() {
790                            let operand = u16::from_le_bytes([chunk.code[pc], chunk.code[pc + 1]]);
791                            pc += 2;
792                            out.push_str(&format!("{:04}  {} {}\n", offset, name, operand));
793                        } else {
794                            out.push_str(&format!("{:04}  {} <truncated>\n", offset, name));
795                        }
796                    }
797                    _ => {
798                        out.push_str(&format!("{:04}  {}\n", offset, name));
799                    }
800                }
801            }
802            None => {
803                out.push_str(&format!(
804                    "{:04}  <invalid opcode 0x{:02x}>\n",
805                    offset, op_byte
806                ));
807            }
808        }
809    }
810    // Append function metadata.
811    for (i, f) in chunk.functions.iter().enumerate() {
812        out.push_str(&format!(
813            "  fn[{}]: {} (params={}, locals={}, offset={}, budget={})\n",
814            i, f.name, f.param_count, f.local_count, f.code_offset, f.budget_steps
815        ));
816    }
817    out
818}
819
820// ── projectional authoring (W1) ────────────────────────────────────
821
822use vibe::projectional::{apply_edit, apply_edits, project_program, Edit, ProjectOptions};
823use vibe::{FieldRepresentation, FieldSupport, NamedArg, Span as VibeSpan};
824
825/// Project a VibeScript program source to canonical form.
826/// Parses the source, then re-projects it from the AST.
827/// This is the core of projectional authoring: structure → text.
828#[wasm_bindgen]
829pub fn project_source(src: &str) -> JsValue {
830    match parse_program(src) {
831        Ok(prog) => {
832            let projected = project_program(&prog, &ProjectOptions::default());
833            let o = Object::new();
834            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
835            Reflect::set(&o, &"source".into(), &JsValue::from_str(&projected)).ok();
836            o.into()
837        }
838        Err(d) => {
839            let o = Object::new();
840            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
841            Reflect::set(&o, &"error".into(), &JsValue::from_str(&d.message)).ok();
842            o.into()
843        }
844    }
845}
846
847/// Apply a structural edit to a VibeScript program and project the result.
848///
849/// The edit is specified as a JSON object with an `op` field and
850/// operation-specific fields. This enables LLMs and browsers to
851/// edit program structure without text patching.
852///
853/// Supported ops:
854/// - `add_field`: { op, name, ty, unit?, support?, representation? }
855/// - `add_material`: { op, name, properties: [{name, value}] }
856/// - `add_law`: { op, name, condition, consequence }
857/// - `remove_item`: { op, index }
858/// - `rename_item`: { op, index, new_name }
859/// - `set_field_unit`: { op, index, unit? }
860/// - `set_field_support`: { op, index, support }
861/// - `set_field_representation`: { op, index, representation }
862/// - `add_material_property`: { op, index, name, value }
863/// - `remove_material_property`: { op, index, name }
864/// - `add_prefix`: { op, prefix, iri }
865/// - `remove_prefix`: { op, prefix }
866#[wasm_bindgen]
867pub fn apply_structural_edit(src: &str, edit_json: &str) -> JsValue {
868    let edit = match parse_edit_json(edit_json) {
869        Ok(e) => e,
870        Err(msg) => {
871            let o = Object::new();
872            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
873            Reflect::set(&o, &"error".into(), &JsValue::from_str(&msg)).ok();
874            return o.into();
875        }
876    };
877
878    match parse_program(src) {
879        Ok(prog) => {
880            let edited = apply_edit(&prog, &edit);
881            let projected = project_program(&edited, &ProjectOptions::default());
882            let o = Object::new();
883            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
884            Reflect::set(&o, &"source".into(), &JsValue::from_str(&projected)).ok();
885            o.into()
886        }
887        Err(d) => {
888            let o = Object::new();
889            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
890            Reflect::set(&o, &"error".into(), &JsValue::from_str(&d.message)).ok();
891            o.into()
892        }
893    }
894}
895
896/// Apply multiple structural edits in sequence.
897/// `edits_json` is a JSON array of edit objects.
898#[wasm_bindgen]
899pub fn apply_structural_edits(src: &str, edits_json: &str) -> JsValue {
900    let edits = match parse_edits_json(edits_json) {
901        Ok(e) => e,
902        Err(msg) => {
903            let o = Object::new();
904            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
905            Reflect::set(&o, &"error".into(), &JsValue::from_str(&msg)).ok();
906            return o.into();
907        }
908    };
909
910    match parse_program(src) {
911        Ok(prog) => {
912            let edited = apply_edits(&prog, &edits);
913            let projected = project_program(&edited, &ProjectOptions::default());
914            let o = Object::new();
915            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
916            Reflect::set(&o, &"source".into(), &JsValue::from_str(&projected)).ok();
917            o.into()
918        }
919        Err(d) => {
920            let o = Object::new();
921            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
922            Reflect::set(&o, &"error".into(), &JsValue::from_str(&d.message)).ok();
923            o.into()
924        }
925    }
926}
927
928fn parse_edit_json(json: &str) -> Result<Edit, String> {
929    let v: serde_json::Value = serde_json::from_str(json).map_err(|e| e.to_string())?;
930    let op = v
931        .get("op")
932        .and_then(|o| o.as_str())
933        .ok_or("missing 'op' field")?;
934
935    match op {
936        "add_field" => {
937            let name = v
938                .get("name")
939                .and_then(|n| n.as_str())
940                .ok_or("missing 'name'")?;
941            let ty = v.get("ty").and_then(|t| t.as_str()).ok_or("missing 'ty'")?;
942            let unit = v
943                .get("unit")
944                .and_then(|u| u.as_str())
945                .map(|s| s.to_string());
946            let support = v
947                .get("support")
948                .and_then(|s| s.as_str())
949                .map(|s| match s {
950                    "region" => FieldSupport::Region,
951                    "point" => FieldSupport::Point,
952                    "continuant" => FieldSupport::Continuant,
953                    "stream" => FieldSupport::Stream,
954                    _ => FieldSupport::Region,
955                })
956                .unwrap_or(FieldSupport::Region);
957            let representation = v
958                .get("representation")
959                .and_then(|r| r.as_str())
960                .map(|r| match r {
961                    "grid" => FieldRepresentation::Grid,
962                    "mesh" => FieldRepresentation::Mesh,
963                    "particles" => FieldRepresentation::Particles,
964                    "analytic" => FieldRepresentation::Analytic,
965                    "sampled" => FieldRepresentation::Sampled,
966                    _ => FieldRepresentation::Grid,
967                })
968                .unwrap_or(FieldRepresentation::Grid);
969            let index = v.get("index").and_then(|i| i.as_u64()).map(|i| i as usize);
970            Ok(Edit::AddItem {
971                item: vibe::projectional::make_field(
972                    name,
973                    ty,
974                    unit.as_deref(),
975                    support,
976                    representation,
977                ),
978                index,
979            })
980        }
981        "add_material" => {
982            let name = v
983                .get("name")
984                .and_then(|n| n.as_str())
985                .ok_or("missing 'name'")?;
986            let props = v
987                .get("properties")
988                .and_then(|p| p.as_array())
989                .ok_or("missing 'properties' array")?;
990            let properties: Vec<(&str, vibe::Expr)> = props
991                .iter()
992                .filter_map(|p| {
993                    let n = p.get("name")?.as_str()?;
994                    let val = p.get("value")?.as_f64()?;
995                    Some((n, vibe::projectional::make_float(val)))
996                })
997                .collect();
998            let index = v.get("index").and_then(|i| i.as_u64()).map(|i| i as usize);
999            Ok(Edit::AddItem {
1000                item: vibe::projectional::make_material(name, properties),
1001                index,
1002            })
1003        }
1004        "add_law" => {
1005            let name = v
1006                .get("name")
1007                .and_then(|n| n.as_str())
1008                .ok_or("missing 'name'")?;
1009            let condition = v
1010                .get("condition")
1011                .and_then(|c| c.as_str())
1012                .ok_or("missing 'condition'")?;
1013            let consequence = v
1014                .get("consequence")
1015                .and_then(|c| c.as_str())
1016                .ok_or("missing 'consequence'")?;
1017            // For simplicity, parse condition/consequence as cell expressions
1018            let cond_expr = vibe::parse_cell(&format!("= {}", condition))
1019                .map_err(|e| format!("condition parse: {}", e.message))?;
1020            let cons_expr = vibe::parse_cell(&format!("= {}", consequence))
1021                .map_err(|e| format!("consequence parse: {}", e.message))?;
1022            let index = v.get("index").and_then(|i| i.as_u64()).map(|i| i as usize);
1023            Ok(Edit::AddItem {
1024                item: vibe::projectional::make_law(name, cond_expr, cons_expr),
1025                index,
1026            })
1027        }
1028        "remove_item" => {
1029            let index = v
1030                .get("index")
1031                .and_then(|i| i.as_u64())
1032                .ok_or("missing 'index'")? as usize;
1033            Ok(Edit::RemoveItem { index })
1034        }
1035        "rename_item" => {
1036            let index = v
1037                .get("index")
1038                .and_then(|i| i.as_u64())
1039                .ok_or("missing 'index'")? as usize;
1040            let new_name = v
1041                .get("new_name")
1042                .and_then(|n| n.as_str())
1043                .ok_or("missing 'new_name'")?
1044                .to_string();
1045            Ok(Edit::RenameItem { index, new_name })
1046        }
1047        "set_field_unit" => {
1048            let index = v
1049                .get("index")
1050                .and_then(|i| i.as_u64())
1051                .ok_or("missing 'index'")? as usize;
1052            let unit = v
1053                .get("unit")
1054                .and_then(|u| u.as_str())
1055                .map(|s| s.to_string());
1056            Ok(Edit::SetFieldUnit { index, unit })
1057        }
1058        "set_field_support" => {
1059            let index = v
1060                .get("index")
1061                .and_then(|i| i.as_u64())
1062                .ok_or("missing 'index'")? as usize;
1063            let support = v
1064                .get("support")
1065                .and_then(|s| s.as_str())
1066                .ok_or("missing 'support'")?;
1067            let support = match support {
1068                "region" => FieldSupport::Region,
1069                "point" => FieldSupport::Point,
1070                "continuant" => FieldSupport::Continuant,
1071                "stream" => FieldSupport::Stream,
1072                _ => return Err(format!("unknown support '{}'", support)),
1073            };
1074            Ok(Edit::SetFieldSupport { index, support })
1075        }
1076        "set_field_representation" => {
1077            let index = v
1078                .get("index")
1079                .and_then(|i| i.as_u64())
1080                .ok_or("missing 'index'")? as usize;
1081            let representation = v
1082                .get("representation")
1083                .and_then(|r| r.as_str())
1084                .ok_or("missing 'representation'")?;
1085            let representation = match representation {
1086                "grid" => FieldRepresentation::Grid,
1087                "mesh" => FieldRepresentation::Mesh,
1088                "particles" => FieldRepresentation::Particles,
1089                "analytic" => FieldRepresentation::Analytic,
1090                "sampled" => FieldRepresentation::Sampled,
1091                _ => return Err(format!("unknown representation '{}'", representation)),
1092            };
1093            Ok(Edit::SetFieldRepresentation {
1094                index,
1095                representation,
1096            })
1097        }
1098        "add_material_property" => {
1099            let index = v
1100                .get("index")
1101                .and_then(|i| i.as_u64())
1102                .ok_or("missing 'index'")? as usize;
1103            let name = v
1104                .get("name")
1105                .and_then(|n| n.as_str())
1106                .ok_or("missing 'name'")?;
1107            let value = v
1108                .get("value")
1109                .and_then(|v| v.as_f64())
1110                .ok_or("missing 'value' (must be a number)")?;
1111            Ok(Edit::AddMaterialProperty {
1112                index,
1113                property: NamedArg {
1114                    span: VibeSpan::point(0),
1115                    name: name.to_string(),
1116                    value: vibe::projectional::make_float(value),
1117                },
1118            })
1119        }
1120        "remove_material_property" => {
1121            let index = v
1122                .get("index")
1123                .and_then(|i| i.as_u64())
1124                .ok_or("missing 'index'")? as usize;
1125            let name = v
1126                .get("name")
1127                .and_then(|n| n.as_str())
1128                .ok_or("missing 'name'")?
1129                .to_string();
1130            Ok(Edit::RemoveMaterialProperty { index, name })
1131        }
1132        "add_prefix" => {
1133            let prefix = v
1134                .get("prefix")
1135                .and_then(|p| p.as_str())
1136                .ok_or("missing 'prefix'")?
1137                .to_string();
1138            let iri = v
1139                .get("iri")
1140                .and_then(|i| i.as_str())
1141                .ok_or("missing 'iri'")?
1142                .to_string();
1143            Ok(Edit::AddPrefix { prefix, iri })
1144        }
1145        "remove_prefix" => {
1146            let prefix = v
1147                .get("prefix")
1148                .and_then(|p| p.as_str())
1149                .ok_or("missing 'prefix'")?
1150                .to_string();
1151            Ok(Edit::RemovePrefix { prefix })
1152        }
1153        _ => Err(format!("unknown op '{}'", op)),
1154    }
1155}
1156
1157fn parse_edits_json(json: &str) -> Result<Vec<Edit>, String> {
1158    let arr: serde_json::Value = serde_json::from_str(json).map_err(|e| e.to_string())?;
1159    let arr = arr.as_array().ok_or("expected a JSON array")?;
1160    arr.iter()
1161        .map(|v| {
1162            let s = serde_json::to_string(v).map_err(|e| e.to_string())?;
1163            parse_edit_json(&s)
1164        })
1165        .collect()
1166}
1167
1168// ── CBOR-LD AST and Receipt Pipeline (VW-01, VW-02, VW-03) ───────────────────
1169
1170/// Tagged CBOR-LD profile identifier for VibeScript programs.
1171pub const VIBE_CBOR_LD_PROFILE: &str = "application/vnd.vibe.ast+cbor; version=0.1";
1172
1173fn fnv1a_hash_bytes(bytes: &[u8]) -> u64 {
1174    let mut h: u64 = 0xcbf29ce484222325;
1175    for &b in bytes {
1176        h ^= b as u64;
1177        h = h.wrapping_mul(0x100000001b3);
1178    }
1179    h
1180}
1181
1182/// Encodes a VibeScript source program into tagged CBOR-LD AST bytes (Tag 4200).
1183/// Validates syntax and type consistency before serializing.
1184#[wasm_bindgen]
1185pub fn encode_program_cborld_wasm(src: &str) -> Result<Uint8Array, JsValue> {
1186    let prog = parse_program(src).map_err(|d| diag_to_js(&d))?;
1187    check_program(&prog).map_err(|d| diag_to_js(&d))?;
1188    let bytes = encode_cbor_ast(&prog);
1189    Ok(Uint8Array::from(bytes.as_slice()))
1190}
1191
1192/// Decodes tagged CBOR-LD AST bytes (Tag 4200) into a canonical representation,
1193/// returning the reconstructed source code, AST hash, and provenance metadata.
1194#[wasm_bindgen]
1195pub fn decode_program_cborld_wasm(bytes: &[u8]) -> Result<JsValue, JsValue> {
1196    let prog = decode_cbor_ast(bytes)
1197        .map_err(|e| JsValue::from_str(&format!("CBOR AST decode error: {e}")))?;
1198    let canonical_source = project_program(&prog, &ProjectOptions::default());
1199    let ast_hash = fnv1a_hash_bytes(bytes);
1200
1201    let o = Object::new();
1202    Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
1203    Reflect::set(&o, &"tag".into(), &JsValue::from_f64(TAG_VIBE_AST as f64)).ok();
1204    Reflect::set(
1205        &o,
1206        &"canonicalSource".into(),
1207        &JsValue::from_str(&canonical_source),
1208    )
1209    .ok();
1210    Reflect::set(
1211        &o,
1212        &"astHash".into(),
1213        &JsValue::from_str(&format!("{:016x}", ast_hash)),
1214    )
1215    .ok();
1216    Reflect::set(
1217        &o,
1218        &"itemsCount".into(),
1219        &JsValue::from_f64(prog.items.len() as f64),
1220    )
1221    .ok();
1222    Reflect::set(
1223        &o,
1224        &"languageVersion".into(),
1225        &JsValue::from_str(LANGUAGE_VERSION),
1226    )
1227    .ok();
1228    Reflect::set(&o, &"hostVersion".into(), &JsValue::from_str(HOST_VERSION)).ok();
1229    Reflect::set(
1230        &o,
1231        &"profile".into(),
1232        &JsValue::from_str(VIBE_CBOR_LD_PROFILE),
1233    )
1234    .ok();
1235    Ok(o.into())
1236}
1237
1238/// Evaluates a Vibe program and returns the evaluated value together with a signed,
1239/// reproducible execution receipt (containing source hash, AST hash, and engine metadata).
1240#[wasm_bindgen]
1241pub fn eval_program_with_receipt_wasm(src: &str) -> JsValue {
1242    let prog = match parse_program(src).and_then(|p| check_program(&p).map(|_| p)) {
1243        Ok(p) => p,
1244        Err(d) => {
1245            let o = Object::new();
1246            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
1247            Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
1248            return o.into();
1249        }
1250    };
1251
1252    let cbor_bytes = encode_cbor_ast(&prog);
1253    let ast_hash = fnv1a_hash_bytes(&cbor_bytes);
1254    let src_hash = fnv1a_hash_bytes(src.as_bytes());
1255
1256    let mut host = LocalHost::default();
1257    let mut env = Env::default();
1258    let result = (|| {
1259        let top_val = {
1260            let mut engine = Engine::with_program(&mut host, Budget::default(), &prog);
1261            engine.eval_program(&prog, &mut env)?
1262        };
1263        let has_main = prog
1264            .items
1265            .iter()
1266            .any(|item| matches!(item, Item::Function(f) if f.name == "main"));
1267        if has_main {
1268            eval_function(&prog, "main", Vec::new(), &mut host, &mut env)
1269        } else {
1270            Ok(top_val)
1271        }
1272    })();
1273
1274    match result {
1275        Ok(v) => {
1276            let o = Object::new();
1277            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(true)).ok();
1278            Reflect::set(&o, &"value".into(), &value_to_js(&v)).ok();
1279
1280            let receipt = Object::new();
1281            Reflect::set(
1282                &receipt,
1283                &"sourceHash".into(),
1284                &JsValue::from_str(&format!("{:016x}", src_hash)),
1285            )
1286            .ok();
1287            Reflect::set(
1288                &receipt,
1289                &"astHash".into(),
1290                &JsValue::from_str(&format!("{:016x}", ast_hash)),
1291            )
1292            .ok();
1293            Reflect::set(
1294                &receipt,
1295                &"languageVersion".into(),
1296                &JsValue::from_str(LANGUAGE_VERSION),
1297            )
1298            .ok();
1299            Reflect::set(
1300                &receipt,
1301                &"hostVersion".into(),
1302                &JsValue::from_str(HOST_VERSION),
1303            )
1304            .ok();
1305            Reflect::set(
1306                &receipt,
1307                &"profile".into(),
1308                &JsValue::from_str(VIBE_CBOR_LD_PROFILE),
1309            )
1310            .ok();
1311            Reflect::set(&receipt, &"status".into(), &JsValue::from_str("success")).ok();
1312
1313            Reflect::set(&o, &"receipt".into(), &receipt).ok();
1314            o.into()
1315        }
1316        Err(d) => {
1317            let o = Object::new();
1318            Reflect::set(&o, &"ok".into(), &JsValue::from_bool(false)).ok();
1319            Reflect::set(&o, &"error".into(), &diag_to_js(&d)).ok();
1320            o.into()
1321        }
1322    }
1323}
1324
1325#[cfg(test)]
1326mod tests {
1327    use super::*;
1328
1329    #[test]
1330    fn test_vibe_cbor_ast_native_roundtrip() {
1331        let src = r#"fn add_vals(x: i64, y: i64) -> i64 {
1332  return x + y;
1333}
1334
1335fn main() -> i64 {
1336  return add_vals(42, 10);
1337}
1338"#;
1339        let prog = parse_program(src).expect("parse should succeed");
1340        check_program(&prog).expect("check should succeed");
1341        let bytes = encode_cbor_ast(&prog);
1342        assert!(!bytes.is_empty());
1343        // Tag 4200: major type 6 (110_00000 = 0xc0), length 25 (ai=25, 2 bytes for 4200)
1344        assert_eq!(bytes[0], (6 << 5) | 25);
1345
1346        let decoded = decode_cbor_ast(&bytes).expect("decode should succeed");
1347        let canon = project_program(&decoded, &ProjectOptions::default());
1348        assert!(canon.contains("add_vals"));
1349
1350        let hash = fnv1a_hash_bytes(&bytes);
1351        assert!(hash > 0);
1352    }
1353}