Skip to main content

hyprstream_ts_codegen/ts_codegen/
client.rs

1//! Generate TypeScript client classes and scoped client factories.
2//!
3//! Each service gets a `{Service}Client` class that wraps builder/parser functions
4//! and provides typed method calls. Scoped clients (detected from nested union patterns)
5//! get their own classes with curried scope fields.
6//!
7//! Scoped client methods call deterministic builder functions and unwrap responses
8//! through the ancestor chain, matching the Rust codegen pattern exactly.
9
10use hyprstream_rpc_build::schema::types::{FieldDef, ParsedSchema, ScopedClient};
11use hyprstream_rpc_build::util::{to_camel_case, to_pascal_case};
12
13/// Emit an error-variant check that throws an `Error` with the RPC error message.
14///
15/// Generates:
16/// ```text
17/// if ({parsed_var}.variant === 'error') {
18///   throw new Error(({parsed_var}.data as { message?: string })?.message ?? 'RPC error');
19/// }
20/// ```
21fn emit_error_throw(out: &mut String, parsed_var: &str) {
22    out.push_str(&format!(
23        "    if ({parsed_var}.variant === 'error') {{\n\
24         \x20     throw new Error(({parsed_var}.data as {{ message?: string }})?.message ?? 'RPC error');\n\
25         \x20   }}\n"
26    ));
27}
28
29use super::{capnp_to_ts_type, is_primitive};
30
31/// Check if any method in the schema returns StreamInfo (indicating streaming support needed).
32pub fn has_streaming_methods(schema: &ParsedSchema) -> bool {
33    schema
34        .response_variants
35        .iter()
36        .any(|v| v.type_name == "StreamInfo")
37        || schema.scoped_clients.iter().any(has_streaming_in_scoped)
38}
39
40fn has_streaming_in_scoped(sc: &ScopedClient) -> bool {
41    sc.inner_response_variants
42        .iter()
43        .any(|v| v.type_name == "StreamInfo")
44        || sc.nested_clients.iter().any(has_streaming_in_scoped)
45}
46
47/// Generate the main client class and scoped client classes.
48///
49/// Clients take a `WasmRpcClient` (from wasm-bindgen) and call only its
50/// service-and-method-bound exports. The method metadata is generated
51/// independently from the canonical Cap'n Proto request union.
52pub fn generate_client(out: &mut String, service_name: &str, schema: &ParsedSchema) {
53    let pascal = to_pascal_case(service_name);
54
55    let has_streaming = has_streaming_methods(schema);
56
57    // Import the exact method-bound WasmRpcClient surface.
58    out.push_str(
59        "/** Per-call authentication overrides for generated RPC methods. */\n\
60         export interface RpcCallOptions {\n\
61         \x20 jwt?: string;\n\
62         \x20 delegatedBearer?: string;\n\
63         }\n\n\
64         /** RPC client interface (matches RpcClient from wasm-bindgen). */\n\
65         export interface RpcTransport {\n\
66         \x20 callForServiceWithMethod(service: string, method: number, bytes: Uint8Array): Promise<Uint8Array>;\n\
67         \x20 callWithOptionsForServiceWithMethod(service: string, method: number, bytes: Uint8Array, jwt?: string, delegatedBearer?: string): Promise<Uint8Array>;\n",
68    );
69    if has_streaming {
70        out.push_str(
71            "  openStreamForServiceWithMethod(service: string, method: number, bytes: Uint8Array): Promise<StreamHandle>;\n\
72             \x20 openStreamWithOptionsForServiceWithMethod(service: string, method: number, bytes: Uint8Array, jwt?: string, delegatedBearer?: string): Promise<StreamHandle>;\n",
73        );
74    }
75    out.push_str(
76        "\x20 nextId(): bigint;\n\
77         }\n\n",
78    );
79
80    // Main client class
81    out.push_str(&format!(
82        "export class {pascal}Client {{\n\
83         \x20 constructor(private readonly client: RpcTransport) {{}}\n\n"
84    ));
85
86    // Filter out scoped variants (they become factory methods)
87    let scoped_names: Vec<&str> = schema
88        .scoped_clients
89        .iter()
90        .map(|sc| sc.factory_name.as_str())
91        .collect();
92
93    // Non-scoped methods on the main client
94    for variant in &schema.request_variants {
95        if scoped_names.contains(&variant.name.as_str()) {
96            continue; // handled as factory method
97        }
98
99        let method_discriminator = schema
100            .request_struct
101            .as_ref()
102            .and_then(|request| {
103                request
104                    .fields
105                    .iter()
106                    .find(|field| field.name == variant.name && field.discriminant_value != 0xFFFF)
107            })
108            .map(|field| field.discriminant_value)
109            .expect("generated TypeScript method must have a root union discriminator");
110
111        let is_void = variant.type_name == "Void";
112        let is_prim = is_primitive(&variant.type_name) && !is_void;
113        let payload_struct = if !is_void && !is_prim {
114            schema.structs.iter().find(|s| s.name == variant.type_name)
115        } else {
116            None
117        };
118
119        // Return type from matching response variant
120        let resp_variant_name = format!("{}Result", variant.name);
121        let resp_variant = schema
122            .response_variants
123            .iter()
124            .find(|v| v.name == resp_variant_name);
125        let resp_type_name = resp_variant
126            .map(|v| v.type_name.as_str())
127            .unwrap_or("unknown");
128        let is_streaming = resp_type_name == "StreamInfo";
129        let return_type = if is_streaming {
130            "StreamHandle".into()
131        } else {
132            capnp_to_ts_type(resp_type_name)
133        };
134
135        // Method signature
136        let mut params = Vec::new();
137        if let Some(ps) = payload_struct {
138            params.push(format!("p: {}", ps.name));
139        } else if is_prim {
140            params.push(format!("p: {}", capnp_to_ts_type(&variant.type_name)));
141        }
142
143        params.push("options?: RpcCallOptions".to_owned());
144        out.push_str(&format!(
145            "  async {}({}): Promise<{}> {{\n",
146            to_camel_case(&variant.name),
147            params.join(", "),
148            return_type
149        ));
150
151        // Build the request
152        let builder_name = format!("build{pascal}Request_{}", variant.name);
153        if is_void {
154            out.push_str(&format!(
155                "    const bytes = {builder_name}(this.client.nextId());\n"
156            ));
157        } else {
158            out.push_str(&format!(
159                "    const bytes = {builder_name}(this.client.nextId(), p);\n"
160            ));
161        }
162
163        if is_streaming {
164            // Streaming method: use callStreaming and return StreamSubscription
165            generate_streaming_body(out, service_name, method_discriminator);
166        } else {
167            // Call transport and parse response
168            emit_bound_unary_call(out, service_name, method_discriminator);
169            out.push_str(&format!(
170                "    const parsed = parse{pascal}Response(resp);\n"
171            ));
172
173            // Error handling
174            emit_error_throw(out, "parsed");
175            out.push_str(&format!("    return parsed.data as {};\n", return_type));
176        }
177        out.push_str("  }\n\n");
178    }
179
180    // Factory methods for scoped clients
181    for sc in &schema.scoped_clients {
182        let params: Vec<String> = sc
183            .scope_fields
184            .iter()
185            .map(|f| {
186                format!(
187                    "{}: {}",
188                    to_camel_case(&f.name),
189                    capnp_to_ts_type(&f.type_name)
190                )
191            })
192            .collect();
193        let args: Vec<String> = sc
194            .scope_fields
195            .iter()
196            .map(|f| to_camel_case(&f.name))
197            .collect();
198
199        out.push_str(&format!(
200            "  {}({}): {} {{\n",
201            to_camel_case(&sc.factory_name),
202            params.join(", "),
203            sc.client_name
204        ));
205        out.push_str(&format!(
206            "    return new {}(this.client, {});\n",
207            sc.client_name,
208            args.join(", ")
209        ));
210        out.push_str("  }\n\n");
211    }
212
213    out.push_str("}\n\n");
214
215    // Generate scoped client classes. The authenticated method commitment is
216    // the root request union arm that selects the scoped request schema.
217    for sc in &schema.scoped_clients {
218        let root_method_discriminator = schema
219            .request_struct
220            .as_ref()
221            .and_then(|request| {
222                request.fields.iter().find(|field| {
223                    field.name == sc.factory_name && field.discriminant_value != 0xFFFF
224                })
225            })
226            .map(|field| field.discriminant_value)
227            .expect("generated scoped TypeScript method must have a root union discriminator");
228        generate_scoped_client(
229            out,
230            service_name,
231            sc,
232            &[],
233            schema,
234            root_method_discriminator,
235        );
236    }
237}
238
239/// Generate a scoped client class (e.g., RepositoryClient).
240///
241/// `ancestors` tracks the scoped client chain from outermost to the parent of `sc`.
242/// The constructor receives ALL accumulated scope fields from ancestors + own.
243/// Methods call deterministic builder functions with the full scope chain.
244fn generate_scoped_client(
245    out: &mut String,
246    service_name: &str,
247    sc: &ScopedClient,
248    ancestors: &[&ScopedClient],
249    schema: &ParsedSchema,
250    root_method_discriminator: u16,
251) {
252    let pascal = to_pascal_case(service_name);
253
254    // All scope fields from ancestors + current
255    let all_scope_fields: Vec<&FieldDef> = ancestors
256        .iter()
257        .flat_map(|a| a.scope_fields.iter())
258        .chain(sc.scope_fields.iter())
259        .collect();
260
261    // Build the name chain for builder function references (matches builders.rs naming)
262    let mut name_chain = String::new();
263    for anc in ancestors {
264        name_chain.push_str(&format!("_{}", anc.factory_name));
265    }
266    name_chain.push_str(&format!("_{}", sc.factory_name));
267
268    // Constructor: transport + all accumulated scope fields
269    let scope_params: Vec<String> = all_scope_fields
270        .iter()
271        .map(|f| {
272            format!(
273                "private readonly {}: {}",
274                to_camel_case(&f.name),
275                capnp_to_ts_type(&f.type_name)
276            )
277        })
278        .collect();
279
280    out.push_str(&format!("export class {} {{\n", sc.client_name));
281    out.push_str("  constructor(\n    private readonly client: RpcTransport,\n");
282    for p in &scope_params {
283        out.push_str(&format!("    {p},\n"));
284    }
285    out.push_str("  ) {}\n\n");
286
287    // Nested scoped client factory names (their variants become factories, not methods)
288    let nested_names: Vec<&str> = sc
289        .nested_clients
290        .iter()
291        .map(|nc| nc.factory_name.as_str())
292        .collect();
293
294    // Chain depth for response unwrapping (ancestors + current scope)
295    let chain_depth = ancestors.len() + 1;
296
297    // Methods for each inner variant
298    for variant in &sc.inner_request_variants {
299        if nested_names.contains(&variant.name.as_str()) {
300            continue;
301        }
302
303        let is_void = variant.type_name == "Void";
304        let is_prim = is_primitive(&variant.type_name) && !is_void;
305        let payload_struct = if !is_void && !is_prim {
306            schema.structs.iter().find(|s| s.name == variant.type_name)
307        } else {
308            None
309        };
310
311        // Return type from matching inner response variant.
312        // Inner response variants use bare names (e.g., "generateStream"),
313        // NOT the "Result" suffix used by top-level response variants.
314        let resp_variant = sc
315            .inner_response_variants
316            .iter()
317            .find(|v| v.name == variant.name);
318        let resp_type_name = resp_variant
319            .map(|v| v.type_name.as_str())
320            .unwrap_or("unknown");
321        let is_streaming = resp_type_name == "StreamInfo";
322        let return_type = if is_streaming {
323            "StreamHandle".into()
324        } else {
325            capnp_to_ts_type(resp_type_name)
326        };
327
328        let mut params = Vec::new();
329        if let Some(ps) = payload_struct {
330            params.push(format!("p: {}", ps.name));
331        } else if is_prim {
332            params.push(format!("p: {}", capnp_to_ts_type(&variant.type_name)));
333        }
334
335        params.push("options?: RpcCallOptions".to_owned());
336        out.push_str(&format!(
337            "  async {}({}): Promise<{}> {{\n",
338            to_camel_case(&variant.name),
339            params.join(", "),
340            return_type
341        ));
342
343        // Build the request using the scoped builder function
344        // Name matches builders.rs: build{Pascal}Request{name_chain}_{method}
345        let builder_name = format!("build{pascal}Request{name_chain}_{}", variant.name);
346
347        // Builder args: transport.nextId() + all scope fields + optional payload
348        let mut builder_args = vec!["this.client.nextId()".to_owned()];
349        for f in &all_scope_fields {
350            builder_args.push(format!("this.{}", to_camel_case(&f.name)));
351        }
352        if !is_void {
353            builder_args.push("p".to_owned());
354        }
355
356        out.push_str(&format!(
357            "    const bytes = {builder_name}({});\n",
358            builder_args.join(", ")
359        ));
360
361        if is_streaming {
362            // Streaming method: use callStreaming and unwrap through scope chain to get StreamInfo
363            generate_streaming_body(out, service_name, root_method_discriminator);
364        } else {
365            // Call transport and parse outer response
366            emit_bound_unary_call(out, service_name, root_method_discriminator);
367            out.push_str(&format!(
368                "    const parsed = parse{pascal}Response(resp);\n"
369            ));
370
371            // Error handling at outer level
372            emit_error_throw(out, "parsed");
373
374            // Unwrap through the scoped response chain.
375            // The parser returns nested { variant, data: { variant, data: ... } } for scoped responses.
376            // Each chain level adds one layer of wrapping.
377            let mut current_var = "parsed.data".to_owned();
378            for depth in 0..chain_depth {
379                let inner_var = format!("_r{depth}");
380                out.push_str(&format!(
381                    "    const {inner_var} = {current_var} as {{ variant: string; data: unknown }};\n"
382                ));
383
384                if depth < chain_depth - 1 {
385                    // Intermediate level: just unwrap to next level
386                    current_var = format!("{inner_var}.data");
387                } else {
388                    // Final scope level: check for error and return the method result
389                    emit_error_throw(out, &inner_var);
390                    out.push_str(&format!(
391                        "    return {inner_var}.data as {};\n",
392                        return_type
393                    ));
394                }
395            }
396        }
397
398        out.push_str("  }\n\n");
399    }
400
401    // Nested scoped client factories
402    for nc in &sc.nested_clients {
403        let params: Vec<String> = nc
404            .scope_fields
405            .iter()
406            .map(|f| {
407                format!(
408                    "{}: {}",
409                    to_camel_case(&f.name),
410                    capnp_to_ts_type(&f.type_name)
411                )
412            })
413            .collect();
414        let args: Vec<String> = nc
415            .scope_fields
416            .iter()
417            .map(|f| to_camel_case(&f.name))
418            .collect();
419
420        // Pass ALL accumulated scope fields through (ancestors + current → child)
421        let mut all_args: Vec<String> = all_scope_fields
422            .iter()
423            .map(|f| format!("this.{}", to_camel_case(&f.name)))
424            .collect();
425        all_args.extend(args);
426
427        out.push_str(&format!(
428            "  {}({}): {} {{\n",
429            to_camel_case(&nc.factory_name),
430            params.join(", "),
431            nc.client_name
432        ));
433        out.push_str(&format!(
434            "    return new {}(this.client, {});\n",
435            nc.client_name,
436            all_args.join(", ")
437        ));
438        out.push_str("  }\n\n");
439    }
440
441    out.push_str("}\n\n");
442
443    // Recursively generate nested scoped clients with updated ancestors
444    let mut new_ancestors: Vec<&ScopedClient> = ancestors.to_vec();
445    new_ancestors.push(sc);
446    for nc in &sc.nested_clients {
447        generate_scoped_client(
448            out,
449            service_name,
450            nc,
451            &new_ancestors,
452            schema,
453            root_method_discriminator,
454        );
455    }
456}
457
458fn emit_bound_unary_call(out: &mut String, service_name: &str, method_discriminator: u16) {
459    out.push_str(&format!(
460        "    const resp = options\n\
461         \x20     ? await this.client.callWithOptionsForServiceWithMethod(\"{service_name}\", {method_discriminator}, bytes, options.jwt, options.delegatedBearer)\n\
462         \x20     : await this.client.callForServiceWithMethod(\"{service_name}\", {method_discriminator}, bytes);\n"
463    ));
464}
465
466fn generate_streaming_body(out: &mut String, service_name: &str, method_discriminator: u16) {
467    // All crypto (ECDH, key derivation, HMAC verification) happens in Rust.
468    // JS supplies independently generated service/method metadata and receives
469    // only the verified StreamHandle.
470    out.push_str(&format!(
471        "    return options\n\
472         \x20     ? await this.client.openStreamWithOptionsForServiceWithMethod(\"{service_name}\", {method_discriminator}, bytes, options.jwt, options.delegatedBearer)\n\
473         \x20     : await this.client.openStreamForServiceWithMethod(\"{service_name}\", {method_discriminator}, bytes);\n"
474    ));
475}
476
477#[cfg(test)]
478mod browser_binding_tests {
479    #![allow(clippy::expect_used)]
480
481    use super::*;
482    use hyprstream_rpc_build::schema::types::{FieldSection, StructDef, UnionVariant};
483
484    fn variant(name: &str, type_name: &str) -> UnionVariant {
485        UnionVariant {
486            name: name.to_owned(),
487            type_name: type_name.to_owned(),
488            description: String::new(),
489            scope: "invoke".to_owned(),
490            scope_exempt: false,
491            cli_hidden: false,
492            doc_example: String::new(),
493            vfs_path: String::new(),
494            vfs_kind: String::new(),
495            vfs_bulk: false,
496            vfs_hidden: false,
497            vfs_mac: String::new(),
498            dispatch_mac: String::new(),
499            dispatch_public: String::new(),
500            mutation_semantics: String::new(),
501            dispatch_mac_present: false,
502            dispatch_public_present: false,
503            mutation_semantics_present: false,
504        }
505    }
506
507    fn field(name: &str, discriminant_value: u16) -> FieldDef {
508        FieldDef {
509            name: name.to_owned(),
510            type_name: "Void".to_owned(),
511            description: String::new(),
512            fixed_size: None,
513            max_len: None,
514            optional: false,
515            slot_offset: 0,
516            section: FieldSection::Data,
517            discriminant_value,
518            serde_rename: None,
519            domain_type: None,
520        }
521    }
522
523    #[test]
524    fn generated_browser_calls_bind_service_method_options_and_streaming() {
525        let schema = ParsedSchema {
526            request_variants: vec![variant("ping", "Void"), variant("watch", "Void")],
527            response_variants: vec![
528                variant("pingResult", "Void"),
529                variant("watchResult", "StreamInfo"),
530            ],
531            structs: vec![],
532            scoped_clients: vec![],
533            enums: vec![],
534            request_struct: Some(StructDef {
535                name: "Request".to_owned(),
536                fields: vec![field("ping", 3), field("watch", 7)],
537                has_union: true,
538                domain_type: None,
539                origin_file: None,
540                data_words: 2,
541                pointer_words: 0,
542                discriminant_count: 2,
543                discriminant_offset: 4,
544                union_arms: vec![],
545            }),
546            response_struct: None,
547        };
548        let mut out = String::new();
549        generate_client(&mut out, "model", &schema);
550        assert!(
551            out.contains("callForServiceWithMethod(\"model\", 3, bytes)"),
552            "{out}"
553        );
554        assert!(
555            out.contains("callWithOptionsForServiceWithMethod(\"model\", 3, bytes"),
556            "{out}"
557        );
558        assert!(
559            out.contains("openStreamForServiceWithMethod(\"model\", 7, bytes)"),
560            "{out}"
561        );
562        assert!(
563            out.contains("openStreamWithOptionsForServiceWithMethod(\"model\", 7, bytes"),
564            "{out}"
565        );
566        assert!(!out.contains("this.client.call(bytes)"), "{out}");
567        assert!(!out.contains("this.client.openStream(bytes)"), "{out}");
568    }
569}