1use 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#[derive(Clone)]
86#[non_exhaustive]
87pub struct Transform(
88 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 pub fn new(runtime: impl Fn(&str) -> String + Send + Sync + 'static) -> Self {
117 Self(Some(Arc::new(runtime)))
118 }
119
120 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#[derive(Debug, Clone)]
162#[non_exhaustive]
163pub struct Rule {
164 pub name: Cow<'static, str>,
166 pub module_path: Cow<'static, str>,
168 pub(crate) data_type: DataTypeFn,
172 pub(crate) serialize: Option<Transform>,
175 pub(crate) deserialize: Option<Transform>,
178}
179
180#[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 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 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 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 ],
255 lossless_bigint: false,
256 lossless_floats: false,
257 }
258 }
259}
260
261impl Configuration {
262 pub fn empty() -> Self {
267 Self {
268 rules: Default::default(),
269 lossless_bigint: false,
270 lossless_floats: false,
271 }
272 }
273
274 pub fn rules_mut(&mut self) -> &mut Vec<Rule> {
278 &mut self.rules
279 }
280
281 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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
1326fn 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
1349fn 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
1372struct Walk<'a> {
1374 transform_for_rule: fn(&Rule) -> &Option<Transform>,
1375 remap_bigint: fn() -> DataType,
1376 types: &'a Types,
1377 stack: Vec<(Cow<'static, str>, Cow<'static, str>)>,
1379 error: Option<Error>,
1381 recursion_cut: bool,
1383 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
1390enum BranchGuard {
1392 Match(String),
1394 Else,
1398}
1399
1400fn 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
1417fn 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
1443fn 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
1487fn 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
1534fn 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
1550fn 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#[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
1633fn 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
1648fn 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
1681fn 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
1699fn 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}