tauri-typed-ipc 0.1.10

Trait-based, type-safe Tauri IPC built on specta; sync by default, async opt-in.
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
//! TypeScript client generation.
//!
//! `#[procedures]` emits a [`ProcedureSet`] descriptor per trait: each
//! procedure's wire signature as specta data types, with the receiver
//! and any injected parameters already stripped. With the `export`
//! feature, [`Bindings`] renders that descriptor to a TypeScript client
//! whose calls are raw `invoke`s -- wire parity with the handler, so the
//! generated file drops in like any hand-written client.
//!
//! The client rides specta's own exporter through its `framework_runtime`
//! hook: tauri_typed_ipc contributes the command wrappers, specta owns the file
//! header, the type definitions, and the multi-file layout's cross-file
//! imports.

use specta::Types;
use specta::datatype::DataType;

/// One procedure's wire signature, lowered to specta data types. The
/// receiver and any injected parameter (an `AppHandle`, managed `State`)
/// are gone: only what the client supplies remains -- the named JSON
/// arguments, plus any streaming [`Channel`](crate::Channel) it passes.
#[derive(Clone)]
pub struct ProcedureType {
    /// Wire command name -- the Rust method's identifier, verbatim.
    pub name: &'static str,
    /// Named wire arguments, in declaration order.
    pub args: Vec<(&'static str, DataType)>,
    /// Streaming `Channel<T>` parameters, each paired with the value
    /// type `T` it sends. The client passes a `Channel`, so these stay
    /// in the binding (rendered as `Channel<T>`), unlike injected
    /// parameters; the inner `T` is what the descriptor carries.
    pub channels: Vec<(&'static str, DataType)>,
    /// Return type -- a `Result`'s success type `T`, or the plain return
    /// (`()` for no return). The procedure resolves with this.
    pub output: DataType,
    /// For a procedure returning `Result<T, E>`, the error `E` it rejects
    /// with (`E: tauri_typed_ipc::Error`); `None` for an infallible procedure.
    pub error: Option<ErrorType>,
}

/// A wire error's shape, generated by `#[derive(tauri_typed_ipc::Error)]` and
/// referenced by every procedure that rejects it. Each variant
/// serializes to `{ type, message }`, so the rendered TypeScript type is
/// a discriminated union over the tags. A built-in error with no variants (the
/// `String` drop-in) renders inline by `name` (`string`) and emits no
/// `export type` alias.
#[derive(Clone)]
pub struct ErrorType {
    /// The TypeScript type the rejection is thrown as -- a derived error's enum
    /// name, or a built-in scalar like `string`.
    pub name: &'static str,
    /// The per-variant `type` tags (lower-camel of each variant). Empty marks a
    /// built-in inline error (`String`), rendered by `name` with no alias.
    pub variants: Vec<&'static str>,
}

/// A trait's binding descriptor, generated by `#[procedures]` as the
/// zero-sized `{Trait}Procedures`. Implemented on a type, not built from
/// an instance, so a client can be rendered without standing up the
/// procedure set.
pub trait ProcedureSet {
    /// Name of the generated TypeScript object -- lower-camel of the
    /// trait (`Faders` -> `faders`), or the explicit `namespace`.
    const OBJECT: &'static str;

    /// An explicit wire namespace from `#[procedures(namespace = "x")]` (or
    /// the taurpc alias `path`): every command becomes `x.<method>` and the
    /// object is named `x`. `None` (default) keeps bare, raw-command wire.
    const NAMESPACE: Option<&'static str> = None;

    /// Collect each procedure's wire signature, registering any named
    /// types it touches into `types`.
    fn procedures(types: &mut Types) -> Vec<ProcedureType>;
}

/// A wire error's binding descriptor, generated by
/// `#[derive(tauri_typed_ipc::Error)]` and implemented on the enum itself, so a
/// procedure's `Result<_, E>` return can name the error it rejects with.
pub trait ErrorSet {
    /// The error's wire shape: its TypeScript name and variant tags.
    fn error_type() -> ErrorType;
}

/// `Result<_, String>` is a drop-in: a `String` error rejects as a bare string
/// on the wire (matching a raw `#[command]` and TauRPC), and the client types the
/// rejection as the built-in `string`. So a `String`-error procedure needs no
/// hand-written error enum -- the taurpc migration path. No variants marks it
/// inline (see [`ErrorType`]): `@throws {string}`, no `export type` alias.
impl ErrorSet for String {
    fn error_type() -> ErrorType {
        ErrorType {
            name: "string",
            variants: Vec::new(),
        }
    }
}

/// One event variant's wire signature, lowered to specta data types.
#[derive(Clone)]
pub struct EventType {
    /// Variant discriminant: the TypeScript `type` tag and the wire
    /// name's suffix.
    pub variant: &'static str,
    /// Wire name, `"{group}:{variant}"`.
    pub name: &'static str,
    /// Payload fields in declaration order (empty for unit and single
    /// tuple-payload variants).
    pub fields: Vec<(&'static str, DataType)>,
    /// A single unnamed tuple payload (`V(T)`): rendered as `data: T`
    /// instead of spread fields. `None` for unit and named variants.
    pub data: Option<DataType>,
}

/// An event enum's binding descriptor, generated by `#[derive(Event)]`
/// and implemented on the enum itself.
pub trait EventSet {
    /// The `events` object key -- lower-camel of the enum with a trailing
    /// `Event` stripped (`FaderEvent` -> `fader`).
    const GROUP: &'static str;
    /// The discriminated-union type name -- the enum's name.
    const NAME: &'static str;
    /// Collect each variant's payload signature, registering named types.
    fn events(types: &mut Types) -> Vec<EventType>;
}

#[cfg(feature = "export")]
pub use render::{Bindings, BindingsError, MethodCase};
#[cfg(feature = "export")]
pub use specta_typescript::Layout;

#[cfg(feature = "export")]
mod render {
    use super::{ErrorType, EventSet, EventType, ProcedureSet, ProcedureType};
    use specta::Types;
    use specta::datatype::DataType;
    use specta_typescript::{Error, Exporter, FrameworkExporter, Layout, Typescript};
    use std::borrow::Cow;
    use std::collections::{BTreeMap, HashSet};
    use std::path::{Path, PathBuf};
    use std::sync::atomic::{AtomicUsize, Ordering};

    /// The "do not edit" banner specta stamps at the top of every file.
    const HEADER: &str = "// This file has been generated by tauri_typed_ipc. DO NOT EDIT.";
    const IMPORT_INVOKE: &str = "import { invoke } from \"@tauri-apps/api/core\";\n";
    /// `Channel` ships from the same module as `invoke`, so a client with
    /// any streaming procedure imports both in one statement.
    const IMPORT_INVOKE_CHANNEL: &str =
        "import { invoke, Channel } from \"@tauri-apps/api/core\";\n";
    const IMPORT_LISTEN: &str = "import { listen } from \"@tauri-apps/api/event\";\n";

    /// How a generated client casts its TypeScript method names. The wire
    /// command name and argument keys are always the Rust identifiers
    /// verbatim (wire parity); argument names in the TypeScript signature
    /// are always camelCase. Only the method name varies.
    #[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
    pub enum MethodCase {
        /// `save_scene` -> `saveScene`. Idiomatic TypeScript, and the
        /// default -- matching the object and event naming.
        #[default]
        Camel,
        /// `save_scene` -> `save_scene`: the Rust identifier verbatim. The
        /// taurpc drop-in -- taurpc names its proxy methods this way
        /// (snake_case method, camelCase arguments), so a frontend
        /// migrating off it keeps its call sites.
        Snake,
    }

    /// Renders a TypeScript client for one or more procedure sets: a
    /// `const` object per set whose methods are wire-parity `invoke`
    /// calls, plus the specta type definitions they reference. One file
    /// by default; [`Layout::Files`] splits them into a directory.
    ///
    /// Wire types must have a symmetric serde shape (serialize ==
    /// deserialize). A type using an asymmetric attribute such as
    /// `skip_serializing_if` errors at export rather than rendering a
    /// wrong shape; per-direction rendering (args via the deserialize
    /// phase, output via serialize) is a post-0.1 enhancement.
    ///
    /// BigInt-style integers (`i64`, `u64`, `usize`, `i128`, ...) also
    /// error at export: lossless transport past 2^53 needs an upstream
    /// tauri invoke reviver hook (responses are parsed with
    /// `response.json()`, with no hook to add one), so it is post-0.1.
    #[must_use]
    pub struct Bindings {
        types: Types,
        sets: Vec<Set>,
        events: Vec<EventGroup>,
        layout: Layout,
        method_case: MethodCase,
        router: Option<Cow<'static, str>>,
        /// Emit the JSON Schema contract + a pre-invoke check into the client
        /// (the `validate` feature). Off by default.
        #[cfg(feature = "validate")]
        validate: bool,
    }

    #[derive(Clone)]
    struct Set {
        object: &'static str,
        namespace: Option<&'static str>,
        procedures: Vec<ProcedureType>,
    }

    #[derive(Clone)]
    struct EventGroup {
        group: &'static str,
        name: &'static str,
        variants: Vec<EventType>,
    }

    impl Bindings {
        /// Start an empty client, single file by default.
        pub fn new() -> Self {
            Self {
                types: Types::default(),
                sets: Vec::new(),
                events: Vec::new(),
                layout: Layout::default(),
                method_case: MethodCase::default(),
                router: None,
                #[cfg(feature = "validate")]
                validate: false,
            }
        }

        /// Choose the file layout. The default [`Layout::FlatFile`] is one
        /// file; [`Layout::Files`] splits the types into a directory of
        /// per-module files with cross-file imports -- write it with
        /// [`export_to`](Self::export_to).
        pub fn layout(mut self, layout: Layout) -> Self {
            self.layout = layout;
            self
        }

        /// Choose how generated method names are cased. Defaults to
        /// [`MethodCase::Camel`]; [`MethodCase::Snake`] is the taurpc
        /// drop-in. Wire names are unaffected.
        pub fn method_case(mut self, method_case: MethodCase) -> Self {
            self.method_case = method_case;
            self
        }

        /// Emit a factory grouping every registered set into one nested
        /// object: `export const {name} = () => ({ set1, set2, ... });`.
        /// Off by default. This is the taurpc `createTauRPCProxy` drop-in:
        /// a frontend that did `const taurpc = createTauRPCProxy()` and
        /// called `taurpc.<set>.method()` keeps its call sites by
        /// re-pointing that one factory at tauri_typed_ipc's output. Pair with
        /// [`MethodCase::Snake`] to match taurpc's method names.
        pub fn router(mut self, name: impl Into<Cow<'static, str>>) -> Self {
            self.router = Some(name.into());
            self
        }

        /// Emit the JSON Schema contract and a pre-invoke check into the
        /// generated client (the `validate` feature). Off by default.
        ///
        /// Each method then validates its arguments before `invoke`, against
        /// the same per-command JSON Schema the Rust
        /// [`Validator`](crate::Validator) compiles -- so a malformed call
        /// fails at the client boundary with a clear error, and both ends check
        /// one contract. The check is a small self-contained function emitted
        /// into the file; the client pulls in no runtime dependency.
        #[cfg(feature = "validate")]
        pub fn validate(mut self, validate: bool) -> Self {
            self.validate = validate;
            self
        }

        /// Add a procedure set's bindings, named by its generated
        /// `{Trait}Procedures` handle.
        pub fn register<P: ProcedureSet>(mut self) -> Self {
            let procedures = P::procedures(&mut self.types);
            self.sets.push(Set {
                object: P::OBJECT,
                namespace: P::NAMESPACE,
                procedures,
            });
            self
        }

        /// Add an event enum's bindings, by the enum type. The generated
        /// `events.{group}.listen` reaches its variants as a discriminated
        /// union.
        pub fn register_events<E: EventSet>(mut self) -> Self {
            let variants = E::events(&mut self.types);
            self.events.push(EventGroup {
                group: E::GROUP,
                name: E::NAME,
                variants,
            });
            self
        }

        /// Render the client to a single TypeScript string. Errors under
        /// [`Layout::Files`], which spans multiple files -- use
        /// [`export_to`](Self::export_to) for that.
        pub fn export(&self) -> Result<String, BindingsError> {
            let block = self.validate_block()?;
            Ok(self
                .exporter(block)
                .export(&self.types, specta_serde::Format)?)
        }

        /// Write the client to disk: a single file under
        /// [`Layout::FlatFile`], or a directory of per-module files under
        /// [`Layout::Files`].
        pub fn export_to(&self, path: impl AsRef<Path>) -> Result<(), BindingsError> {
            let block = self.validate_block()?;
            self.exporter(block)
                .export_to(path, &self.types, specta_serde::Format)?;
            Ok(())
        }

        /// Check the rendered client against what is committed at `path`:
        /// `Ok(())` if they match, [`BindingsError::Drift`] if they differ,
        /// [`BindingsError::Read`] on an I/O failure (a missing file, an
        /// unreadable directory).
        ///
        /// This is the consumer's CI drift guard against the tax of stale
        /// bindings -- local `cargo` and `tsc` both pass while nothing yet
        /// consumes a new field, so drift slips through without it. Call it
        /// in a test; pair it with [`export_to`](Self::export_to) behind an
        /// env var or flag to regenerate on demand. A single-file layout
        /// compares against the file at `path`; [`Layout::Files`] renders to
        /// a temporary directory and compares the tree against the directory
        /// at `path`.
        pub fn check(&self, path: impl AsRef<Path>) -> Result<(), BindingsError> {
            let path = path.as_ref();
            if self.layout == Layout::Files {
                return self.check_files(path);
            }
            let generated = self.export()?;
            let committed = std::fs::read_to_string(path)
                .map_err(|source| BindingsError::read(path, source))?;
            if generated == committed {
                Ok(())
            } else {
                Err(BindingsError::Drift {
                    path: path.to_path_buf(),
                })
            }
        }

        /// The [`Layout::Files`] arm of [`check`](Self::check): render to a
        /// temporary directory (specta only writes multi-file output to
        /// disk), then compare that tree against the committed directory.
        fn check_files(&self, path: &Path) -> Result<(), BindingsError> {
            let temp = TempDir::new().map_err(|source| BindingsError::read(path, source))?;
            self.export_to(temp.path())?;
            let generated = read_tree(temp.path())
                .map_err(|source| BindingsError::read(temp.path(), source))?;
            let committed = read_tree(path).map_err(|source| BindingsError::read(path, source))?;
            if generated == committed {
                Ok(())
            } else {
                Err(BindingsError::Drift {
                    path: path.to_path_buf(),
                })
            }
        }

        /// The specta exporter that carries tauri_typed_ipc's command wrappers
        /// (the `framework_runtime` hook) and the chosen layout.
        fn exporter(&self, validate_block: Option<String>) -> Exporter {
            let sets = self.sets.clone();
            let events = self.events.clone();
            let method_case = self.method_case;
            let router = self.router.clone();
            Exporter::from(Typescript::new())
                .framework_prelude(HEADER)
                .layout(self.layout)
                .framework_runtime(move |exporter| {
                    render_runtime(
                        &sets,
                        &events,
                        method_case,
                        router.as_deref(),
                        validate_block.as_deref(),
                        &exporter,
                    )
                })
        }

        /// The pre-invoke check block -- the validator function plus the
        /// per-command JSON Schemas -- or `None` when validation is off. Built
        /// from the same descriptor the client is rendered from, so what the
        /// client checks against cannot drift from the types it declares.
        fn validate_block(&self) -> Result<Option<String>, BindingsError> {
            #[cfg(feature = "validate")]
            if self.validate {
                let sets: Vec<crate::validate::SchemaSet<'_>> = self
                    .sets
                    .iter()
                    .map(|set| crate::validate::SchemaSet {
                        namespace: set.namespace,
                        procedures: &set.procedures,
                    })
                    .collect();
                let schemas = crate::validate::build_command_schemas(self.types.clone(), &sets)?;
                return Ok(Some(render_validate_block(&schemas)));
            }
            Ok(None)
        }
    }

    impl Default for Bindings {
        fn default() -> Self {
            Self::new()
        }
    }

    /// The framework-runtime body: the runtime imports, one `invoke`
    /// object per procedure set, then the event union types and the
    /// `events` listener object. specta appends the referenced type
    /// definitions after this.
    fn render_runtime(
        sets: &[Set],
        events: &[EventGroup],
        method_case: MethodCase,
        router: Option<&str>,
        validate_block: Option<&str>,
        exporter: &FrameworkExporter,
    ) -> Result<Cow<'static, str>, Error> {
        let validate = validate_block.is_some();
        let mut out = String::new();
        if !sets.is_empty() {
            let any_channels = sets
                .iter()
                .flat_map(|set| &set.procedures)
                .any(|proc| !proc.channels.is_empty());
            out.push_str(if any_channels {
                IMPORT_INVOKE_CHANNEL
            } else {
                IMPORT_INVOKE
            });
        }
        if !events.is_empty() {
            out.push_str(IMPORT_LISTEN);
        }
        // The validator and the per-command schemas, once, ahead of the set
        // objects whose methods call into them.
        if let Some(block) = validate_block {
            out.push('\n');
            out.push_str(block);
        }
        for set in sets {
            out.push('\n');
            out.push_str(&render_object(set, method_case, validate, exporter)?);
        }
        for error in collect_errors(sets) {
            out.push('\n');
            out.push_str(&render_error(error));
        }
        for group in events {
            out.push('\n');
            out.push_str(&render_union(group, exporter)?);
        }
        if !events.is_empty() {
            out.push('\n');
            out.push_str(&render_events(events, exporter)?);
        }
        // The factory renders last so it can reference both the set objects and
        // the `events` object by name (resolved when the factory is called).
        if let Some(name) = router
            && (!sets.is_empty() || !events.is_empty())
        {
            out.push('\n');
            out.push_str(&render_router(name, sets, events));
        }
        Ok(Cow::Owned(out))
    }

    fn render_object(
        set: &Set,
        method_case: MethodCase,
        validate: bool,
        exporter: &FrameworkExporter,
    ) -> Result<String, Error> {
        let mut methods = Vec::with_capacity(set.procedures.len());
        for proc in &set.procedures {
            // Arg names are camelCase in the signature; the wire keys stay
            // the Rust identifiers, so the invoke object maps one to the
            // other (shorthand when they coincide -- a single-word name).
            let count = proc.args.len() + proc.channels.len();
            let mut params = Vec::with_capacity(count);
            let mut fields = Vec::with_capacity(count);
            for (wire, ty) in &proc.args {
                let param = to_camel(wire);
                params.push(format!("{param}: {}", render_ty(exporter, ty)?));
                if &param == wire {
                    fields.push((*wire).to_string());
                } else {
                    fields.push(format!("{wire}: {param}"));
                }
            }
            // A `Channel<T>` is passed by the client like any argument
            // (it serializes to its id on the wire), but renders as
            // `Channel<T>`. Channels come after the plain arguments.
            for (wire, ty) in &proc.channels {
                let param = to_camel(wire);
                params.push(format!("{param}: Channel<{}>", render_ty(exporter, ty)?));
                if &param == wire {
                    fields.push((*wire).to_string());
                } else {
                    fields.push(format!("{wire}: {param}"));
                }
            }
            let ret = render_ty(exporter, &proc.output)?;
            let wire = match set.namespace {
                Some(ns) => format!("{ns}.{}", proc.name),
                None => proc.name.to_string(),
            };
            // The argument object, shared by the invoke call and the
            // pre-invoke check so both see the same wire keys.
            let args_obj = if count == 0 {
                "{}".to_string()
            } else {
                format!("{{ {} }}", fields.join(", "))
            };
            let call = if count == 0 {
                format!("invoke(\"{wire}\")")
            } else {
                format!("invoke(\"{wire}\", {args_obj})")
            };
            // With validation on, check the arguments against the command's
            // schema before the call, so a bad payload fails at the boundary
            // rather than after a round-trip.
            let guard = if validate {
                format!("    __ttipcValidate(\"{wire}\", {args_obj});\n")
            } else {
                String::new()
            };
            let method = match method_case {
                MethodCase::Camel => to_camel(proc.name),
                MethodCase::Snake => proc.name.to_string(),
            };
            // A fallible procedure rejects with its typed error; the
            // signature stays `Promise<T>` (wire parity -- it rejects),
            // and a `@throws` ties it to the emitted error union.
            let throws = match &proc.error {
                Some(error) => format!("  /** @throws {{{}}} */\n", error.name),
                None => String::new(),
            };
            methods.push(format!(
                "{throws}  {method}({params}): Promise<{ret}> {{\n{guard}    return {call};\n  }}",
                params = params.join(", "),
            ));
        }
        Ok(format!(
            "export const {} = {{\n{},\n}};\n",
            set.object,
            methods.join(",\n\n"),
        ))
    }

    /// The pre-invoke check block: the per-command JSON Schemas the client was
    /// generated from, plus a small self-contained validator over the subset of
    /// JSON Schema those documents use. No runtime dependency -- the client
    /// stays dep-light. Each command's schema is self-contained (it carries the
    /// definitions it references), so the validator needs no shared registry.
    #[cfg(feature = "validate")]
    fn render_validate_block(schemas: &[(String, serde_json::Value)]) -> String {
        let mut entries = String::new();
        for (wire, schema) in schemas {
            // Infallible: a wire name is a string and the schema is a Value we
            // just built, both of which always serialize to JSON.
            let key = serde_json::to_string(wire).expect("a wire name serializes");
            let value = serde_json::to_string(schema).expect("a schema serializes");
            entries.push_str("  ");
            entries.push_str(&key);
            entries.push_str(": ");
            entries.push_str(&value);
            entries.push_str(",\n");
        }
        format!("const __ttipcSchemas: Record<string, any> = {{\n{entries}}};\n\n{VALIDATOR_TS}")
    }

    /// The self-contained argument validator emitted alongside the schemas. A
    /// pared-down JSON Schema checker: it follows `$ref` into the embedded
    /// definitions and enforces `type`, `properties`/`required`, `items`, and
    /// `enum`; unions and nullable shapes are accepted as-is, so it never
    /// rejects a valid payload, only flags a clearly wrong one.
    #[cfg(feature = "validate")]
    const VALIDATOR_TS: &str = r#"function __ttipcDefs(root: any): Record<string, any> {
  return (root.$defs ?? root.definitions ?? {}) as Record<string, any>;
}

function __ttipcCheck(value: unknown, schema: any, root: any, path: string): string | null {
  if (schema === true || schema === undefined || schema === null) return null;
  if (typeof schema.$ref === "string") {
    const name = schema.$ref.split("/").pop() as string;
    return __ttipcCheck(value, __ttipcDefs(root)[name], root, path);
  }
  if (schema.oneOf || schema.anyOf || schema.allOf || Array.isArray(schema.type)) {
    return null;
  }
  if (Array.isArray(schema.enum) && !schema.enum.some((v: unknown) => v === value)) {
    return `${path} is not an allowed value`;
  }
  const type: unknown = schema.type;
  if (type === "object" || schema.properties || schema.required) {
    if (typeof value !== "object" || value === null || Array.isArray(value)) {
      return `${path} must be an object`;
    }
    const obj = value as Record<string, unknown>;
    for (const key of (schema.required ?? []) as string[]) {
      if (!(key in obj)) return `${path}.${key} is required`;
    }
    const props = schema.properties ?? {};
    for (const key of Object.keys(props)) {
      if (key in obj) {
        const err = __ttipcCheck(obj[key], props[key], root, `${path}.${key}`);
        if (err !== null) return err;
      }
    }
    return null;
  }
  if (type === "array") {
    if (!Array.isArray(value)) return `${path} must be an array`;
    if (schema.items) {
      for (let i = 0; i < value.length; i++) {
        const err = __ttipcCheck(value[i], schema.items, root, `${path}[${i}]`);
        if (err !== null) return err;
      }
    }
    return null;
  }
  if (type === "string" && typeof value !== "string") return `${path} must be a string`;
  if ((type === "integer" || type === "number") && typeof value !== "number") {
    return `${path} must be a number`;
  }
  if (type === "integer" && typeof value === "number" && !Number.isInteger(value)) {
    return `${path} must be an integer`;
  }
  if (type === "boolean" && typeof value !== "boolean") return `${path} must be a boolean`;
  if (type === "null" && value !== null) return `${path} must be null`;
  return null;
}

function __ttipcValidate(command: string, args: unknown): void {
  const schema = __ttipcSchemas[command];
  if (schema === undefined) return;
  const error = __ttipcCheck(args, schema, schema, "arguments");
  if (error !== null) {
    throw new Error(`invalid arguments for ${command}: ${error}`);
  }
}
"#;

    /// A factory grouping every registered set into one nested object --
    /// the taurpc `createTauRPCProxy` drop-in. A frontend that did
    /// `const x = name(); x.<set>.method()` keeps its call sites by
    /// re-pointing that one factory at tauri_typed_ipc's output.
    fn render_router(name: &str, sets: &[Set], events: &[EventGroup]) -> String {
        let has_events = |ns: &str| events.iter().any(|group| group.group == ns);
        let mut entries = Vec::with_capacity(sets.len() + events.len());
        // A method namespace; if an event group shares its name, expose its
        // listener at `<ns>.event.on` (the taurpc shape) beside the methods.
        for set in sets {
            if has_events(set.object) {
                entries.push(format!(
                    "  {obj}: {{ ...{obj}, event: {{ on: events.{obj}.listen }} }}",
                    obj = set.object,
                ));
            } else {
                entries.push(format!("  {}", set.object));
            }
        }
        // Event groups with no matching method set get an events-only entry.
        for group in events {
            if !sets.iter().any(|set| set.object == group.group) {
                entries.push(format!(
                    "  {grp}: {{ event: {{ on: events.{grp}.listen }} }}",
                    grp = group.group,
                ));
            }
        }
        format!(
            "export const {name} = () => ({{\n{},\n}});\n",
            entries.join(",\n")
        )
    }

    /// A snake_case Rust identifier as camelCase: `save_scene` ->
    /// `saveScene`, `set` -> `set`. Each `_` is dropped and the next
    /// letter uppercased.
    fn to_camel(snake: &str) -> String {
        let mut out = String::with_capacity(snake.len());
        let mut upper_next = false;
        for ch in snake.chars() {
            if ch == '_' {
                upper_next = true;
            } else if upper_next {
                out.extend(ch.to_uppercase());
                upper_next = false;
            } else {
                out.push(ch);
            }
        }
        out
    }

    /// The unique error types rejected by any procedure across all sets,
    /// in first-seen order so the output is deterministic.
    fn collect_errors(sets: &[Set]) -> Vec<&ErrorType> {
        let mut seen = HashSet::new();
        let mut errors = Vec::new();
        for set in sets {
            for proc in &set.procedures {
                if let Some(error) = &proc.error
                    // A built-in inline error (`string`) renders by name with no
                    // alias, so it never reaches the runtime `export type` section.
                    && !error.variants.is_empty()
                    && seen.insert(error.name)
                {
                    errors.push(error);
                }
            }
        }
        errors
    }

    /// One error's discriminated union: `{ type: "<tag>"; message: string
    /// }` per variant. Every variant serializes to `{ type, message }`
    /// (the Error derive's wire shape), so only the tag varies.
    fn render_error(error: &ErrorType) -> String {
        let members: Vec<String> = error
            .variants
            .iter()
            .map(|tag| format!("{{ type: \"{tag}\"; message: string }}"))
            .collect();
        format!("export type {} = {};\n", error.name, members.join(" | "))
    }

    /// Render one wire type to its TypeScript form. A top-level named
    /// type goes through `reference` (its name, plus an import in the
    /// multi-file layout); everything else inlines, tracking any named
    /// types nested inside.
    fn render_ty(exporter: &FrameworkExporter, ty: &DataType) -> Result<String, Error> {
        match ty {
            DataType::Reference(reference) => exporter.reference(reference),
            other => exporter.inline(other),
        }
    }

    /// The discriminated union for an event group: one
    /// `{ type: "variant"; ...fields }` member per variant.
    fn render_union(group: &EventGroup, exporter: &FrameworkExporter) -> Result<String, Error> {
        let mut members = Vec::with_capacity(group.variants.len());
        for variant in &group.variants {
            let mut parts = vec![format!("type: \"{}\"", variant.variant)];
            if let Some(data) = &variant.data {
                parts.push(format!("data: {}", render_ty(exporter, data)?));
            } else {
                parts.extend(render_fields(variant, exporter)?);
            }
            members.push(format!("{{ {} }}", parts.join("; ")));
        }
        Ok(format!(
            "export type {} = {};\n",
            group.name,
            members.join(" | ")
        ))
    }

    /// The `events` object: per group a `listen` that forwards the
    /// discriminated union. A single-variant group returns its one
    /// subscription directly -- Tauri's `UnlistenFn` is already
    /// `() => void`, so no wrapper is needed. A multi-variant group fans
    /// out: it awaits every subscription, then returns one unlisten that
    /// drops them all.
    fn render_events(events: &[EventGroup], exporter: &FrameworkExporter) -> Result<String, Error> {
        let mut groups = Vec::with_capacity(events.len());
        for group in events {
            let mut listeners = Vec::with_capacity(group.variants.len());
            for variant in &group.variants {
                let payload = render_payload(variant, exporter)?;
                let forward = if variant.data.is_some() {
                    format!(
                        "(event) => callback({{ type: \"{}\", data: event.payload }})",
                        variant.variant,
                    )
                } else if variant.fields.is_empty() {
                    format!("() => callback({{ type: \"{}\" }})", variant.variant)
                } else {
                    format!(
                        "(event) => callback({{ type: \"{}\", ...event.payload }})",
                        variant.variant,
                    )
                };
                listeners.push(format!(
                    "listen<{payload}>(\"{name}\", {forward})",
                    name = variant.name,
                ));
            }
            let body = if let [only] = listeners.as_slice() {
                format!(
                    "    listen(callback: (event: {name}) => void): \
                     Promise<() => void> {{\n      return {only};\n    }},",
                    name = group.name,
                )
            } else {
                let calls = listeners
                    .iter()
                    .map(|call| format!("        {call},"))
                    .collect::<Vec<_>>()
                    .join("\n");
                format!(
                    "    async listen(callback: (event: {name}) => void): \
                     Promise<() => void> {{\n      const unlisten = await Promise.all([\n{calls}\n      \
                     ]);\n      return () => unlisten.forEach((un) => un());\n    }},",
                    name = group.name,
                )
            };
            groups.push(format!("  {group}: {{\n{body}\n  }}", group = group.group));
        }
        Ok(format!(
            "export const events = {{\n{},\n}};\n",
            groups.join(",\n\n"),
        ))
    }

    /// A variant's TypeScript field list: `["channel: number", ...]`.
    fn render_fields(
        variant: &EventType,
        exporter: &FrameworkExporter,
    ) -> Result<Vec<String>, Error> {
        variant
            .fields
            .iter()
            .map(|(name, ty)| Ok(format!("{name}: {}", render_ty(exporter, ty)?)))
            .collect()
    }

    /// A variant's wire payload type: an object of its fields, or `null`
    /// for a unit variant.
    fn render_payload(variant: &EventType, exporter: &FrameworkExporter) -> Result<String, Error> {
        if let Some(data) = &variant.data {
            return render_ty(exporter, data);
        }
        let fields = render_fields(variant, exporter)?;
        if fields.is_empty() {
            Ok("null".to_string())
        } else {
            Ok(format!("{{ {} }}", fields.join("; ")))
        }
    }

    /// Failure rendering or checking the TypeScript client.
    #[derive(Debug, thiserror::Error)]
    pub enum BindingsError {
        /// specta-typescript could not render a type.
        #[error("rendering TypeScript failed: {0}")]
        Render(#[from] Error),
        /// Building the JSON Schema contract for the pre-invoke check failed
        /// (the `validate` feature).
        #[cfg(feature = "validate")]
        #[error(transparent)]
        Validate(#[from] crate::validate::ValidatorError),
        /// An I/O failure during [`check`](Bindings::check) -- a missing or
        /// unreadable committed client, or the temporary render it compares
        /// against under [`Layout::Files`].
        #[error("checking the client at {path:?} failed: {source}")]
        Read {
            /// The path involved in the failure.
            path: PathBuf,
            /// The underlying I/O error.
            #[source]
            source: std::io::Error,
        },
        /// [`check`](Bindings::check) found the committed client out of date.
        #[error("the committed client at {path:?} is out of date; regenerate it")]
        Drift {
            /// The path whose contents drifted from the generator.
            path: PathBuf,
        },
    }

    impl BindingsError {
        /// An I/O failure touching `path`.
        fn read(path: &Path, source: std::io::Error) -> Self {
            Self::Read {
                path: path.to_path_buf(),
                source,
            }
        }
    }

    /// A uniquely-named temporary directory, removed on drop. Used by
    /// [`Bindings::check`] to render a [`Layout::Files`] client somewhere
    /// disposable before comparing it against the committed tree.
    struct TempDir(PathBuf);

    impl TempDir {
        fn new() -> std::io::Result<Self> {
            static COUNTER: AtomicUsize = AtomicUsize::new(0);
            let unique = COUNTER.fetch_add(1, Ordering::Relaxed);
            let dir = std::env::temp_dir().join(format!(
                "tauri_typed_ipc-check-{}-{unique}",
                std::process::id()
            ));
            std::fs::create_dir_all(&dir)?;
            Ok(Self(dir))
        }

        fn path(&self) -> &Path {
            &self.0
        }
    }

    impl Drop for TempDir {
        fn drop(&mut self) {
            let _ = std::fs::remove_dir_all(&self.0);
        }
    }

    /// Every file under `root`, keyed by its path relative to `root`, so two
    /// rendered trees compare by structure and content regardless of where
    /// each is rooted.
    fn read_tree(root: &Path) -> std::io::Result<BTreeMap<PathBuf, String>> {
        let mut files = BTreeMap::new();
        let mut stack = vec![root.to_path_buf()];
        while let Some(dir) = stack.pop() {
            for entry in std::fs::read_dir(&dir)? {
                let path = entry?.path();
                if path.is_dir() {
                    stack.push(path);
                } else {
                    let rel = path
                        .strip_prefix(root)
                        .expect("entry is under root")
                        .to_path_buf();
                    files.insert(rel, std::fs::read_to_string(&path)?);
                }
            }
        }
        Ok(files)
    }
}