Skip to main content

specta_typescript/
semantic.rs

1//! Runtime-aware TypeScript type remapping.
2//!
3//! Semantic types are Rust types whose TypeScript runtime value should be more
4//! specific than their JSON-compatible wire representation.
5//!
6//! This enables the following default rules:
7//!  - [`bytes::Bytes`](https://docs.rs/bytes/latest/bytes/struct.Bytes.html) to become [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
8//!  - [`bytes::BytesMut`](https://docs.rs/bytes/latest/bytes/struct.BytesMut.html) to become [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array)
9//!  - [`url::Url`](https://docs.rs/url/latest/url/struct.Url.html) to become [`Url`](https://developer.mozilla.org/en-US/docs/Web/API/URL/URL)
10//!  - [`chrono::DateTime`](https://docs.rs/chrono/latest/chrono/struct.DateTime.html) to become [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
11//!  - [`chrono::NaiveDate`](https://docs.rs/chrono/latest/chrono/struct.NaiveDate.html) to become [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
12//!  - [`jiff::Timestamp`](https://docs.rs/jiff/latest/jiff/struct.Timestamp.html) to become [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
13//!  - [`jiff::civil::Date`](https://docs.rs/jiff/latest/jiff/civil/struct.Date.html) to become [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date)
14//!
15//! This could also allow you to map your own Rust types into custom JavaScript types like custom classes. Refer to [`semantic::Configuration::define`](Configuration::define) for building your own rules.
16//!
17//! This is intended the be implemented by frameworks like [Tauri Specta](https://github.com/specta-rs/tauri-specta), [TauRPC](https://github.com/MatsDK/TauRPC) and [rspc](https://github.com/specta-rs/rspc) as they have control of the runtime and type layer.
18//!
19//! <div class="warning">
20//!
21//! **WARNING:** The current implementation relies on the frontend and backend being versioned in-step. This works for a Tauri desktop application but may become an issue for a HTTP API unless you have something like [Skew Protection](https://vercel.com/docs/skew-protection).
22//!
23//! We will likely lift this as a hard restriction in the future!
24//!
25//! </div>
26//!
27//! <details>
28//! <summary>Implementing into your own framework</summary>
29//!
30//! # Implementing into your own framework
31//!
32//! A framework needs to be integrated properly for this feature to work, as it requires both type-level and runtime JS to make it work properly.
33//!
34//! I would highly recommend reading [specta-rs/specta#203](https://github.com/specta-rs/specta/issues/203) and understanding it as it's the core work which inspired this feature.
35//!
36//! Documentation coming soon... For now refer to [specta-rs/tauri-specta#219](https://github.com/specta-rs/tauri-specta/pull/219) which was the original implementation into [Tauri Specta](https://github.com/specta-rs/tauri-specta).
37//!
38//! </details>
39//!
40
41use std::{borrow::Cow, collections::BTreeSet, fmt, sync::Arc};
42
43use specta::{
44    Type, Types,
45    datatype::{
46        DataType, Enum, Field, Fields, NamedDataType, NamedReferenceType, Primitive, Reference,
47        Variant,
48    },
49};
50
51use crate::{
52    Error, define,
53    primitives::{escape_typescript_string_literal, is_identifier},
54};
55
56/// A JavaScript expression that converts between a semantic
57/// TypeScript runtime value and its JSON-compatible representation.
58///
59/// The closure receives the JavaScript identifier/expression being transformed
60/// and must return a JavaScript expression using that value.
61///
62/// # Examples
63///
64/// Convert a JSON string into a TypeScript `Date`:
65///
66/// ```rust
67/// use specta_typescript::semantic::Transform;
68///
69/// let transform = Transform::new(|value| format!("new Date({value})"));
70/// # let _ = transform;
71/// ```
72///
73/// Convert a `Uint8Array` into a JSON array of numbers:
74///
75/// ```rust
76/// use specta_typescript::semantic::Transform;
77///
78/// let transform = Transform::new(|value| format!("[...{value}]"));
79/// # let _ = transform;
80/// ```
81///
82/// Use [`Transform::identity`] when the TypeScript runtime value already has
83/// the same representation as the value crossing the wire or when JSON.stringify/JSON.parse
84/// is already able to handle the transformation for you.
85#[derive(Clone)]
86#[non_exhaustive]
87pub struct Transform(
88    /// The runtime transform function
89    ///
90    /// This is called with the argument being a Typescript identifier.
91    /// It should output some transformation on the identifier.
92    /// Eg. `|i| format!("new Date({i})")` could be one valid implementation.
93    Option<Arc<dyn Fn(&str) -> String + Send + Sync>>,
94);
95
96impl fmt::Debug for Transform {
97    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
98        match &self.0 {
99            Some(r) => write!(f, "{r:p}"),
100            None => write!(f, "<none>"),
101        }
102    }
103}
104
105impl Transform {
106    /// Construct a runtime transform from a JavaScript identifier mapper.
107    ///
108    /// The mapper should return a JavaScript expression, not a statement.
109    ///
110    /// ```rust
111    /// use specta_typescript::semantic::Transform;
112    ///
113    /// let transform = Transform::new(|ident| format!("new URL({ident})"));
114    /// # let _ = transform;
115    /// ```
116    pub fn new(runtime: impl Fn(&str) -> String + Send + Sync + 'static) -> Self {
117        Self(Some(Arc::new(runtime)))
118    }
119
120    /// Construct an identity runtime transform.
121    ///
122    /// This is useful when a rule only changes the exported TypeScript type, or
123    /// when one direction does not need runtime conversion.
124    ///
125    /// ```rust
126    /// use specta_typescript::semantic::Transform;
127    ///
128    /// let transform = Transform::identity();
129    /// # let _ = transform;
130    /// ```
131    pub fn identity() -> Self {
132        Self(None)
133    }
134
135    fn apply(&self, ident: &str) -> String {
136        match &self.0 {
137            Some(runtime) => runtime(ident),
138            None => ident.to_owned(),
139        }
140    }
141}
142
143#[derive(Clone)]
144pub(crate) struct DataTypeFn(Arc<dyn Fn(DataType) -> DataType + Send + Sync>);
145
146impl DataTypeFn {
147    pub(crate) fn new(f: impl Fn(DataType) -> DataType + Send + Sync + 'static) -> Self {
148        Self(Arc::new(f))
149    }
150}
151
152impl fmt::Debug for DataTypeFn {
153    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
154        f.debug_tuple("DataTypeFn")
155            .field(&format!("{:p}", self.0))
156            .finish()
157    }
158}
159
160/// A rule for a specific named data type.
161#[derive(Debug, Clone)]
162#[non_exhaustive]
163pub struct Rule {
164    /// Matched against [`NamedDataType::name`](specta::datatype::NamedDataType::name) to determine if rule should apply
165    pub name: Cow<'static, str>,
166    /// Matched against [`NamedDataType::module_path`](specta::datatype::NamedDataType::module_path) to determine if rule should apply
167    pub module_path: Cow<'static, str>,
168    /// The type transformation function
169    ///
170    /// This must match up with the type produced or consumed by the runtime.
171    pub(crate) data_type: DataTypeFn,
172    /// The type transformation for serializing.
173    /// This is JS -> Rust
174    pub(crate) serialize: Option<Transform>,
175    /// The type transformation for deserializing.
176    /// This is Rust -> JS
177    pub(crate) deserialize: Option<Transform>,
178}
179
180/// Configuration for runtime-aware TypeScript type remapping.
181///
182/// By default this contains a set of default rules as defined on [the module](crate::semantic). If you don't want them use [`Configuration::empty()`](Configuration::empty) instead.
183///
184/// You can add your own rules via [`Configuration::define(...)`](Configuration::define).
185///
186#[derive(Debug, Clone)]
187pub struct Configuration {
188    rules: Vec<Rule>,
189    lossless_bigint: bool,
190    lossless_floats: bool,
191}
192
193impl Default for Configuration {
194    fn default() -> Self {
195        Self {
196            rules: vec![
197                // Uint8Array
198                Rule {
199                    name: "Bytes".into(),
200                    module_path: "bytes".into(),
201                    data_type: DataTypeFn::new(|_| define("Uint8Array").into()),
202                    serialize: Some(Transform::new(|i| format!("[...{i}]"))),
203                    deserialize: Some(Transform::new(|i| format!("new Uint8Array({i})"))),
204                },
205                Rule {
206                    name: "BytesMut".into(),
207                    module_path: "bytes".into(),
208                    data_type: DataTypeFn::new(|_| define("Uint8Array").into()),
209                    serialize: Some(Transform::new(|i| format!("[...{i}]"))),
210                    deserialize: Some(Transform::new(|i| format!("new Uint8Array({i})"))),
211                },
212                // URL
213                Rule {
214                    name: "Url".into(),
215                    module_path: "url".into(),
216                    data_type: DataTypeFn::new(|_| define("URL").into()),
217                    serialize: None,
218                    deserialize: Some(Transform::new(|i| format!("new URL({i})"))),
219                },
220                // Date
221                Rule {
222                    name: "DateTime".into(),
223                    module_path: "chrono".into(),
224                    data_type: DataTypeFn::new(|_| define("Date").into()),
225                    serialize: None,
226                    deserialize: Some(Transform::new(|i| format!("new Date({i})"))),
227                },
228                Rule {
229                    name: "NaiveDate".into(),
230                    module_path: "chrono".into(),
231                    data_type: DataTypeFn::new(|_| define("Date").into()),
232                    serialize: Some(Transform::new(|i| {
233                        format!("{i}.toISOString().slice(0, 10)")
234                    })),
235                    deserialize: Some(Transform::new(|i| format!("new Date({i})"))),
236                },
237                Rule {
238                    name: "Timestamp".into(),
239                    module_path: "jiff".into(),
240                    data_type: DataTypeFn::new(|_| define("Date").into()),
241                    serialize: Some(Transform::new(|i| format!("{i}.toISOString()"))),
242                    deserialize: Some(Transform::new(|i| format!("new Date({i})"))),
243                },
244                Rule {
245                    name: "Date".into(),
246                    module_path: "jiff::civil".into(),
247                    data_type: DataTypeFn::new(|_| define("Date").into()),
248                    serialize: Some(Transform::new(|i| {
249                        format!("{i}.toISOString().slice(0, 10)")
250                    })),
251                    deserialize: Some(Transform::new(|i| format!("new Date({i})"))),
252                },
253                // We don't implement support for `chrono::NaiveDateTime`, and many `jiff` types as lack of timezone is an issue with JS's `Date`
254            ],
255            lossless_bigint: false,
256            lossless_floats: false,
257        }
258    }
259}
260
261impl Configuration {
262    /// Construct a [`Configuration`] without the default rules.
263    ///
264    /// Prefer [`Configuration::default`] when possible; the default
265    /// rules cover common ecosystem types and may grow over time.
266    pub fn empty() -> Self {
267        Self {
268            rules: Default::default(),
269            lossless_bigint: false,
270            lossless_floats: false,
271        }
272    }
273
274    /// Exposes the rules applies to this instance for manual manipulation.
275    ///
276    /// This could be used to filter the default rules if you want to exclude certain ones.
277    pub fn rules_mut(&mut self) -> &mut Vec<Rule> {
278        &mut self.rules
279    }
280
281    /// Define a new rule for a given type `T`.
282    ///
283    /// `dt` receives the original [`DataType`] for `T` and must return the
284    /// TypeScript-facing [`DataType`] that should replace it. `serialize`
285    /// transforms TypeScript runtime values before sending them to Rust.
286    /// `deserialize` transforms values received from Rust into TypeScript
287    /// runtime values.
288    ///
289    /// This only works for named types, such as types generated by the
290    /// [`Type`] derive macro. It does not work for primitives.
291    ///
292    /// ```rust
293    /// use specta::Type;
294    /// use specta_typescript::{define, semantic::{Configuration, Transform}};
295    ///
296    /// #[derive(Type)]
297    /// struct MyCustomUrl(String);
298    ///
299    /// let mut semantic_types = Configuration::empty();
300    /// semantic_types.define::<MyCustomUrl>(
301    ///     |_| define("URL").into(), // Runtime Specta Type
302    ///     Some(Transform::new(|value| format!("{value}.toString()"))), // JS -> JSON
303    ///     Some(Transform::new(|value| format!("new URL({value})"))), // JSON -> JS
304    /// );
305    /// ```
306    pub fn define<T: Type>(
307        mut self,
308        dt: impl Fn(DataType) -> DataType + Send + Sync + 'static,
309        serialize: Option<Transform>,
310        deserialize: Option<Transform>,
311    ) -> Self {
312        let mut types = Types::default();
313        let ndt = match T::definition(&mut types) {
314            DataType::Reference(Reference::Named(r)) => types.get(&r),
315            _ => None,
316        };
317        if let Some(ndt) = ndt {
318            self.rules.push(Rule {
319                name: ndt.name.clone(),
320                module_path: ndt.module_path.clone(),
321                data_type: DataTypeFn(Arc::new(dt)),
322                serialize,
323                deserialize,
324            });
325        }
326
327        self
328    }
329
330    /// Enable lossless support for large integer types (`BigInt`s).
331    ///
332    /// This remaps `usize`, `isize`, `u64`, `i64`, `u128`, and `i128` so they
333    /// are a [`BigInt`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) in JavaScript.
334    ///
335    /// This is only safe if your serialization and deserialization layer can losslessly transmit `BigInt`s to the frontend.
336    ///
337    /// Refer to [specta-rs/specta#203](https://github.com/specta-rs/specta/issues/203) for implementation details.
338    pub fn enable_lossless_bigints(mut self) -> Self {
339        if !self.lossless_bigint {
340            self.lossless_bigint = true;
341        }
342
343        self
344    }
345
346    /// Enable lossless float support.
347    ///
348    /// By enabling this, you assert that your runtime *must* preserve `NaN`,
349    /// `Infinity`, and `-Infinity` values from JavaScript to Rust and we will flatten `number | null` into `number`.
350    ///
351    /// Refer to [specta-rs/specta#203](https://github.com/specta-rs/specta/issues/203) for implementation details.
352    pub fn enable_lossless_floats(mut self) -> Self {
353        if !self.lossless_floats {
354            self.lossless_floats = true;
355        }
356
357        self
358    }
359
360    /// Transform a [`Types`] collection using the configured rules.
361    ///
362    /// This rewrites registered named types so their exported TypeScript shapes
363    /// match the values produced or consumed by the runtime transforms.
364    ///
365    /// Call this after any format-specific mapping that changes the type graph,
366    /// and before exporting the final TypeScript definitions.
367    pub fn apply_types<'a>(&self, types: &'a Types) -> Cow<'a, Types> {
368        let mut types = Cow::Borrowed(types);
369
370        if self.has_builtin_remaps() {
371            types = Cow::Owned(types.into_owned().map(|mut ndt| {
372                let remap_bigint = if ndt.name.ends_with("_Serialize") {
373                    serialize_bigint
374                } else {
375                    deserialize_bigint
376                };
377
378                ndt.generics.to_mut().iter_mut().for_each(|generic| {
379                    if let Some(dt) = &mut generic.default {
380                        apply_builtin_remaps(
381                            dt,
382                            remap_bigint,
383                            self.lossless_bigint,
384                            self.lossless_floats,
385                        );
386                    }
387                });
388                if let Some(dt) = &mut ndt.ty {
389                    apply_builtin_remaps(
390                        dt,
391                        remap_bigint,
392                        self.lossless_bigint,
393                        self.lossless_floats,
394                    );
395                }
396
397                ndt
398            }));
399        }
400
401        if !self.rules.is_empty() {
402            let source = types.into_owned();
403            let lookup = source.clone();
404            types = Cow::Owned(source.map(|mut ndt| {
405                if let Some(dt) = &mut ndt.ty {
406                    self.apply_rules_to_dt(&lookup, dt);
407                }
408
409                if let Some(rule) = self
410                    .rules
411                    .iter()
412                    .find(|r| r.name == ndt.name && r.module_path == ndt.module_path)
413                    && let Some(dt) = ndt.ty.take()
414                {
415                    ndt.ty = Some((rule.data_type.0)(dt));
416                }
417
418                ndt
419            }));
420        }
421
422        types
423    }
424
425    fn apply_rules_to_dt(&self, types: &Types, dt: &mut DataType) {
426        if let DataType::Reference(Reference::Named(reference)) = dt
427            && let Some(rule) = self.rule_for_reference(types, reference)
428        {
429            *dt = (rule.data_type.0)(Self::reference_source_dt(types, reference));
430            return;
431        }
432
433        match dt {
434            DataType::Primitive(_) | DataType::Generic(_) => {}
435            DataType::List(list) => self.apply_rules_to_dt(types, &mut list.ty),
436            DataType::Map(map) => {
437                self.apply_rules_to_dt(types, map.key_ty_mut());
438                self.apply_rules_to_dt(types, map.value_ty_mut());
439            }
440            DataType::Struct(s) => self.apply_rules_to_fields(types, &mut s.fields),
441            DataType::Enum(e) => {
442                for (_, variant) in &mut e.variants {
443                    self.apply_rules_to_fields(types, &mut variant.fields);
444                }
445            }
446            DataType::Tuple(tuple) => {
447                for dt in &mut tuple.elements {
448                    self.apply_rules_to_dt(types, dt);
449                }
450            }
451            DataType::Nullable(dt) => self.apply_rules_to_dt(types, dt),
452            DataType::Intersection(dts) => {
453                for dt in dts {
454                    self.apply_rules_to_dt(types, dt);
455                }
456            }
457            DataType::Reference(Reference::Named(reference)) => match &mut reference.inner {
458                NamedReferenceType::Recursive(_) | NamedReferenceType::Reference { .. } => {}
459                NamedReferenceType::Inline { dt, .. } => self.apply_rules_to_dt(types, dt),
460            },
461            DataType::Reference(Reference::Opaque(_)) => {}
462        }
463    }
464
465    fn apply_rules_to_fields(&self, types: &Types, fields: &mut Fields) {
466        match fields {
467            Fields::Unit => {}
468            Fields::Unnamed(fields) => {
469                for field in &mut fields.fields {
470                    if let Some(dt) = &mut field.ty {
471                        self.apply_rules_to_dt(types, dt);
472                    }
473                }
474            }
475            Fields::Named(fields) => {
476                for (_, field) in &mut fields.fields {
477                    if let Some(dt) = &mut field.ty {
478                        self.apply_rules_to_dt(types, dt);
479                    }
480                }
481            }
482        }
483    }
484
485    /// Scan a [`DataType`] tree applying serialize-facing rules.
486    ///
487    /// This assumes [`Configuration::apply_types`] has already been applied to the [`Types`].
488    /// Therefore the type updates will be shallow (up until references to the `Types`).
489    ///
490    /// The returned JavaScript expression is built around `js_ident` and may be
491    /// deeply nested for structs, tuples, lists, nullable values, and
492    /// intersections.
493    ///
494    /// If a registered graph contains no runtime transform, `None` is returned;
495    /// its type-only changes are handled by [`Configuration::apply_types`]. For
496    /// inline inputs, a type-only result is retained with an identity runtime
497    /// expression because there is no registered type for `apply_types` to rewrite.
498    ///
499    /// This method is non-panicking. A construct that cannot be transformed is
500    /// skipped: it contributes no runtime change, and enclosing structs/lists
501    /// still transform their other parts. When the *root* cannot be transformed,
502    /// `None` is returned. Use [`Configuration::try_apply_serialize`] to find out
503    /// why a transform was skipped.
504    pub fn apply_serialize(
505        &self,
506        types: &Types,
507        dt: &DataType,
508        js_ident: &str,
509    ) -> Option<(Option<DataType>, String)> {
510        self.apply(
511            serialize_bigint,
512            |rule| &rule.serialize,
513            types,
514            dt,
515            js_ident,
516        )
517    }
518
519    /// Fallible counterpart to [`Configuration::apply_serialize`].
520    ///
521    /// Returns an [`Error`] when a non-identity transform is required beneath a
522    /// construct whose wire shape cannot be discriminated without guessing (for
523    /// example overlapping `#[serde(untagged)]` variants, or a recursive enum
524    /// whose expansion would leave nested values untransformed). Emitting a
525    /// transform there would let the exported type and the runtime value
526    /// diverge, so the unsupported part is skipped and reported instead.
527    pub fn try_apply_serialize(
528        &self,
529        types: &Types,
530        dt: &DataType,
531        js_ident: &str,
532    ) -> Result<Option<(Option<DataType>, String)>, Error> {
533        self.try_apply(
534            serialize_bigint,
535            |rule| &rule.serialize,
536            types,
537            dt,
538            js_ident,
539        )
540    }
541
542    /// Scan a [`DataType`] tree applying deserialize-facing rules.
543    ///
544    /// Use this for values received from Rust before exposing them to
545    /// TypeScript callers.
546    ///
547    /// This method is non-panicking. See [`Configuration::apply_serialize`] for
548    /// the skipping semantics, and [`Configuration::try_apply_deserialize`] to
549    /// find out why a transform was skipped.
550    pub fn apply_deserialize(
551        &self,
552        types: &Types,
553        dt: &DataType,
554        js_ident: &str,
555    ) -> Option<(Option<DataType>, String)> {
556        self.apply(
557            deserialize_bigint,
558            |rule| &rule.deserialize,
559            types,
560            dt,
561            js_ident,
562        )
563    }
564
565    /// Fallible counterpart to [`Configuration::apply_deserialize`].
566    ///
567    /// See [`Configuration::try_apply_serialize`] for the rejection semantics.
568    pub fn try_apply_deserialize(
569        &self,
570        types: &Types,
571        dt: &DataType,
572        js_ident: &str,
573    ) -> Result<Option<(Option<DataType>, String)>, Error> {
574        self.try_apply(
575            deserialize_bigint,
576            |rule| &rule.deserialize,
577            types,
578            dt,
579            js_ident,
580        )
581    }
582
583    /// Run a traversal and keep the diagnostic if a part could not be
584    /// transformed. The infallible API drops the diagnostic and keeps whatever
585    /// could be generated.
586    fn run(
587        &self,
588        remap_bigint: fn() -> DataType,
589        transform_for_rule: fn(&Rule) -> &Option<Transform>,
590        types: &Types,
591        dt: &DataType,
592        js_ident: &str,
593    ) -> (Option<(Option<DataType>, String)>, Option<Error>) {
594        let mut walk = Walk {
595            transform_for_rule,
596            remap_bigint,
597            types,
598            stack: Vec::new(),
599            error: None,
600            recursion_cut: false,
601            current: None,
602        };
603        let result = self.apply_inner(&mut walk, dt, js_ident);
604        (prune_identity_root(types, dt, js_ident, result), walk.error)
605    }
606
607    fn apply(
608        &self,
609        remap_bigint: fn() -> DataType,
610        transform_for_rule: fn(&Rule) -> &Option<Transform>,
611        types: &Types,
612        dt: &DataType,
613        js_ident: &str,
614    ) -> Option<(Option<DataType>, String)> {
615        self.run(remap_bigint, transform_for_rule, types, dt, js_ident)
616            .0
617    }
618
619    fn try_apply(
620        &self,
621        remap_bigint: fn() -> DataType,
622        transform_for_rule: fn(&Rule) -> &Option<Transform>,
623        types: &Types,
624        dt: &DataType,
625        js_ident: &str,
626    ) -> Result<Option<(Option<DataType>, String)>, Error> {
627        let (result, error) = self.run(remap_bigint, transform_for_rule, types, dt, js_ident);
628        match error {
629            Some(error) => Err(error),
630            None => Ok(result),
631        }
632    }
633
634    fn apply_inner(
635        &self,
636        walk: &mut Walk<'_>,
637        dt: &DataType,
638        js_ident: &str,
639    ) -> Option<(Option<DataType>, String)> {
640        let result = match dt {
641            DataType::Reference(Reference::Named(r)) => {
642                if let Some(rule) = self.rule_for_reference(walk.types, r) {
643                    return Some((
644                        Some((rule.data_type.0)(Self::reference_source_dt(walk.types, r))),
645                        (walk.transform_for_rule)(rule).as_ref().map_or_else(
646                            || js_ident.to_owned(),
647                            |transform| transform.apply(js_ident),
648                        ),
649                    ));
650                }
651
652                match &r.inner {
653                    NamedReferenceType::Inline { dt, .. } => self.apply_inner(walk, dt, js_ident),
654                    // An inline cycle was cut short during definition. Treat it
655                    // like the cycle-stack cutoff so an enclosing enum reports
656                    // it rather than emitting a silently partial transform.
657                    NamedReferenceType::Recursive(_) => {
658                        walk.recursion_cut = true;
659                        None
660                    }
661                    NamedReferenceType::Reference { .. } => {
662                        let ndt = walk.types.get(r)?;
663
664                        let ty = ndt.ty.as_ref()?;
665                        let key = (ndt.name.clone(), ndt.module_path.clone());
666                        if walk.stack.contains(&key) {
667                            walk.recursion_cut = true;
668                            return None;
669                        }
670                        walk.stack.push(key);
671                        let previous = walk.current.replace(ndt);
672                        let result = self
673                            .apply_inner(walk, ty, js_ident)
674                            .map(|(_, runtime)| (None, runtime));
675                        walk.current = previous;
676                        walk.stack.pop();
677                        result
678                    }
679                }
680            }
681            DataType::Struct(s) => {
682                self.apply_fields(walk, &s.fields, js_ident)
683                    .map(|(fields, runtime)| {
684                        let ty = fields.map(|fields| {
685                            let mut next = s.clone();
686                            next.fields = fields;
687                            DataType::Struct(next)
688                        });
689                        (ty, runtime)
690                    })
691            }
692            DataType::Tuple(tuple) => {
693                let mut ty = tuple.clone();
694                let mut changed = false;
695                let parts = tuple
696                    .elements
697                    .iter()
698                    .enumerate()
699                    .filter_map(|(idx, element)| {
700                        let ident = format!("{js_ident}[{idx}]");
701                        let (next_ty, runtime) = self.apply_inner(walk, element, &ident)?;
702                        if let Some(next_ty) = next_ty {
703                            ty.elements[idx] = next_ty;
704                            changed = true;
705                        }
706                        (runtime != ident).then_some((idx, runtime))
707                    })
708                    .collect::<Vec<_>>();
709
710                if parts.is_empty() {
711                    changed.then_some((Some(DataType::Tuple(ty)), js_ident.to_owned()))
712                } else {
713                    Some((
714                        changed.then_some(DataType::Tuple(ty)),
715                        array_transform(js_ident, tuple.elements.len(), parts),
716                    ))
717                }
718            }
719            DataType::Map(map) => {
720                let item = "v";
721                let (next_ty, runtime) = self.apply_inner(walk, map.value_ty(), item)?;
722
723                let mut ty = map.clone();
724                let mut changed = false;
725                if let Some(next_ty) = next_ty {
726                    ty.set_value_ty(next_ty);
727                    changed = true;
728                }
729
730                Some((
731                    changed.then_some(DataType::Map(ty)),
732                    if runtime == item {
733                        js_ident.to_owned()
734                    } else {
735                        format!(
736                            "Object.fromEntries(Object.entries({js_ident}).map(([k,{item}])=>[k,{runtime}]))"
737                        )
738                    },
739                ))
740            }
741            DataType::List(list) => {
742                let item = "i";
743                let (next_ty, runtime) = self.apply_inner(walk, &list.ty, item)?;
744                let mut ty = list.clone();
745                let mut changed = false;
746                if let Some(next_ty) = next_ty {
747                    ty.ty = Box::new(next_ty);
748                    changed = true;
749                }
750                Some((
751                    changed.then_some(DataType::List(ty)),
752                    if runtime == item {
753                        js_ident.to_owned()
754                    } else {
755                        format!("{js_ident}.map({item}=>{runtime})")
756                    },
757                ))
758            }
759            DataType::Nullable(inner) => {
760                let (next_ty, runtime) = self.apply_inner(walk, inner, js_ident)?;
761                Some((
762                    next_ty.map(|dt| DataType::Nullable(Box::new(dt))),
763                    if runtime == js_ident {
764                        js_ident.to_owned()
765                    } else {
766                        format!("{js_ident}==null?{js_ident}:{runtime}")
767                    },
768                ))
769            }
770            DataType::Intersection(items) => {
771                let mut ty = items.clone();
772                let mut changed = false;
773                let mut parts = items
774                    .iter()
775                    .enumerate()
776                    .filter_map(|(idx, item)| {
777                        let (next_ty, runtime) = self.apply_inner(walk, item, js_ident)?;
778                        if let Some(next_ty) = next_ty {
779                            ty[idx] = next_ty;
780                            changed = true;
781                        }
782                        Some(runtime)
783                    })
784                    .collect::<Vec<_>>();
785
786                parts.dedup();
787
788                match parts.as_slice() {
789                    [] => None,
790                    [runtime] => Some((
791                        changed.then_some(DataType::Intersection(ty)),
792                        runtime.clone(),
793                    )),
794                    _ => Some((
795                        changed.then_some(DataType::Intersection(ty)),
796                        spread_transform(
797                            "",
798                            parts.into_iter().map(|p| format!("...{p}")).collect(),
799                        ),
800                    )),
801                }
802            }
803            DataType::Enum(e) => self.apply_enum(walk, e, js_ident),
804            DataType::Primitive(_)
805            | DataType::Generic(_)
806            | DataType::Reference(Reference::Opaque(_)) => None,
807        };
808
809        self.apply_builtin_remaps(walk.remap_bigint, dt, js_ident, result)
810    }
811
812    /// Apply the configured rules to one variant/struct [`Fields`] layout.
813    ///
814    /// Returns `None` when the layout needs neither a type nor a runtime
815    /// change, and otherwise the (possibly unchanged) fields plus the runtime
816    /// expression. This is shared by structs and enum variant payloads so the
817    /// two stay in agreement.
818    fn apply_fields(
819        &self,
820        walk: &mut Walk<'_>,
821        fields: &Fields,
822        js_ident: &str,
823    ) -> Option<(Option<Fields>, String)> {
824        match fields {
825            Fields::Unit => None,
826            Fields::Named(named) => {
827                let mut ty = named.clone();
828                let mut changed = false;
829                let mut parts = Vec::new();
830
831                for (name, field) in &named.fields {
832                    let Some(field_ty) = &field.ty else { continue };
833                    let field_ident = js_property_access(js_ident, name);
834                    let Some((next_ty, runtime)) = self.apply_inner(walk, field_ty, &field_ident)
835                    else {
836                        continue;
837                    };
838
839                    if let Some(next_ty) = next_ty
840                        && let Some((_, field)) = ty.fields.iter_mut().find(|(n, _)| n == name)
841                    {
842                        field.ty = Some(next_ty);
843                        changed = true;
844                    }
845                    if runtime != field_ident {
846                        parts.push(format!("{}:{runtime}", js_object_key(name)));
847                    }
848                }
849
850                if parts.is_empty() {
851                    changed.then_some((Some(Fields::Named(ty)), js_ident.to_owned()))
852                } else {
853                    Some((
854                        changed.then_some(Fields::Named(ty)),
855                        spread_transform(js_ident, parts),
856                    ))
857                }
858            }
859            Fields::Unnamed(unnamed) => {
860                let mut ty = unnamed.clone();
861                let mut changed = false;
862                let is_newtype = unnamed.fields.len() == 1;
863                let parts = unnamed
864                    .fields
865                    .iter()
866                    .enumerate()
867                    .filter_map(|(idx, field)| {
868                        let field_ty = field.ty.as_ref()?;
869                        let field_ident = if is_newtype {
870                            js_ident.to_owned()
871                        } else {
872                            format!("{js_ident}[{idx}]")
873                        };
874                        let (next_ty, runtime) = self.apply_inner(walk, field_ty, &field_ident)?;
875
876                        if let Some(next_ty) = next_ty {
877                            ty.fields[idx].ty = Some(next_ty);
878                            changed = true;
879                        }
880
881                        (runtime != field_ident).then_some((idx, runtime))
882                    })
883                    .collect::<Vec<_>>();
884
885                if parts.is_empty() {
886                    changed.then_some((Some(Fields::Unnamed(ty)), js_ident.to_owned()))
887                } else {
888                    Some((
889                        changed.then_some(Fields::Unnamed(ty)),
890                        if is_newtype {
891                            parts.into_iter().next()?.1
892                        } else {
893                            array_transform(js_ident, unnamed.fields.len(), parts)
894                        },
895                    ))
896                }
897            }
898        }
899    }
900
901    /// Generate a representation-aware runtime transform for an enum.
902    ///
903    /// The wire shape is the one produced by the format layer (for example
904    /// `specta_serde`): external variants are keyed by their serialized name,
905    /// internally/adjacently tagged variants carry a discriminator field, and
906    /// untagged variants carry no discriminant (and are told apart by their
907    /// payload shape). Each active variant's payload is transformed with the
908    /// same [`Fields`] traversal structs use, then the branches are dispatched
909    /// on the wire shape so the runtime value matches the remapped type.
910    ///
911    /// When a non-identity transform would be required beneath a shape that
912    /// cannot be discriminated without guessing (or beneath a recursive enum,
913    /// whose single-expression expansion would be partial), this records an
914    /// explicit [`Error`] and returns `None` rather than emitting an expression
915    /// that would let the exported type and the runtime value diverge.
916    fn apply_enum(
917        &self,
918        walk: &mut Walk<'_>,
919        e: &Enum,
920        js_ident: &str,
921    ) -> Option<(Option<DataType>, String)> {
922        let active = e
923            .variants
924            .iter()
925            .filter(|(_, variant)| !variant.skip)
926            .collect::<Vec<_>>();
927        if active.is_empty() {
928            return None;
929        }
930
931        let cut_before = walk.recursion_cut;
932
933        let mut branches = Vec::with_capacity(active.len());
934        let mut changed = false;
935        let mut needs_transform = false;
936        for (_, variant) in &active {
937            let (fields, runtime) = match self.apply_fields(walk, &variant.fields, js_ident) {
938                Some((fields, runtime)) => (fields, runtime),
939                None => (None, js_ident.to_owned()),
940            };
941            changed |= fields.is_some();
942            needs_transform |= runtime != js_ident;
943            branches.push((fields, runtime));
944        }
945
946        // A recursive expansion is cut short by the cycle stack, so the single
947        // expression we could emit would leave the nested values untransformed
948        // while the exported type claims otherwise. Report it instead.
949        if walk.recursion_cut && !cut_before {
950            self.record_unsupported(walk, RECURSIVE_ENUM_REASON);
951            return None;
952        }
953
954        let build = |branches: &mut Vec<(Option<Fields>, String)>| -> Option<DataType> {
955            if !changed {
956                return None;
957            }
958            let mut next = e.clone();
959            for ((_, variant), (fields, _)) in next
960                .variants
961                .iter_mut()
962                .filter(|(_, variant)| !variant.skip)
963                .zip(branches.iter_mut())
964            {
965                if let Some(fields) = fields.take() {
966                    variant.fields = fields;
967                }
968            }
969            Some(DataType::Enum(next))
970        };
971
972        if !needs_transform {
973            return build(&mut branches).map(|ty| (Some(ty), js_ident.to_owned()));
974        }
975
976        // A lone variant is never ambiguous: every value belongs to it.
977        if branches.len() == 1 {
978            let next_ty = build(&mut branches);
979            let (_, runtime) = branches.pop()?;
980            return Some((next_ty, runtime));
981        }
982
983        let needs = branches
984            .iter()
985            .map(|(_, runtime)| runtime != js_ident)
986            .collect::<Vec<_>>();
987        let Some(guards) = enum_branch_guards(walk.types, &active, &needs, js_ident) else {
988            self.record_unsupported(walk, UNSUPPORTED_ENUM_REASON);
989            return None;
990        };
991
992        let has_else = guards
993            .iter()
994            .any(|guard| matches!(guard, BranchGuard::Else));
995        let mut parts = Vec::new();
996        let mut fallback = None;
997        for ((_, runtime), guard) in branches.iter().zip(&guards) {
998            match guard {
999                BranchGuard::Match(condition) => {
1000                    if has_else || runtime != js_ident {
1001                        parts.push(format!("{condition}?{runtime}"));
1002                    }
1003                }
1004                BranchGuard::Else => fallback = Some(runtime.clone()),
1005            }
1006        }
1007
1008        let default = fallback.unwrap_or_else(|| js_ident.to_owned());
1009        let runtime = if parts.is_empty() {
1010            default
1011        } else {
1012            format!("{}:{}", parts.join(":"), default)
1013        };
1014
1015        let next_ty = build(&mut branches);
1016        Some((next_ty, runtime))
1017    }
1018
1019    /// Record the first unsupported construct, attaching the named type
1020    /// currently being expanded so the diagnostic can name it.
1021    fn record_unsupported(&self, walk: &mut Walk<'_>, reason: &'static str) {
1022        if walk.error.is_some() {
1023            return;
1024        }
1025
1026        let mut error = Error::unsupported_semantic_transform(reason);
1027        if let Some(ndt) = walk.current {
1028            error = error.with_named_datatype(ndt);
1029        }
1030        walk.error = Some(error);
1031    }
1032
1033    fn rule_for_reference<'a>(
1034        &'a self,
1035        types: &'a Types,
1036        reference: &specta::datatype::NamedReference,
1037    ) -> Option<&'a Rule> {
1038        let ndt = types.get(reference)?;
1039        self.rules
1040            .iter()
1041            .find(|rule| rule.name == ndt.name && rule.module_path == ndt.module_path)
1042    }
1043
1044    fn reference_source_dt(
1045        types: &Types,
1046        reference: &specta::datatype::NamedReference,
1047    ) -> DataType {
1048        match &reference.inner {
1049            NamedReferenceType::Inline { dt, .. } => (**dt).clone(),
1050            NamedReferenceType::Reference { .. } | NamedReferenceType::Recursive(_) => types
1051                .get(reference)
1052                .and_then(|ndt| ndt.ty.clone())
1053                .unwrap_or_else(|| DataType::Reference(Reference::Named(reference.clone()))),
1054        }
1055    }
1056
1057    fn has_builtin_remaps(&self) -> bool {
1058        self.lossless_bigint || self.lossless_floats
1059    }
1060
1061    fn apply_builtin_remaps(
1062        &self,
1063        remap_bigint: fn() -> DataType,
1064        dt: &DataType,
1065        js_ident: &str,
1066        result: Option<(Option<DataType>, String)>,
1067    ) -> Option<(Option<DataType>, String)> {
1068        if !self.has_builtin_remaps() {
1069            return result;
1070        }
1071
1072        let source = result
1073            .as_ref()
1074            .and_then(|(dt, _)| dt.clone())
1075            .unwrap_or_else(|| dt.clone());
1076        let mut remapped = source.clone();
1077        apply_builtin_remaps(
1078            &mut remapped,
1079            remap_bigint,
1080            self.lossless_bigint,
1081            self.lossless_floats,
1082        );
1083
1084        let runtime = result
1085            .as_ref()
1086            .map(|(_, runtime)| runtime.as_str())
1087            .unwrap_or(js_ident);
1088        let runtime = if is_lossless_bigint_primitive(&source)
1089            && self.lossless_bigint
1090            && remap_bigint() == deserialize_bigint()
1091        {
1092            format!("BigInt({runtime})")
1093        } else {
1094            runtime.to_owned()
1095        };
1096
1097        if remapped == source {
1098            result
1099        } else {
1100            Some((Some(remapped), runtime))
1101        }
1102    }
1103}
1104
1105fn prune_identity_root(
1106    types: &Types,
1107    dt: &DataType,
1108    js_ident: &str,
1109    result: Option<(Option<DataType>, String)>,
1110) -> Option<(Option<DataType>, String)> {
1111    let registered_root = matches!(
1112        dt,
1113        DataType::Reference(Reference::Named(reference))
1114            if !matches!(reference.inner, NamedReferenceType::Inline { .. })
1115                && types.get(reference).is_some_and(|ndt| ndt.ty.is_some())
1116    );
1117
1118    result.filter(|(next_ty, runtime)| {
1119        runtime != js_ident
1120            || next_ty
1121                .as_ref()
1122                .is_some_and(|next_ty| !registered_root || registered_generics_changed(dt, next_ty))
1123    })
1124}
1125
1126fn registered_generics_changed(dt: &DataType, next_ty: &DataType) -> bool {
1127    let (
1128        DataType::Reference(Reference::Named(source)),
1129        DataType::Reference(Reference::Named(remapped)),
1130    ) = (dt, next_ty)
1131    else {
1132        return false;
1133    };
1134    let (
1135        NamedReferenceType::Reference {
1136            generics: source, ..
1137        },
1138        NamedReferenceType::Reference {
1139            generics: remapped, ..
1140        },
1141    ) = (&source.inner, &remapped.inner)
1142    else {
1143        return false;
1144    };
1145
1146    source != remapped
1147}
1148
1149fn is_lossless_bigint_primitive(dt: &DataType) -> bool {
1150    matches!(
1151        dt,
1152        DataType::Primitive(
1153            Primitive::usize
1154                | Primitive::isize
1155                | Primitive::u64
1156                | Primitive::i64
1157                | Primitive::u128
1158                | Primitive::i128
1159        )
1160    )
1161}
1162
1163fn apply_builtin_remaps(
1164    dt: &mut DataType,
1165    remap_bigint: fn() -> DataType,
1166    lossless_bigint: bool,
1167    lossless_floats: bool,
1168) {
1169    if let DataType::Primitive(primitive) = dt
1170        && let Some(remapped) = remap_primitive(
1171            primitive.clone(),
1172            remap_bigint,
1173            lossless_bigint,
1174            lossless_floats,
1175        )
1176    {
1177        *dt = remapped;
1178        return;
1179    }
1180
1181    match dt {
1182        DataType::Primitive(_) | DataType::Generic(_) => {}
1183        DataType::List(list) => {
1184            apply_builtin_remaps(&mut list.ty, remap_bigint, lossless_bigint, lossless_floats)
1185        }
1186        DataType::Map(map) => {
1187            // Built-in lossless remaps (`BigInt`, `Number`) must not rewrite a
1188            // map key, including through generic/inline wrappers: keys are
1189            // JSON object property names, which the serializer stringifies.
1190            // `primitives::map_key_datatype` renders the key shape instead.
1191            apply_builtin_remaps(
1192                map.value_ty_mut(),
1193                remap_bigint,
1194                lossless_bigint,
1195                lossless_floats,
1196            );
1197        }
1198        DataType::Struct(s) => apply_builtin_remaps_to_fields(
1199            &mut s.fields,
1200            remap_bigint,
1201            lossless_bigint,
1202            lossless_floats,
1203        ),
1204        DataType::Enum(e) => {
1205            for (_, variant) in &mut e.variants {
1206                apply_builtin_remaps_to_fields(
1207                    &mut variant.fields,
1208                    remap_bigint,
1209                    lossless_bigint,
1210                    lossless_floats,
1211                );
1212            }
1213        }
1214        DataType::Tuple(tuple) => {
1215            for dt in &mut tuple.elements {
1216                apply_builtin_remaps(dt, remap_bigint, lossless_bigint, lossless_floats);
1217            }
1218        }
1219        DataType::Nullable(dt) => {
1220            apply_builtin_remaps(dt, remap_bigint, lossless_bigint, lossless_floats);
1221        }
1222        DataType::Intersection(dts) => {
1223            for dt in dts {
1224                apply_builtin_remaps(dt, remap_bigint, lossless_bigint, lossless_floats);
1225            }
1226        }
1227        DataType::Reference(reference) => {
1228            let Reference::Named(reference) = reference else {
1229                return;
1230            };
1231
1232            match &mut reference.inner {
1233                NamedReferenceType::Recursive(_) => {}
1234                NamedReferenceType::Inline { dt, .. } => {
1235                    apply_builtin_remaps(dt, remap_bigint, lossless_bigint, lossless_floats);
1236                }
1237                NamedReferenceType::Reference { generics, .. } => {
1238                    for (_, dt) in generics {
1239                        apply_builtin_remaps(dt, remap_bigint, lossless_bigint, lossless_floats);
1240                    }
1241                }
1242            }
1243        }
1244    }
1245}
1246
1247fn apply_builtin_remaps_to_fields(
1248    fields: &mut Fields,
1249    remap_bigint: fn() -> DataType,
1250    lossless_bigint: bool,
1251    lossless_floats: bool,
1252) {
1253    match fields {
1254        Fields::Unit => {}
1255        Fields::Unnamed(fields) => {
1256            for field in &mut fields.fields {
1257                if let Some(dt) = &mut field.ty {
1258                    apply_builtin_remaps(dt, remap_bigint, lossless_bigint, lossless_floats);
1259                }
1260            }
1261        }
1262        Fields::Named(fields) => {
1263            for (_, field) in &mut fields.fields {
1264                if let Some(dt) = &mut field.ty {
1265                    apply_builtin_remaps(dt, remap_bigint, lossless_bigint, lossless_floats);
1266                }
1267            }
1268        }
1269    }
1270}
1271
1272fn remap_primitive(
1273    primitive: Primitive,
1274    remap_bigint: fn() -> DataType,
1275    lossless_bigint: bool,
1276    lossless_floats: bool,
1277) -> Option<DataType> {
1278    if lossless_bigint
1279        && matches!(
1280            primitive,
1281            Primitive::usize
1282                | Primitive::isize
1283                | Primitive::u64
1284                | Primitive::i64
1285                | Primitive::u128
1286                | Primitive::i128
1287        )
1288    {
1289        return Some(remap_bigint());
1290    }
1291
1292    if lossless_floats && matches!(primitive, Primitive::f16 | Primitive::f32 | Primitive::f64) {
1293        return Some(Reference::opaque(crate::opaque::Number).into());
1294    }
1295
1296    None
1297}
1298
1299fn serialize_bigint() -> DataType {
1300    crate::define("bigint | number").into()
1301}
1302
1303fn deserialize_bigint() -> DataType {
1304    Reference::opaque(crate::opaque::BigInt).into()
1305}
1306
1307fn spread_transform(js_ident: &str, mut parts: Vec<String>) -> String {
1308    if !js_ident.is_empty() {
1309        parts.insert(0, format!("...{js_ident}"));
1310    }
1311    format!("({{{}}})", parts.join(","))
1312}
1313
1314fn array_transform(js_ident: &str, len: usize, parts: Vec<(usize, String)>) -> String {
1315    let mut items = (0..len)
1316        .map(|idx| format!("{js_ident}[{idx}]"))
1317        .collect::<Vec<_>>();
1318
1319    for (idx, runtime) in parts {
1320        items[idx] = runtime;
1321    }
1322
1323    format!("([{}])", items.join(","))
1324}
1325
1326/// Render a property read of `name` on `base`.
1327///
1328/// `__proto__` needs an own-property-safe read: both `base.__proto__` and
1329/// `base["__proto__"]` resolve to the inherited `Object.prototype` accessor
1330/// when no own property exists, so a transform body would run against the
1331/// prototype object (`new URL(Object.prototype)`). The descriptor form yields
1332/// the own value when present and `undefined` otherwise, and stays a valid base
1333/// expression for nested reads (`?.[]` short-circuits the whole chain).
1334///
1335/// Regression coverage for https://github.com/specta-rs/specta/issues/611.
1336fn js_property_access(base: &str, name: &str) -> String {
1337    if name == "__proto__" {
1338        format!(
1339            "Object.getOwnPropertyDescriptor({base},{})?.value",
1340            js_string_literal(name)
1341        )
1342    } else if is_identifier(name) {
1343        format!("{base}.{name}")
1344    } else {
1345        format!("{base}[\"{}\"]", escape_typescript_string_literal(name))
1346    }
1347}
1348
1349/// Render a wire key as an object-literal property key for a transform body.
1350///
1351/// `__proto__` must be a *computed* key. In an object literal, `__proto__:`
1352/// triggers the legacy prototype setter instead of defining an own property, so
1353/// `{...value, __proto__: new URL(value.__proto__)}` would silently keep the
1354/// wire value. Quoting the key does not help (`"__proto__":` is the same
1355/// special case); only `["__proto__"]:` defines an own property.
1356///
1357/// Regression coverage for https://github.com/specta-rs/specta/issues/611.
1358fn js_object_key(name: &str) -> Cow<'_, str> {
1359    if name == "__proto__" {
1360        Cow::Owned(format!("[{}]", js_string_literal(name)))
1361    } else if is_identifier(name) {
1362        Cow::Borrowed(name)
1363    } else {
1364        Cow::Owned(format!("\"{}\"", escape_typescript_string_literal(name)))
1365    }
1366}
1367
1368fn js_string_literal(value: &str) -> String {
1369    format!("\"{}\"", escape_typescript_string_literal(value))
1370}
1371
1372/// Mutable state shared across one `apply_serialize` / `apply_deserialize` call.
1373struct Walk<'a> {
1374    transform_for_rule: fn(&Rule) -> &Option<Transform>,
1375    remap_bigint: fn() -> DataType,
1376    types: &'a Types,
1377    /// Named types currently being expanded, used to cut recursive cycles.
1378    stack: Vec<(Cow<'static, str>, Cow<'static, str>)>,
1379    /// The first unsupported construct encountered, if any.
1380    error: Option<Error>,
1381    /// Set when a recursive reference was cut short by [`Walk::stack`].
1382    recursion_cut: bool,
1383    /// The named type currently being expanded, used to name errors.
1384    current: Option<&'a NamedDataType>,
1385}
1386
1387const UNSUPPORTED_ENUM_REASON: &str = "the enum's wire shape cannot be discriminated without guessing (for example overlapping `#[serde(untagged)]` variants); use a tagged representation or apply the rule to a non-ambiguous position";
1388const RECURSIVE_ENUM_REASON: &str = "the enum is recursive, so a single expression cannot transform nested values without the exported type claiming more than the runtime value provides";
1389
1390/// How a single enum branch is selected at runtime.
1391enum BranchGuard {
1392    /// A JavaScript expression that is truthy exactly for this variant.
1393    Match(String),
1394    /// The variant is the unguarded fallback: either a remapped untagged
1395    /// variant whose runtime shape may differ from its wire shape, or (for
1396    /// tagged enums) nothing.
1397    Else,
1398}
1399
1400/// Work out how to select each active variant from its wire value.
1401///
1402/// Prefers a shared discriminator field (internally/adjacently tagged enums),
1403/// then the external representation's per-variant key or string literal, then
1404/// structural discrimination of untagged variants. Returns `None` when no
1405/// unambiguous discrimination exists.
1406fn enum_branch_guards(
1407    types: &Types,
1408    active: &[&(Cow<'static, str>, Variant)],
1409    needs: &[bool],
1410    js_ident: &str,
1411) -> Option<Vec<BranchGuard>> {
1412    tag_branch_guards(active, js_ident)
1413        .or_else(|| external_branch_guards(active, js_ident))
1414        .or_else(|| untagged_branch_guards(types, active, needs, js_ident))
1415}
1416
1417/// Guards for a tagged enum: a field present in every variant with distinct
1418/// string-literal values (`#[serde(tag = ...)]`, optionally with `content`).
1419fn tag_branch_guards(
1420    active: &[&(Cow<'static, str>, Variant)],
1421    js_ident: &str,
1422) -> Option<Vec<BranchGuard>> {
1423    let candidates = active
1424        .iter()
1425        .map(|(_, variant)| variant_tag_candidates(variant))
1426        .collect::<Vec<_>>();
1427    let (key, literals) = common_tag_key(&candidates)?;
1428
1429    Some(
1430        literals
1431            .iter()
1432            .map(|literal| {
1433                BranchGuard::Match(format!(
1434                    "{js_ident}!=null&&{}==={}",
1435                    js_property_access(js_ident, &key),
1436                    js_string_literal(literal),
1437                ))
1438            })
1439            .collect(),
1440    )
1441}
1442
1443/// Guards for the external representation: a non-unit variant is keyed by its
1444/// serialized name, while a unit (or collapsed) variant is the bare string.
1445/// The discriminators must be distinct so overlapping shapes are rejected
1446/// rather than mis-dispatched.
1447///
1448/// The keyed guard uses an own-property check rather than `value.name !==
1449/// undefined`: the latter is also true for members inherited from
1450/// `Object.prototype` (a variant named `constructor`, `valueOf`, `toString`,
1451/// … would otherwise be selected for any object). The `=== literal` guard for
1452/// unit variants compares against a specific string, so it is unaffected.
1453fn external_branch_guards(
1454    active: &[&(Cow<'static, str>, Variant)],
1455    js_ident: &str,
1456) -> Option<Vec<BranchGuard>> {
1457    let mut discriminators = BTreeSet::new();
1458    let mut guards = Vec::with_capacity(active.len());
1459
1460    for (_, variant) in active {
1461        let (discriminator, guard) = match &variant.fields {
1462            Fields::Named(named) if named.fields.len() == 1 => {
1463                let name = named.fields[0].0.to_string();
1464                let guard = format!(
1465                    "{js_ident}!=null&&Object.prototype.hasOwnProperty.call({js_ident},{})",
1466                    js_string_literal(&name),
1467                );
1468                (name, guard)
1469            }
1470            Fields::Unnamed(unnamed) if unnamed.fields.len() == 1 => {
1471                let literal = string_literal_of(unnamed.fields[0].ty.as_ref()?)?;
1472                let guard = format!("{js_ident}==={}", js_string_literal(&literal));
1473                (literal, guard)
1474            }
1475            _ => return None,
1476        };
1477
1478        if !discriminators.insert(discriminator) {
1479            return None;
1480        }
1481        guards.push(BranchGuard::Match(guard));
1482    }
1483
1484    Some(guards)
1485}
1486
1487/// Guards for untagged enums, which have no discriminant and must be told
1488/// apart by their payload shape.
1489///
1490/// Every variant must occupy a distinct wire shape (`null`, `boolean`,
1491/// `number`, `string`, `Array.isArray`, object). At most one variant may have a
1492/// non-identity runtime transform, because a remapped payload can change its
1493/// runtime shape; that variant becomes the unguarded fallback. Overlapping
1494/// shapes are rejected rather than guessed.
1495fn untagged_branch_guards(
1496    types: &Types,
1497    active: &[&(Cow<'static, str>, Variant)],
1498    needs: &[bool],
1499    js_ident: &str,
1500) -> Option<Vec<BranchGuard>> {
1501    let mut shapes = Vec::with_capacity(active.len());
1502    let mut fallback = None;
1503
1504    for (idx, (_, variant)) in active.iter().enumerate() {
1505        let shape = untagged_payload_shape(types, variant)?;
1506        if needs[idx] && fallback.replace(idx).is_some() {
1507            return None;
1508        }
1509        shapes.push(shape);
1510    }
1511
1512    let mut seen = BTreeSet::new();
1513    for shape in &shapes {
1514        if !seen.insert(*shape) {
1515            return None;
1516        }
1517    }
1518
1519    Some(
1520        shapes
1521            .iter()
1522            .enumerate()
1523            .map(|(idx, shape)| {
1524                if Some(idx) == fallback {
1525                    BranchGuard::Else
1526                } else {
1527                    BranchGuard::Match(shape_guard(*shape, js_ident))
1528                }
1529            })
1530            .collect(),
1531    )
1532}
1533
1534/// The wire shape of an untagged variant's payload.
1535fn untagged_payload_shape(types: &Types, variant: &Variant) -> Option<UntaggedShape> {
1536    match &variant.fields {
1537        Fields::Unit => Some(UntaggedShape::Null),
1538        Fields::Named(_) => Some(UntaggedShape::Object),
1539        Fields::Unnamed(unnamed) => {
1540            let mut live = unnamed.fields.iter().filter_map(|field| field.ty.as_ref());
1541            let first = live.next()?;
1542            if live.next().is_some() {
1543                return Some(UntaggedShape::Array);
1544            }
1545            wire_shape(types, first, WIRE_SHAPE_DEPTH)
1546        }
1547    }
1548}
1549
1550/// The JavaScript value shape a wire datatype occupies, resolving newtype
1551/// wrappers and named references to the underlying wire type. Returns `None`
1552/// for shapes that cannot be classified (for example nullable payloads).
1553fn wire_shape(types: &Types, ty: &DataType, depth: usize) -> Option<UntaggedShape> {
1554    if depth == 0 {
1555        return None;
1556    }
1557
1558    match ty {
1559        DataType::Primitive(primitive) => Some(primitive_shape(primitive)),
1560        DataType::Tuple(tuple) if tuple.elements.is_empty() => Some(UntaggedShape::Null),
1561        DataType::List(_) => Some(UntaggedShape::Array),
1562        DataType::Map(_) => Some(UntaggedShape::Object),
1563        DataType::Struct(s) => match &s.fields {
1564            Fields::Named(_) => Some(UntaggedShape::Object),
1565            Fields::Unit => Some(UntaggedShape::Null),
1566            Fields::Unnamed(unnamed) => {
1567                let mut live = unnamed.fields.iter().filter_map(|field| field.ty.as_ref());
1568                let first = live.next()?;
1569                if live.next().is_some() {
1570                    Some(UntaggedShape::Array)
1571                } else {
1572                    wire_shape(types, first, depth - 1)
1573                }
1574            }
1575        },
1576        DataType::Reference(Reference::Named(r)) => {
1577            let source = Configuration::reference_source_dt(types, r);
1578            wire_shape(types, &source, depth - 1)
1579        }
1580        _ => None,
1581    }
1582}
1583
1584const WIRE_SHAPE_DEPTH: usize = 32;
1585
1586fn primitive_shape(primitive: &Primitive) -> UntaggedShape {
1587    match primitive {
1588        Primitive::bool => UntaggedShape::Boolean,
1589        Primitive::str | Primitive::char => UntaggedShape::String,
1590        Primitive::i8
1591        | Primitive::i16
1592        | Primitive::i32
1593        | Primitive::i64
1594        | Primitive::i128
1595        | Primitive::isize
1596        | Primitive::u8
1597        | Primitive::u16
1598        | Primitive::u32
1599        | Primitive::u64
1600        | Primitive::u128
1601        | Primitive::usize
1602        | Primitive::f16
1603        | Primitive::f32
1604        | Primitive::f64
1605        | Primitive::f128 => UntaggedShape::Number,
1606    }
1607}
1608
1609/// A JavaScript value shape used to tell untagged variants apart.
1610#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1611enum UntaggedShape {
1612    Null,
1613    Boolean,
1614    Number,
1615    String,
1616    Array,
1617    Object,
1618}
1619
1620fn shape_guard(shape: UntaggedShape, js_ident: &str) -> String {
1621    match shape {
1622        UntaggedShape::Null => format!("{js_ident}===null"),
1623        UntaggedShape::Boolean => format!("typeof {js_ident}===\"boolean\""),
1624        UntaggedShape::Number => format!("typeof {js_ident}===\"number\""),
1625        UntaggedShape::String => format!("typeof {js_ident}===\"string\""),
1626        UntaggedShape::Array => format!("Array.isArray({js_ident})"),
1627        UntaggedShape::Object => {
1628            format!("{js_ident}!=null&&typeof {js_ident}===\"object\"&&!Array.isArray({js_ident})")
1629        }
1630    }
1631}
1632
1633/// The literal value of a synthetic single-variant string enum, if `ty` is one.
1634fn string_literal_of(ty: &DataType) -> Option<String> {
1635    let DataType::Enum(e) = ty else {
1636        return None;
1637    };
1638
1639    let mut variants = e.variants.iter();
1640    let (name, variant) = variants.next()?;
1641    if variants.next().is_some() || !matches!(variant.fields, Fields::Unit) {
1642        return None;
1643    }
1644
1645    Some(name.to_string())
1646}
1647
1648/// Every `(key, literal)` discriminator candidate directly on a variant's wire
1649/// shape.
1650fn variant_tag_candidates(variant: &Variant) -> Vec<(String, String)> {
1651    let mut candidates = Vec::new();
1652    match &variant.fields {
1653        Fields::Named(named) => collect_tag_candidates(&named.fields, &mut candidates),
1654        Fields::Unnamed(unnamed) => {
1655            for field in &unnamed.fields {
1656                if let Some(ty) = &field.ty {
1657                    collect_datatype_tag_candidates(ty, &mut candidates);
1658                }
1659            }
1660        }
1661        Fields::Unit => {}
1662    }
1663    candidates
1664}
1665
1666fn collect_tag_candidates(
1667    fields: &[(Cow<'static, str>, Field)],
1668    candidates: &mut Vec<(String, String)>,
1669) {
1670    for (name, field) in fields {
1671        if field.optional {
1672            continue;
1673        }
1674        let Some(ty) = &field.ty else { continue };
1675        if let Some(literal) = string_literal_of(ty) {
1676            candidates.push((name.to_string(), literal));
1677        }
1678    }
1679}
1680
1681/// Descend the intersection/struct wrappers an internally tagged tuple variant
1682/// is rewritten into so its tag field is visible.
1683fn collect_datatype_tag_candidates(ty: &DataType, candidates: &mut Vec<(String, String)>) {
1684    match ty {
1685        DataType::Intersection(parts) => {
1686            for part in parts {
1687                collect_datatype_tag_candidates(part, candidates);
1688            }
1689        }
1690        DataType::Struct(s) => {
1691            if let Fields::Named(named) = &s.fields {
1692                collect_tag_candidates(&named.fields, candidates);
1693            }
1694        }
1695        _ => {}
1696    }
1697}
1698
1699/// The key shared by every variant with distinct literal values, if any, plus
1700/// the literal for each variant in order.
1701fn common_tag_key(candidates: &[Vec<(String, String)>]) -> Option<(String, Vec<String>)> {
1702    let first = candidates.first()?;
1703
1704    'keys: for (key, _) in first {
1705        let mut literals = Vec::with_capacity(candidates.len());
1706        let mut seen = BTreeSet::new();
1707        for variant in candidates {
1708            let matching = variant
1709                .iter()
1710                .filter(|(candidate, _)| candidate == key)
1711                .collect::<Vec<_>>();
1712            let [(_, literal)] = matching.as_slice() else {
1713                continue 'keys;
1714            };
1715            if !seen.insert(literal.clone()) {
1716                continue 'keys;
1717            }
1718            literals.push(literal.clone());
1719        }
1720
1721        return Some((key.clone(), literals));
1722    }
1723
1724    None
1725}