rong 0.2.0

RongJS runtime and embedding API
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
# Rust-Driven JavaScript APIs and Classes

This guide explains how to expose Rust functions and classes to JavaScript in the Rong engine.

## Table of Contents

- [Quick Overview]#quick-overview
- [Part 1: JavaScript Functions]#part-1-javascript-functions
  - [Async Functions]#async-functions
  - [Sync Functions]#sync-functions
  - [Function Registration]#function-registration
  - [Optional Parameters]#optional-parameters
- [Part 2: JavaScript Classes]#part-2-javascript-classes
  - [Class Definition]#class-definition
  - [Constructor]#constructor
  - [Instance Methods]#instance-methods
  - [Getters and Setters]#getters-and-setters
  - [Static Methods]#static-methods
  - [Mutable Methods]#mutable-methods
- [Advanced Topics]#advanced-topics
  - [Complex Input Types with FromJSObj]#complex-input-types-with-fromjsobj
  - [Attribute Reference]#attribute-reference
- [Complete Examples]#complete-examples

---

## Quick Overview

Rong provides two main approaches for exposing Rust to JavaScript:

| Approach        | Use Case                              | Example                    |
| :---            | :---                                  | :---                       |
| **Functions**   | Standalone utilities, module APIs     | `Rong.readFile()`          |
| **Classes**     | Stateful objects with methods         | `new Point2D(10, 20)`      |

**Key macros:**

- `#[js_export]` — Mark a struct to be exposed to JavaScript
- `#[js_class]` — Mark an `impl` block to define JS class methods
- `#[js_method]` — Mark individual methods to expose to JavaScript

---

## Part 1: JavaScript Functions

### Async Functions

Most Rust functions that perform I/O should be async. Rong automatically converts them to JavaScript Promises.

**Example:** File system operations

```rust
use rong::*;

/// Rename a file or directory
async fn rename(from: String, to: String) -> JSResult<()> {
    tokio::fs::rename(&from, &to)
        .await
        .map_err(|e| HostError::new("FS_IO", format!("Failed to rename: {}", e)).into())
}

/// Read a file's contents
async fn read_file(path: String) -> JSResult<String> {
    tokio::fs::read_to_string(&path)
        .await
        .map_err(|e| HostError::new("FS_IO", format!("Failed to read: {}", e)).into())
}
```

**JavaScript usage:**

```javascript
// These return Promises automatically
await Rong.rename("old.txt", "new.txt");
const content = await Rong.readFile("data.txt");
```

### Sync Functions

Synchronous functions are also supported, but use them only for non-blocking operations.

```rust
/// Get the current working directory
fn cwd() -> JSResult<String> {
    std::env::current_dir()
        .map(|p| p.to_string_lossy().into_owned())
        .map_err(|e| HostError::new("FS_IO", format!("Failed to get cwd: {}", e)).into())
}

/// Check if a path is absolute
fn is_absolute(path: String) -> bool {
    std::path::Path::new(&path).is_absolute()
}
```

**JavaScript usage:**

```javascript
// Sync functions return values directly
const dir = Rong.cwd();
const absolute = Rong.isAbsolute("/usr/bin");
```

### Function Registration

Register functions using `JSFunc::new()` and attach them to global objects or modules.

```rust
pub fn init(ctx: &JSContext) -> JSResult<()> {
    let rong = ctx.rong();

    // Register async function
    let rename_fn = JSFunc::new(ctx, rename)?.name("rename")?;
    rong.set("rename", rename_fn)?;

    // Register sync function
    let cwd_fn = JSFunc::new(ctx, cwd)?.name("cwd")?;
    rong.set("cwd", cwd_fn)?;

    Ok(())
}
```

**Registration pattern breakdown:**

1. `JSFunc::new(ctx, function)` — Wrap the Rust function
2. `.name("functionName")` — Set the function name (for stack traces)
3. `rong.set("key", func)` — Attach to the global `Rong` object

### Optional Parameters

Use `Optional<T>` from `rong::function` for optional parameters.

```rust
use rong::function::Optional;

async fn read_file_with_encoding(
    path: String,
    encoding: Optional<String>
) -> JSResult<String> {
    let enc = encoding.0.unwrap_or_else(|| "utf-8".to_string());
    // Use encoding...
    todo!()
}
```

**JavaScript usage:**

```javascript
// Both calls work
await Rong.readFile("file.txt");
await Rong.readFile("file.txt", "utf-16");
```

---

## Part 2: JavaScript Classes

### Class Definition

Use `#[js_export]` on the struct and `#[js_class]` on the impl block.

**Basic example:**

```rust
use rong::*;
use rong::{js_export, js_class, js_method};

#[js_export]
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

#[js_class(rename = "Point2D")]
impl Point {
    #[js_method(constructor)]
    fn new(x: i32, y: i32) -> Self {
        Self { x, y }
    }
}
```

**JavaScript usage:**

```javascript
const p = new Point2D(10, 20);
```

**Notes:**
- `#[js_export]` makes the struct available to the macro system
- `rename = "Point2D"` sets the JavaScript class name (optional, defaults to struct name)
- `#[derive(Debug)]` is optional but helpful for debugging

### Constructor

Mark the constructor with `#[js_method(constructor)]`.

```rust
#[js_class]
impl Point {
    #[js_method(constructor)]
    fn new(x: i32, y: i32) -> Self {
        Self { x, y }
    }
}
```

**Rules:**
- Must return `Self`
- Can have any number of parameters
- Can return `JSResult<Self>` for fallible construction

**Fallible constructor:**

```rust
#[js_method(constructor)]
fn new(x: i32, y: i32) -> JSResult<Self> {
    if x < 0 || y < 0 {
        return Err(HostError::new(
            "INVALID_ARG",
            "Coordinates must be non-negative"
        ).into());
    }
    Ok(Self { x, y })
}
```

### Instance Methods

Regular instance methods take `&self` or `&mut self`.

```rust
#[js_class]
impl Point {
    /// Calculate distance from origin
    #[js_method]
    fn distance(&self) -> f64 {
        ((self.x.pow(2) + self.y.pow(2)) as f64).sqrt()
    }

    /// Add another point
    #[js_method(rename = "add")]
    fn add(&self, other: Point) -> Self {
        Self {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}
```

**JavaScript usage:**

```javascript
const p1 = new Point2D(3, 4);
console.log(p1.distance()); // 5

const p2 = new Point2D(10, 20);
const p3 = p1.add(p2); // Point2D(13, 24)
```

### Getters and Setters

Use `#[js_method(getter)]` and `#[js_method(setter)]` for property access.

```rust
#[js_class]
impl Point {
    // Getter
    #[js_method(getter, enumerable)]
    fn x(&self) -> i32 {
        self.x
    }

    // Setter
    #[js_method(setter, rename = "x")]
    fn set_x(&mut self, x: i32) {
        self.x = x;
    }

    #[js_method(getter, enumerable)]
    fn y(&self) -> i32 {
        self.y
    }

    #[js_method(setter, rename = "y")]
    fn set_y(&mut self, y: i32) {
        self.y = y;
    }
}
```

**JavaScript usage:**

```javascript
const p = new Point2D(10, 20);

// Use like properties
console.log(p.x); // 10
p.x = 15;
p.y = 25;

// enumerable makes them show up in Object.keys()
console.log(Object.keys(p)); // ['x', 'y']
```

**Notes:**
- `enumerable` makes the property show up in `Object.keys()` and `for...in` loops
- Setter must use `rename` to match the getter's name
- Setter requires `&mut self`

### Static Methods

Methods without `self` become static methods.

```rust
#[js_class]
impl Point {
    /// Create a point at the origin
    #[js_method]
    fn origin() -> Self {
        Self { x: 0, y: 0 }
    }

    /// Create a point from polar coordinates
    #[js_method(rename = "fromPolar")]
    fn from_polar(r: f64, theta: f64) -> Self {
        Self {
            x: (r * theta.cos()) as i32,
            y: (r * theta.sin()) as i32,
        }
    }
}
```

**JavaScript usage:**

```javascript
const origin = Point2D.origin();
const p = Point2D.fromPolar(10, Math.PI / 4);
```

### Mutable Methods

Methods that modify the instance require `&mut self`.

```rust
#[js_class]
impl Point {
    #[js_method(rename = "moveBy")]
    fn move_by(&mut self, dx: i32, dy: i32) {
        self.x += dx;
        self.y += dy;
    }

    #[js_method]
    fn scale(&mut self, factor: i32) {
        self.x *= factor;
        self.y *= factor;
    }
}
```

**JavaScript usage:**

```javascript
const p = new Point2D(10, 20);
p.moveBy(5, 5);   // p is now (15, 25)
p.scale(2);       // p is now (30, 50)
```

---

## Advanced Topics

### Complex Input Types with FromJSObj

For methods that accept JavaScript objects, use `#[derive(FromJSObj)]`.

**Example:** Storage options (input)

```rust
use rong::FromJSObj;

#[derive(FromJSObj, Default)]
pub struct StorageOptions {
    #[rename = "maxKeySize"]
    max_key_size: Option<u32>,

    #[rename = "maxValueSize"]
    max_value_size: Option<u32>,

    #[rename = "maxDataSize"]
    max_data_size: Option<u32>,
}

#[js_export]
pub struct Storage {
    // ...
}

#[js_class]
impl Storage {
    #[js_method(constructor)]
    fn new(path: String, options: Optional<StorageOptions>) -> JSResult<Self> {
        let opts = options.0.unwrap_or_default();
        // Use opts.max_key_size, etc.
        todo!()
    }
}
```

**JavaScript usage:**

```javascript
// Pass an object with camelCase properties
const storage = new Storage("./data.db", {
    maxKeySize: 1024,
    maxValueSize: 65536
});
```

**FromJSObj features:**
- Automatically converts JavaScript objects to Rust structs
- `#[rename = "jsName"]` maps JS property names to Rust field names
- Works with `Option<T>` for optional fields
- Supports nested objects and arrays

### Returning Complex Objects with IntoJSObj

For methods that return JavaScript objects, use `#[derive(IntoJSObj)]`.

**Example:** Storage info (output)

```rust
use rong::IntoJSObj;

#[derive(IntoJSObj)]
pub struct StorageInfo {
    #[rename = "currentSize"]
    current_size: u32,

    #[rename = "limitSize"]
    limit_size: u32,

    #[rename = "keyCount"]
    key_count: u32,
}

#[js_class]
impl Storage {
    #[js_method]
    fn info(&self) -> JSResult<StorageInfo> {
        Ok(StorageInfo {
            current_size: 1024,
            limit_size: 10240,
            key_count: 42,
        })
    }
}
```

**JavaScript usage:**

```javascript
const info = storage.info();
console.log(info.currentSize);  // 1024
console.log(info.keyCount);     // 42

// The object is a plain JavaScript object
console.log(Object.keys(info)); // ['currentSize', 'limitSize', 'keyCount']
```

**IntoJSObj features:**
- Automatically converts Rust structs to JavaScript objects
- `#[rename = "jsName"]` maps Rust field names to JS property names
- `Option<T>` fields are omitted if `None`
- Supports nested structs and common types (`String`, `i32`, `f64`, `bool`, etc.)

### Attribute Reference

#### `#[js_export]`

Must be applied to structs you want to expose to JavaScript.

```rust
#[js_export]
struct MyClass { /* ... */ }
```

#### `#[js_class]`

Applied to `impl` blocks to expose methods to JavaScript.

**Attributes:**
- `rename = "JsName"` — Set the JavaScript class name

```rust
#[js_class(rename = "MyJSClass")]
impl MyClass { /* ... */ }
```

#### `#[js_method]`

Applied to individual methods within a `#[js_class]` impl block.

**Attributes:**

| Attribute      | Description                           | Example                             |
| :---           | :---                                  | :---                                |
| `constructor`  | Mark as class constructor             | `#[js_method(constructor)]`         |
| `rename = "x"` | Set JavaScript method/property name   | `#[js_method(rename = "moveBy")]`   |
| `getter`       | Expose as property getter             | `#[js_method(getter)]`              |
| `setter`       | Expose as property setter             | `#[js_method(setter, rename = "x")]`|
| `enumerable`   | Make property enumerable              | `#[js_method(getter, enumerable)]`  |

**Combining attributes:**

```rust
#[js_method(getter, enumerable, rename = "myProp")]
fn get_my_prop(&self) -> i32 { /* ... */ }
```

---

## Complete Examples

### Example 1: File System Module

```rust
use rong::*;

/// Read file contents
async fn read_file(path: String) -> JSResult<String> {
    tokio::fs::read_to_string(&path)
        .await
        .map_err(|e| HostError::new("FS_IO", format!("Read failed: {}", e)).into())
}

/// Write file contents
async fn write_file(path: String, content: String) -> JSResult<()> {
    tokio::fs::write(&path, content)
        .await
        .map_err(|e| HostError::new("FS_IO", format!("Write failed: {}", e)).into())
}

/// Check if path exists
async fn exists(path: String) -> bool {
    tokio::fs::metadata(&path).await.is_ok()
}

pub fn init_fs(ctx: &JSContext) -> JSResult<()> {
    let rong = ctx.rong();

    let read_fn = JSFunc::new(ctx, read_file)?.name("readFile")?;
    rong.set("readFile", read_fn)?;

    let write_fn = JSFunc::new(ctx, write_file)?.name("writeFile")?;
    rong.set("writeFile", write_fn)?;

    let exists_fn = JSFunc::new(ctx, exists)?.name("exists")?;
    rong.set("exists", exists_fn)?;

    Ok(())
}
```

**JavaScript usage:**

```javascript
// All async operations return Promises
const exists = await Rong.exists("data.txt");
if (exists) {
    const content = await Rong.readFile("data.txt");
    console.log(content);
}

await Rong.writeFile("output.txt", "Hello, World!");
```

### Example 2: Point Class (Complete)

```rust
use rong::*;
use rong::{js_export, js_class, js_method};

#[js_export]
#[derive(Debug, Clone)]
struct Point {
    x: i32,
    y: i32,
}

#[js_class(rename = "Point2D")]
impl Point {
    // Constructor
    #[js_method(constructor)]
    fn new(x: i32, y: i32) -> Self {
        Self { x, y }
    }

    // Getters and setters
    #[js_method(getter, enumerable)]
    fn x(&self) -> i32 {
        self.x
    }

    #[js_method(setter, rename = "x")]
    fn set_x(&mut self, x: i32) {
        self.x = x;
    }

    #[js_method(getter, enumerable)]
    fn y(&self) -> i32 {
        self.y
    }

    #[js_method(setter, rename = "y")]
    fn set_y(&mut self, y: i32) {
        self.y = y;
    }

    // Instance methods
    #[js_method]
    fn distance(&self) -> f64 {
        ((self.x.pow(2) + self.y.pow(2)) as f64).sqrt()
    }

    #[js_method(rename = "add")]
    fn add(&self, other: Point) -> Self {
        Self {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }

    // Mutable method
    #[js_method(rename = "moveBy")]
    fn move_by(&mut self, dx: i32, dy: i32) {
        self.x += dx;
        self.y += dy;
    }

    // Static methods
    #[js_method]
    fn origin() -> Self {
        Self { x: 0, y: 0 }
    }
}

fn main() {
    let rt = RongJS::runtime();
    let ctx = rt.context();

    // Register the class
    ctx.register_class::<Point>().unwrap();

    // Use from JavaScript
    let result = ctx.eval::<String>(Source::from_bytes(r#"
        const p1 = new Point2D(10, 20);
        const p2 = new Point2D(30, 40);

        p1.x = 15;  // Use setter
        p1.moveBy(5, 5);  // Now at (20, 25)

        const p3 = p1.add(p2);  // (50, 65)
        const origin = Point2D.origin();

        `p1: (${p1.x}, ${p1.y}), p3: (${p3.x}, ${p3.y}), origin: (${origin.x}, ${origin.y})`
    "#)).unwrap();

    println!("{}", result);
}
```

### Example 3: Storage Class with Options

```rust
use rong::*;
use rong::{js_export, js_class, js_method, FromJSObj};
use rong::function::Optional;

#[derive(FromJSObj, Default)]
pub struct StorageOptions {
    #[rename = "maxSize"]
    max_size: Option<u32>,

    compression: Option<bool>,
}

#[js_export]
pub struct Storage {
    path: String,
    max_size: u32,
    compression: bool,
}

#[js_class]
impl Storage {
    #[js_method(constructor)]
    fn new(path: String, options: Optional<StorageOptions>) -> JSResult<Self> {
        let opts = options.0.unwrap_or_default();

        Ok(Self {
            path,
            max_size: opts.max_size.unwrap_or(1024 * 1024),
            compression: opts.compression.unwrap_or(false),
        })
    }

    #[js_method]
    async fn set(&self, key: String, value: String) -> JSResult<()> {
        // Store key-value pair
        todo!()
    }

    #[js_method]
    async fn get(&self, key: String) -> JSResult<Option<String>> {
        // Retrieve value
        todo!()
    }

    #[js_method(getter)]
    fn path(&self) -> String {
        self.path.clone()
    }
}
```

**JavaScript usage:**

```javascript
const storage = new Storage("./data.db", {
    maxSize: 10485760,  // 10MB
    compression: true
});

await storage.set("user:1", JSON.stringify({ name: "Alice" }));
const data = await storage.get("user:1");
console.log(storage.path); // "./data.db"
```

---

## See Also

- [Value System and Type Conversion]./value_system.md - Understanding type conversions between Rust and JavaScript
- [Error Handling]./error_handling.md - Creating and throwing JavaScript errors from Rust