use std::collections::{BTreeMap, BTreeSet};
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::Arc;
use laravel::http::{Request, Response};
use serde_json::{Map, Value, json};
use crate::errors::{ApiError, ApiErrorCode};
use crate::time;
pub const HEADER: &str = "api-version";
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct ApiVersion {
pub date: String,
pub name: Option<String>,
}
impl ApiVersion {
#[must_use]
pub fn parse(value: &str) -> Option<Self> {
let (date, name) = match value.split_once('.') {
Some((date, name)) => (date, Some(name)),
None => (value, None),
};
time::parse_date(date)?;
if let Some(name) = name {
let mut chars = name.chars();
let first_ok = chars.next().is_some_and(|c| c.is_ascii_lowercase());
if !first_ok || !chars.all(|c| c.is_ascii_lowercase() || c.is_ascii_digit() || c == '-')
{
return None;
}
}
Some(Self {
date: date.to_owned(),
name: name.map(str::to_owned),
})
}
fn must(value: &str) -> Self {
Self::parse(value).unwrap_or_else(|| {
panic!("[{value}] is not a valid API version. Use YYYY-MM-DD or YYYY-MM-DD.name.")
})
}
}
impl fmt::Display for ApiVersion {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.name {
Some(name) => write!(f, "{}.{name}", self.date),
None => f.write_str(&self.date),
}
}
}
pub type LegacyHandler = Arc<
dyn Fn(Request) -> Pin<Box<dyn Future<Output = laravel::Result<Response>> + Send>>
+ Send
+ Sync,
>;
pub fn legacy<F, Fut>(handler: F) -> LegacyHandler
where
F: Fn(Request) -> Fut + Send + Sync + 'static,
Fut: Future<Output = laravel::Result<Response>> + Send + 'static,
{
Arc::new(move |request| Box::pin(handler(request)))
}
pub trait VersionChange: Send + Sync + 'static {
fn description(&self) -> &str;
fn resources(&self) -> &[&'static str] {
&[]
}
fn added_routes(&self) -> &[&'static str] {
&[]
}
fn removed_routes(&self) -> &[&'static str] {
&[]
}
fn unavailable_to_older_versions(&self) -> &[&'static str] {
&[]
}
fn legacy_handlers(&self) -> Vec<(&'static str, LegacyHandler)> {
Vec::new()
}
fn transform_request(&self, payload: &mut Map<String, Value>) {
let _ = payload;
}
fn transform_response(&self, document: &mut Value) {
let _ = document;
}
}
#[derive(Debug, Clone, Default)]
pub struct Deprecated {
since: Option<String>,
sunset: Option<String>,
brownouts: Vec<(String, String)>,
}
impl Deprecated {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn since(mut self, moment: &str) -> Self {
self.since = Some(moment.to_owned());
self
}
#[must_use]
pub fn sunset(mut self, moment: &str) -> Self {
self.sunset = Some(moment.to_owned());
self
}
#[must_use]
pub fn brownout(mut self, start: &str, end: &str) -> Self {
self.brownouts.push((start.to_owned(), end.to_owned()));
self
}
}
#[derive(Clone)]
pub struct Versions {
latest: String,
default: Option<String>,
changes: Vec<(String, Vec<Arc<dyn VersionChange>>)>,
retired: Vec<String>,
keep: Option<usize>,
deprecated: Vec<(String, Deprecated)>,
pub(crate) upgrade_guide_url: Option<String>,
pub(crate) changelog_url: Option<String>,
}
impl Versions {
#[must_use]
pub fn new(latest: &str) -> Self {
Self {
latest: latest.to_owned(),
default: None,
changes: Vec::new(),
retired: Vec::new(),
keep: Some(2),
deprecated: Vec::new(),
upgrade_guide_url: None,
changelog_url: None,
}
}
#[must_use]
pub fn default_version(mut self, version: &str) -> Self {
self.default = Some(version.to_owned());
self
}
#[must_use]
pub fn version(mut self, version: &str, changes: Vec<Arc<dyn VersionChange>>) -> Self {
self.changes.push((version.to_owned(), changes));
self
}
#[must_use]
pub fn retired(mut self, version: &str) -> Self {
self.retired.push(version.to_owned());
self
}
#[must_use]
pub const fn keep(mut self, keep: Option<usize>) -> Self {
self.keep = keep;
self
}
#[must_use]
pub fn deprecated(mut self, version: &str, deprecated: Deprecated) -> Self {
self.deprecated.push((version.to_owned(), deprecated));
self
}
#[must_use]
pub fn upgrade_guide_url(mut self, url: &str) -> Self {
self.upgrade_guide_url = Some(url.to_owned());
self
}
#[must_use]
pub fn changelog_url(mut self, url: &str) -> Self {
self.changelog_url = Some(url.to_owned());
self
}
}
#[derive(Debug, Clone)]
pub(crate) struct Deprecation {
pub(crate) since: i64,
pub(crate) sunset: Option<i64>,
brownouts: Vec<(i64, i64)>,
}
impl Deprecation {
fn brownout_end(&self, now: i64) -> Option<i64> {
self.brownouts
.iter()
.find(|(start, end)| now >= *start && now < *end)
.map(|(_, end)| *end)
}
}
pub(crate) struct Registry {
versions: BTreeMap<String, ApiVersion>,
pub(crate) latest: ApiVersion,
pub(crate) default: ApiVersion,
retired: BTreeSet<String>,
changes: BTreeMap<String, Vec<Arc<dyn VersionChange>>>,
deprecations: BTreeMap<String, Deprecation>,
pub(crate) upgrade_guide_url: Option<String>,
pub(crate) changelog_url: Option<String>,
}
fn moment(value: &str, field: &str) -> i64 {
time::parse_moment(value).unwrap_or_else(|| {
panic!("{field} needs dates such as \"2027-06-01\" or \"2027-05-04 14:00\".")
})
}
impl Registry {
pub(crate) fn new(config: &Versions) -> Self {
let latest = ApiVersion::must(&config.latest);
let default = config
.default
.as_deref()
.map_or_else(|| latest.clone(), ApiVersion::must);
let changed: Vec<ApiVersion> = config
.changes
.iter()
.map(|(version, _)| ApiVersion::must(version))
.collect();
let retired: Vec<ApiVersion> = config
.retired
.iter()
.map(|version| ApiVersion::must(version))
.collect();
for version in std::iter::once(&default).chain(&retired) {
assert!(
version.date <= latest.date,
"API version [{version}] is newer than the latest version [{latest}]."
);
}
let mut versions: BTreeMap<String, ApiVersion> = BTreeMap::new();
for version in [&latest, &default]
.into_iter()
.chain(&changed)
.chain(&retired)
{
if let Some(existing) = versions.get(&version.date) {
assert!(
existing.name == version.name,
"API versions [{existing}] and [{version}] share a date. Each date can have only one version."
);
}
versions.insert(version.date.clone(), version.clone());
}
let retired_dates: BTreeSet<String> =
retired.iter().map(|version| version.date.clone()).collect();
for version in [&latest, &default] {
assert!(
!retired_dates.contains(&version.date),
"API version [{version}] is the latest or default version, so it cannot be retired."
);
}
let mut changes = BTreeMap::new();
for ((_, classes), version) in config.changes.iter().zip(&changed) {
changes.insert(version.date.clone(), classes.clone());
}
let released: Vec<&ApiVersion> = versions
.values()
.filter(|version| version.date <= latest.date && !retired_dates.contains(&version.date))
.collect();
let mut deprecations = BTreeMap::new();
if let Some(keep) = config.keep {
assert!(
keep >= 1,
"keep must be at least 1, or None to keep every version."
);
let cut = released.len().saturating_sub(keep);
for (index, version) in released.iter().take(cut).enumerate() {
let since = moment(&released[index + keep].date, "keep");
deprecations.insert(
version.date.clone(),
Deprecation {
since,
sunset: None,
brownouts: Vec::new(),
},
);
}
}
for (key, settings) in &config.deprecated {
let version = ApiVersion::must(key);
let known = versions.get(&version.date);
assert!(
known.is_some_and(|known| version.name.is_none() || version.name == known.name),
"API version [{key}] is deprecated but is not a version of this API."
);
assert!(
version.date < latest.date,
"API version [{key}] is the latest version or newer, so it cannot be deprecated."
);
let next = released
.iter()
.find(|newer| newer.date > version.date)
.map_or(&latest, |newer| *newer);
let field = format!("deprecated.{key}");
let brownouts = settings
.brownouts
.iter()
.map(|(start, end)| {
let (start, end) = (moment(start, &field), moment(end, &field));
assert!(end > start, "A brownout in {field} ends before it starts.");
(start, end)
})
.collect();
deprecations.insert(
version.date.clone(),
Deprecation {
since: moment(settings.since.as_deref().unwrap_or(&next.date), &field),
sunset: settings
.sunset
.as_deref()
.map(|sunset| moment(sunset, &field)),
brownouts,
},
);
}
Self {
versions,
latest,
default,
retired: retired_dates,
changes,
deprecations,
upgrade_guide_url: config.upgrade_guide_url.clone(),
changelog_url: config.changelog_url.clone(),
}
}
pub(crate) fn is_unreleased(&self, version: &ApiVersion) -> bool {
version.date > self.latest.date
}
pub(crate) fn by_date(&self, date: &str) -> Option<&ApiVersion> {
self.versions.get(date)
}
pub(crate) fn history(&self) -> Vec<(&ApiVersion, &[Arc<dyn VersionChange>])> {
self.versions
.iter()
.rev()
.map(|(date, version)| {
(
version,
self.changes.get(date).map_or(&[][..], Vec::as_slice),
)
})
.collect()
}
pub(crate) fn status(&self, version: &ApiVersion, now: i64) -> String {
let retired = self.is_retired(version, now);
let deprecated = self.deprecation(version).filter(|_| !retired).map(|d| {
d.sunset.map_or_else(
|| "deprecated".to_owned(),
|sunset| format!("deprecated (sunset {})", time::date(sunset)),
)
});
[
self.is_unreleased(version).then(|| "unreleased".to_owned()),
(*version == self.latest).then(|| "latest".to_owned()),
(*version == self.default).then(|| "default".to_owned()),
retired.then(|| "retired".to_owned()),
deprecated,
]
.into_iter()
.flatten()
.collect::<Vec<_>>()
.join(", ")
}
fn find(&self, requested: &ApiVersion) -> Option<&ApiVersion> {
let version = self.versions.get(&requested.date)?;
if self.is_unreleased(version)
|| (requested.name.is_some() && requested.name != version.name)
{
return None;
}
Some(version)
}
pub(crate) fn deprecation(&self, version: &ApiVersion) -> Option<&Deprecation> {
if self.retired.contains(&version.date) {
None
} else {
self.deprecations.get(&version.date)
}
}
pub(crate) fn is_retired(&self, version: &ApiVersion, now: i64) -> bool {
self.retired.contains(&version.date)
|| self
.deprecation(version)
.and_then(|d| d.sunset)
.is_some_and(|sunset| now >= sunset)
}
fn about(&self, error: ApiError) -> ApiError {
match &self.upgrade_guide_url {
Some(url) => error.link("about", url.clone()),
None => error,
}
}
pub(crate) fn named(&self, name: &str) -> Option<ApiVersion> {
ApiVersion::parse(name)
.and_then(|requested| self.find(&requested))
.cloned()
}
pub(crate) fn resolve(
&self,
header: Option<&str>,
now: i64,
) -> Result<ApiVersion, Box<ApiError>> {
let header = header.map(str::trim).unwrap_or_default();
if header.is_empty() {
return Ok(self.default.clone());
}
let latest = self.latest.to_string();
let Some(version) = ApiVersion::parse(header)
.and_then(|requested| self.find(&requested))
.cloned()
else {
return Err(Box::new(
ApiError::new(
ApiErrorCode::InvalidApiVersion,
format!(
"[{header}] is not a version of this API. The latest version is {latest}."
),
)
.meta("latest_version", &latest),
));
};
if self.is_retired(&version, now) {
return Err(Box::new(
self.about(
ApiError::new(
ApiErrorCode::ApiVersionRetired,
format!("API version {version} has been retired. Upgrade to {latest}."),
)
.meta("latest_version", &latest),
),
));
}
if let Some(deprecation) = self.deprecation(&version)
&& let Some(end) = deprecation.brownout_end(now)
{
let sunset = deprecation
.sunset
.map(|sunset| format!(" that it stops working on {}", time::date(sunset)))
.unwrap_or_default();
let mut error = ApiError::new(
ApiErrorCode::ApiVersionBrownout,
format!(
"API version {version} is deprecated and is switched off until {} UTC as a reminder{sunset}. Upgrade to {latest}.",
time::date_time(end)
),
)
.meta("latest_version", &latest)
.meta("brownout_ends_at", time::atom(end));
if let Some(sunset) = deprecation.sunset {
error = error.meta("sunset", time::atom(sunset));
}
return Err(Box::new(
self.about(error)
.header("Retry-After", (end - now).max(1).to_string()),
));
}
Ok(version)
}
pub(crate) fn assert_route_available(
&self,
route: &str,
method: &str,
path: &str,
version: &ApiVersion,
) -> Result<(), Box<ApiError>> {
for (date, changes) in &self.changes {
let older = version.date < *date;
for change in changes {
if (older && matches(change.added_routes(), route))
|| (!older && matches(change.removed_routes(), route))
{
return Err(Box::new(ApiError::new(
ApiErrorCode::NotFound,
format!("The route {path} could not be found."),
)));
}
if older && matches(change.unavailable_to_older_versions(), route) {
let introduced = self
.versions
.get(date)
.map_or_else(|| date.clone(), ToString::to_string);
return Err(Box::new(self.about(
ApiError::new(
ApiErrorCode::EndpointUnavailableForVersion,
format!("{method} /{path} is not available in API version {version}. Upgrade to {introduced} or later to use it."),
)
.meta("minimum_version", &introduced)
.meta("latest_version", self.latest.to_string()),
)));
}
}
}
Ok(())
}
pub(crate) fn legacy_handler(
&self,
route: &str,
version: &ApiVersion,
) -> Option<(LegacyHandler, String)> {
for (date, changes) in self.changes.range::<String, _>((
std::ops::Bound::Excluded(&version.date),
std::ops::Bound::Unbounded,
)) {
for change in changes {
if let Some((_, handler)) = change
.legacy_handlers()
.into_iter()
.find(|(pattern, _)| crate::glob(pattern, route))
{
return Some((handler, date.clone()));
}
}
}
None
}
pub(crate) fn changes_after(
&self,
version: &ApiVersion,
before: Option<&str>,
) -> Vec<Arc<dyn VersionChange>> {
self.changes
.iter()
.filter(|(date, _)| {
**date > version.date && before.is_none_or(|before| date.as_str() < before)
})
.flat_map(|(_, changes)| changes.iter().cloned())
.collect()
}
}
fn matches(patterns: &[&str], route: &str) -> bool {
patterns.iter().any(|pattern| crate::glob(pattern, route))
}
pub(crate) fn applies_to(change: &dyn VersionChange, types: &[String], route: &str) -> bool {
let resources = change.resources();
resources.is_empty()
|| resources
.iter()
.any(|resource| types.iter().any(|t| t == resource) || crate::glob(resource, route))
}
const ATTRIBUTE_MARKER: &str = "\u{0}fusion-stack:attribute";
const RELATIONSHIP_MARKER: &str = "\u{0}fusion-stack:relationship";
pub(crate) fn upgrade_name(
changes: &[Arc<dyn VersionChange>],
route: &str,
kind: &str,
field: Option<&str>,
) -> (String, Option<String>) {
let (mut kind, mut field) = (kind.to_owned(), field.map(str::to_owned));
for change in changes {
if applies_to(change.as_ref(), std::slice::from_ref(&kind), route) {
(kind, field) = probe(&kind, field.as_deref(), |document| {
if let Value::Object(payload) = document {
change.transform_request(payload);
}
});
}
}
(kind, field)
}
pub(crate) fn downgrade_name(
changes: &[Arc<dyn VersionChange>],
route: &str,
kind: &str,
field: Option<&str>,
) -> (String, Option<String>) {
let (mut kind, mut field) = (kind.to_owned(), field.map(str::to_owned));
for change in changes.iter().rev() {
if applies_to(change.as_ref(), std::slice::from_ref(&kind), route) {
(kind, field) = probe(&kind, field.as_deref(), |document| {
change.transform_response(document)
});
}
}
(kind, field)
}
fn probe(
kind: &str,
field: Option<&str>,
transform: impl Fn(&mut Value),
) -> (String, Option<String>) {
let mut resource = Map::new();
resource.insert("type".into(), Value::String(kind.to_owned()));
if let Some(field) = field {
resource.insert("attributes".into(), json!({ field: ATTRIBUTE_MARKER }));
resource.insert(
"relationships".into(),
json!({ field: { "data": RELATIONSHIP_MARKER } }),
);
}
let mut document = json!({ "data": resource });
transform(&mut document);
let Some(data) = document.get("data").filter(|data| data.is_object()) else {
return (kind.to_owned(), field.map(str::to_owned));
};
let kind = data
.get("type")
.and_then(Value::as_str)
.unwrap_or(kind)
.to_owned();
let Some(field) = field else {
return (kind, None);
};
let attribute = data
.get("attributes")
.and_then(|attributes| find(attributes, ATTRIBUTE_MARKER));
let relationship = data
.get("relationships")
.and_then(|relationships| find(relationships, RELATIONSHIP_MARKER))
.map(|path| path.into_iter().take(1).collect::<Vec<_>>());
let moved = [attribute, relationship]
.into_iter()
.flatten()
.find(|path| !path.is_empty() && path.as_slice() != [field.to_owned()]);
(
kind,
Some(moved.map_or_else(|| field.to_owned(), |path| path.join("."))),
)
}
fn find(value: &Value, marker: &str) -> Option<Vec<String>> {
match value {
Value::String(text) if text == marker => Some(Vec::new()),
Value::Object(map) => map.iter().find_map(|(key, value)| {
find(value, marker).map(|mut path| {
path.insert(0, key.clone());
path
})
}),
Value::Array(items) => items.iter().enumerate().find_map(|(index, value)| {
find(value, marker).map(|mut path| {
path.insert(0, index.to_string());
path
})
}),
_ => None,
}
}
pub mod document {
use serde_json::{Map, Value};
fn is_json_api(document: &Value) -> bool {
document.get("data").is_some() || document.get("errors").is_some()
}
#[must_use]
pub fn types(document: &Value) -> Vec<String> {
let mut types = Vec::new();
let mut collect = |resource: &Value| {
if let Some(kind) = resource.get("type").and_then(Value::as_str)
&& !types.iter().any(|t| t == kind)
{
types.push(kind.to_owned());
}
};
match document.get("data") {
Some(Value::Array(items)) => items.iter().for_each(&mut collect),
Some(item @ Value::Object(_)) => collect(item),
_ => {}
}
if let Some(Value::Array(items)) = document.get("included") {
items.iter().for_each(collect);
}
types
}
pub fn map_attributes(
document: &mut Value,
types: &[&str],
mut callback: impl FnMut(&mut Map<String, Value>),
) {
if !is_json_api(document) {
if let Value::Object(attributes) = document {
callback(attributes);
}
return;
}
let mut apply = |resource: &mut Value| {
let kind = resource
.get("type")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
if !types.is_empty() && !types.contains(&kind.as_str()) {
return;
}
if let Some(Value::Object(attributes)) = resource.get_mut("attributes") {
callback(attributes);
}
};
match document.get_mut("data") {
Some(Value::Array(items)) => items.iter_mut().for_each(&mut apply),
Some(item @ Value::Object(_)) => apply(item),
_ => {}
}
if let Some(Value::Array(items)) = document.get_mut("included") {
items.iter_mut().for_each(apply);
}
}
pub fn rename_key(map: &mut Map<String, Value>, from: &str, to: &str) {
if !map.contains_key(from) {
return;
}
let old = std::mem::take(map);
for (key, value) in old {
if key == from {
map.insert(to.to_owned(), value);
} else if key != to {
map.insert(key, value);
}
}
}
pub fn rename_attribute(document: &mut Value, types: &[&str], from: &str, to: &str) {
map_attributes(document, types, |attributes| {
rename_key(attributes, from, to)
});
if let Some(Value::Array(errors)) = document.get_mut("errors") {
for error in errors {
if let Some(Value::String(pointer)) = error
.get_mut("source")
.and_then(|source| source.get_mut("pointer"))
{
for prefix in ["/data/attributes/", "/"] {
if let Some(rest) = pointer.strip_prefix(prefix) {
if rest == from || rest.starts_with(&format!("{from}/")) {
*pointer = format!("{prefix}{to}{}", &rest[from.len()..]);
}
break;
}
}
}
}
}
}
pub fn remove_attribute(document: &mut Value, types: &[&str], attribute: &str) {
map_attributes(document, types, |attributes| {
attributes.shift_remove(attribute);
});
}
pub fn add_attribute(
document: &mut Value,
types: &[&str],
attribute: &str,
value: impl Fn(&Map<String, Value>) -> Value,
) {
map_attributes(document, types, |attributes| {
if !attributes.contains_key(attribute) {
let computed = value(attributes);
attributes.insert(attribute.to_owned(), computed);
}
});
}
}
#[cfg(test)]
mod tests {
use serde_json::json;
use super::*;
struct Rename;
impl VersionChange for Rename {
fn description(&self) -> &str {
"customer.name renamed to customer.full_name"
}
fn resources(&self) -> &[&'static str] {
&["customers"]
}
fn added_routes(&self) -> &[&'static str] {
&["GET /v1/customers/{customer}/orders"]
}
fn transform_response(&self, document: &mut Value) {
document::rename_attribute(document, self.resources(), "full_name", "name");
}
}
fn registry() -> Registry {
Registry::new(
&Versions::new("2026-11-30.atlas")
.default_version("2026-06-01")
.version("2026-06-01", vec![])
.version("2026-11-30.atlas", vec![Arc::new(Rename)])
.retired("2025-12-01")
.deprecated(
"2026-06-01",
Deprecated::new()
.sunset("2027-06-01")
.brownout("2027-05-04 14:00", "2027-05-04 15:00"),
),
)
}
#[test]
fn versions_parse_like_the_php_package() {
assert_eq!(
ApiVersion::parse("2026-11-30.atlas").unwrap().to_string(),
"2026-11-30.atlas"
);
assert!(ApiVersion::parse("2026-02-30").is_none());
assert!(ApiVersion::parse("2026-1-30").is_none());
assert!(ApiVersion::parse("2026-11-30.Atlas").is_none());
assert!(ApiVersion::parse("2026-11-30.").is_none());
}
#[test]
fn requests_resolve_to_the_default_a_named_version_or_an_error() {
let registry = registry();
let now = time::parse_moment("2026-12-01").unwrap();
assert_eq!(
registry.resolve(None, now).unwrap().to_string(),
"2026-06-01"
);
assert_eq!(
registry
.resolve(Some("2026-11-30"), now)
.unwrap()
.to_string(),
"2026-11-30.atlas"
);
assert_eq!(
registry
.resolve(Some("2026-06-01.atlas"), now)
.unwrap_err()
.code(),
"invalid_api_version"
);
assert_eq!(
registry
.resolve(Some("2025-12-01"), now)
.unwrap_err()
.code(),
"api_version_retired"
);
}
#[test]
fn deprecated_versions_brown_out_then_retire_at_their_sunset() {
let registry = registry();
let during = time::parse_moment("2027-05-04 14:30").unwrap();
let error = registry.resolve(Some("2026-06-01"), during).unwrap_err();
assert_eq!(error.code(), "api_version_brownout");
assert_eq!(error.status(), 410);
let after = time::parse_moment("2027-05-04 15:00").unwrap();
assert!(registry.resolve(Some("2026-06-01"), after).is_ok());
let sunset = time::parse_moment("2027-06-01").unwrap();
assert_eq!(
registry
.resolve(Some("2026-06-01"), sunset)
.unwrap_err()
.code(),
"api_version_retired"
);
}
#[test]
fn deprecation_since_defaults_to_the_next_released_version() {
let registry = registry();
let deprecation = registry
.deprecation(&ApiVersion::must("2026-06-01"))
.unwrap();
assert_eq!(deprecation.since, 1_795_996_800); }
#[test]
fn routes_added_later_are_missing_from_older_versions_only() {
let registry = registry();
let route = "GET /v1/customers/{customer}/orders";
assert!(
registry
.assert_route_available(
route,
"GET",
"v1/customers/1/orders",
&ApiVersion::must("2026-06-01")
)
.is_err()
);
assert!(
registry
.assert_route_available(
route,
"GET",
"v1/customers/1/orders",
&ApiVersion::must("2026-11-30.atlas")
)
.is_ok()
);
}
#[test]
fn rename_keeps_key_order_and_moves_error_pointers() {
let mut document = json!({"data": {"type": "customers", "attributes": {"full_name": "A", "email": "a@x"}}});
Rename.transform_response(&mut document);
assert_eq!(
serde_json::to_string(&document).unwrap(),
r#"{"data":{"type":"customers","attributes":{"name":"A","email":"a@x"}}}"#
);
let mut other = json!({"data": {"type": "orders", "attributes": {"full_name": "A"}}});
Rename.transform_response(&mut other);
assert_eq!(other["data"]["attributes"]["full_name"], "A");
let mut errors = json!({"errors": [{"source": {"pointer": "/data/attributes/full_name"}}, {"source": {"pointer": "/full_name"}}]});
Rename.transform_response(&mut errors);
assert_eq!(
errors["errors"][0]["source"]["pointer"],
"/data/attributes/name"
);
assert_eq!(errors["errors"][1]["source"]["pointer"], "/name");
}
}