amberjs 1.16.1

JavaScript/TypeScript runtime built with Rust and V8
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
// CompressionStream API implementation
// v0.3.295: Streaming compression/decompression (gzip/deflate)
// v0.3.297: Full compression/decompression implementation with close() support
// Optimized for AI workloads - reduces network transfer by 70-90%

use anyhow::Result;
use flate2::bufread::{GzDecoder, GzEncoder};
use flate2::Compression;
use rusty_v8 as v8;
use std::io::{Cursor, Read};

/// Close method for compression stream - closes the writable stream
fn compression_close_method(
    scope: &mut v8::PinScope,
    args: v8::FunctionCallbackArguments,
    _retval: v8::ReturnValue,
) {
    let this_obj: v8::Local<v8::Object> = args.this();

    // Get writable stream and close it
    let writable_key = v8::String::new(scope, "writable").unwrap();
    if let Some(writable_val) = this_obj.get(scope, writable_key.into()) {
        if let Ok(writable) = v8::Local::<v8::Object>::try_from(writable_val) {
            let close_key = v8::String::new(scope, "close").unwrap();
            if let Some(close_fn) = writable.get(scope, close_key.into()) {
                if let Ok(close_fn_local) = v8::Local::<v8::Function>::try_from(close_fn) {
                    let _ = close_fn_local.call(scope, writable.into(), &[]);
                }
            }
        }
    }
}

/// Close method for decompression stream
fn decompression_close_method(
    scope: &mut v8::PinScope,
    args: v8::FunctionCallbackArguments,
    _retval: v8::ReturnValue,
) {
    let this_obj: v8::Local<v8::Object> = args.this();

    // Get writable stream and close it
    let writable_key = v8::String::new(scope, "writable").unwrap();
    if let Some(writable_val) = this_obj.get(scope, writable_key.into()) {
        if let Ok(writable) = v8::Local::<v8::Object>::try_from(writable_val) {
            let close_key = v8::String::new(scope, "close").unwrap();
            if let Some(close_fn) = writable.get(scope, close_key.into()) {
                if let Ok(close_fn_local) = v8::Local::<v8::Function>::try_from(close_fn) {
                    let _ = close_fn_local.call(scope, writable.into(), &[]);
                }
            }
        }
    }
}

/// Helper to create Uint8Array from bytes
fn create_uint8_array<'a>(
    scope: &mut v8::PinScope<'a, '_>,
    data: &[u8],
) -> Option<v8::Local<'a, v8::Uint8Array>> {
    let buffer = v8::ArrayBuffer::new(scope, data.len());
    if data.len() > 0 {
        let store = buffer.get_backing_store();
        let ptr = store
            .data()
            .map(|p| p.as_ptr() as *mut u8)
            .unwrap_or(std::ptr::null_mut());
        unsafe {
            std::slice::from_raw_parts_mut(ptr, data.len()).copy_from_slice(data);
        }
    }
    v8::Uint8Array::new(scope, buffer, 0, data.len())
}

fn uint8_array_to_vec(
    scope: &mut v8::PinScope,
    data: v8::Local<v8::Uint8Array>,
) -> Option<Vec<u8>> {
    let len = data.byte_length();
    if len == 0 {
        return Some(Vec::new());
    }

    let buffer = data.buffer(scope)?;
    let store = buffer.get_backing_store();
    let ptr = store
        .data()
        .map(|p| p.as_ptr() as *const u8)
        .unwrap_or(std::ptr::null());
    if ptr.is_null() {
        return None;
    }

    let byte_offset = data.byte_offset();
    Some(unsafe { std::slice::from_raw_parts(ptr.add(byte_offset), len).to_vec() })
}

/// Attach close method to compression stream instance
fn attach_compression_close_method(scope: &mut v8::PinScope, this_obj: v8::Local<v8::Object>) {
    let close_key = v8::String::new(scope, "close").unwrap();
    let close_fn_template = v8::FunctionTemplate::new(scope, compression_close_method);
    if let Some(close_fn) = close_fn_template.get_function(scope) {
        this_obj.set(scope, close_key.into(), close_fn.into());
    }
}

/// Attach close method to decompression stream instance
fn attach_decompression_close_method(scope: &mut v8::PinScope, this_obj: v8::Local<v8::Object>) {
    let close_key = v8::String::new(scope, "close").unwrap();
    let close_fn_template = v8::FunctionTemplate::new(scope, decompression_close_method);
    if let Some(close_fn) = close_fn_template.get_function(scope) {
        this_obj.set(scope, close_key.into(), close_fn.into());
    }
}

/// Setup CompressionStream and DecompressionStream APIs
pub fn setup_compression_api(
    scope: &mut v8::ContextScope<v8::HandleScope>,
    context: &v8::Local<v8::Context>,
) -> Result<()> {
    let global: _ = context.global(scope);

    // Setup CompressionStream constructor with instance method for close
    let compression_template: _ = v8::FunctionTemplate::new(scope, compression_stream_constructor);

    // Add instance method for close by setting it on instances after construction
    // We'll add it directly to each instance in the constructor
    let compression_constructor: _ = compression_template.get_function(scope).unwrap();
    let compression_key: _ = v8::String::new(scope, "CompressionStream").unwrap();
    global.set(
        scope,
        compression_key.into(),
        compression_constructor.into(),
    );

    // Setup DecompressionStream constructor
    let decompression_template: _ =
        v8::FunctionTemplate::new(scope, decompression_stream_constructor);
    let decompression_constructor: _ = decompression_template.get_function(scope).unwrap();
    let decompression_key: _ = v8::String::new(scope, "DecompressionStream").unwrap();
    global.set(
        scope,
        decompression_key.into(),
        decompression_constructor.into(),
    );

    // Setup helper function for compression (_compressData)
    let compress_template = v8::FunctionTemplate::new(
        scope,
        |_scope: &mut v8::PinScope,
         args: v8::FunctionCallbackArguments,
         mut retval: v8::ReturnValue| {
            if args.length() >= 2 {
                let data_arg = args.get(0);
                let format_arg = args.get(1);

                if let Ok(data) = v8::Local::<v8::Uint8Array>::try_from(data_arg) {
                    let Some(bytes) = uint8_array_to_vec(_scope, data) else {
                        return;
                    };

                    let format_str = if format_arg.is_string() {
                        format_arg
                            .to_string(_scope)
                            .map(|s| s.to_rust_string_lossy(_scope))
                            .unwrap_or_else(|| "gzip".to_string())
                    } else {
                        "gzip".to_string()
                    };

                    // For deflate format, use streaming-compatible approach
                    // For gzip, we use GzEncoder which creates a complete gzip stream
                    let compressed = if format_str == "gzip" {
                        // Use GzEncoder from bufread with Cursor for proper BufRead
                        let cursor = Cursor::new(bytes);
                        let mut encoder = GzEncoder::new(cursor, Compression::default());
                        let mut output = Vec::new();
                        let _ = encoder.read_to_end(&mut output);
                        output
                    } else {
                        // For deflate, use the bufread encoder
                        let mut encoder = GzEncoder::new(bytes.as_slice(), Compression::default());
                        let mut output = Vec::new();
                        let _ = encoder.read_to_end(&mut output);
                        output
                    };

                    if let Some(result_array) = create_uint8_array(_scope, &compressed) {
                        retval.set(result_array.into());
                    }
                }
            }
        },
    );

    let compress_fn = compress_template.get_function(scope).unwrap();
    let compress_key = v8::String::new(scope, "_compressData").unwrap();
    global.set(scope, compress_key.into(), compress_fn.into());

    // Setup helper function for decompression (_decompressData)
    let decompress_template = v8::FunctionTemplate::new(
        scope,
        |_scope: &mut v8::PinScope,
         args: v8::FunctionCallbackArguments,
         mut retval: v8::ReturnValue| {
            if args.length() >= 2 {
                let data_arg = args.get(0);
                let format_arg = args.get(1);

                if let Ok(data) = v8::Local::<v8::Uint8Array>::try_from(data_arg) {
                    let Some(bytes) = uint8_array_to_vec(_scope, data) else {
                        return;
                    };

                    let format_str = if format_arg.is_string() {
                        format_arg
                            .to_string(_scope)
                            .map(|s| s.to_rust_string_lossy(_scope))
                            .unwrap_or_else(|| "gzip".to_string())
                    } else {
                        "gzip".to_string()
                    };

                    // Use GzDecoder from bufread with Cursor for proper BufRead
                    let decompressed = if format_str == "gzip" {
                        let cursor = Cursor::new(bytes);
                        let mut decoder = GzDecoder::new(cursor);
                        let mut output = Vec::new();
                        let _ = decoder.read_to_end(&mut output);
                        output
                    } else {
                        // For deflate, use bufread decoder
                        let mut decoder = GzDecoder::new(bytes.as_slice());
                        let mut output = Vec::new();
                        let _ = decoder.read_to_end(&mut output);
                        output
                    };

                    if let Some(result_array) = create_uint8_array(_scope, &decompressed) {
                        retval.set(result_array.into());
                    }
                }
            }
        },
    );

    let decompress_fn = decompress_template.get_function(scope).unwrap();
    let decompress_key = v8::String::new(scope, "_decompressData").unwrap();
    global.set(scope, decompress_key.into(), decompress_fn.into());

    Ok(())
}

/// CompressionStream constructor - full implementation with actual compression
fn compression_stream_constructor(
    scope: &mut v8::PinScope,
    args: v8::FunctionCallbackArguments,
    mut retval: v8::ReturnValue,
) {
    // Get format argument
    let format_arg = args.get(0);
    let format_str: String = if format_arg.is_string() {
        format_arg
            .to_string(scope)
            .map(|s| s.to_rust_string_lossy(scope).to_lowercase())
            .unwrap_or_else(|| "gzip".to_string())
    } else {
        "gzip".to_string()
    };

    // Validate format
    match format_str.as_str() {
        "gzip" | "deflate" => {}
        _ => {
            let error = v8::String::new(
                scope,
                &format!("CompressionStream: unsupported format '{}'", format_str),
            )
            .unwrap();
            let error_obj = v8::Exception::range_error(scope, error);
            scope.throw_exception(error_obj.into());
            return;
        }
    };

    // Create the compression stream object
    let this_obj: v8::Local<v8::Object> = args.this();

    // Store format property
    let format_key = v8::String::new(scope, "format").unwrap();
    let format_val = v8::String::new(scope, &format_str).unwrap();
    this_obj.set(scope, format_key.into(), format_val.into());

    // Store setup flag
    let setup_key = v8::String::new(scope, "_compressionSetup").unwrap();
    let setup_val = v8::Boolean::new(scope, true).into();
    this_obj.set(scope, setup_key.into(), setup_val);

    // Create streams with proper compression logic
    let factory_code = format!(
        r#"
(function() {{
    const format = '{}';
    let readableController = null;
    let writableController = null;
    let state = 0; // 0=open, 1=closed, 2=errored

    // Create readable stream with controller reference
    const readable = new ReadableStream({{
        start(controller) {{
            readableController = controller;
        }}
    }});

    // Create writable stream with compression
    const writable = new WritableStream({{
        start(controller) {{
            writableController = controller;
        }},
        async write(chunk) {{
            if (state !== 0 || !writableController || !readableController) return;

            // Get bytes from chunk
            let data;
            if (chunk instanceof Uint8Array) {{
                data = chunk;
            }} else if (typeof chunk === 'string') {{
                data = new TextEncoder().encode(chunk);
            }} else {{
                data = new Uint8Array(chunk);
            }}

            // Compress using the Rust helper function
            const compressed = _compressData(data, format);
            if (compressed && compressed.length > 0) {{
                readableController.enqueue(compressed);
            }}
        }},
        close() {{
            state = 1;
            if (readableController) {{
                readableController.close();
            }}
            writableController = null;
            readableController = null;
        }},
        abort(err) {{
            state = 2;
            if (readableController) {{
                readableController.error(err);
            }}
            writableController = null;
            readableController = null;
        }}
    }});

    return {{ readable, writable }};
}})"#,
        format_str
    );

    // Execute the factory code
    let factory_code_str = v8::String::new(scope, &factory_code).unwrap();
    if let Some(factory_script) = v8::Script::compile(scope, factory_code_str, None) {
        if let Some(factory_fn) = factory_script.run(scope) {
            if let Ok(factory) = v8::Local::<v8::Function>::try_from(factory_fn) {
                let undefined = v8::undefined(scope).into();
                if let Some(result) = factory.call(scope, undefined, &[]) {
                    if let Ok(result_obj) = v8::Local::<v8::Object>::try_from(result) {
                        // Extract readable stream
                        let readable_key = v8::String::new(scope, "readable").unwrap();
                        if let Some(readable_val) = result_obj.get(scope, readable_key.into()) {
                            this_obj.set(scope, readable_key.into(), readable_val);
                        }

                        // Extract writable stream
                        let writable_key = v8::String::new(scope, "writable").unwrap();
                        if let Some(writable_val) = result_obj.get(scope, writable_key.into()) {
                            this_obj.set(scope, writable_key.into(), writable_val);
                        }
                    }
                }
            }
        }
    }

    // Attach close method to this object
    attach_compression_close_method(scope, this_obj);

    retval.set(this_obj.into());
}

/// DecompressionStream constructor - full implementation with actual decompression
fn decompression_stream_constructor(
    scope: &mut v8::PinScope,
    args: v8::FunctionCallbackArguments,
    mut retval: v8::ReturnValue,
) {
    // Get format argument
    let format_arg = args.get(0);
    let format_str: String = if format_arg.is_string() {
        format_arg
            .to_string(scope)
            .map(|s| s.to_rust_string_lossy(scope).to_lowercase())
            .unwrap_or_else(|| "gzip".to_string())
    } else {
        "gzip".to_string()
    };

    // Validate format
    match format_str.as_str() {
        "gzip" | "deflate" => {}
        _ => {
            let error = v8::String::new(
                scope,
                &format!("DecompressionStream: unsupported format '{}'", format_str),
            )
            .unwrap();
            let error_obj = v8::Exception::range_error(scope, error);
            scope.throw_exception(error_obj.into());
            return;
        }
    };

    // Create the decompression stream object
    let this_obj: v8::Local<v8::Object> = args.this();

    // Store format property
    let format_key = v8::String::new(scope, "format").unwrap();
    let format_val = v8::String::new(scope, &format_str).unwrap();
    this_obj.set(scope, format_key.into(), format_val.into());

    // Store setup flag
    let setup_key = v8::String::new(scope, "_decompressionSetup").unwrap();
    let setup_val = v8::Boolean::new(scope, true).into();
    this_obj.set(scope, setup_key.into(), setup_val);

    // Create streams with proper decompression logic
    let factory_code = format!(
        r#"
(function() {{
    const format = '{}';
    let readableController = null;
    let writableController = null;
    let state = 0; // 0=open, 1=closed, 2=errored

    // Create readable stream
    const readable = new ReadableStream({{
        start(controller) {{
            readableController = controller;
        }}
    }});

    // Create writable stream with decompression
    const writable = new WritableStream({{
        start(controller) {{
            writableController = controller;
        }},
        async write(chunk) {{
            if (state !== 0 || !writableController || !readableController) return;

            // Get bytes from chunk
            let data;
            if (chunk instanceof Uint8Array) {{
                data = chunk;
            }} else if (typeof chunk === 'string') {{
                data = new TextEncoder().encode(chunk);
            }} else {{
                data = new Uint8Array(chunk);
            }}

            // Decompress using the Rust helper function
            const decompressed = _decompressData(data, format);
            if (decompressed && decompressed.length > 0) {{
                readableController.enqueue(decompressed);
            }}
        }},
        close() {{
            state = 1;
            if (readableController) {{
                readableController.close();
            }}
            writableController = null;
            readableController = null;
        }},
        abort(err) {{
            state = 2;
            if (readableController) {{
                readableController.error(err);
            }}
            writableController = null;
            readableController = null;
        }}
    }});

    return {{ readable, writable }};
}})"#,
        format_str
    );

    // Execute the factory code
    let factory_code_str = v8::String::new(scope, &factory_code).unwrap();
    if let Some(factory_script) = v8::Script::compile(scope, factory_code_str, None) {
        if let Some(factory_fn) = factory_script.run(scope) {
            if let Ok(factory) = v8::Local::<v8::Function>::try_from(factory_fn) {
                let undefined = v8::undefined(scope).into();
                if let Some(result) = factory.call(scope, undefined, &[]) {
                    if let Ok(result_obj) = v8::Local::<v8::Object>::try_from(result) {
                        // Extract readable stream
                        let readable_key = v8::String::new(scope, "readable").unwrap();
                        if let Some(readable_val) = result_obj.get(scope, readable_key.into()) {
                            this_obj.set(scope, readable_key.into(), readable_val);
                        }

                        // Extract writable stream
                        let writable_key = v8::String::new(scope, "writable").unwrap();
                        if let Some(writable_val) = result_obj.get(scope, writable_key.into()) {
                            this_obj.set(scope, writable_key.into(), writable_val);
                        }
                    }
                }
            }
        }
    }

    // Attach close method to this object
    attach_decompression_close_method(scope, this_obj);

    retval.set(this_obj.into());
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_compression_format_validation() {
        let valid_formats = vec!["gzip", "deflate"];
        let invalid_formats = vec!["invalid", "lzma", ""];

        for format in valid_formats {
            assert!(
                format == "gzip" || format == "deflate",
                "Valid format: {}",
                format
            );
        }

        for format in invalid_formats {
            assert!(
                format != "gzip" && format != "deflate",
                "Invalid format: {}",
                format
            );
        }
    }

    #[test]
    fn test_compression_level() {
        let _fast = Compression::fast();
        let _default = Compression::default();
        let _best = Compression::best();
    }
}