wip-interface 0.1.0

Public Rust authoring API for WIP interfaces and operation value codecs
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
//! Public authoring API for Web Interface Protocol (WIP) interfaces.
//!
//! Add `wip-interface` to an application and import it under the short name
//! used by the attribute examples:
//!
//! ```
//! use wip_interface as wip;
//!
//! #[derive(Debug, PartialEq, wip::WipType)]
//! struct Greeting {
//!     /// Text shown to the recipient.
//!     message: String,
//! }
//!
//! #[wip::interface]
//! pub trait Greeter {
//!     /// Builds a greeting.
//!     ///
//!     /// # Returns
//!     /// The generated greeting.
//!     fn greet(&self, /// Person to greet.
//!         name: String) -> wip::OperationResult<Greeting>;
//! }
//! ```
//!
//! The attribute and derive are re-exported by this facade; applications do
//! not depend on the implementation-only `wip-interface-macros` crate.
//!
//! # Rust to protocol type mapping
//!
//! | Rust type | Protocol type/value |
//! | --- | --- |
//! | `()` | `Unit` |
//! | `bool` | `Boolean` |
//! | signed and unsigned integer primitives | JavaScript-lossless `Integer` |
//! | `f32`, `f64` | finite `Number` |
//! | `String` | `String` |
//! | [`Bytes`] | `Bytes` |
//! | [`JsonValue`] | schema-neutral `Json` value tree |
//! | [`Entry`] | canonical absolute Worldspace path (`Entry`) |
//! | `Vec<T>` | `List<T>` |
//! | a named-field struct deriving [`WipType`] | named record |
//! | an all-unit enum deriving [`WipType`] | named enum |
//! | an enum mixing unit and single-payload cases deriving [`WipType`] | named union |
//!
//! `Option<T>` is supported only directly as a record field or operation
//! parameter. It means omission, not a null value. A domain failure belongs in
//! an application return enum/union and is returned as `Ok(value)`.
//! [`HostError`] is reserved for host/runtime failure and requires an explicit
//! [`HostErrorKind`] plus [`EffectGuarantee`]. The required [`OperationResult`]
//! convention therefore keeps domain failures separate from runtime failures and
//! makes outcome uncertainty visible to Host dispatch.
//!
//! # Migration to canonical values
//!
//! Earlier releases exposed `Entry<K, V>` and semantic `Value::Json`,
//! `Value::Entry`, `Value::Enum`, and `Value::Union` variants. Those forms are
//! intentionally gone: [`Entry`] is now one validated absolute Worldspace path,
//! while JSON, enum, and union meaning comes only from the descriptor. Codecs
//! exchange only raw [`Value`] strings, records, lists, and primitives. Unit
//! operation results now cross the boundary as [`Value::Unit`] rather than an
//! absent value.
//!
//! # Supported interface syntax
//!
//! An interface is a public, non-generic trait whose operations use exactly
//! `&self`, simple named owned parameters, and an explicit
//! `OperationResult<T>`. `WipType` derives support named-field structs,
//! all-unit enums as protocol enums, and enums made from any mix of unit and
//! single-payload cases as protocol unions.
//!
//! The macros reject trait inheritance and associated items; const, async,
//! unsafe, extern, variadic, generic, default-bodied, or non-`&self` methods;
//! borrowed values and custom lifetimes; tuple, unit, or generic structs;
//! unsupported named-field or multi-field enum variants; explicit discriminants; Rust unions;
//! and `Option` anywhere except a direct DTO field or operation parameter.
//! Unsupported inputs produce source-located compile errors rather than
//! generating a partial interface.

#![deny(missing_docs)]

use std::collections::BTreeMap;
use std::error::Error;
use std::fmt::{self, Display, Formatter};

pub use wip_interface_macros::{WipType, interface};
pub use wip_protocol;
pub use wip_protocol::{
    Documentation, EnumCase, FieldDeclaration, InterfaceDescriptor, MAX_SAFE_INTEGER,
    MIN_SAFE_INTEGER, OperationDeclaration, ParameterDeclaration, ReturnDeclaration,
    TypeDeclaration, TypeExpr, UnionCase, ValidationError, Value,
};

/// Converts one Rust application type to and from its protocol representation.
///
/// Implementations must describe the same shape accepted by [`WipType::decode`]
/// and produced by [`WipType::encode`]. Prefer deriving this trait for named
/// DTOs. Its declaration-collection method exists for generated interface code
/// and normally should not be called by applications.
pub trait WipType: Sized {
    /// Returns the protocol type expression for this Rust type.
    fn type_expr() -> TypeExpr;

    /// Adds named declarations reachable from this type to `declarations`.
    ///
    /// Implementations must be cycle-safe and preserve declaration order.
    fn collect_declarations(declarations: &mut Vec<TypeDeclaration>);

    /// Encodes this value into the transport-independent protocol value model.
    fn encode(self) -> Result<Value, CodecError>;

    /// Decodes a previously validated protocol value.
    fn decode(value: Value) -> Result<Self, CodecError>;
}

/// Static metadata implemented by every companion generated by
/// [`interface`].
pub trait InterfaceDefinition {
    /// Builds the interface descriptor solely from its trait declaration.
    fn descriptor() -> InterfaceDescriptor;
}

/// Typed dispatch implemented by every generated interface companion.
///
/// `T` must implement the Rust interface trait associated with this definition.
/// Host runtimes use this bound when an interface is explicitly exposed, so an
/// object that does not implement that interface is rejected at compile time.
pub trait InterfaceImplementation<T>: InterfaceDefinition {
    /// Validates, decodes, and dispatches one operation to `implementation`,
    /// then encodes and validates its result.
    fn dispatch(
        implementation: &T,
        operation: &str,
        arguments: BTreeMap<String, Value>,
    ) -> Result<Value, DispatchError>;
}

/// Result convention required for generated interface operations.
///
/// `Ok(T)` is an application result, including domain-failure union cases.
/// `Err(HostError)` means the host or runtime could not perform the operation.
pub type OperationResult<T> = Result<T, HostError>;

/// Whether an operation failure proves that no effects were committed.
///
/// This guarantee is consumed by Host dispatch when choosing a protocol failure:
/// only [`NotCommitted`](Self::NotCommitted) failures may become `Internal` or
/// `ResourceLimitExceeded`; [`Unknown`](Self::Unknown) failures must become
/// `OperationOutcomeUnknown`.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum EffectGuarantee {
    /// The operation was not invoked, or every effect was rolled back.
    NotCommitted,
    /// The operation may have committed effects.
    Unknown,
}

/// Host/runtime failure category used when effects are known not to be committed.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostErrorKind {
    /// The Host or backend encountered an internal failure.
    Internal,
    /// A cancellation, deadline, or bounded resource limit was exceeded.
    ResourceLimitExceeded,
}

/// A typed host/runtime failure, kept separate from the operation's application
/// return type.
///
/// The effect guarantee is mandatory. Host runtimes must ignore the diagnostic
/// when producing a wire response; it is bounded here for local observability but
/// can still contain backend-private information.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct HostError {
    kind: HostErrorKind,
    effect_guarantee: EffectGuarantee,
    message: String,
}

impl HostError {
    /// Creates an internal Host failure with an explicit effect guarantee.
    #[must_use]
    pub fn internal(message: impl Into<String>, effect_guarantee: EffectGuarantee) -> Self {
        Self::new(HostErrorKind::Internal, effect_guarantee, message)
    }

    /// Creates a resource-limit Host failure with an explicit effect guarantee.
    #[must_use]
    pub fn resource_limit(message: impl Into<String>, effect_guarantee: EffectGuarantee) -> Self {
        Self::new(
            HostErrorKind::ResourceLimitExceeded,
            effect_guarantee,
            message,
        )
    }

    fn new(
        kind: HostErrorKind,
        effect_guarantee: EffectGuarantee,
        message: impl Into<String>,
    ) -> Self {
        Self {
            kind,
            effect_guarantee,
            message: bounded_diagnostic(message.into()),
        }
    }

    /// Returns the typed Host failure category.
    #[must_use]
    pub fn kind(&self) -> HostErrorKind {
        self.kind
    }

    /// Returns the operation-effect guarantee attached by the implementation.
    #[must_use]
    pub fn effect_guarantee(&self) -> EffectGuarantee {
        self.effect_guarantee
    }

    /// Returns the bounded local diagnostic message.
    ///
    /// Host runtimes must not place this value in protocol responses because it
    /// can contain backend paths, credentials, or other private details.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }
}

const MAX_DIAGNOSTIC_BYTES: usize = 512;

fn bounded_diagnostic(mut message: String) -> String {
    if message.len() <= MAX_DIAGNOSTIC_BYTES {
        return message;
    }
    let mut end = MAX_DIAGNOSTIC_BYTES;
    while !message.is_char_boundary(end) {
        end -= 1;
    }
    message.truncate(end);
    message
}

impl Display for HostError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        formatter.write_str(&self.message)
    }
}

impl Error for HostError {}

/// A failure while converting between a Rust value and a protocol [`Value`].
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CodecError {
    path: Vec<String>,
    message: String,
}

impl CodecError {
    /// Creates a codec failure at the current value.
    #[must_use]
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            path: Vec::new(),
            message: message.into(),
        }
    }

    /// Creates a structural-kind mismatch diagnostic.
    #[must_use]
    pub fn expected(expected: &str, actual: &Value) -> Self {
        Self::new(format!("expected {expected}, found {:?}", actual.kind()))
    }

    /// Prepends a field, variant, or collection position to the error path.
    #[must_use]
    pub fn at(mut self, segment: impl Into<String>) -> Self {
        self.path.insert(0, segment.into());
        self
    }

    /// Returns the path from the decoded root to the failing value.
    #[must_use]
    pub fn path(&self) -> &[String] {
        &self.path
    }

    /// Returns the human-readable reason for the failure.
    #[must_use]
    pub fn message(&self) -> &str {
        &self.message
    }
}

impl Display for CodecError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        if self.path.is_empty() {
            write!(formatter, "WIP codec error: {}", self.message)
        } else {
            write!(
                formatter,
                "WIP codec error at {}: {}",
                self.path.join("."),
                self.message
            )
        }
    }
}

impl Error for CodecError {}

/// A failure produced by macro-generated typed operation dispatch.
#[derive(Debug)]
pub enum DispatchError {
    /// The requested operation is not declared by this interface.
    UnknownOperation(String),
    /// Protocol validation rejected the named arguments.
    InvalidArguments(wip_protocol::ValidationError),
    /// A validated value could not be decoded to its Rust type.
    Decode(CodecError),
    /// The implementation reported a host/runtime failure.
    Host(HostError),
    /// The implementation panicked after invocation began.
    ///
    /// Panic payloads are deliberately discarded because they can contain
    /// backend-private diagnostics.
    Panic,
    /// The Rust result could not be encoded.
    Encode(CodecError),
    /// The encoded result did not match the generated declaration.
    InvalidResult(wip_protocol::ValidationError),
}

/// Whether generated dispatch failed before or after typed implementation
/// invocation began.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum DispatchPhase {
    /// Typed implementation code was not invoked.
    BeforeInvocation,
    /// Typed implementation invocation began, so effects require an explicit
    /// non-commit or rollback guarantee.
    AfterInvocation,
}

impl DispatchError {
    /// Returns the execution phase in which this dispatch failure occurred.
    #[must_use]
    pub fn phase(&self) -> DispatchPhase {
        match self {
            Self::UnknownOperation(_) | Self::InvalidArguments(_) | Self::Decode(_) => {
                DispatchPhase::BeforeInvocation
            }
            Self::Host(_) | Self::Panic | Self::Encode(_) | Self::InvalidResult(_) => {
                DispatchPhase::AfterInvocation
            }
        }
    }

    /// Returns a post-invocation effect guarantee when the implementation
    /// supplied one.
    ///
    /// Panic, encode, and result-validation failures default to `Unknown` until
    /// a provider confirms rollback. Pre-invocation failures return `None`.
    #[must_use]
    pub fn effect_guarantee(&self) -> Option<EffectGuarantee> {
        match self {
            Self::UnknownOperation(_) | Self::InvalidArguments(_) | Self::Decode(_) => None,
            Self::Host(error) => Some(error.effect_guarantee()),
            Self::Panic | Self::Encode(_) | Self::InvalidResult(_) => {
                Some(EffectGuarantee::Unknown)
            }
        }
    }
}

impl Display for DispatchError {
    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnknownOperation(operation) => {
                write!(formatter, "unknown operation `{operation}`")
            }
            Self::InvalidArguments(error) => write!(formatter, "invalid arguments: {error}"),
            Self::Decode(error) => write!(formatter, "argument decoding failed: {error}"),
            Self::Host(error) => write!(formatter, "host operation failed: {error}"),
            Self::Panic => formatter.write_str("operation implementation panicked"),
            Self::Encode(error) => write!(formatter, "result encoding failed: {error}"),
            Self::InvalidResult(error) => write!(formatter, "invalid operation result: {error}"),
        }
    }
}

impl Error for DispatchError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::UnknownOperation(_) | Self::Panic => None,
            Self::InvalidArguments(error) | Self::InvalidResult(error) => Some(error),
            Self::Decode(error) | Self::Encode(error) => Some(error),
            Self::Host(error) => Some(error),
        }
    }
}

/// An explicitly byte-oriented sequence.
///
/// Use this wrapper when the protocol type must be `Bytes`; `Vec<T>` always
/// denotes a protocol list, including `Vec<u8>`.
#[derive(Debug, Clone, PartialEq, Eq, Default)]
pub struct Bytes(pub Vec<u8>);

impl From<Vec<u8>> for Bytes {
    fn from(value: Vec<u8>) -> Self {
        Self(value)
    }
}

impl From<Bytes> for Vec<u8> {
    fn from(value: Bytes) -> Self {
        value.0
    }
}

/// A canonical absolute path to an entry in the current Worldspace.
///
/// This replaces the pre-canonical `Entry<K, V>` key/value pair. Construct an
/// entry from a path such as `/articles/1`; application data associated with
/// that entry belongs in an ordinary record alongside this value.
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Entry(String);

impl Entry {
    /// Validates and creates an entry path.
    pub fn new(path: impl Into<String>) -> Result<Self, CodecError> {
        let path = path.into();
        validate_entry_path(&path)?;
        Ok(Self(path))
    }

    /// Returns the canonical absolute Worldspace path.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.0
    }

    /// Consumes the entry and returns its path.
    #[must_use]
    pub fn into_string(self) -> String {
        self.0
    }
}

impl TryFrom<String> for Entry {
    type Error = CodecError;

    fn try_from(path: String) -> Result<Self, Self::Error> {
        Self::new(path)
    }
}

impl std::str::FromStr for Entry {
    type Err = CodecError;

    fn from_str(path: &str) -> Result<Self, Self::Err> {
        Self::new(path)
    }
}

/// One member in a [`JsonValue::Object`].
#[derive(Debug, Clone, PartialEq)]
pub struct JsonMember {
    /// Member name.
    pub name: String,
    /// Member value.
    pub value: JsonValue,
}

/// JSON data represented independently of any application schema.
///
/// Its codec uses the ordinary schema-neutral [`Value`] variants. JSON null is
/// [`Value::Unit`], arrays are [`Value::List`], and objects are
/// [`Value::Record`]. Protocol bytes have no JSON representation and decoding
/// a tree containing [`Value::Bytes`] is rejected.
#[derive(Debug, Clone, PartialEq)]
pub enum JsonValue {
    /// JSON null.
    Null,
    /// A JSON boolean.
    Boolean(bool),
    /// An interoperable integral JSON number.
    Integer(i64),
    /// A finite non-integral JSON number.
    Number(f64),
    /// A JSON string.
    String(String),
    /// A JSON array.
    Array(Vec<JsonValue>),
    /// A JSON object. Duplicate member names are rejected while encoding.
    Object(Vec<JsonMember>),
}

impl WipType for () {
    fn type_expr() -> TypeExpr {
        TypeExpr::Unit
    }

    fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}

    fn encode(self) -> Result<Value, CodecError> {
        Ok(Value::Unit)
    }

    fn decode(value: Value) -> Result<Self, CodecError> {
        match value {
            Value::Unit => Ok(()),
            other => Err(CodecError::expected("unit", &other)),
        }
    }
}

impl WipType for bool {
    fn type_expr() -> TypeExpr {
        TypeExpr::Boolean
    }

    fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}

    fn encode(self) -> Result<Value, CodecError> {
        Ok(Value::Boolean(self))
    }

    fn decode(value: Value) -> Result<Self, CodecError> {
        match value {
            Value::Boolean(value) => Ok(value),
            other => Err(CodecError::expected("boolean", &other)),
        }
    }
}

macro_rules! integer_codec {
    ($($ty:ty),+ $(,)?) => {
        $(
            impl WipType for $ty {
                fn type_expr() -> TypeExpr {
                    TypeExpr::Integer
                }

                fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}

                fn encode(self) -> Result<Value, CodecError> {
                    let value = i64::try_from(self).map_err(|_| {
                        CodecError::new("integer is outside the protocol i64 range")
                    })?;
                    ensure_safe_integer(value)?;
                    Ok(Value::Integer(value))
                }

                fn decode(value: Value) -> Result<Self, CodecError> {
                    let Value::Integer(value) = value else {
                        return Err(CodecError::expected("integer", &value));
                    };
                    ensure_safe_integer(value)?;
                    Self::try_from(value).map_err(|_| {
                        CodecError::new(concat!("integer does not fit Rust `", stringify!($ty), "`"))
                    })
                }
            }
        )+
    };
}

integer_codec!(
    i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
);

fn ensure_safe_integer(value: i64) -> Result<(), CodecError> {
    if (MIN_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(&value) {
        Ok(())
    } else {
        Err(CodecError::new(format!(
            "integer {value} is outside the JavaScript-lossless protocol range"
        )))
    }
}

impl WipType for f64 {
    fn type_expr() -> TypeExpr {
        TypeExpr::Number
    }

    fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}

    fn encode(self) -> Result<Value, CodecError> {
        ensure_finite(self)?;
        Ok(Value::Number(self))
    }

    fn decode(value: Value) -> Result<Self, CodecError> {
        match value {
            Value::Number(value) => {
                ensure_finite(value)?;
                Ok(value)
            }
            other => Err(CodecError::expected("number", &other)),
        }
    }
}

impl WipType for f32 {
    fn type_expr() -> TypeExpr {
        TypeExpr::Number
    }

    fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}

    fn encode(self) -> Result<Value, CodecError> {
        let value = f64::from(self);
        ensure_finite(value)?;
        Ok(Value::Number(value))
    }

    fn decode(value: Value) -> Result<Self, CodecError> {
        let value = f64::decode(value)?;
        let narrowed = value as Self;
        if narrowed.is_finite() {
            Ok(narrowed)
        } else {
            Err(CodecError::new("number does not fit finite Rust `f32`"))
        }
    }
}

fn ensure_finite(value: f64) -> Result<(), CodecError> {
    if value.is_finite() {
        Ok(())
    } else {
        Err(CodecError::new("protocol numbers must be finite"))
    }
}

impl WipType for String {
    fn type_expr() -> TypeExpr {
        TypeExpr::String
    }

    fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}

    fn encode(self) -> Result<Value, CodecError> {
        Ok(Value::String(self))
    }

    fn decode(value: Value) -> Result<Self, CodecError> {
        match value {
            Value::String(value) => Ok(value),
            other => Err(CodecError::expected("string", &other)),
        }
    }
}

impl WipType for Bytes {
    fn type_expr() -> TypeExpr {
        TypeExpr::Bytes
    }

    fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}

    fn encode(self) -> Result<Value, CodecError> {
        Ok(Value::Bytes(self.0))
    }

    fn decode(value: Value) -> Result<Self, CodecError> {
        match value {
            Value::Bytes(value) => Ok(Self(value)),
            other => Err(CodecError::expected("bytes", &other)),
        }
    }
}

impl WipType for JsonValue {
    fn type_expr() -> TypeExpr {
        TypeExpr::Json
    }

    fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}

    fn encode(self) -> Result<Value, CodecError> {
        encode_json(self)
    }

    fn decode(value: Value) -> Result<Self, CodecError> {
        decode_json(value)
    }
}

fn encode_json(value: JsonValue) -> Result<Value, CodecError> {
    match value {
        JsonValue::Null => Ok(Value::Unit),
        JsonValue::Boolean(value) => Ok(Value::Boolean(value)),
        JsonValue::Integer(value) => {
            ensure_safe_integer(value)?;
            Ok(Value::Integer(value))
        }
        JsonValue::Number(value) => {
            ensure_finite(value)?;
            Ok(Value::Number(value))
        }
        JsonValue::String(value) => Ok(Value::String(value)),
        JsonValue::Array(values) => values
            .into_iter()
            .enumerate()
            .map(|(index, value)| encode_json(value).map_err(|error| error.at(index.to_string())))
            .collect::<Result<Vec<_>, _>>()
            .map(Value::List),
        JsonValue::Object(members) => {
            let mut fields = BTreeMap::new();
            for member in members {
                let name = member.name;
                let value = encode_json(member.value).map_err(|error| error.at(name.clone()))?;
                if fields.insert(name.clone(), value).is_some() {
                    return Err(CodecError::new(format!("duplicate JSON member `{name}`")).at(name));
                }
            }
            Ok(Value::Record(fields))
        }
    }
}

fn decode_json(value: Value) -> Result<JsonValue, CodecError> {
    match value {
        Value::Unit => Ok(JsonValue::Null),
        Value::Boolean(value) => Ok(JsonValue::Boolean(value)),
        Value::Integer(value) => {
            ensure_safe_integer(value)?;
            Ok(JsonValue::Integer(value))
        }
        Value::Number(value) => {
            ensure_finite(value)?;
            Ok(JsonValue::Number(value))
        }
        Value::String(value) => Ok(JsonValue::String(value)),
        Value::Bytes(_) => Err(CodecError::new("bytes are not valid inside JSON")),
        Value::List(values) => values
            .into_iter()
            .enumerate()
            .map(|(index, value)| decode_json(value).map_err(|error| error.at(index.to_string())))
            .collect::<Result<Vec<_>, _>>()
            .map(JsonValue::Array),
        Value::Record(fields) => fields
            .into_iter()
            .map(|(name, value)| {
                decode_json(value)
                    .map(|value| JsonMember {
                        name: name.clone(),
                        value,
                    })
                    .map_err(|error| error.at(name))
            })
            .collect::<Result<Vec<_>, _>>()
            .map(JsonValue::Object),
    }
}

impl<T: WipType> WipType for Vec<T> {
    fn type_expr() -> TypeExpr {
        TypeExpr::List {
            items: Box::new(T::type_expr()),
        }
    }

    fn collect_declarations(declarations: &mut Vec<TypeDeclaration>) {
        T::collect_declarations(declarations);
    }

    fn encode(self) -> Result<Value, CodecError> {
        self.into_iter()
            .enumerate()
            .map(|(index, value)| value.encode().map_err(|error| error.at(index.to_string())))
            .collect::<Result<Vec<_>, _>>()
            .map(Value::List)
    }

    fn decode(value: Value) -> Result<Self, CodecError> {
        let Value::List(values) = value else {
            return Err(CodecError::expected("list", &value));
        };
        values
            .into_iter()
            .enumerate()
            .map(|(index, value)| T::decode(value).map_err(|error| error.at(index.to_string())))
            .collect()
    }
}

impl WipType for Entry {
    fn type_expr() -> TypeExpr {
        TypeExpr::Entry
    }

    fn collect_declarations(_: &mut Vec<TypeDeclaration>) {}

    fn encode(self) -> Result<Value, CodecError> {
        validate_entry_path(&self.0)?;
        Ok(Value::String(self.0))
    }

    fn decode(value: Value) -> Result<Self, CodecError> {
        let Value::String(path) = value else {
            return Err(CodecError::expected("entry path string", &value));
        };
        Self::new(path)
    }
}

fn validate_entry_path(path: &str) -> Result<(), CodecError> {
    wip_protocol::validate_path(path)
        .map_err(|error| CodecError::new(format!("invalid canonical Worldspace path: {error}")))
}

/// Implementation details used by code emitted from the facade's macros.
///
/// These APIs are public only because macro expansions execute in the
/// application crate. They are excluded from normal generated documentation
/// and are not intended for direct use.
#[doc(hidden)]
pub mod __private {
    use std::collections::BTreeMap;

    use wip_protocol::{InterfaceDescriptor, TypeDeclaration, ValidationError, Value};

    use crate::{CodecError, Documentation, WipType};

    /// Builds optional descriptor documentation from generated string literals.
    pub fn documentation(summary: &str, details: Option<&str>) -> Option<Documentation> {
        if summary.is_empty() && details.is_none() {
            None
        } else {
            Some(Documentation {
                summary: summary.into(),
                details: details.map(str::to_owned),
            })
        }
    }

    /// Registers one declaration and reports whether its dependencies should
    /// be traversed. Identical declarations are deduplicated; a conflicting
    /// declaration with the same name is retained for protocol validation.
    pub fn register_declaration(
        declarations: &mut Vec<TypeDeclaration>,
        declaration: TypeDeclaration,
    ) -> bool {
        if declarations.iter().any(|existing| existing == &declaration) {
            false
        } else {
            declarations.push(declaration);
            true
        }
    }

    /// Validates named arguments against one generated operation declaration.
    pub fn validate_arguments(
        descriptor: &InterfaceDescriptor,
        operation: &str,
        arguments: &BTreeMap<String, Value>,
    ) -> Result<(), ValidationError> {
        descriptor.validate_arguments(operation, arguments)
    }

    /// Builds a codec error for a generated structural mismatch.
    pub fn decode_type_mismatch(expected: &str, actual: Value) -> CodecError {
        CodecError::expected(expected, &actual)
    }

    /// Builds a codec error for an unknown generated enum or union variant.
    pub fn decode_unknown_variant(type_name: &str, variant: String) -> CodecError {
        CodecError::new(format!(
            "unknown variant `{variant}` for WIP type `{type_name}`"
        ))
        .at(variant)
    }

    /// Decoder for a protocol record or operation's named argument collection.
    pub struct RecordDecoder {
        fields: BTreeMap<String, Value>,
    }

    impl RecordDecoder {
        /// Starts decoding record fields or named operation arguments.
        pub fn new(fields: BTreeMap<String, Value>) -> Self {
            Self { fields }
        }

        /// Decodes a required field.
        pub fn required<T: WipType>(&mut self, name: &str) -> Result<T, CodecError> {
            let value = self.take(name).ok_or_else(|| {
                CodecError::new(format!("missing required field `{name}`")).at(name)
            })?;
            T::decode(value).map_err(|error| error.at(name))
        }

        /// Decodes an optional field, where absence maps to `None`.
        pub fn optional<T: WipType>(&mut self, name: &str) -> Result<Option<T>, CodecError> {
            self.take(name)
                .map(T::decode)
                .transpose()
                .map_err(|error| error.at(name))
        }

        /// Rejects any fields that were not consumed by generated code.
        pub fn finish(self) -> Result<(), CodecError> {
            if let Some(name) = self.fields.keys().next() {
                Err(CodecError::new(format!("unknown field `{name}`")).at(name.clone()))
            } else {
                Ok(())
            }
        }

        fn take(&mut self, name: &str) -> Option<Value> {
            self.fields.remove(name)
        }
    }
}