componentize-qjs-cli 0.1.0

CLI for converting JavaScript to WebAssembly components using QuickJS
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
//! Async component model tests for componentize-qjs.

mod common;

use std::pin::Pin;
use std::task::{Context, Poll};

use common::{TestCase, WasiCtxState};
use wasmtime::component::{
    Destination, StreamProducer, StreamReader, StreamResult, Val, VecBuffer,
};
use wasmtime::StoreContextMut;

#[tokio::test]
async fn test_async_echo_u32() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:async-echo;
            world async-echo {
                export echo-u32: async func(x: u32) -> u32;
            }
            "#,
        )
        .script("async function echoU32(x) { return x; }")
        .build_async()
        .await
        .unwrap();

    let result = instance
        .call1_async("echo-u32", &[Val::U32(42)])
        .await
        .unwrap();
    assert_eq!(result, Val::U32(42));
}

#[tokio::test]
async fn test_async_echo_string() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:async-echo;
            world async-echo {
                export echo-string: async func(s: string) -> string;
            }
            "#,
        )
        .script(r#"async function echoString(s) { return s; }"#)
        .build_async()
        .await
        .unwrap();

    let result = instance
        .call1_async("echo-string", &[Val::String("hello async".into())])
        .await
        .unwrap();
    assert_eq!(result, Val::String("hello async".into()));
}

#[tokio::test]
async fn test_async_echo_bool() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:async-echo;
            world async-echo {
                export echo-bool: async func(b: bool) -> bool;
            }
            "#,
        )
        .script("async function echoBool(b) { return b; }")
        .build_async()
        .await
        .unwrap();

    let result = instance
        .call1_async("echo-bool", &[Val::Bool(true)])
        .await
        .unwrap();
    assert_eq!(result, Val::Bool(true));
}

#[tokio::test]
async fn test_async_void_function() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:async-void;
            world async-void {
                export do-nothing: async func();
            }
            "#,
        )
        .script("async function doNothing() { }")
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("do-nothing", &[], 0).await.unwrap();
    assert!(results.is_empty());
}

#[tokio::test]
async fn test_async_with_await() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:async-await;
            world async-await {
                export delayed-echo: async func(x: u32) -> u32;
            }
            "#,
        )
        .script(
            r#"
            async function delayedEcho(x) {
                // Simulate async work with a resolved promise chain
                await Promise.resolve();
                return x + 1;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let result = instance
        .call1_async("delayed-echo", &[Val::U32(99)])
        .await
        .unwrap();
    assert_eq!(result, Val::U32(100));
}

#[tokio::test]
async fn test_async_echo_record() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:async-record;
            world async-record {
                record point {
                    x: f64,
                    y: f64,
                }
                export echo-point: async func(p: point) -> point;
            }
            "#,
        )
        .script(
            r#"
            async function echoPoint(p) {
                return { x: p.x * 2, y: p.y * 2 };
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let input = Val::Record(vec![
        ("x".to_string(), Val::Float64(1.5)),
        ("y".to_string(), Val::Float64(2.5)),
    ]);
    let result = instance.call1_async("echo-point", &[input]).await.unwrap();

    match result {
        Val::Record(fields) => {
            assert_eq!(fields.len(), 2);
            assert_eq!(fields[0].0, "x");
            assert_eq!(fields[1].0, "y");
            assert_eq!(fields[0].1, Val::Float64(3.0));
            assert_eq!(fields[1].1, Val::Float64(5.0));
        }
        other => panic!("expected Record, got {:?}", other),
    }
}

#[tokio::test]
async fn test_async_echo_option() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:async-option;
            world async-option {
                export echo-option: async func(x: option<u32>) -> option<u32>;
            }
            "#,
        )
        .script(
            r#"
            async function echoOption(x) {
                return x;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    // Some case
    let result = instance
        .call1_async("echo-option", &[Val::Option(Some(Box::new(Val::U32(42))))])
        .await
        .unwrap();
    assert_eq!(result, Val::Option(Some(Box::new(Val::U32(42)))));

    // None case
    let result = instance
        .call1_async("echo-option", &[Val::Option(None)])
        .await
        .unwrap();
    assert_eq!(result, Val::Option(None));
}

#[tokio::test]
async fn test_async_echo_result() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:async-result;
            world async-result {
                export safe-divide: async func(a: f64, b: f64) -> result<f64, string>;
            }
            "#,
        )
        .script(
            r#"
            async function safeDivide(a, b) {
                if (b === 0) {
                    return { tag: "err", val: "division by zero" };
                }
                return { tag: "ok", val: a / b };
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    // Ok case
    let result = instance
        .call1_async("safe-divide", &[Val::Float64(10.0), Val::Float64(2.0)])
        .await
        .unwrap();
    assert_eq!(result, Val::Result(Ok(Some(Box::new(Val::Float64(5.0))))));

    // Error case
    let result = instance
        .call1_async("safe-divide", &[Val::Float64(10.0), Val::Float64(0.0)])
        .await
        .unwrap();
    assert_eq!(
        result,
        Val::Result(Err(Some(Box::new(Val::String("division by zero".into())))))
    );
}

#[tokio::test]
async fn test_async_echo_list() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:async-list;
            world async-list {
                export double-list: async func(xs: list<u32>) -> list<u32>;
            }
            "#,
        )
        .script(
            r#"
            async function doubleList(xs) {
                return xs.map(x => x * 2);
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let input = Val::List(vec![Val::U32(1), Val::U32(2), Val::U32(3)]);
    let result = instance.call1_async("double-list", &[input]).await.unwrap();
    assert_eq!(
        result,
        Val::List(vec![Val::U32(2), Val::U32(4), Val::U32(6)])
    );
}

#[tokio::test]
async fn test_stream_create_and_return_u8() {
    // Verify stream<u8> factory creates valid stream handles
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:stream-u8;
            world stream-u8 {
                export make-stream: async func() -> stream<u8>;
            }
            "#,
        )
        .script(
            r#"
            async function makeStream() {
                const { readable, writable } = wit.Stream();
                writable.drop();
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("make-stream", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_stream_create_and_return_u32() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:stream-u32;
            world stream-u32 {
                export make-stream: async func() -> stream<u32>;
            }
            "#,
        )
        .script(
            r#"
            async function makeStream() {
                const { readable, writable } = wit.Stream();
                writable.drop();
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("make-stream", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_stream_create_and_return_string() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:stream-string;
            world stream-string {
                export make-stream: async func() -> stream<string>;
            }
            "#,
        )
        .script(
            r#"
            async function makeStream() {
                const { readable, writable } = wit.Stream();
                writable.drop();
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("make-stream", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_stream_object_return_shape() {
    // Verify the factory returns { readable, writable } not [writable, readable]
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:stream-shape;
            world stream-shape {
                export check-shape: async func() -> stream<u8>;
            }
            "#,
        )
        .script(
            r#"
            async function checkShape() {
                const pair = wit.Stream();
                // Verify it's an object with named properties
                if (pair.readable === undefined) throw new Error("missing readable");
                if (pair.writable === undefined) throw new Error("missing writable");
                if (typeof pair.readable.read !== 'function') throw new Error("readable missing read");
                if (typeof pair.writable.write !== 'function') throw new Error("writable missing write");
                pair.writable.drop();
                return pair.readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("check-shape", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_stream_enum_factory() {
    // Verify wit.Stream(wit.Stream.U8) works with enum constants
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:stream-enum;
            world stream-enum {
                export check-enum: async func() -> stream<u8>;
            }
            "#,
        )
        .script(
            r#"
            async function checkEnum() {
                const { readable, writable } = wit.Stream(wit.Stream.U8);
                if (readable === undefined) throw new Error("missing readable");
                if (writable === undefined) throw new Error("missing writable");
                writable.drop();
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("check-enum", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_future_enum_factory() {
    // Verify wit.Future(wit.Future.STRING) works with enum constants
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:future-enum;
            world future-enum {
                export check-enum: async func() -> future<string>;
            }
            "#,
        )
        .script(
            r#"
            async function checkEnum() {
                const { readable, writable } = wit.Future(wit.Future.STRING);
                if (readable === undefined) throw new Error("missing readable");
                if (writable === undefined) throw new Error("missing writable");
                writable.write("test");
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("check-enum", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_stream_record_type_constant() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:stream-record;
            world stream-record {
                record point { x: f64, y: f64 }
                export make-stream: async func() -> stream<point>;
            }
            "#,
        )
        .script(
            r#"
            async function makeStream() {
                // Use the named record type constant
                const { readable, writable } = wit.Stream(wit.Stream.POINT);
                writable.drop();
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("make-stream", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_stream_result_type_constant() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:stream-result;
            world stream-result {
                export make-stream: async func() -> stream<result<string, u32>>;
            }
            "#,
        )
        .script(
            r#"
            async function makeStream() {
                const { readable, writable } = wit.Stream(wit.Stream.RESULT_STRING_U32);
                writable.drop();
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("make-stream", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_stream_option_type_constant() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:stream-option;
            world stream-option {
                export make-stream: async func() -> stream<option<u32>>;
            }
            "#,
        )
        .script(
            r#"
            async function makeStream() {
                const { readable, writable } = wit.Stream(wit.Stream.OPTION_U32);
                writable.drop();
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("make-stream", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_stream_tuple_type_constant() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:stream-tuple;
            world stream-tuple {
                export make-stream: async func() -> stream<tuple<u32, string>>;
            }
            "#,
        )
        .script(
            r#"
            async function makeStream() {
                const { readable, writable } = wit.Stream(wit.Stream.TUPLE_U32_STRING);
                writable.drop();
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("make-stream", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_future_result_type_constant() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:future-result;
            world future-result {
                export make-future: async func() -> future<result<string, string>>;
            }
            "#,
        )
        .script(
            r#"
            async function makeFuture() {
                const { readable, writable } = wit.Future(wit.Future.RESULT_STRING_STRING);
                writable.write({ tag: "ok", val: "hello" });
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("make-future", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_stream_build_with_input_output() {
    // Verify component builds when WIT has stream params and returns
    let _instance = TestCase::new()
        .wit(
            r#"
            package test:stream-io;
            world stream-io {
                export echo-bytes: async func(input: stream<u8>) -> stream<u8>;
            }
            "#,
        )
        .script(
            r#"
            async function echoBytes(input) {
                const { readable, writable } = wit.Stream();
                (async () => {
                    const data = await input.read(1024);
                    await writable.write(data);
                    writable.drop();
                })();
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();
}

#[tokio::test]
async fn test_future_create_and_return_u32() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:future-u32;
            world future-u32 {
                export make-future: async func() -> future<u32>;
            }
            "#,
        )
        .script(
            r#"
            async function makeFuture() {
                const { readable, writable } = wit.Future();
                // Fire-and-forget write: completes when host reads the future
                writable.write(42);
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("make-future", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_future_create_and_return_string() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:future-string;
            world future-string {
                export make-future: async func() -> future<string>;
            }
            "#,
        )
        .script(
            r#"
            async function makeFuture() {
                const { readable, writable } = wit.Future();
                writable.write("hello from future");
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("make-future", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_future_object_return_shape() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:future-shape;
            world future-shape {
                export check-shape: async func() -> future<string>;
            }
            "#,
        )
        .script(
            r#"
            async function checkShape() {
                const pair = wit.Future();
                if (pair.readable === undefined) throw new Error("missing readable");
                if (pair.writable === undefined) throw new Error("missing writable");
                if (typeof pair.readable.read !== 'function') throw new Error("readable missing read");
                if (typeof pair.writable.write !== 'function') throw new Error("writable missing write");
                pair.writable.write("test");
                return pair.readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let results = instance.call_async("check-shape", &[], 1).await.unwrap();
    assert_eq!(results.len(), 1);
}

#[tokio::test]
async fn test_future_build_with_input_output() {
    // Verify component builds when WIT has future params and returns
    let _instance = TestCase::new()
        .wit(
            r#"
            package test:future-io;
            world future-io {
                export echo-future: async func(input: future<string>) -> future<string>;
            }
            "#,
        )
        .script(
            r#"
            async function echoFuture(input) {
                const { readable, writable } = wit.Future();
                (async () => {
                    const val = await input.read();
                    await writable.write(val);
                })();
                return readable;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();
}

#[tokio::test]
async fn test_async_multiple_awaits() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:multi-await;
            world multi-await {
                export chain: async func(x: u32) -> u32;
            }
            "#,
        )
        .script(
            r#"
            async function chain(x) {
                let result = x;
                // Multiple promise resolutions to test the callback loop
                result = await Promise.resolve(result + 1);
                result = await Promise.resolve(result + 1);
                result = await Promise.resolve(result + 1);
                return result;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let result = instance
        .call1_async("chain", &[Val::U32(10)])
        .await
        .unwrap();
    assert_eq!(result, Val::U32(13));
}

#[tokio::test]
async fn test_async_error_in_promise() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:async-error;
            world async-error {
                export might-fail: async func(fail: bool) -> u32;
            }
            "#,
        )
        .script(
            r#"
            async function mightFail(fail) {
                if (fail) {
                    throw new Error("intentional failure");
                }
                return 42;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    // Success case
    let result = instance
        .call1_async("might-fail", &[Val::Bool(false)])
        .await
        .unwrap();
    assert_eq!(result, Val::U32(42));

    let result = instance
        .call_async("might-fail", &[Val::Bool(true)], 1)
        .await;

    assert!(result.is_ok() || result.is_err());
}

#[tokio::test]
async fn test_async_result_no_error_payload() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:async-result-no-err;
            world async-result-no-err {
                export validate: async func(x: u32) -> result<u32>;
            }
            "#,
        )
        .script(
            r#"
            async function validate(x) {
                if (x > 100) {
                    return { tag: "err" };
                }
                return { tag: "ok", val: x * 2 };
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let result = instance
        .call1_async("validate", &[Val::U32(50)])
        .await
        .unwrap();
    assert_eq!(result, Val::Result(Ok(Some(Box::new(Val::U32(100))))));

    let result = instance
        .call1_async("validate", &[Val::U32(200)])
        .await
        .unwrap();
    assert_eq!(result, Val::Result(Err(None)));
}

#[tokio::test]
async fn test_async_variant_mixed_payloads() {
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:async-variant;
            world async-variant {
                variant response {
                    empty,
                    message(string),
                    code(u32),
                }
                export process: async func(kind: u32) -> response;
            }
            "#,
        )
        .script(
            r#"
            async function process(kind) {
                if (kind === 0) return { tag: 0 };
                if (kind === 1) return { tag: 1, val: "hello" };
                return { tag: 2, val: 42 };
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    let result = instance
        .call1_async("process", &[Val::U32(0)])
        .await
        .unwrap();

    match &result {
        Val::Variant(name, val) => {
            assert_eq!(name, "empty");
            assert!(val.is_none());
        }
        other => panic!("expected Variant, got {:?}", other),
    }

    // String payload case
    let result = instance
        .call1_async("process", &[Val::U32(1)])
        .await
        .unwrap();
    match &result {
        Val::Variant(name, val) => {
            assert_eq!(name, "message");
            assert_eq!(**val.as_ref().unwrap(), Val::String("hello".into()));
        }
        other => panic!("expected Variant, got {:?}", other),
    }

    // U32 payload case
    let result = instance
        .call1_async("process", &[Val::U32(2)])
        .await
        .unwrap();
    match &result {
        Val::Variant(name, val) => {
            assert_eq!(name, "code");
            assert_eq!(**val.as_ref().unwrap(), Val::U32(42));
        }
        other => panic!("expected Variant, got {:?}", other),
    }
}

/// A StreamProducer that yields a fixed set of bytes.
struct ByteProducer {
    data: Vec<u8>,
    offset: usize,
}

impl ByteProducer {
    fn new(data: Vec<u8>) -> Self {
        Self { data, offset: 0 }
    }
}

impl StreamProducer<WasiCtxState> for ByteProducer {
    type Item = u8;
    type Buffer = VecBuffer<u8>;

    fn poll_produce<'a>(
        mut self: Pin<&mut Self>,
        _cx: &mut Context<'_>,
        _store: StoreContextMut<'a, WasiCtxState>,
        mut destination: Destination<'a, Self::Item, Self::Buffer>,
        _finish: bool,
    ) -> Poll<wasmtime::Result<StreamResult>> {
        if self.offset >= self.data.len() {
            return Poll::Ready(Ok(StreamResult::Dropped));
        }
        let remaining = &self.data[self.offset..];
        let buf = VecBuffer::from(remaining.to_vec());
        self.offset = self.data.len();
        destination.set_buffer(buf);
        Poll::Ready(Ok(StreamResult::Dropped))
    }
}

#[tokio::test]
async fn test_host_stream_to_guest() {
    // Host provides stream<u8>, JS guest reads it and returns the count
    let mut instance = TestCase::new()
        .wit(
            r#"
            package test:host-stream;
            world host-stream {
                export count-bytes: async func(input: stream<u8>) -> u32;
            }
            "#,
        )
        .script(
            r#"
            async function countBytes(input) {
                let total = 0;
                const data = await input.read(1024);
                total += data.length;
                input.drop();
                return total;
            }
            "#,
        )
        .build_async()
        .await
        .unwrap();

    // Create a host-side stream producing 5 bytes
    let (inst, store) = instance.parts();
    let reader = StreamReader::new(&mut *store, ByteProducer::new(vec![1, 2, 3, 4, 5]));

    // Get the typed function and call it with the stream
    let func = inst
        .get_typed_func::<(StreamReader<u8>,), (u32,)>(&mut *store, "count-bytes")
        .unwrap();

    let (count,) = func.call_async(&mut *store, (reader,)).await.unwrap();

    assert_eq!(count, 5);
}