use std::fmt;
use std::path::Path;
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
#[repr(transparent)]
pub struct SeatId(String);
impl SeatId {
pub const LEN: usize = 16;
pub fn of_canonical_dir(dir: &Path) -> SeatId {
let h = Sha256::digest(dir.to_string_lossy().as_bytes());
let mut s = hex::encode(h);
s.truncate(Self::LEN);
SeatId(s)
}
pub fn from_stored(s: impl Into<String>) -> SeatId {
SeatId(s.into())
}
pub fn looks_like_id(s: &str) -> bool {
s.len() == Self::LEN
&& s.bytes()
.all(|b| b.is_ascii_digit() || (b'a'..=b'f').contains(&b))
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[cfg(test)]
impl From<&str> for SeatId {
fn from(s: &str) -> SeatId {
SeatId(s.to_string())
}
}
impl std::borrow::Borrow<str> for SeatId {
fn borrow(&self) -> &str {
&self.0
}
}
impl fmt::Display for SeatId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
#[repr(transparent)]
pub struct ProjectKey(String);
impl ProjectKey {
pub fn from_stored(s: impl Into<String>) -> ProjectKey {
ProjectKey(s.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
#[repr(transparent)]
pub struct LoginId(String);
impl LoginId {
pub fn from_stored(s: impl Into<String>) -> LoginId {
LoginId(s.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
}
impl std::borrow::Borrow<str> for LoginId {
fn borrow(&self) -> &str {
&self.0
}
}
impl fmt::Display for LoginId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
#[repr(transparent)]
pub struct SessionId(String);
impl SessionId {
pub fn new(s: impl Into<String>) -> SessionId {
SessionId(s.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
pub fn short(&self) -> &str {
short(&self.0)
}
}
impl std::borrow::Borrow<str> for SessionId {
fn borrow(&self) -> &str {
&self.0
}
}
impl fmt::Display for SessionId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
impl From<&str> for SessionId {
fn from(s: &str) -> SessionId {
SessionId(s.to_string())
}
}
impl PartialEq<str> for SessionId {
fn eq(&self, other: &str) -> bool {
self.0 == other
}
}
impl PartialEq<&str> for SessionId {
fn eq(&self, other: &&str) -> bool {
self.0 == *other
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(transparent)]
#[repr(transparent)]
pub struct AccountId(String);
impl AccountId {
pub fn of(account_uuid: &str, org_uuid: Option<&str>) -> AccountId {
match org_uuid.filter(|o| !o.is_empty()) {
Some(org) => AccountId(format!("{account_uuid}/{org}")),
None => AccountId(account_uuid.to_string()),
}
}
pub fn new(s: impl Into<String>) -> AccountId {
AccountId(s.into())
}
pub fn as_str(&self) -> &str {
&self.0
}
pub fn user_uuid(&self) -> &str {
self.0.split_once('/').map_or(self.0.as_str(), |(u, _)| u)
}
pub fn org_uuid(&self) -> Option<&str> {
self.0
.split_once('/')
.map(|(_, o)| o)
.filter(|o| !o.is_empty())
}
pub fn has_org(&self) -> bool {
self.org_uuid().is_some()
}
pub fn completed(self, seat: Option<&AccountId>, known: &[AccountId]) -> AccountId {
if self.has_org() {
return self;
}
if let Some(s) = seat.filter(|s| s.has_org() && s.user_uuid() == self.as_str()) {
return s.clone();
}
let mut same = known
.iter()
.filter(|k| k.has_org() && k.user_uuid() == self.as_str());
match (same.next(), same.next()) {
(Some(one), None) => one.clone(),
(None, _) | (Some(_), Some(_)) => self,
}
}
pub fn short(&self) -> &str {
short(&self.0)
}
}
pub fn short_account(id: &str) -> String {
if let Some((u, o)) = id.split_once('/')
&& !o.is_empty()
{
format!("{}/{}", short(u), short(o))
} else {
short(id).to_string()
}
}
#[cfg(test)]
impl From<&str> for AccountId {
fn from(s: &str) -> AccountId {
AccountId(s.to_string())
}
}
impl fmt::Display for AccountId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
pub fn short(s: &str) -> &str {
match s.char_indices().nth(8) {
Some((i, _)) => s.get(..i).unwrap_or(s),
None => s,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_ids_never_panic() {
assert_eq!(SessionId::new("").short(), "");
assert_eq!(SessionId::new("s1").short(), "s1");
assert_eq!(SessionId::new("12345678").short(), "12345678");
assert_eq!(
SessionId::new("0f9e1a2b-3c4d-4e5f-8a9b-0c1d2e3f4a5b").short(),
"0f9e1a2b"
);
assert_eq!(SessionId::new("abcdefgé-xyz").short(), "abcdefgé");
assert_eq!(SessionId::new("ééééééééé").short(), "éééééééé");
assert_eq!(AccountId::new("ab").short(), "ab");
}
#[test]
fn seat_ids_come_from_the_path_only() {
let a = SeatId::of_canonical_dir(Path::new("/h/.claude-work"));
assert_eq!(a, SeatId::of_canonical_dir(Path::new("/h/.claude-work")));
assert_ne!(a, SeatId::of_canonical_dir(Path::new("/h/.claude-home")));
assert_eq!(a.as_str().len(), SeatId::LEN);
assert!(SeatId::looks_like_id(a.as_str()));
assert!(!SeatId::looks_like_id("work"));
assert!(!SeatId::looks_like_id("0123456789ABCDEF"));
let full = hex::encode(Sha256::digest(b"/h/.claude-work"));
assert_eq!(a.as_str(), &full[..16]);
}
#[test]
fn account_ids_carry_user_and_organization() {
let bare = AccountId::of("acc-123456789", None);
assert_eq!(bare.as_str(), "acc-123456789");
assert_eq!(bare.user_uuid(), "acc-123456789");
assert_eq!(bare.org_uuid(), None);
assert!(!bare.has_org());
assert_eq!(short_account(bare.as_str()), "acc-1234");
let empty_org = AccountId::of("acc-123456789", Some(""));
assert_eq!(empty_org, bare);
let scoped = AccountId::of("acc-123456789", Some("org-abcdef0123"));
assert_eq!(scoped.as_str(), "acc-123456789/org-abcdef0123");
assert_eq!(scoped.user_uuid(), "acc-123456789");
assert_eq!(scoped.org_uuid(), Some("org-abcdef0123"));
assert!(scoped.has_org());
assert_eq!(short_account(scoped.as_str()), "acc-1234/org-abcd");
assert_ne!(
scoped,
AccountId::of("acc-123456789", Some("org-other")),
"two organizations of the same user are distinct accounts"
);
}
#[test]
fn a_bare_owner_is_completed_only_when_the_organization_is_certain() {
let bare = || AccountId::new("u1");
let o1 = AccountId::of("u1", Some("o1"));
let o2 = AccountId::of("u1", Some("o2"));
let other = AccountId::of("u2", Some("o9"));
assert_eq!(bare().completed(Some(&o2), std::slice::from_ref(&o1)), o2);
assert_eq!(
bare().completed(Some(&other), std::slice::from_ref(&o1)),
o1
);
assert_eq!(
bare().completed(Some(&other), &[o1.clone(), o2.clone()]),
bare()
);
assert_eq!(bare().completed(None, &[]), bare());
assert_eq!(
o1.clone().completed(Some(&o2), std::slice::from_ref(&o2)),
o1
);
}
}