alef 0.23.29

Opinionated polyglot binding generator for Rust libraries
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
use super::*;
use crate::core::config::ResolvedCrateConfig;
use crate::core::ir::{
    ApiSurface, EntrypointDef, EntrypointKind, HandlerContractDef, MethodDef, ParamDef, PrimitiveType, ReceiverKind,
    RegistrationDef, ServiceDef, TypeRef,
};

/// Construct a minimal test config with default exclude settings.
fn make_test_config() -> ResolvedCrateConfig {
    ResolvedCrateConfig {
        name: "my_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    }
}

/// Construct a minimal but realistic [`ApiSurface`] that exercises:
/// - A service with a constructor, one configurator, one registration
///   (bound to an async handler contract), and Run entrypoint.
/// - One [`HandlerContractDef`] with wire request/response DTO names.
fn make_fixture_surface() -> ApiSurface {
    let constructor = MethodDef {
        name: "new".to_owned(),
        params: vec![],
        return_type: TypeRef::Unit,
        is_async: false,
        is_static: true,
        error_type: None,
        doc: "Create a new service owner.".to_owned(),
        receiver: None,
        sanitized: false,
        trait_source: None,
        returns_ref: false,
        returns_cow: false,
        return_newtype_wrapper: None,
        has_default_impl: false,
        binding_excluded: false,
        binding_exclusion_reason: None,
    };

    let configurator = MethodDef {
        name: "with_timeout".to_owned(),
        params: vec![ParamDef {
            name: "timeout_ms".to_owned(),
            ty: TypeRef::Primitive(PrimitiveType::U64),
            optional: false,
            default: None,
            ..ParamDef::default()
        }],
        return_type: TypeRef::Named("TestService".to_owned()),
        is_async: false,
        is_static: false,
        error_type: None,
        doc: "Set request timeout.".to_owned(),
        receiver: Some(ReceiverKind::RefMut),
        sanitized: false,
        trait_source: None,
        returns_ref: false,
        returns_cow: false,
        return_newtype_wrapper: None,
        has_default_impl: false,
        binding_excluded: false,
        binding_exclusion_reason: None,
    };

    let registration = RegistrationDef {
        method: "add_handler".to_owned(),
        callback_param: "handler".to_owned(),
        callback_contract: "RequestHandler".to_owned(),
        metadata_params: vec![
            ParamDef {
                name: "path".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            },
            ParamDef {
                name: "method".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            },
        ],
        receiver: Some(ReceiverKind::RefMut),
        return_type: TypeRef::Unit,
        error_type: None,
        doc: "Register a request handler for a path and method.".to_owned(),
        variants: vec![],
    };

    let run_ep = EntrypointDef {
        method: "run".to_owned(),
        kind: EntrypointKind::Run,
        is_async: true,
        params: vec![ParamDef {
            name: "addr".to_owned(),
            ty: TypeRef::String,
            optional: false,
            default: None,
            ..ParamDef::default()
        }],
        return_type: TypeRef::Unit,
        error_type: Some("ServiceError".to_owned()),
        doc: "Run the service.".to_owned(),
    };

    let service = ServiceDef {
        name: "TestService".to_owned(),
        rust_path: "my_crate::TestService".to_owned(),
        constructor,
        configurators: vec![configurator],
        registrations: vec![registration],
        entrypoints: vec![run_ep],
        doc: "A test service owner.".to_owned(),
        cfg: None,
    };

    let dispatch_method = MethodDef {
        name: "handle".to_owned(),
        params: vec![ParamDef {
            name: "request".to_owned(),
            ty: TypeRef::Named("RequestData".to_owned()),
            optional: false,
            default: None,
            ..ParamDef::default()
        }],
        return_type: TypeRef::Named("ResponseData".to_owned()),
        is_async: true,
        is_static: false,
        error_type: Some("HandlerError".to_owned()),
        doc: "Dispatch a request.".to_owned(),
        receiver: Some(ReceiverKind::Ref),
        sanitized: false,
        trait_source: None,
        returns_ref: false,
        returns_cow: false,
        return_newtype_wrapper: None,
        has_default_impl: false,
        binding_excluded: false,
        binding_exclusion_reason: None,
    };

    let contract = HandlerContractDef {
        trait_name: "RequestHandler".to_owned(),
        rust_path: "my_crate::RequestHandler".to_owned(),
        dispatch: dispatch_method,
        optional_methods: vec![],
        wire_request_type: Some("RequestData".to_owned()),
        wire_response_type: Some("ResponseData".to_owned()),
        dispatch_extra_params: vec![],
        wire_param_name: None,
        dispatch_return_type: None,
        response_adapter: None,
        doc: "Async trait for handling requests.".to_owned(),
    };

    ApiSurface {
        crate_name: "my_crate".to_owned(),
        version: "0.1.0".to_owned(),
        services: vec![service],
        handler_contracts: vec![contract],
        ..ApiSurface::default()
    }
}

#[test]
fn typescript_output_contains_service_class() {
    let surface = make_fixture_surface();
    let config = make_test_config();
    let output = gen_service_ts(&surface, "my_crate", &config);
    assert!(
        output.contains("export class TestService"),
        "expected `export class TestService` in output:\n{output}"
    );
}

#[test]
fn typescript_output_contains_constructor() {
    let surface = make_fixture_surface();
    let config = make_test_config();
    let output = gen_service_ts(&surface, "my_crate", &config);
    assert!(
        output.contains("constructor()"),
        "expected `constructor()` in output:\n{output}"
    );
}

#[test]
fn typescript_output_contains_private_registrations() {
    let surface = make_fixture_surface();
    let config = make_test_config();
    let output = gen_service_ts(&surface, "my_crate", &config);
    assert!(
        output.contains("private _registrations"),
        "expected `private _registrations` in output:\n{output}"
    );
}

#[test]
fn typescript_output_contains_configurator() {
    let surface = make_fixture_surface();
    let config = make_test_config();
    let output = gen_service_ts(&surface, "my_crate", &config);
    assert!(
        output.contains("with_timeout(timeout_ms: number)"),
        "expected `with_timeout` configurator:\n{output}"
    );
    assert!(
        output.contains("return this;"),
        "expected `return this;` in configurator:\n{output}"
    );
}

#[test]
fn typescript_output_contains_registration_method() {
    let surface = make_fixture_surface();
    let config = make_test_config();
    let output = gen_service_ts(&surface, "my_crate", &config);
    assert!(
        output.contains("add_handler(path: string, method: string)"),
        "expected `add_handler` registration method:\n{output}"
    );
}

#[test]
fn typescript_output_contains_run_entrypoint() {
    let surface = make_fixture_surface();
    let config = make_test_config();
    let output = gen_service_ts(&surface, "my_crate", &config);
    assert!(
        output.contains("async run(addr: string)"),
        "expected `async run` entrypoint:\n{output}"
    );
}

#[test]
fn rust_output_contains_handler_bridge() {
    let surface = make_fixture_surface();
    let config = ResolvedCrateConfig {
        name: "my_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };
    let output = gen_service_rs(&surface, &config);
    assert!(
        output.contains("pub struct RequestHandlerBridge"),
        "expected `RequestHandlerBridge` struct in output:\n{output}"
    );
}

#[test]
fn rust_output_contains_run_function() {
    let surface = make_fixture_surface();
    let config = ResolvedCrateConfig {
        name: "my_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };
    let output = gen_service_rs(&surface, &config);
    assert!(
        output.contains("pub async fn test_service_run"),
        "expected `test_service_run` function in output:\n{output}"
    );
}

#[test]
fn rust_output_contains_thread_safe_function() {
    let surface = make_fixture_surface();
    let config = ResolvedCrateConfig {
        name: "my_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };
    let output = gen_service_rs(&surface, &config);
    assert!(
        output.contains("ThreadsafeFunction"),
        "expected `ThreadsafeFunction` in output:\n{output}"
    );
}

#[test]
fn rust_output_implements_trait() {
    let surface = make_fixture_surface();
    let config = ResolvedCrateConfig {
        name: "my_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };
    let output = gen_service_rs(&surface, &config);
    assert!(
        output.contains("impl my_crate::RequestHandler for RequestHandlerBridge"),
        "expected trait impl in output:\n{output}"
    );
}

#[test]
fn rust_output_extracts_metadata_params() {
    let surface = make_fixture_surface();
    let config = ResolvedCrateConfig {
        name: "my_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };
    let output = gen_service_rs(&surface, &config);

    // Assert metadata params are extracted as real typed variables, not stubs
    assert!(
        !output.contains("/* placeholder: extract metadata */"),
        "expected no placeholder in output:\n{output}"
    );
    assert!(
        !output.contains("placeholder: extract metadata"),
        "expected no unsupported marker in output:\n{output}"
    );

    // Assert the "path" metadata param is extracted and declared with proper type
    assert!(
        output.contains("let path: String"),
        "expected `let path: String` extraction in output:\n{output}"
    );

    // Assert the "method" metadata param is extracted and declared with proper type
    assert!(
        output.contains("let method: String"),
        "expected `let method: String` extraction in output:\n{output}"
    );

    // Assert both metadata params are passed to the registration method call
    assert!(
        output.contains("owner.add_handler(path, method, handler)"),
        "expected owner.add_handler(path, method, handler) call in output:\n{output}"
    );

    // Assert metadata is accessed from the _metadata vector
    assert!(
        output.contains("_metadata.get("),
        "expected _metadata.get(...) access in output:\n{output}"
    );
}

#[test]
fn registration_variants_emit_napi_methods() {
    use crate::core::ir::{RegistrationVariant, WrapperConstructorArg, WrapperConstructorCall};

    let mut surface = make_fixture_surface();

    // Add a variant to the registration
    if let Some(reg) = surface.services[0].registrations.first_mut() {
        reg.variants.push(RegistrationVariant {
            name: "get".to_owned(),
            overrides: vec![],
            wrapper_call: Some(WrapperConstructorCall {
                metadata_param: "builder".to_owned(),
                wrapper_type_path: "my_crate::RouteBuilder".to_owned(),
                wrapper_type_name: "RouteBuilder".to_owned(),
                constructor_method: "new".to_owned(),
                args: vec![
                    WrapperConstructorArg::Fixed {
                        param_name: "method".to_owned(),
                        value_expr: "my_crate::Method::GET".to_owned(),
                    },
                    WrapperConstructorArg::Free {
                        param: ParamDef {
                            name: "path".to_owned(),
                            ty: TypeRef::String,
                            optional: false,
                            default: None,
                            ..ParamDef::default()
                        },
                    },
                ],
            }),
            signature_params: vec![ParamDef {
                name: "path".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            doc: Some("Register a GET handler.".to_owned()),
            style: Default::default(),
        });
    }

    let config = ResolvedCrateConfig {
        name: "my_crate".to_owned(),
        ..ResolvedCrateConfig::default()
    };
    let output = gen_service_rs(&surface, &config);

    // Assert the variant methods are wrapped in an impl block (default prefix "Js")
    assert!(
        output.contains("impl JsTestService {"),
        "expected `impl JsTestService {{` wrapping in output:\n{output}"
    );

    // Assert the use statement is emitted before the impl block
    assert!(
        output.contains("use crate::JsTestService;"),
        "expected `use crate::JsTestService;` in output:\n{output}"
    );

    // Assert the variant method is emitted with #[napi] (indented inside impl block)
    assert!(
        output.contains("#[napi]\n    pub fn get("),
        "expected `#[napi]\\n    pub fn get(` inside impl block in output:\n{output}"
    );

    // Assert the wrapper builder is constructed
    assert!(
        output.contains("my_crate::RouteBuilder::new("),
        "expected wrapper constructor call in output:\n{output}"
    );

    // Assert the fixed arg is substituted
    assert!(
        output.contains("my_crate::Method::GET"),
        "expected fixed arg substitution in output:\n{output}"
    );
}

#[test]
fn typescript_output_skips_excluded_entrypoint() {
    let surface = make_fixture_surface();
    let mut config = make_test_config();
    // Add the entrypoint method to the exclude list
    config.exclude.methods.push("TestService.run".to_string());

    let output = gen_service_ts(&surface, "my_crate", &config);

    // Should NOT contain the run method when excluded
    assert!(
        !output.contains("async run(addr: string)"),
        "excluded `async run` entrypoint should not be present:\n{output}"
    );

    // Should NOT import the native function when excluded
    assert!(
        !output.contains("import { test_service_run }"),
        "excluded native function import should not be present:\n{output}"
    );

    // But should still contain the class
    assert!(
        output.contains("export class TestService"),
        "service class should still be present even with excluded entrypoint:\n{output}"
    );
}

#[test]
fn rust_output_skips_excluded_entrypoint() {
    let surface = make_fixture_surface();
    let mut config = make_test_config();
    // Add the entrypoint method to the exclude list
    config.exclude.methods.push("TestService.run".to_string());

    let output = gen_service_rs(&surface, &config);

    // Should NOT contain the napi function when excluded
    assert!(
        !output.contains("pub async fn test_service_run"),
        "excluded `test_service_run` napi function should not be present:\n{output}"
    );

    // But should still contain the handler bridge
    assert!(
        output.contains("pub struct RequestHandlerBridge"),
        "RequestHandlerBridge should still be present even with excluded entrypoint:\n{output}"
    );
}

#[test]
fn typescript_variant_verb_decorator_style() {
    use crate::core::ir::{RegistrationVariant, RegistrationVariantStyle};

    let mut surface = make_fixture_surface();

    if let Some(reg) = surface.services[0].registrations.first_mut() {
        reg.variants.push(RegistrationVariant {
            name: "get".to_owned(),
            overrides: vec![],
            wrapper_call: None,
            signature_params: vec![ParamDef {
                name: "path".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            doc: Some("Register a GET handler.".to_owned()),
            style: RegistrationVariantStyle::VerbDecorator,
        });
    }

    let config = make_test_config();
    let output = gen_service_ts(&surface, "my_crate", &config);

    // VerbDecorator should emit only the direct form: get(path, handler): this
    assert!(
        output.contains("get(path: string, handler: (...args: any[]) => any): this"),
        "expected VerbDecorator form `get(path, handler): this` in output:\n{output}"
    );

    // Should return `this` for chaining
    assert!(
        output.contains("return this;"),
        "expected `return this;` for chaining in VerbDecorator form:\n{output}"
    );

    // Should NOT emit decorator-factory form
    let get_count = output.matches("  get(").count();
    assert_eq!(
        get_count, 1,
        "expected exactly one `get(` method in VerbDecorator style, found {}: {}",
        get_count, output
    );
}

#[test]
fn typescript_variant_builder_style() {
    use crate::core::ir::{RegistrationVariant, RegistrationVariantStyle};

    let mut surface = make_fixture_surface();

    if let Some(reg) = surface.services[0].registrations.first_mut() {
        reg.variants.push(RegistrationVariant {
            name: "get".to_owned(),
            overrides: vec![],
            wrapper_call: None,
            signature_params: vec![ParamDef {
                name: "path".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            doc: Some("Register a GET handler.".to_owned()),
            style: RegistrationVariantStyle::Builder,
        });
    }

    let config = make_test_config();
    let output = gen_service_ts(&surface, "my_crate", &config);

    // Builder should emit only the decorator-factory form: get(path) returns a function
    assert!(
        output.contains("get(path: string): (fn: (...args: any[]) => any) => (...args: any[]) => any"),
        "expected Builder form `get(path): (fn) => ...` in output:\n{output}"
    );

    // Should return the handler unchanged (for decorator form)
    assert!(
        output.contains("return fn;"),
        "expected `return fn;` in Builder form:\n{output}"
    );

    // Should NOT emit direct form with handler parameter
    assert!(
        !output.contains("get(path: string, handler: (...args: any[]) => any): this"),
        "Builder form should not emit direct method with handler parameter:\n{output}"
    );
}

#[test]
fn typescript_variant_hybrid_style() {
    use crate::core::ir::{RegistrationVariant, RegistrationVariantStyle};

    let mut surface = make_fixture_surface();

    if let Some(reg) = surface.services[0].registrations.first_mut() {
        reg.variants.push(RegistrationVariant {
            name: "get".to_owned(),
            overrides: vec![],
            wrapper_call: None,
            signature_params: vec![ParamDef {
                name: "path".to_owned(),
                ty: TypeRef::String,
                optional: false,
                default: None,
                ..ParamDef::default()
            }],
            doc: Some("Register a GET handler.".to_owned()),
            style: RegistrationVariantStyle::Hybrid,
        });
    }

    let config = make_test_config();
    let output = gen_service_ts(&surface, "my_crate", &config);

    // Hybrid should emit both forms
    assert!(
        output.contains("get(path: string, handler: (...args: any[]) => any): this"),
        "expected Hybrid to include direct form `get(path, handler): this`:\n{output}"
    );

    assert!(
        output.contains("get(path: string): (fn: (...args: any[]) => any) => (...args: any[]) => any"),
        "expected Hybrid to include factory form `get(path): (fn) => ...`:\n{output}"
    );

    // Should have both `return this;` and `return fn;`
    let this_count = output.matches("return this;").count();
    let fn_count = output.matches("return fn;").count();
    assert!(
        this_count >= 1 && fn_count >= 1,
        "Hybrid form should have both return forms; this={}, fn={}: {}",
        this_count,
        fn_count,
        output
    );
}

#[test]
fn rust_output_emits_entrypoint_methods_with_inner_accessor() {
    let config = {
        let mut cfg = make_test_config();
        // Register TestService with a host_app_inner_accessor so entrypoint methods are emitted
        cfg.services = vec![crate::core::config::ServiceConfig {
            owner_type: "TestService".to_string(),
            constructor: None,
            configurators: vec![],
            registrations: vec![],
            entrypoints: vec![],
            skip_languages: vec![],
            host_app_inner_accessor: Some("self.inner.lock().expect(\"mutex poisoned\")".to_string()),
        }];
        cfg
    };

    let api = make_fixture_surface();
    let output = gen_service_rs(&api, &config);

    // Should emit entrypoint method on the wrapper class (not just free function)
    assert!(
        output.contains("#[napi(js_name = \"nativeRun\")]"),
        "entrypoint method should have napi attribute with js_name; output:\n{output}"
    );

    assert!(
        output.contains("pub async fn run(&self, addr: String)"),
        "entrypoint method should be emitted as async method on wrapper; output:\n{output}"
    );

    // Should use the configured inner accessor to move the owner out before awaiting.
    assert!(
        output.contains("let mut guard = self.inner.lock().expect(\"mutex poisoned\");"),
        "entrypoint method should use configured inner accessor; output:\n{output}"
    );

    assert!(
        output.contains("owner.run(addr)"),
        "entrypoint method should call the inner method; output:\n{output}"
    );

    // The free function should still be emitted for backward compatibility
    assert!(
        output.contains("pub async fn test_service_run("),
        "free function entrypoint should still be emitted; output:\n{output}"
    );
}

#[test]
fn rust_output_skips_entrypoint_methods_without_inner_accessor() {
    let config = make_test_config();
    // No host_app_inner_accessor configured, so entrypoint methods should NOT be emitted

    let api = make_fixture_surface();
    let output = gen_service_rs(&api, &config);

    // Should NOT emit entrypoint method on the wrapper class
    assert!(
        !output.contains("#[napi(js_name = \"nativeRun\")]"),
        "entrypoint method should not be emitted without host_app_inner_accessor; output:\n{output}"
    );

    // The free function should still be emitted
    assert!(
        output.contains("pub async fn test_service_run("),
        "free function entrypoint should still be emitted; output:\n{output}"
    );
}