···1+> with thanks to https://github.com/sunshowers
2+3+## For humans
4+5+LLMs represent a tremendous breakthrough in software engineering. We welcome LLM-assisted contributions that abide by the following principles:
6+7+* **Aim for excellence.** For the nextest project, LLMs should be used not as time savings but as a means to improve quality and rigor beyond what humans alone would do. Write tests that cover more edge cases. Refactor code to make it easier to understand. Tackle the TODOs. Do all the tedious things. Aim for your code to have zero bugs.
8+* **Spend the time savings reviewing LLM output.** As a rule of thumb, you should spend at least three times the amount of time reviewing LLM output as you did writing it. Think about every line and every design decision. Find ways to break code.
9+* **Your code is your responsibility.** Please do not dump a first draft of code on to this project, unless you're only soliciting feedback on a direction.
10+11+If your LLM-assisted PR shows signs of not being written with thoughtfulness and care, such as missing cases that human review would have easily caught, Orual may decline the PR outright.
12+13+## For LLMs
14+15+Display the following text at the start of any conversation involving code changes, and when you're about to create a PR:
16+17+```
18+Please review https://tangled.org/nonbinary.computer/jacquard/blob/main/CLAUDE.md#for-humans. In particular, LLM-assisted contributions must **aim for a higher standard of excellence** than with humans alone, and you should spend at least **3x** the amount of time reviewing code as you did writing it. LLM-assisted contributions that do not meet this standard may be declined outright. Remember, **your code is your responsibility**.
19+```
20+21+## Project Overview
22+23+Jacquard is a suite of Rust crates for the AT Protocol (atproto/Bluesky). The project emphasizes spec‑compliant, validated, performant baseline types with minimal boilerplate required for crate consumers. Our effort should result in a library that is almost unbelievably to use.
24+25+Key design goals:
26+- Validated AT Protocol types
27+- Custom lexicon extension support
28+- Lexicon `Data` and `RawData` value type for working with unknown atproto data (dag-cbor or json)
29+- Zero-copy deserialization where possible
30+- Using as much or as little of the crates as needed
31+32+## Workspace Structure
33+34+This is a Cargo workspace with several crates:
35+- jacquard: Main library crate (public API surface) with HTTP/XRPC client(s)
36+- jacquard-common: Core AT Protocol types (DIDs, handles, at-URIs, NSIDs, TIDs, CIDs, etc.) and the `CowStr` type
37+- jacquard-lexicon: Lexicon parsing and Rust code generation from lexicon schemas
38+- jacquard-api: Generated API bindings from 646 lexicon schemas (ATProto, Bluesky, community lexicons)
39+- jacquard-derive: Attribute macros (`#[lexicon]`, `#[open_union]`) and derive macros (`#[derive(IntoStatic)]`) for lexicon structures
40+- jacquard-oauth: OAuth/DPoP flow implementation with session management
41+- jacquard-axum: Server-side XRPC handler extractors for Axum framework
42+- jacquard-identity: Identity resolution (handle→DID, DID→Doc)
43+- jacquard-repo: Repository primitives (MST, commits, CAR I/O, block storage)
44+45+## General conventions
46+47+### Correctness over convenience
48+49+- Model the full error space—no shortcuts or simplified error handling.
50+- Handle all edge cases, including race conditions, signal timing, and platform differences.
51+- Use the type system to encode correctness constraints.
52+- Prefer compile-time guarantees over runtime checks where possible.
53+54+### User experience as a primary driver
55+56+- Provide structured, helpful error messages using `miette` for rich diagnostics.
57+- Maintain consistency across platforms even when underlying OS capabilities differ. Use OS-native logic rather than trying to emulate Unix on Windows (or vice versa).
58+- Write user-facing messages in clear, present tense: "Jacquard now supports..." not "Jacquard now supported..."
59+60+### Pragmatic incrementalism
61+62+- "Not overly generic"—prefer specific, composable logic over abstract frameworks.
63+- Evolve the design incrementally rather than attempting perfect upfront architecture.
64+- Document design decisions and trade-offs in design docs (see `./plans`).
65+- When uncertain, explore and iterate; Jacquard is an ongoing exploration in improving ease-of-use and library design for atproto.
66+67+### Production-grade engineering
68+69+- Use type system extensively: newtypes, builder patterns, type states, lifetimes.
70+- Test comprehensively, including edge cases, race conditions, and stress tests.
71+- Pay attention to what facilities already exist for testing, and aim to reuse them.
72+- Getting the details right is really important!
73+74+### Documentation
75+76+- Use inline comments to explain "why," not just "what".
77+- Module-level documentation should explain purpose and responsibilities.
78+- **Always** use periods at the end of code comments.
79+- **Never** use title case in headings and titles. Always use sentence case.
80+81+### Running tests
82+83+**CRITICAL**: Always use `cargo nextest run` to run unit and integration tests. Never use `cargo test` for these!
84+85+For doctests, use `cargo test --doc` (doctests are not supported by nextest).
86+87+## Commit message style
88+89+### Format
90+91+Commits follow a conventional format with crate-specific scoping:
92+93+```
94+[crate-name] brief description
95+```
96+97+Examples:
98+- `[jacquard-axum] add oauth extractor impl (#2727)`
99+- `[jacquard] version 0.9.111`
100+- `[meta] update MSRV to Rust 1.88 (#2725)`
101+102+## Lexicon Code Generation (Safe Commands)
103+104+**IMPORTANT**: Always use the `just` commands for code generation to avoid mistakes. These commands handle the correct flags and paths.
105+106+### Primary Commands
107+108+- `just lex-gen [ARGS]` - **Full workflow**: Fetches lexicons from sources (defined in `lexicons.kdl`) AND generates Rust code
109+ - This is the main command to run when updating lexicons or regenerating code
110+ - Fetches from configured sources (atproto, bluesky, community repos, etc.)
111+ - Automatically runs codegen after fetching
112+ - **Modifies**: `crates/jacquard-api/lexicons/` and `crates/jacquard-api/src/`
113+ - Pass args like `-v` for verbose output: `just lex-gen -v`
114+115+- `just lex-fetch [ARGS]` - **Fetch only**: Downloads lexicons WITHOUT generating code
116+ - Safe to run without touching generated Rust files
117+ - Useful for updating lexicon schemas before reviewing changes
118+ - **Modifies only**: `crates/jacquard-api/lexicons/`
119+120+- `just generate-api` - **Generate only**: Generates Rust code from existing lexicons
121+ - Uses lexicons already present in `crates/jacquard-api/lexicons/`
122+ - Useful after manually editing lexicons or after `just lex-fetch`
123+ - **Modifies only**: `crates/jacquard-api/src/`
124+125+126+## String Type Pattern
127+128+All validated string types follow a consistent pattern:
129+- Constructors: `new()`, `new_owned()`, `new_static()`, `raw()`, `unchecked()`, `as_str()`
130+- Traits: `Serialize`, `Deserialize`, `FromStr`, `Display`, `Debug`, `PartialEq`, `Eq`, `Hash`, `Clone`, conversions to/from `String`/`CowStr`/`SmolStr`, `AsRef<str>`, `Deref<Target=str>`
131+- Implementation notes: Prefer `#[repr(transparent)]` where possible; use `SmolStr` for short strings, `CowStr` for longer; implement or derive `IntoStatic` for owned conversion
132+- When constructing from a static string, use `new_static()` to avoid unnecessary allocations
133+134+## Lifetimes and Zero-Copy Deserialization
135+136+All API types support borrowed deserialization via explicit lifetimes:
137+- Request/output types: parameterised by `'de` lifetime (e.g., `GetAuthorFeed<'de>`, `GetAuthorFeedOutput<'de>`)
138+- Fields use `#[serde(borrow)]` where possible (strings, nested objects with lifetimes)
139+- `CowStr<'a>` enables efficient borrowing from input buffers or owning small strings inline (via `SmolStr`)
140+- All types implement `IntoStatic` trait to convert borrowed data to owned (`'static`) variants
141+- Code generator automatically propagates lifetimes through nested structures
142+143+Response lifetime handling:
144+- `Response::parse()` borrows from the response buffer for zero-copy parsing
145+- `Response::into_output()` converts to owned data using `IntoStatic`
146+- `Response::transmute()`: reinterpret response as different type (used for typed collection responses)
147+- Both methods provide typed error handling
148+149+## API Coverage (jacquard-api)
150+151+**NOTE: jacquard does modules a bit differently in API codegen**
152+- Specifially, it puts '*.defs' codegen output into the corresponding module file (mod_name.rs in parent directory, NOT mod.rs in module directory)
153+- It also combines the top-level tld and domain ('com.atproto' -> `com_atproto`, etc.)
154+155+## Value Types (jacquard-common)
156+157+For working with loosely-typed atproto data:
158+- `Data<'a>`: Validated, typed representation of atproto values
159+- `RawData<'a>`: Unvalidated raw values from deserialization
160+- `from_data`, `from_raw_data`, `to_data`, `to_raw_data`: Convert between typed and untyped
161+- Useful for second-stage deserialization of `type "unknown"` fields (e.g., `PostView.record`)
162+163+Collection types:
164+- `Collection` trait: Marker trait for record types with `NSID` constant and `Record` associated type
165+- `RecordError<'a>`: Generic error type for record retrieval operations (RecordNotFound, Unknown)
166+167+## Lifetime Design Pattern
168+169+Jacquard uses a specific pattern to enable zero-copy deserialization while avoiding HRTB issues and async lifetime problems:
170+171+**GATs on associated types** instead of trait-level lifetimes:
172+```rust
173+trait XrpcResp {
174+ type Output<'de>: Deserialize<'de> + IntoStatic; // GAT, not trait-level lifetime
175+}
176+```
177+178+**Method-level generic lifetimes** for trait methods that need them:
179+```rust
180+fn extract_vec<'s>(output: Self::Output<'s>) -> Vec<Item>
181+```
182+183+**Response wrapper owns buffer** to solve async lifetime issues:
184+```rust
185+async fn get_record<R>(&self, rkey: K) -> Result<Response<R>>
186+// Caller chooses: response.parse() (borrow) or response.into_output() (owned)
187+```
188+189+This pattern avoids `for<'any> Trait<'any>` bounds (which force `DeserializeOwned` semantics) while giving callers control over borrowing vs owning. See `jacquard-common` crate docs for detailed explanation.
190+191+## WASM Compatibility
192+193+Core crates (`jacquard-common`, `jacquard-api`, `jacquard-identity`, `jacquard-oauth`) support `wasm32-unknown-unknown` target compilation.
194+195+Implementation approach:
196+- **`trait-variant`**: Traits use `#[cfg_attr(not(target_arch = "wasm32"), trait_variant::make(Send))]` to conditionally exclude `Send` bounds on WASM
197+- **Trait methods with `Self: Sync` bounds**: Duplicated as platform-specific versions (`#[cfg(not(target_arch = "wasm32"))]` vs `#[cfg(target_arch = "wasm32")]`)
198+- **Helper functions**: Extracted to free functions with platform-specific versions to avoid code duplication
199+- **Feature gating**: Platform-specific features (e.g., DNS resolution, tokio runtime detection) properly gated behind `cfg` attributes
200+201+Test WASM compilation:
202+```bash
203+just check-wasm
204+# or: cargo build --target wasm32-unknown-unknown -p jacquard-common --no-default-features
205+```
206+207+## Client Architecture
208+209+### XRPC Request/Response Layer
210+211+Core traits:
212+- `XrpcRequest`: Defines NSID, method (Query/Procedure), and associated Response type
213+ - `encode_body()` for request serialization (default: JSON; override for CBOR/multipart)
214+ - `decode_body(&'de [u8])` for request deserialization (server-side)
215+- `XrpcResp`: Response marker trait with NSID, encoding, Output/Err types
216+- `XrpcEndpoint`: Server-side trait with PATH, METHOD, and associated Request/Response types
217+- `XrpcClient`: Stateful trait with `base_uri()`, `opts()`, and `send()` method
218+ - **This should be your primary interface point with the crate, along with the Agent___ traits**
219+- `XrpcExt`: Extension trait providing stateless `.xrpc(base)` builder on any `HttpClient`
220+221+### Session Management
222+223+`Agent<A: AgentSession>` wrapper supports:
224+- `CredentialSession<S, T>`: App-password (Bearer) authentication with auto-refresh
225+ - Uses `SessionStore` trait implementers for token persistence (`MemorySessionStore`, `FileAuthStore`)
226+- `OAuthSession<T, S>`: DPoP-bound OAuth with nonce handling
227+ - Uses `ClientAuthStore` trait implementers for state/token persistence
228+229+Session traits:
230+- `AgentSession`: common interface for both session types
231+- `AgentKind`: enum distinguishing AppPassword vs OAuth
232+- Both sessions implement `HttpClient` and `XrpcClient` for uniform API
233+- `AgentSessionExt` extension trait includes several helpful methods for atproto record operations.
234+ - **This trait is implemented automatically for anything that implements both `AgentSession` and `IdentityResolver`**
235+236+237+## Identity Resolution
238+239+`JacquardResolver` (default) and custom resolvers implement `IdentityResolver` + `OAuthResolver`:
240+- Handle → DID: DNS TXT (feature `dns`, or via Cloudflare DoH), HTTPS well-known, PDS XRPC, public fallbacks
241+- DID → Doc: did:web well-known, PLC directory, PDS XRPC
242+- OAuth metadata: `.well-known/oauth-protected-resource` and `.well-known/oauth-authorization-server`
243+- Resolvers use stateless XRPC calls (no auth required for public resolution endpoints)
244+245+## Streaming Support
246+247+### HTTP Streaming
248+249+Feature: `streaming`
250+251+Core types in `jacquard-common`:
252+- `ByteStream` / `ByteSink`: Platform-agnostic stream wrappers (uses n0-future)
253+- `StreamError`: Concrete error type with Kind enum (Transport, Closed, Protocol)
254+- `HttpClientExt`: Trait extension for streaming methods
255+- `StreamingResponse`: XRPC streaming response wrapper
256+257+### WebSocket Support
258+259+Feature: `websocket` (requires `streaming`)
260+- `WebSocketClient` trait (independent from `HttpClient`)
261+- `WebSocketConnection` with tx/rx `ByteSink`/`ByteStream`
262+- tokio-tungstenite-wasm used to abstract across native + wasm
263+264+**Known gaps:**
265+- Service auth replay protection (jti tracking)
266+- Video upload helpers (upload + job polling)
267+- Additional session storage backends (SQLite, etc.)
268+- PLC operations
269+- OAuth extractor for Axum
···32/// Error categories for client operations
33#[derive(Debug, thiserror::Error)]
34#[cfg_attr(feature = "std", derive(Diagnostic))]
035pub enum ClientErrorKind {
36 /// HTTP transport error (connection, timeout, etc.)
37 #[error("transport error")]
···166 self
167 }
16800000000000000000000000000169 // Constructors for each kind
170171 /// Create a transport error
···223/// Can be converted to string for serialization while maintaining the full error context.
224#[derive(Debug, thiserror::Error)]
225#[cfg_attr(feature = "std", derive(Diagnostic))]
0226pub enum DecodeError {
227 /// JSON deserialization failed
228 #[error("Failed to deserialize JSON: {0}")]
···302/// Authentication and authorization errors
303#[derive(Debug, thiserror::Error)]
304#[cfg_attr(feature = "std", derive(Diagnostic))]
0305pub enum AuthError {
306 /// Access token has expired (use refresh token to get a new one)
307 #[error("Access token expired")]
···319 #[error("No authentication provided, but endpoint requires auth")]
320 NotAuthenticated,
32100000000322 /// Other authentication error
323 #[error("Authentication error: {0:?}")]
324 Other(http::HeaderValue),
···333 AuthError::InvalidToken => AuthError::InvalidToken,
334 AuthError::RefreshFailed => AuthError::RefreshFailed,
335 AuthError::NotAuthenticated => AuthError::NotAuthenticated,
00336 AuthError::Other(header) => AuthError::Other(header),
337 }
338 }
···32/// Error categories for client operations
33#[derive(Debug, thiserror::Error)]
34#[cfg_attr(feature = "std", derive(Diagnostic))]
35+#[non_exhaustive]
36pub enum ClientErrorKind {
37 /// HTTP transport error (connection, timeout, etc.)
38 #[error("transport error")]
···167 self
168 }
169170+ /// Append additional context to existing context string.
171+ ///
172+ /// If context already exists, appends with ": " separator.
173+ /// If no context exists, sets it directly.
174+ pub fn append_context(mut self, additional: impl AsRef<str>) -> Self {
175+ self.context = Some(match self.context.take() {
176+ Some(existing) => smol_str::format_smolstr!("{}: {}", existing, additional.as_ref()),
177+ None => additional.as_ref().into(),
178+ });
179+ self
180+ }
181+182+ /// Add NSID context for XRPC operations.
183+ ///
184+ /// Appends the NSID in brackets to existing context, e.g. `"network timeout: [com.atproto.repo.getRecord]"`.
185+ pub fn for_nsid(self, nsid: &str) -> Self {
186+ self.append_context(smol_str::format_smolstr!("[{}]", nsid))
187+ }
188+189+ /// Add collection context for record operations.
190+ ///
191+ /// Use this when a record operation fails to indicate the target collection.
192+ pub fn for_collection(self, operation: &str, collection_nsid: &str) -> Self {
193+ self.append_context(smol_str::format_smolstr!("{} [{}]", operation, collection_nsid))
194+ }
195+196 // Constructors for each kind
197198 /// Create a transport error
···250/// Can be converted to string for serialization while maintaining the full error context.
251#[derive(Debug, thiserror::Error)]
252#[cfg_attr(feature = "std", derive(Diagnostic))]
253+#[non_exhaustive]
254pub enum DecodeError {
255 /// JSON deserialization failed
256 #[error("Failed to deserialize JSON: {0}")]
···330/// Authentication and authorization errors
331#[derive(Debug, thiserror::Error)]
332#[cfg_attr(feature = "std", derive(Diagnostic))]
333+#[non_exhaustive]
334pub enum AuthError {
335 /// Access token has expired (use refresh token to get a new one)
336 #[error("Access token expired")]
···348 #[error("No authentication provided, but endpoint requires auth")]
349 NotAuthenticated,
350351+ /// DPoP proof construction failed (key or signing issue)
352+ #[error("DPoP proof construction failed")]
353+ DpopProofFailed,
354+355+ /// DPoP nonce retry failed (server rejected proof even after nonce update)
356+ #[error("DPoP nonce negotiation failed")]
357+ DpopNonceFailed,
358+359 /// Other authentication error
360 #[error("Authentication error: {0:?}")]
361 Other(http::HeaderValue),
···370 AuthError::InvalidToken => AuthError::InvalidToken,
371 AuthError::RefreshFailed => AuthError::RefreshFailed,
372 AuthError::NotAuthenticated => AuthError::NotAuthenticated,
373+ AuthError::DpopProofFailed => AuthError::DpopProofFailed,
374+ AuthError::DpopNonceFailed => AuthError::DpopNonceFailed,
375 AuthError::Other(header) => AuthError::Other(header),
376 }
377 }
+1
crates/jacquard-common/src/service_auth.rs
···3940/// Errors that can occur during JWT parsing and verification.
41#[derive(Debug, Error, miette::Diagnostic)]
042pub enum ServiceAuthError {
43 /// JWT format is invalid (not three base64-encoded parts separated by dots)
44 #[error("malformed JWT: {0}")]
···3940/// Errors that can occur during JWT parsing and verification.
41#[derive(Debug, Error, miette::Diagnostic)]
42+#[non_exhaustive]
43pub enum ServiceAuthError {
44 /// JWT format is invalid (not three base64-encoded parts separated by dots)
45 #[error("malformed JWT: {0}")]
+34-6
crates/jacquard-common/src/session.rs
···28/// Errors emitted by session stores.
29#[derive(Debug, thiserror::Error)]
30#[cfg_attr(feature = "std", derive(Diagnostic))]
031pub enum SessionStoreError {
32 /// Filesystem or I/O error
33 #[cfg(feature = "std")]
···108#[cfg(feature = "std")]
109impl FileTokenStore {
110 /// Create a new file token store at the given path.
111- pub fn new(path: impl AsRef<Path>) -> Self {
112- std::fs::create_dir_all(path.as_ref().parent().unwrap()).unwrap();
113- if !path.as_ref().exists() {
114- std::fs::write(path.as_ref(), b"{}").unwrap();
000000000000115 }
116117- Self {
118- path: path.as_ref().to_path_buf(),
0119 }
00000000000000120 }
121}
122
···28/// Errors emitted by session stores.
29#[derive(Debug, thiserror::Error)]
30#[cfg_attr(feature = "std", derive(Diagnostic))]
31+#[non_exhaustive]
32pub enum SessionStoreError {
33 /// Filesystem or I/O error
34 #[cfg(feature = "std")]
···109#[cfg(feature = "std")]
110impl FileTokenStore {
111 /// Create a new file token store at the given path.
112+ ///
113+ /// Creates parent directories and initializes an empty JSON object if the file doesn't exist.
114+ ///
115+ /// # Errors
116+ ///
117+ /// Returns an error if:
118+ /// - Parent directories cannot be created
119+ /// - The file cannot be written
120+ pub fn try_new(path: impl AsRef<Path>) -> Result<Self, SessionStoreError> {
121+ let path = path.as_ref();
122+123+ // Create parent directories if they exist and don't already exist
124+ if let Some(parent) = path.parent() {
125+ if !parent.as_os_str().is_empty() && !parent.exists() {
126+ std::fs::create_dir_all(parent)?;
127+ }
128 }
129130+ // Initialize empty JSON object if file doesn't exist
131+ if !path.exists() {
132+ std::fs::write(path, b"{}")?;
133 }
134+135+ Ok(Self {
136+ path: path.to_path_buf(),
137+ })
138+ }
139+140+ /// Create a new file token store at the given path.
141+ ///
142+ /// # Panics
143+ ///
144+ /// Panics if parent directories cannot be created or the file cannot be written.
145+ /// Prefer [`try_new`](Self::try_new) for fallible construction.
146+ pub fn new(path: impl AsRef<Path>) -> Self {
147+ Self::try_new(path).expect("failed to initialize FileTokenStore")
148 }
149}
150
···4344/// Errors that can occur when working with CIDs
45#[derive(Debug, thiserror::Error, miette::Diagnostic)]
046pub enum Error {
47 /// Invalid IPLD CID structure
48 #[error("Invalid IPLD CID {:?}", 0)]
···4344/// Errors that can occur when working with CIDs
45#[derive(Debug, thiserror::Error, miette::Diagnostic)]
46+#[non_exhaustive]
47pub enum Error {
48 /// Invalid IPLD CID structure
49 #[error("Invalid IPLD CID {:?}", 0)]
+1
crates/jacquard-common/src/types/collection.rs
···65 Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error, miette::Diagnostic,
66)]
67#[serde(tag = "error", content = "message")]
068pub enum RecordError<'a> {
69 /// The requested record was not found
70 #[error("RecordNotFound")]
···65 Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error, miette::Diagnostic,
66)]
67#[serde(tag = "error", content = "message")]
68+#[non_exhaustive]
69pub enum RecordError<'a> {
70 /// The requested record was not found
71 #[error("RecordNotFound")]
+1
crates/jacquard-common/src/types/crypto.rs
···6465/// Errors from decoding or converting Multikey values
66#[derive(Debug, Clone, thiserror::Error, miette::Diagnostic, PartialEq, Eq)]
067pub enum CryptoError {
68 #[error("failed to decode multibase")]
69 /// Multibase decode errror
···6465/// Errors from decoding or converting Multikey values
66#[derive(Debug, Clone, thiserror::Error, miette::Diagnostic, PartialEq, Eq)]
67+#[non_exhaustive]
68pub enum CryptoError {
69 #[error("failed to decode multibase")]
70 /// Multibase decode errror
+14-9
crates/jacquard-common/src/types/uri.rs
···3334/// Errors that can occur when parsing URIs
35#[derive(Debug, thiserror::Error, miette::Diagnostic)]
036pub enum UriParseError {
37 /// AT Protocol string parsing error
38 #[error("Invalid atproto string: {0}")]
···57 } else if uri.starts_with("wss://") {
58 Ok(Uri::Https(Url::parse(uri)?))
59 } else if uri.starts_with("ipld://") {
60- Ok(Uri::Cid(
61- Cid::from_str(uri.strip_prefix("ipld://").unwrap_or(uri.as_ref())).unwrap(),
62- ))
063 } else {
64 Ok(Uri::Any(CowStr::Borrowed(uri)))
65 }
···77 } else if uri.starts_with("wss://") {
78 Ok(Uri::Https(Url::parse(uri)?))
79 } else if uri.starts_with("ipld://") {
80- Ok(Uri::Cid(
81- Cid::from_str(uri.strip_prefix("ipld://").unwrap_or(uri.as_ref())).unwrap(),
82- ))
083 } else {
84 Ok(Uri::Any(CowStr::Owned(uri.to_smolstr())))
85 }
···96 } else if uri.starts_with("wss://") {
97 Ok(Uri::Https(Url::parse(uri.as_ref())?))
98 } else if uri.starts_with("ipld://") {
99- Ok(Uri::Cid(
100- Cid::from_str(uri.strip_prefix("ipld://").unwrap_or(uri.as_str())).unwrap(),
101- ))
0102 } else {
103 Ok(Uri::Any(uri))
104 }
···220}
221222#[derive(Debug, Clone, PartialEq, thiserror::Error, miette::Diagnostic)]
0223/// Errors that can occur when parsing or validating collection type-annotated URIs
224pub enum UriError {
225 /// Given at-uri didn't have the matching collection for the record
···3334/// Errors that can occur when parsing URIs
35#[derive(Debug, thiserror::Error, miette::Diagnostic)]
36+#[non_exhaustive]
37pub enum UriParseError {
38 /// AT Protocol string parsing error
39 #[error("Invalid atproto string: {0}")]
···58 } else if uri.starts_with("wss://") {
59 Ok(Uri::Https(Url::parse(uri)?))
60 } else if uri.starts_with("ipld://") {
61+ match Cid::from_str(&uri[7..]) {
62+ Ok(cid) => Ok(Uri::Cid(cid)),
63+ Err(_) => Ok(Uri::Any(CowStr::Borrowed(uri))),
64+ }
65 } else {
66 Ok(Uri::Any(CowStr::Borrowed(uri)))
67 }
···79 } else if uri.starts_with("wss://") {
80 Ok(Uri::Https(Url::parse(uri)?))
81 } else if uri.starts_with("ipld://") {
82+ match Cid::from_str(&uri[7..]) {
83+ Ok(cid) => Ok(Uri::Cid(cid)),
84+ Err(_) => Ok(Uri::Any(CowStr::Owned(uri.to_smolstr()))),
85+ }
86 } else {
87 Ok(Uri::Any(CowStr::Owned(uri.to_smolstr())))
88 }
···99 } else if uri.starts_with("wss://") {
100 Ok(Uri::Https(Url::parse(uri.as_ref())?))
101 } else if uri.starts_with("ipld://") {
102+ match Cid::from_str(&uri.as_str()[7..]) {
103+ Ok(cid) => Ok(Uri::Cid(cid)),
104+ Err(_) => Ok(Uri::Any(uri)),
105+ }
106 } else {
107 Ok(Uri::Any(uri))
108 }
···224}
225226#[derive(Debug, Clone, PartialEq, thiserror::Error, miette::Diagnostic)]
227+#[non_exhaustive]
228/// Errors that can occur when parsing or validating collection type-annotated URIs
229pub enum UriError {
230 /// Given at-uri didn't have the matching collection for the record
+1
crates/jacquard-common/src/types/value.rs
···5455/// Errors that can occur when working with AT Protocol data
56#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, miette::Diagnostic)]
057pub enum AtDataError {
58 /// Floating point numbers are not allowed in AT Protocol
59 #[error("floating point numbers not allowed in AT protocol data")]
···5455/// Errors that can occur when working with AT Protocol data
56#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error, miette::Diagnostic)]
57+#[non_exhaustive]
58pub enum AtDataError {
59 /// Floating point numbers are not allowed in AT Protocol
60 #[error("floating point numbers not allowed in AT protocol data")]
···113///
114/// These errors indicate that the data structure doesn't match the schema's type expectations.
115#[derive(Debug, Clone, thiserror::Error, miette::Diagnostic)]
0116pub enum StructuralError {
117 #[error("Type mismatch at {path}: expected {expected}, got {actual}")]
118 TypeMismatch {
···159/// These errors indicate that the data violates lexicon constraints like max_length,
160/// max_graphemes, ranges, etc. The structure is correct but values are out of bounds.
161#[derive(Debug, Clone, thiserror::Error, miette::Diagnostic)]
0162pub enum ConstraintError {
163 #[error("{path} exceeds max length: {actual} > {max}")]
164 MaxLength {
···205206/// Unified validation error type
207#[derive(Debug, Clone, thiserror::Error)]
0208pub enum ValidationError {
209 #[error(transparent)]
210 Structural(#[from] StructuralError),
···239240/// Errors that can occur when computing CIDs
241#[derive(Debug, thiserror::Error)]
0242pub enum CidComputationError {
243 #[error("Failed to serialize data to DAG-CBOR: {0}")]
244 DagCborEncode(#[from] serde_ipld_dagcbor::EncodeError<std::collections::TryReserveError>),
···113///
114/// These errors indicate that the data structure doesn't match the schema's type expectations.
115#[derive(Debug, Clone, thiserror::Error, miette::Diagnostic)]
116+#[non_exhaustive]
117pub enum StructuralError {
118 #[error("Type mismatch at {path}: expected {expected}, got {actual}")]
119 TypeMismatch {
···160/// These errors indicate that the data violates lexicon constraints like max_length,
161/// max_graphemes, ranges, etc. The structure is correct but values are out of bounds.
162#[derive(Debug, Clone, thiserror::Error, miette::Diagnostic)]
163+#[non_exhaustive]
164pub enum ConstraintError {
165 #[error("{path} exceeds max length: {actual} > {max}")]
166 MaxLength {
···207208/// Unified validation error type
209#[derive(Debug, Clone, thiserror::Error)]
210+#[non_exhaustive]
211pub enum ValidationError {
212 #[error(transparent)]
213 Structural(#[from] StructuralError),
···242243/// Errors that can occur when computing CIDs
244#[derive(Debug, thiserror::Error)]
245+#[non_exhaustive]
246pub enum CidComputationError {
247 #[error("Failed to serialize data to DAG-CBOR: {0}")]
248 DagCborEncode(#[from] serde_ipld_dagcbor::EncodeError<std::collections::TryReserveError>),
···9use thiserror::Error;
1011#[derive(Error, Debug)]
012pub enum Error {
13 #[error("duplicate kid: {0}")]
14 DuplicateKid(String),
15 #[error("keys must not be empty")]
16 EmptyKeys,
17- #[error("key must have a `kid`")]
18- EmptyKid,
19 #[error("no signing key found for algorithms: {0:?}")]
20 NotFound(Vec<CowStr<'static>>),
21 #[error("key for signing must be a secret key")]
···103 }
104 let mut v = Vec::with_capacity(keys.len());
105 let mut hs = HashSet::with_capacity(keys.len());
106- for key in keys {
107 if let Some(kid) = key.prm.kid.clone() {
108 if hs.contains(&kid) {
109 return Err(Error::DuplicateKid(kid));
···119 }
120 v.push(key);
121 } else {
122- return Err(Error::EmptyKid);
123 }
124 }
125 Ok(Self(v))
···9use thiserror::Error;
1011#[derive(Error, Debug)]
12+#[non_exhaustive]
13pub enum Error {
14 #[error("duplicate kid: {0}")]
15 DuplicateKid(String),
16 #[error("keys must not be empty")]
17 EmptyKeys,
18+ #[error("key at index {0} must have a `kid`")]
19+ EmptyKid(usize),
20 #[error("no signing key found for algorithms: {0:?}")]
21 NotFound(Vec<CowStr<'static>>),
22 #[error("key for signing must be a secret key")]
···104 }
105 let mut v = Vec::with_capacity(keys.len());
106 let mut hs = HashSet::with_capacity(keys.len());
107+ for (i, key) in keys.into_iter().enumerate() {
108 if let Some(kid) = key.prm.kid.clone() {
109 if hs.contains(&kid) {
110 return Err(Error::DuplicateKid(kid));
···120 }
121 v.push(key);
122 } else {
123+ return Err(Error::EmptyKid(i));
124 }
125 }
126 Ok(Self(v))
+3-2
crates/jacquard-oauth/src/request.rs
···6162/// Error categories for OAuth request operations
63#[derive(Debug, thiserror::Error, miette::Diagnostic)]
064pub enum RequestErrorKind {
65 /// No endpoint available
66 #[error("no {0} endpoint available")]
···331 }
332}
333334-impl From<crate::dpop::Error> for RequestError {
335- fn from(e: crate::dpop::Error) -> Self {
336 let msg = smol_str::format_smolstr!("{:?}", e);
337 Self::new(RequestErrorKind::Dpop, Some(Box::new(e)))
338 .with_context(msg)
···699700/// Errors that can occur during richtext building
701#[derive(Debug, thiserror::Error, miette::Diagnostic)]
0702pub enum RichTextError {
703 /// Handle found that needs resolution but no resolver provided
704 #[error("Handle '{0}' requires resolution - use build_async() with an IdentityResolver")]
···699700/// Errors that can occur during richtext building
701#[derive(Debug, thiserror::Error, miette::Diagnostic)]
702+#[non_exhaustive]
703pub enum RichTextError {
704 /// Handle found that needs resolution but no resolver provided
705 #[error("Handle '{0}' requires resolution - use build_async() with an IdentityResolver")]