use std::collections::BTreeMap;
use std::sync::LazyLock;
use serde::{Deserialize, Serialize};
use serde_json::{Map, Value};
use crate::core::custom_fields::{
CheckoutCustomField, decode_custom_fields, encode_custom_fields, parse_custom_fields_loose,
};
trait WireEnum: Sized + Copy {
fn parse_wire(value: &str) -> Option<Self>;
}
macro_rules! wire_enum {
(
$(#[$meta:meta])*
$name:ident {
$( $(#[$vmeta:meta])* $variant:ident => $wire:literal ),+ $(,)?
}
) => {
$(#[$meta])*
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum $name {
$( $(#[$vmeta])* $variant, )+
}
impl $name {
pub const fn as_str(self) -> &'static str {
match self { $( Self::$variant => $wire, )+ }
}
pub fn from_wire(value: &str) -> Option<Self> {
match value {
$( $wire => Some(Self::$variant), )+
_ => None,
}
}
}
impl WireEnum for $name {
fn parse_wire(value: &str) -> Option<Self> { Self::from_wire(value) }
}
impl std::fmt::Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(self.as_str())
}
}
impl Serialize for $name {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
s.serialize_str(self.as_str())
}
}
impl<'de> Deserialize<'de> for $name {
fn deserialize<D: serde::Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
let raw = String::deserialize(d)?;
Self::from_wire(&raw).ok_or_else(|| {
serde::de::Error::custom(format!(
concat!("unknown ", stringify!($name), " value: {}"),
raw
))
})
}
}
};
}
wire_enum! {
CornerRadius {
Square => "square",
Small => "small",
Medium => "medium",
Large => "large",
Pill => "pill",
}
}
wire_enum! {
NonPillRadius {
Square => "square",
Small => "small",
Medium => "medium",
Large => "large",
}
}
impl From<NonPillRadius> for CornerRadius {
fn from(value: NonPillRadius) -> Self {
match value {
NonPillRadius::Square => CornerRadius::Square,
NonPillRadius::Small => CornerRadius::Small,
NonPillRadius::Medium => CornerRadius::Medium,
NonPillRadius::Large => CornerRadius::Large,
}
}
}
wire_enum! {
SpacingScale {
Compact => "compact",
Comfortable => "comfortable",
Spacious => "spacious",
}
}
wire_enum! {
SizeScale {
Sm => "sm",
Md => "md",
Lg => "lg",
}
}
wire_enum! {
SurfaceStyle {
Flat => "flat",
Outlined => "outlined",
Elevated => "elevated",
}
}
wire_enum! {
FontFamily {
Inter => "inter",
System => "system",
Serif => "serif",
Mono => "mono",
Roboto => "roboto",
Poppins => "poppins",
Manrope => "manrope",
DmSans => "dm-sans",
SpaceGrotesk => "space-grotesk",
PlexSans => "plex-sans",
WorkSans => "work-sans",
OpenSans => "open-sans",
Lora => "lora",
Playfair => "playfair",
PlexMono => "plex-mono",
JetbrainsMono => "jetbrains-mono",
}
}
wire_enum! {
FontWeight {
Regular => "regular",
Medium => "medium",
Semibold => "semibold",
Bold => "bold",
}
}
wire_enum! {
LayoutStyle {
Compact => "compact",
Split => "split",
}
}
wire_enum! {
SummaryPosition {
Left => "left",
Right => "right",
}
}
wire_enum! {
LabelStyle {
Above => "above",
Hidden => "hidden",
}
}
wire_enum! {
LegacyLabelType {
Above => "above",
Never => "never",
}
}
wire_enum! {
PaymentLayout {
Tabs => "tabs",
Accordion => "accordion",
SpacedAccordion => "spaced_accordion",
}
}
wire_enum! {
LogoShape {
Square => "square",
Rounded => "rounded",
Circle => "circle",
}
}
wire_enum! {
LogoSize {
Sm => "sm",
Md => "md",
Lg => "lg",
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TrustBadge {
pub id: String,
pub label: String,
pub text_color: String,
pub background_color: String,
#[serde(default)]
pub border_color: Option<String>,
}
impl TrustBadge {
pub fn new(
id: impl Into<String>,
label: impl Into<String>,
text_color: impl Into<String>,
background_color: impl Into<String>,
) -> Self {
Self {
id: id.into(),
label: label.into(),
text_color: text_color.into(),
background_color: background_color.into(),
border_color: None,
}
}
#[must_use]
pub fn border_color(mut self, colour: impl Into<String>) -> Self {
self.border_color = Some(colour.into());
self
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct CheckoutBranding {
pub display_name: String,
pub logo_url: String,
pub tagline: String,
pub show_logo: bool,
pub logo_shape: LogoShape,
pub logo_size: LogoSize,
pub primary: String,
pub background: String,
pub surface: String,
pub text: String,
pub heading: String,
pub muted: String,
pub border: String,
pub accent_text: String,
pub button_background: String,
pub button_text: String,
pub font_family: FontFamily,
pub heading_weight: FontWeight,
pub radius_surface: NonPillRadius,
pub radius_input: NonPillRadius,
pub radius_button: CornerRadius,
pub radius_badge: CornerRadius,
pub surface_style: SurfaceStyle,
pub surface_padding: SpacingScale,
pub vertical_gap: SpacingScale,
pub input_size: SizeScale,
pub button_size: SizeScale,
pub layout: LayoutStyle,
pub summary_position: SummaryPosition,
pub show_order_summary: bool,
pub summary_gradient: bool,
pub show_total: bool,
pub total_label: String,
pub show_currency_code: bool,
pub show_order_items: bool,
pub trust_badges: Vec<TrustBadge>,
pub custom_fields: Vec<CheckoutCustomField>,
pub header_text: String,
pub pay_button_label: String,
pub card_terms_message: String,
pub footer_text: String,
pub support_email: String,
pub payment_layout: PaymentLayout,
pub label_style: LabelStyle,
pub show_powered_by: bool,
pub custom_css: String,
}
impl Default for CheckoutBranding {
fn default() -> Self {
DEFAULT_BRANDING.clone()
}
}
pub const fn font_stack(family: FontFamily) -> &'static str {
match family {
FontFamily::Inter => "'Inter Variable', 'Inter', system-ui, -apple-system, sans-serif",
FontFamily::System => {
"system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', sans-serif"
}
FontFamily::Serif => "Georgia, 'Times New Roman', serif",
FontFamily::Mono => "ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",
FontFamily::Roboto => "'Roboto', system-ui, sans-serif",
FontFamily::Poppins => "'Poppins', system-ui, sans-serif",
FontFamily::Manrope => "'Manrope Variable', 'Manrope', system-ui, sans-serif",
FontFamily::DmSans => "'DM Sans Variable', 'DM Sans', system-ui, sans-serif",
FontFamily::SpaceGrotesk => {
"'Space Grotesk Variable', 'Space Grotesk', system-ui, sans-serif"
}
FontFamily::PlexSans => "'IBM Plex Sans', system-ui, sans-serif",
FontFamily::WorkSans => "'Work Sans Variable', 'Work Sans', system-ui, sans-serif",
FontFamily::OpenSans => "'Open Sans Variable', 'Open Sans', system-ui, sans-serif",
FontFamily::Lora => "'Lora Variable', 'Lora', Georgia, serif",
FontFamily::Playfair => "'Playfair Display Variable', 'Playfair Display', Georgia, serif",
FontFamily::PlexMono => "'IBM Plex Mono', ui-monospace, monospace",
FontFamily::JetbrainsMono => {
"'JetBrains Mono Variable', 'JetBrains Mono', ui-monospace, monospace"
}
}
}
pub const fn radius_value(radius: CornerRadius) -> &'static str {
match radius {
CornerRadius::Square => "0px",
CornerRadius::Small => "6px",
CornerRadius::Medium => "12px",
CornerRadius::Large => "20px",
CornerRadius::Pill => "999px",
}
}
pub const fn font_weight_value(weight: FontWeight) -> &'static str {
match weight {
FontWeight::Regular => "400",
FontWeight::Medium => "500",
FontWeight::Semibold => "600",
FontWeight::Bold => "700",
}
}
pub const fn surface_pad_value(scale: SpacingScale) -> &'static str {
match scale {
SpacingScale::Compact => "1rem",
SpacingScale::Comfortable => "1.5rem",
SpacingScale::Spacious => "2rem",
}
}
pub const fn vertical_gap_value(scale: SpacingScale) -> &'static str {
match scale {
SpacingScale::Compact => "0.75rem",
SpacingScale::Comfortable => "1rem",
SpacingScale::Spacious => "1.5rem",
}
}
pub const fn input_pad_value(size: SizeScale) -> &'static str {
match size {
SizeScale::Sm => "0.5rem 0.75rem",
SizeScale::Md => "0.625rem 0.75rem",
SizeScale::Lg => "0.875rem 0.875rem",
}
}
pub const fn button_pad_value(size: SizeScale) -> &'static str {
match size {
SizeScale::Sm => "0.625rem 1rem",
SizeScale::Md => "0.875rem 1.25rem",
SizeScale::Lg => "1.125rem 1.5rem",
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct LogoDimensions {
pub px: u32,
pub radius: u32,
}
pub const fn logo_dimensions(size: LogoSize) -> LogoDimensions {
match size {
LogoSize::Sm => LogoDimensions { px: 36, radius: 8 },
LogoSize::Lg => LogoDimensions { px: 64, radius: 16 },
LogoSize::Md => LogoDimensions { px: 48, radius: 12 },
}
}
pub const fn shadow_for(style: SurfaceStyle) -> &'static str {
match style {
SurfaceStyle::Elevated => {
"0 1px 2px rgba(15, 23, 42, 0.04), 0 8px 32px -12px rgba(15, 23, 42, 0.08)"
}
SurfaceStyle::Outlined | SurfaceStyle::Flat => "none",
}
}
pub fn is_hex_color(value: &str) -> bool {
let t = value.trim();
let Some(rest) = t.strip_prefix('#') else {
return false;
};
if rest.len() != 3 && rest.len() != 6 {
return false;
}
rest.bytes().all(|b| b.is_ascii_hexdigit())
}
pub fn is_dark_surface(color: &str) -> bool {
let stripped = color.replacen('#', "", 1);
let m = stripped.trim();
if m.len() != 3 && m.len() != 6 {
return false;
}
let full: String = if m.len() == 3 {
m.chars().flat_map(|c| [c, c]).collect()
} else {
m.to_string()
};
let bytes = full.as_bytes();
if !bytes.iter().all(u8::is_ascii_hexdigit) {
return false;
}
let pair = |i: usize| -> u32 { u32::from_str_radix(&full[i..i + 2], 16).unwrap_or(0) };
let (r, g, b) = (pair(0), pair(2), pair(4));
let luma = (r * 299 + g * 587 + b * 114) / 1000;
luma < 128
}
pub static DEFAULT_BADGES: LazyLock<Vec<TrustBadge>> = LazyLock::new(|| {
vec![
TrustBadge::new("secure", "Secure", "#047857", "#ecfdf5").border_color("#a7f3d0"),
TrustBadge::new("ssl", "256-bit SSL", "#1E4FEB", "#eff6ff").border_color("#bfdbfe"),
]
});
pub static DEFAULT_BADGES_DARK: LazyLock<Vec<TrustBadge>> = LazyLock::new(|| {
vec![
TrustBadge::new("secure", "Secure", "#34d399", "#064e3b").border_color("#065f46"),
TrustBadge::new("ssl", "256-bit SSL", "#60a5fa", "#172554").border_color("#1e40af"),
]
});
fn default_branding_base() -> CheckoutBranding {
CheckoutBranding {
display_name: String::new(),
logo_url: String::new(),
tagline: String::new(),
show_logo: false,
logo_shape: LogoShape::Rounded,
logo_size: LogoSize::Md,
primary: String::new(),
background: String::new(),
surface: String::new(),
text: String::new(),
heading: String::new(),
muted: String::new(),
border: String::new(),
accent_text: String::new(),
button_background: String::new(),
button_text: String::new(),
font_family: FontFamily::Inter,
heading_weight: FontWeight::Semibold,
radius_surface: NonPillRadius::Medium,
radius_input: NonPillRadius::Medium,
radius_button: CornerRadius::Medium,
radius_badge: CornerRadius::Pill,
surface_style: SurfaceStyle::Elevated,
surface_padding: SpacingScale::Comfortable,
vertical_gap: SpacingScale::Comfortable,
input_size: SizeScale::Md,
button_size: SizeScale::Md,
layout: LayoutStyle::Split,
summary_position: SummaryPosition::Left,
show_order_summary: true,
summary_gradient: false,
show_total: true,
total_label: "Total".to_string(),
show_currency_code: false,
show_order_items: true,
trust_badges: Vec::new(),
custom_fields: Vec::new(),
header_text: String::new(),
pay_button_label: String::new(),
card_terms_message: String::new(),
footer_text: String::new(),
support_email: String::new(),
payment_layout: PaymentLayout::Tabs,
label_style: LabelStyle::Above,
show_powered_by: true,
custom_css: String::new(),
}
}
pub static DEFAULT_BRANDING: LazyLock<CheckoutBranding> = LazyLock::new(|| CheckoutBranding {
primary: "#1E4FEB".to_string(),
background: "#f8fafc".to_string(),
surface: "#ffffff".to_string(),
text: "#1e293b".to_string(),
heading: "#0A1130".to_string(),
muted: "#64748b".to_string(),
border: "#e2e8f0".to_string(),
accent_text: "#1E4FEB".to_string(),
button_background: "#0A1130".to_string(),
button_text: "#ffffff".to_string(),
trust_badges: DEFAULT_BADGES.clone(),
..default_branding_base()
});
pub static DEFAULT_BRANDING_DARK: LazyLock<CheckoutBranding> = LazyLock::new(|| CheckoutBranding {
primary: "#1E4FEB".to_string(),
background: "#020617".to_string(),
surface: "#0f172a".to_string(),
text: "#e2e8f0".to_string(),
heading: "#f8fafc".to_string(),
muted: "#94a3b8".to_string(),
border: "#1e293b".to_string(),
accent_text: "#60a5fa".to_string(),
button_background: "#1E4FEB".to_string(),
button_text: "#ffffff".to_string(),
surface_style: SurfaceStyle::Flat,
trust_badges: DEFAULT_BADGES_DARK.clone(),
..default_branding_base()
});
pub fn default_branding() -> CheckoutBranding {
clone_branding(&DEFAULT_BRANDING)
}
pub fn clone_branding(b: &CheckoutBranding) -> CheckoutBranding {
b.clone()
}
pub const CUSTOM_CSS_MAX_LENGTH: usize = 50_000;
pub fn sanitize_custom_css(raw: Option<&str>) -> Option<String> {
let raw = raw?;
let trimmed = raw.trim();
if trimmed.is_empty() {
return None;
}
if utf16_len(trimmed) > CUSTOM_CSS_MAX_LENGTH {
return None;
}
let mut out = trimmed.to_string();
out = escape_style_close(&out);
out = strip_imports(&out);
out = comment_out(&out, "expression", Some('('), "/* expression( */", false);
out = comment_out(&out, "behavior", Some(':'), "/* behavior: */", true);
out = comment_out(
&out,
"-moz-binding",
Some(':'),
"/* -moz-binding: */",
false,
);
out = neutralize_javascript_urls(&out);
Some(out)
}
fn utf16_len(s: &str) -> usize {
s.encode_utf16().count()
}
fn find_ci(hay: &str, needle: &str, from: usize) -> Option<usize> {
let hb = hay.as_bytes();
let nb = needle.as_bytes();
if nb.is_empty() || hb.len() < nb.len() {
return None;
}
(from..=hb.len() - nb.len()).find(|&i| {
hb[i..i + nb.len()]
.iter()
.zip(nb)
.all(|(a, b)| a.to_ascii_lowercase() == *b)
})
}
fn skip_ws(s: &str, mut i: usize) -> usize {
while let Some(c) = s[i..].chars().next() {
if c.is_whitespace() || c == '\u{feff}' {
i += c.len_utf8();
} else {
break;
}
}
i
}
fn escape_style_close(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut i = 0;
while let Some(idx) = find_ci(s, "</style", i) {
out.push_str(&s[i..idx]);
out.push_str("<\\/style");
i = idx + "</style".len();
}
out.push_str(&s[i..]);
out
}
fn is_word_byte(b: u8) -> bool {
b.is_ascii_alphanumeric() || b == b'_'
}
fn strip_imports(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut i = 0;
while let Some(idx) = find_ci(s, "@import", i) {
let after = idx + "@import".len();
if s.as_bytes().get(after).copied().is_some_and(is_word_byte) {
out.push_str(&s[i..idx + 1]);
i = idx + 1;
continue;
}
out.push_str(&s[i..idx]);
i = match s[after..].find(';') {
Some(rel) => after + rel + 1,
None => s.len(),
};
}
out.push_str(&s[i..]);
out
}
fn comment_out(
s: &str,
token: &str,
terminator: Option<char>,
replacement: &str,
guard_prefix: bool,
) -> String {
let mut out = String::with_capacity(s.len());
let mut i = 0;
while let Some(idx) = find_ci(s, token, i) {
if guard_prefix
&& idx > 0
&& s[..idx]
.chars()
.next_back()
.is_some_and(|c| c.is_ascii_alphabetic() || c == '-')
{
out.push_str(&s[i..idx + 1]);
i = idx + 1;
continue;
}
let after = skip_ws(s, idx + token.len());
let end = match terminator {
Some(t) if s[after..].starts_with(t) => after + t.len_utf8(),
Some(_) => {
out.push_str(&s[i..idx + 1]);
i = idx + 1;
continue;
}
None => after,
};
out.push_str(&s[i..idx]);
out.push_str(replacement);
i = end;
}
out.push_str(&s[i..]);
out
}
fn neutralize_javascript_urls(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut i = 0;
while let Some(idx) = find_ci(s, "url", i) {
let mut p = skip_ws(s, idx + 3);
if !s[p..].starts_with('(') {
out.push_str(&s[i..idx + 1]);
i = idx + 1;
continue;
}
p = skip_ws(s, p + 1);
if s[p..].starts_with('"') || s[p..].starts_with('\'') {
p += 1;
}
p = skip_ws(s, p);
if find_ci(s, "javascript:", p) != Some(p) {
out.push_str(&s[i..idx + 1]);
i = idx + 1;
continue;
}
out.push_str(&s[i..idx]);
out.push_str("url(invalid:");
i = p + "javascript:".len();
}
out.push_str(&s[i..]);
out
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct BrandingSource {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub merchant_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub seller_name: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub merchant_logo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub logo: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub merchant_description: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub theme: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub background_colour: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payment_button_colour: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payment_button_text_colour: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payment_form_header_text: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payment_button_text: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub custom_message_for_card_terms: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub branding_visibility: Option<bool>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sdk_layout: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub payment_form_label_type: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sdk_ui_rules: Option<Map<String, Value>>,
}
const BRANDING_GROUP_KEY: &str = "branding";
fn s(v: &Option<String>) -> &str {
v.as_deref().unwrap_or("")
}
fn or_else(value: &str, fallback: &str) -> String {
if value.is_empty() {
fallback.to_string()
} else {
value.to_string()
}
}
fn pick_enum<T: WireEnum>(value: Option<&Value>, fallback: T) -> T {
match value.and_then(Value::as_str) {
Some(raw) => T::parse_wire(raw).unwrap_or(fallback),
None => fallback,
}
}
fn parse_bool(value: Option<&Value>, fallback: bool) -> bool {
match value {
Some(Value::Bool(b)) => *b,
Some(Value::String(raw)) if raw == "true" => true,
Some(Value::String(raw)) if raw == "false" => false,
_ => fallback,
}
}
fn bag_str<'a>(bag: &'a Map<String, Value>, key: &str) -> &'a str {
bag.get(key).and_then(Value::as_str).unwrap_or("")
}
pub fn decode_badges(raw: Option<&str>) -> Option<Vec<TrustBadge>> {
let raw = raw?;
let parsed: Value = serde_json::from_str(raw).ok()?;
let items = parsed.as_array()?;
Some(
items
.iter()
.enumerate()
.filter_map(|(i, item)| {
let obj = item.as_object()?;
let str_field = |k: &str| obj.get(k).and_then(Value::as_str);
Some(TrustBadge {
id: match str_field("id") {
Some(id) if !id.is_empty() => id.to_string(),
_ => format!("badge-{i}"),
},
label: str_field("label").unwrap_or("").to_string(),
text_color: str_field("textColor").unwrap_or("#0f172a").to_string(),
background_color: str_field("backgroundColor")
.unwrap_or("#f1f5f9")
.to_string(),
border_color: str_field("borderColor")
.filter(|v| !v.is_empty())
.map(str::to_string),
})
})
.filter(|b| !b.label.is_empty())
.collect(),
)
}
#[derive(Serialize)]
struct BadgeWire<'a> {
id: &'a str,
label: &'a str,
#[serde(rename = "textColor")]
text_color: &'a str,
#[serde(rename = "backgroundColor")]
background_color: &'a str,
#[serde(rename = "borderColor", skip_serializing_if = "Option::is_none")]
border_color: Option<&'a str>,
}
pub fn encode_badges(badges: &[TrustBadge]) -> String {
let wire: Vec<BadgeWire<'_>> = badges
.iter()
.map(|b| BadgeWire {
id: &b.id,
label: &b.label,
text_color: &b.text_color,
background_color: &b.background_color,
border_color: b.border_color.as_deref().filter(|v| !v.is_empty()),
})
.collect();
serde_json::to_string(&wire).unwrap_or_else(|_| "[]".to_string())
}
pub fn decode_branding(source: Option<&BrandingSource>) -> CheckoutBranding {
let Some(source) = source else {
return clone_branding(&DEFAULT_BRANDING);
};
let dflt = &*DEFAULT_BRANDING;
let empty = Map::new();
let extras: &Map<String, Value> = source
.sdk_ui_rules
.as_ref()
.and_then(|rules| rules.get(BRANDING_GROUP_KEY))
.and_then(Value::as_object)
.unwrap_or(&empty);
let decoded_badges = decode_badges(extras.get("trustBadges").and_then(Value::as_str));
let decoded_custom_fields =
decode_custom_fields(extras.get("customFields").and_then(Value::as_str));
let display_name = or_else(s(&source.merchant_name), s(&source.seller_name));
let logo_url = or_else(s(&source.merchant_logo), s(&source.logo));
let tagline = or_else(bag_str(extras, "tagline"), s(&source.merchant_description));
let label_style = {
let from_bag = bag_str(extras, "labelStyle");
match from_bag {
"above" | "floating" => LabelStyle::Above,
"hidden" => LabelStyle::Hidden,
_ => match s(&source.payment_form_label_type) {
"above" | "floating" => LabelStyle::Above,
"hidden" | "never" => LabelStyle::Hidden,
_ => dflt.label_style,
},
}
};
CheckoutBranding {
display_name,
logo_url,
tagline,
show_logo: parse_bool(extras.get("showLogo"), dflt.show_logo),
logo_shape: pick_enum(extras.get("logoShape"), dflt.logo_shape),
logo_size: pick_enum(extras.get("logoSize"), dflt.logo_size),
primary: or_else(s(&source.theme), &dflt.primary),
background: or_else(s(&source.background_colour), &dflt.background),
surface: or_else(bag_str(extras, "surface"), &dflt.surface),
text: or_else(bag_str(extras, "text"), &dflt.text),
heading: or_else(
bag_str(extras, "heading"),
&or_else(bag_str(extras, "text"), &dflt.heading),
),
muted: or_else(bag_str(extras, "muted"), &dflt.muted),
border: or_else(bag_str(extras, "border"), &dflt.border),
accent_text: or_else(
bag_str(extras, "accentText"),
&or_else(s(&source.theme), &dflt.accent_text),
),
button_background: or_else(
s(&source.payment_button_colour),
&or_else(s(&source.theme), &dflt.button_background),
),
button_text: or_else(s(&source.payment_button_text_colour), &dflt.button_text),
font_family: pick_enum(extras.get("fontFamily"), dflt.font_family),
heading_weight: pick_enum(extras.get("headingWeight"), dflt.heading_weight),
radius_surface: pick_enum(extras.get("radiusSurface"), dflt.radius_surface),
radius_input: pick_enum(extras.get("radiusInput"), dflt.radius_input),
radius_button: pick_enum(extras.get("radiusButton"), dflt.radius_button),
radius_badge: pick_enum(extras.get("radiusBadge"), dflt.radius_badge),
surface_style: pick_enum(extras.get("surfaceStyle"), dflt.surface_style),
surface_padding: pick_enum(extras.get("surfacePadding"), dflt.surface_padding),
vertical_gap: pick_enum(extras.get("verticalGap"), dflt.vertical_gap),
input_size: pick_enum(extras.get("inputSize"), dflt.input_size),
button_size: pick_enum(extras.get("buttonSize"), dflt.button_size),
layout: pick_enum(extras.get("layout"), dflt.layout),
summary_position: pick_enum(extras.get("summaryPosition"), dflt.summary_position),
show_order_summary: parse_bool(extras.get("showOrderSummary"), dflt.show_order_summary),
summary_gradient: parse_bool(extras.get("summaryGradient"), dflt.summary_gradient),
show_total: parse_bool(extras.get("showTotal"), dflt.show_total),
total_label: or_else(bag_str(extras, "totalLabel"), &dflt.total_label),
show_currency_code: parse_bool(extras.get("showCurrencyCode"), dflt.show_currency_code),
show_order_items: parse_bool(extras.get("showOrderItems"), dflt.show_order_items),
trust_badges: decoded_badges.unwrap_or_else(|| dflt.trust_badges.clone()),
custom_fields: decoded_custom_fields.unwrap_or_default(),
header_text: s(&source.payment_form_header_text).to_string(),
pay_button_label: s(&source.payment_button_text).to_string(),
card_terms_message: s(&source.custom_message_for_card_terms).to_string(),
footer_text: bag_str(extras, "footerText").to_string(),
support_email: bag_str(extras, "supportEmail").to_string(),
payment_layout: PaymentLayout::from_wire(s(&source.sdk_layout))
.unwrap_or(dflt.payment_layout),
label_style,
show_powered_by: source.branding_visibility != Some(false),
custom_css: bag_str(extras, "customCss").to_string(),
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EncodedBranding {
pub theme: String,
pub logo: Option<String>,
pub seller_name: Option<String>,
pub sdk_layout: PaymentLayout,
pub payment_button_text: Option<String>,
pub payment_button_colour: String,
pub payment_button_text_colour: String,
pub background_colour: String,
pub payment_form_header_text: Option<String>,
pub payment_form_label_type: LegacyLabelType,
pub custom_message_for_card_terms: Option<String>,
pub sdk_ui_rules: BTreeMap<String, BTreeMap<String, String>>,
pub branding_visibility: bool,
}
fn trim_opt(v: &str) -> Option<String> {
let t = v.trim();
if t.is_empty() {
None
} else {
Some(t.to_string())
}
}
fn branding_extras(branding: &CheckoutBranding) -> BTreeMap<String, String> {
let mut extras = BTreeMap::new();
let mut put = |k: &str, v: String| {
extras.insert(k.to_string(), v);
};
put("surface", branding.surface.clone());
put("text", branding.text.clone());
put("heading", branding.heading.clone());
put("muted", branding.muted.clone());
put("border", branding.border.clone());
put("accentText", branding.accent_text.clone());
put("fontFamily", branding.font_family.as_str().to_string());
put(
"headingWeight",
branding.heading_weight.as_str().to_string(),
);
put(
"radiusSurface",
branding.radius_surface.as_str().to_string(),
);
put("radiusInput", branding.radius_input.as_str().to_string());
put("radiusButton", branding.radius_button.as_str().to_string());
put("radiusBadge", branding.radius_badge.as_str().to_string());
put("surfaceStyle", branding.surface_style.as_str().to_string());
put(
"surfacePadding",
branding.surface_padding.as_str().to_string(),
);
put("verticalGap", branding.vertical_gap.as_str().to_string());
put("inputSize", branding.input_size.as_str().to_string());
put("buttonSize", branding.button_size.as_str().to_string());
put("layout", branding.layout.as_str().to_string());
put(
"summaryPosition",
branding.summary_position.as_str().to_string(),
);
put("showOrderSummary", branding.show_order_summary.to_string());
put("summaryGradient", branding.summary_gradient.to_string());
put("showTotal", branding.show_total.to_string());
put("totalLabel", branding.total_label.clone());
put("showCurrencyCode", branding.show_currency_code.to_string());
put("showOrderItems", branding.show_order_items.to_string());
put("showLogo", branding.show_logo.to_string());
put("logoShape", branding.logo_shape.as_str().to_string());
put("logoSize", branding.logo_size.as_str().to_string());
put("labelStyle", branding.label_style.as_str().to_string());
put("trustBadges", encode_badges(&branding.trust_badges));
if !branding.custom_fields.is_empty() {
put(
"customFields",
encode_custom_fields(&branding.custom_fields),
);
}
if let Some(v) = trim_opt(&branding.tagline) {
put("tagline", v);
}
if let Some(v) = trim_opt(&branding.footer_text) {
put("footerText", v);
}
if let Some(v) = trim_opt(&branding.support_email) {
put("supportEmail", v);
}
if let Some(v) = trim_opt(&branding.custom_css) {
put("customCss", v);
}
extras
}
pub fn encode_branding(branding: &CheckoutBranding) -> EncodedBranding {
let mut rules = BTreeMap::new();
rules.insert(BRANDING_GROUP_KEY.to_string(), branding_extras(branding));
encoded_with_rules(branding, rules)
}
fn encoded_with_rules(
branding: &CheckoutBranding,
sdk_ui_rules: BTreeMap<String, BTreeMap<String, String>>,
) -> EncodedBranding {
EncodedBranding {
theme: branding.primary.clone(),
logo: trim_opt(&branding.logo_url),
seller_name: trim_opt(&branding.display_name),
sdk_layout: branding.payment_layout,
payment_button_text: trim_opt(&branding.pay_button_label),
payment_button_colour: branding.button_background.clone(),
payment_button_text_colour: branding.button_text.clone(),
background_colour: branding.background.clone(),
payment_form_header_text: trim_opt(&branding.header_text),
payment_form_label_type: match branding.label_style {
LabelStyle::Hidden => LegacyLabelType::Never,
LabelStyle::Above => LegacyLabelType::Above,
},
custom_message_for_card_terms: trim_opt(&branding.card_terms_message),
sdk_ui_rules,
branding_visibility: branding.show_powered_by,
}
}
pub fn encode_branding_with_base(branding: &CheckoutBranding, base: Option<&Value>) -> Value {
let base_obj = base.and_then(Value::as_object);
let mut rules: BTreeMap<String, BTreeMap<String, String>> = BTreeMap::new();
if let Some(existing) = base_obj
.and_then(|o| o.get("sdk_ui_rules"))
.and_then(Value::as_object)
{
for (group, value) in existing {
let Some(entries) = value.as_object() else {
continue;
};
let mut group_map = BTreeMap::new();
for (k, v) in entries {
if let Some(sv) = v.as_str() {
group_map.insert(k.clone(), sv.to_string());
}
}
rules.insert(group.clone(), group_map);
}
}
rules.insert(BRANDING_GROUP_KEY.to_string(), branding_extras(branding));
let flat = encoded_with_rules(branding, rules);
let mut out: Map<String, Value> = base_obj.cloned().unwrap_or_default();
if let Value::Object(flat_map) = serde_json::to_value(&flat).unwrap_or(Value::Null) {
for (k, v) in flat_map {
out.insert(k, v);
}
}
Value::Object(out)
}
pub const BRANDING_EXPORT_FORMAT: &str = "delopay-checkout-branding";
pub const BRANDING_EXPORT_VERSION: u32 = 1;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BrandingExport {
pub format: String,
pub version: u32,
pub exported_at: String,
pub branding: CheckoutBranding,
}
pub fn build_branding_export(branding: &CheckoutBranding) -> BrandingExport {
let now = std::time::SystemTime::now();
let millis = match now.duration_since(std::time::UNIX_EPOCH) {
Ok(d) => d.as_millis() as i64,
Err(e) => -(e.duration().as_millis() as i64),
};
build_branding_export_at(branding, millis)
}
pub fn build_branding_export_at(branding: &CheckoutBranding, unix_millis: i64) -> BrandingExport {
BrandingExport {
format: BRANDING_EXPORT_FORMAT.to_string(),
version: BRANDING_EXPORT_VERSION,
exported_at: iso8601_millis(unix_millis),
branding: clone_branding(branding),
}
}
fn iso8601_millis(unix_millis: i64) -> String {
const MS_PER_DAY: i64 = 86_400_000;
let days = unix_millis.div_euclid(MS_PER_DAY);
let ms_of_day = unix_millis.rem_euclid(MS_PER_DAY);
let (hour, minute, second, milli) = (
ms_of_day / 3_600_000,
(ms_of_day / 60_000) % 60,
(ms_of_day / 1_000) % 60,
ms_of_day % 1_000,
);
let z = days + 719_468;
let era = z.div_euclid(146_097);
let doe = z - era * 146_097;
let yoe = (doe - doe / 1_460 + doe / 36_524 - doe / 146_096) / 365;
let y = yoe + era * 400;
let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
let mp = (5 * doy + 2) / 153;
let d = doy - (153 * mp + 2) / 5 + 1;
let m = if mp < 10 { mp + 3 } else { mp - 9 };
let year = y + i64::from(m <= 2);
format!("{year:04}-{m:02}-{d:02}T{hour:02}:{minute:02}:{second:02}.{milli:03}Z")
}
fn value_str(v: Option<&Value>, fallback: &str) -> String {
match v.and_then(Value::as_str) {
Some(raw) => raw.to_string(),
None => fallback.to_string(),
}
}
fn value_hex(v: Option<&Value>, fallback: &str) -> String {
match v.and_then(Value::as_str) {
Some(raw) if is_hex_color(raw) => raw.to_string(),
_ => fallback.to_string(),
}
}
fn parse_trust_badges_loose(raw: Option<&Value>) -> Option<Vec<TrustBadge>> {
let items = raw?.as_array()?;
Some(
items
.iter()
.enumerate()
.filter_map(|(i, item)| {
let obj = item.as_object()?;
let hex = |k: &str| {
obj.get(k)
.and_then(Value::as_str)
.filter(|v| is_hex_color(v))
};
Some(TrustBadge {
id: match obj.get("id").and_then(Value::as_str) {
Some(id) if !id.is_empty() => id.to_string(),
_ => format!("badge-{i}"),
},
label: obj
.get("label")
.and_then(Value::as_str)
.unwrap_or("")
.to_string(),
text_color: hex("textColor").unwrap_or("#0f172a").to_string(),
background_color: hex("backgroundColor").unwrap_or("#f1f5f9").to_string(),
border_color: hex("borderColor").map(str::to_string),
})
})
.filter(|b| !b.label.is_empty())
.collect(),
)
}
pub fn parse_imported_branding(raw: &Value) -> CheckoutBranding {
let root: Option<&Map<String, Value>> = match raw.as_object() {
Some(obj) => match obj.get("branding").and_then(Value::as_object) {
Some(inner) => Some(inner),
None => Some(obj),
},
None => None,
};
let Some(root) = root else {
return clone_branding(&DEFAULT_BRANDING);
};
let dflt = &*DEFAULT_BRANDING;
let g = |k: &str| root.get(k);
let trust_badges =
parse_trust_badges_loose(g("trustBadges")).unwrap_or_else(|| dflt.trust_badges.clone());
let custom_fields = g("customFields")
.and_then(parse_custom_fields_loose)
.unwrap_or_default();
let label_style = pick_enum(g("labelStyle"), dflt.label_style);
CheckoutBranding {
display_name: value_str(g("displayName"), &dflt.display_name),
logo_url: value_str(g("logoUrl"), &dflt.logo_url),
tagline: value_str(g("tagline"), &dflt.tagline),
show_logo: parse_bool(g("showLogo"), dflt.show_logo),
logo_shape: pick_enum(g("logoShape"), dflt.logo_shape),
logo_size: pick_enum(g("logoSize"), dflt.logo_size),
primary: value_hex(g("primary"), &dflt.primary),
background: value_hex(g("background"), &dflt.background),
surface: value_hex(g("surface"), &dflt.surface),
text: value_hex(g("text"), &dflt.text),
heading: value_hex(g("heading"), &dflt.heading),
muted: value_hex(g("muted"), &dflt.muted),
border: value_hex(g("border"), &dflt.border),
accent_text: value_hex(g("accentText"), &dflt.accent_text),
button_background: value_hex(g("buttonBackground"), &dflt.button_background),
button_text: value_hex(g("buttonText"), &dflt.button_text),
font_family: pick_enum(g("fontFamily"), dflt.font_family),
heading_weight: pick_enum(g("headingWeight"), dflt.heading_weight),
radius_surface: pick_enum(g("radiusSurface"), dflt.radius_surface),
radius_input: pick_enum(g("radiusInput"), dflt.radius_input),
radius_button: pick_enum(g("radiusButton"), dflt.radius_button),
radius_badge: pick_enum(g("radiusBadge"), dflt.radius_badge),
surface_style: pick_enum(g("surfaceStyle"), dflt.surface_style),
surface_padding: pick_enum(g("surfacePadding"), dflt.surface_padding),
vertical_gap: pick_enum(g("verticalGap"), dflt.vertical_gap),
input_size: pick_enum(g("inputSize"), dflt.input_size),
button_size: pick_enum(g("buttonSize"), dflt.button_size),
layout: pick_enum(g("layout"), dflt.layout),
summary_position: pick_enum(g("summaryPosition"), dflt.summary_position),
show_order_summary: parse_bool(g("showOrderSummary"), dflt.show_order_summary),
summary_gradient: parse_bool(g("summaryGradient"), dflt.summary_gradient),
show_total: parse_bool(g("showTotal"), dflt.show_total),
total_label: value_str(g("totalLabel"), &dflt.total_label),
show_currency_code: parse_bool(g("showCurrencyCode"), dflt.show_currency_code),
show_order_items: parse_bool(g("showOrderItems"), dflt.show_order_items),
trust_badges,
custom_fields,
header_text: value_str(g("headerText"), &dflt.header_text),
pay_button_label: value_str(g("payButtonLabel"), &dflt.pay_button_label),
card_terms_message: value_str(g("cardTermsMessage"), &dflt.card_terms_message),
footer_text: value_str(g("footerText"), &dflt.footer_text),
support_email: value_str(g("supportEmail"), &dflt.support_email),
payment_layout: pick_enum(g("paymentLayout"), dflt.payment_layout),
label_style,
show_powered_by: parse_bool(g("showPoweredBy"), dflt.show_powered_by),
custom_css: truncate_utf16(&value_str(g("customCss"), &dflt.custom_css)),
}
}
fn truncate_utf16(s: &str) -> String {
if utf16_len(s) <= CUSTOM_CSS_MAX_LENGTH {
return s.to_string();
}
let mut out = String::new();
let mut units = 0;
for c in s.chars() {
let w = c.len_utf16();
if units + w > CUSTOM_CSS_MAX_LENGTH {
break;
}
units += w;
out.push(c);
}
out
}
pub fn branding_variables(b: &CheckoutBranding) -> Vec<(&'static str, String)> {
vec![
("--dp-primary", b.primary.clone()),
("--dp-bg", b.background.clone()),
("--dp-surface", b.surface.clone()),
("--dp-text", b.text.clone()),
("--dp-heading", b.heading.clone()),
("--dp-muted", b.muted.clone()),
("--dp-border", b.border.clone()),
("--dp-accent-text", b.accent_text.clone()),
("--dp-btn-bg", b.button_background.clone()),
("--dp-btn-fg", b.button_text.clone()),
(
"--dp-radius-surface",
radius_value(b.radius_surface.into()).to_string(),
),
(
"--dp-radius-input",
radius_value(b.radius_input.into()).to_string(),
),
(
"--dp-radius-button",
radius_value(b.radius_button).to_string(),
),
(
"--dp-radius-badge",
radius_value(b.radius_badge).to_string(),
),
("--dp-font", font_stack(b.font_family).to_string()),
(
"--dp-heading-weight",
font_weight_value(b.heading_weight).to_string(),
),
(
"--dp-pad-surface",
surface_pad_value(b.surface_padding).to_string(),
),
(
"--dp-gap-vertical",
vertical_gap_value(b.vertical_gap).to_string(),
),
("--dp-input-pad", input_pad_value(b.input_size).to_string()),
(
"--dp-button-pad",
button_pad_value(b.button_size).to_string(),
),
("--dp-shadow", shadow_for(b.surface_style).to_string()),
(
"--dp-surface-border",
if b.surface_style == SurfaceStyle::Outlined {
format!("1px solid {}", b.border)
} else {
"1px solid transparent".to_string()
},
),
]
}
pub fn branding_variables_css(b: &CheckoutBranding) -> String {
let mut out = String::from(":root{");
for (k, v) in branding_variables(b) {
out.push_str(k);
out.push(':');
out.push_str(&v);
out.push(';');
}
out.push('}');
out
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn token_maps_have_the_documented_values() {
assert_eq!(
font_stack(FontFamily::Inter),
"'Inter Variable', 'Inter', system-ui, -apple-system, sans-serif"
);
assert_eq!(
font_stack(FontFamily::Serif),
"Georgia, 'Times New Roman', serif"
);
assert_eq!(
font_stack(FontFamily::DmSans),
"'DM Sans Variable', 'DM Sans', system-ui, sans-serif"
);
assert_eq!(radius_value(CornerRadius::Square), "0px");
assert_eq!(radius_value(CornerRadius::Small), "6px");
assert_eq!(radius_value(CornerRadius::Medium), "12px");
assert_eq!(radius_value(CornerRadius::Large), "20px");
assert_eq!(radius_value(CornerRadius::Pill), "999px");
assert_eq!(font_weight_value(FontWeight::Regular), "400");
assert_eq!(font_weight_value(FontWeight::Medium), "500");
assert_eq!(font_weight_value(FontWeight::Semibold), "600");
assert_eq!(font_weight_value(FontWeight::Bold), "700");
assert_eq!(surface_pad_value(SpacingScale::Compact), "1rem");
assert_eq!(surface_pad_value(SpacingScale::Comfortable), "1.5rem");
assert_eq!(surface_pad_value(SpacingScale::Spacious), "2rem");
assert_eq!(vertical_gap_value(SpacingScale::Compact), "0.75rem");
assert_eq!(vertical_gap_value(SpacingScale::Comfortable), "1rem");
assert_eq!(vertical_gap_value(SpacingScale::Spacious), "1.5rem");
assert_eq!(input_pad_value(SizeScale::Sm), "0.5rem 0.75rem");
assert_eq!(input_pad_value(SizeScale::Md), "0.625rem 0.75rem");
assert_eq!(input_pad_value(SizeScale::Lg), "0.875rem 0.875rem");
assert_eq!(button_pad_value(SizeScale::Sm), "0.625rem 1rem");
assert_eq!(button_pad_value(SizeScale::Md), "0.875rem 1.25rem");
assert_eq!(button_pad_value(SizeScale::Lg), "1.125rem 1.5rem");
}
#[test]
fn logo_dimensions_scale() {
assert_eq!(
logo_dimensions(LogoSize::Sm),
LogoDimensions { px: 36, radius: 8 }
);
assert_eq!(
logo_dimensions(LogoSize::Md),
LogoDimensions { px: 48, radius: 12 }
);
assert_eq!(
logo_dimensions(LogoSize::Lg),
LogoDimensions { px: 64, radius: 16 }
);
}
#[test]
fn shadow_only_on_elevated() {
assert_eq!(
shadow_for(SurfaceStyle::Elevated),
"0 1px 2px rgba(15, 23, 42, 0.04), 0 8px 32px -12px rgba(15, 23, 42, 0.08)"
);
assert_eq!(shadow_for(SurfaceStyle::Flat), "none");
assert_eq!(shadow_for(SurfaceStyle::Outlined), "none");
}
#[test]
fn is_hex_color_accepts_three_and_six_digits_only() {
assert!(is_hex_color("#fff"));
assert!(is_hex_color("#FFFFFF"));
assert!(is_hex_color(" #1E4FEB "), "surrounding space is trimmed");
assert!(!is_hex_color("fff"), "leading # required");
assert!(!is_hex_color("#ffff"));
assert!(!is_hex_color("#fffffff"));
assert!(!is_hex_color("#gggggg"));
assert!(!is_hex_color("#"));
assert!(!is_hex_color(""));
}
#[test]
fn is_dark_surface_uses_perceived_luminance() {
assert!(is_dark_surface("#000000"));
assert!(is_dark_surface("#000"));
assert!(is_dark_surface("#1E4FEB"), "brand blue is dark (luma 82)");
assert!(!is_dark_surface("#ffffff"));
assert!(!is_dark_surface("#f8fafc"));
assert!(!is_dark_surface("#808080"));
assert!(is_dark_surface("#7f7f7f"), "one step darker flips it");
assert!(!is_dark_surface("not-a-color"));
assert!(!is_dark_surface("#zzzzzz"));
assert!(!is_dark_surface(""));
}
fn sanitize(css: &str) -> String {
sanitize_custom_css(Some(css)).expect("expected sanitized output")
}
#[test]
fn sanitize_rejects_absent_blank_and_oversized_input() {
assert_eq!(sanitize_custom_css(None), None);
assert_eq!(sanitize_custom_css(Some("")), None);
assert_eq!(sanitize_custom_css(Some(" \n\t ")), None);
let big = "a".repeat(CUSTOM_CSS_MAX_LENGTH + 1);
assert_eq!(sanitize_custom_css(Some(&big)), None);
let at_limit = "a".repeat(CUSTOM_CSS_MAX_LENGTH);
assert_eq!(sanitize_custom_css(Some(&at_limit)), Some(at_limit));
}
#[test]
fn sanitize_trims_and_passes_benign_css_through() {
assert_eq!(
sanitize(" .dp-card { background: linear-gradient(#fff, #000); } "),
".dp-card { background: linear-gradient(#fff, #000); }"
);
assert_eq!(
sanitize("@media (min-width: 40rem) { .x { transform: rotate(1deg) } }"),
"@media (min-width: 40rem) { .x { transform: rotate(1deg) } }"
);
}
#[test]
fn sanitize_escapes_style_close_tag() {
assert_eq!(
sanitize(".x{}</style><script>alert(1)</script>"),
".x{}<\\/style><script>alert(1)</script>",
"only the </style break-out is escaped"
);
assert_eq!(sanitize("</STYLE>"), "<\\/style>");
assert_eq!(sanitize("</styled-tag"), "<\\/styled-tag");
}
#[test]
fn sanitize_strips_import_rules() {
assert_eq!(
sanitize("@import url(https://evil.test/x.css); .a{}"),
" .a{}"
);
assert_eq!(sanitize("@IMPORT 'x.css';.a{}"), ".a{}");
assert_eq!(sanitize(".a{}\n@import \"x.css\""), ".a{}\n");
assert_eq!(
sanitize("@importantly { color: red }"),
"@importantly { color: red }"
);
}
#[test]
fn sanitize_comments_out_expression() {
assert_eq!(
sanitize("width: expression(alert(1));"),
"width: /* expression( */alert(1));"
);
assert_eq!(
sanitize("width: EXPRESSION (1)"),
"width: /* expression( */1)"
);
assert_eq!(
sanitize("/* expression of intent */"),
"/* expression of intent */"
);
}
#[test]
fn sanitize_comments_out_behavior_but_not_prefixed_properties() {
assert_eq!(sanitize("behavior: url(#x)"), "/* behavior: */ url(#x)");
assert_eq!(
sanitize(".a{ behavior : url(#x) }"),
".a{ /* behavior: */ url(#x) }"
);
assert_eq!(sanitize(".a{ BEHAVIOR:x }"), ".a{ /* behavior: */x }");
assert_eq!(sanitize("-webkit-behavior: x"), "-webkit-behavior: x");
assert_eq!(sanitize("scrollbehavior: x"), "scrollbehavior: x");
}
#[test]
fn sanitize_comments_out_moz_binding() {
assert_eq!(
sanitize("-moz-binding: url(evil.xml#x)"),
"/* -moz-binding: */ url(evil.xml#x)"
);
assert_eq!(sanitize("-MOZ-BINDING :x"), "/* -moz-binding: */x");
}
#[test]
fn sanitize_neutralizes_javascript_urls() {
assert_eq!(
sanitize("background: url(javascript:alert(1))"),
"background: url(invalid:alert(1))"
);
assert_eq!(
sanitize("background: URL ( \"javascript:alert(1)\" )"),
"background: url(invalid:alert(1)\" )"
);
assert_eq!(
sanitize("background: url('JAVASCRIPT:x')"),
"background: url(invalid:x')"
);
assert_eq!(
sanitize("background: url(https://cdn.test/a.png)"),
"background: url(https://cdn.test/a.png)"
);
}
#[test]
fn sanitize_handles_several_constructs_in_one_payload() {
let out = sanitize(
"@import url(evil);\n.a{ behavior: url(#x); -moz-binding: url(y); \
background: url( 'javascript:1' ); width: expression(2) }</style",
);
assert_eq!(
out,
"\n.a{ /* behavior: */ url(#x); /* -moz-binding: */ url(y); \
background: url(invalid:1' ); width: /* expression( */2) }<\\/style"
);
assert!(!out.contains("@import"), "{out}");
assert!(!out.contains("javascript:"), "{out}");
assert!(!out.contains("</style"), "{out}");
assert!(out.contains("url(invalid:"), "{out}");
assert!(out.contains("/* behavior: */"), "{out}");
assert!(out.contains("/* -moz-binding: */"), "{out}");
assert!(out.contains("/* expression( */"), "{out}");
assert!(out.contains("<\\/style"), "{out}");
}
#[test]
fn encode_badges_matches_the_typescript_json_string() {
assert_eq!(
encode_badges(&DEFAULT_BADGES),
"[{\"id\":\"secure\",\"label\":\"Secure\",\"textColor\":\"#047857\",\
\"backgroundColor\":\"#ecfdf5\",\"borderColor\":\"#a7f3d0\"},\
{\"id\":\"ssl\",\"label\":\"256-bit SSL\",\"textColor\":\"#1E4FEB\",\
\"backgroundColor\":\"#eff6ff\",\"borderColor\":\"#bfdbfe\"}]"
);
assert_eq!(
encode_badges(&[TrustBadge::new("a", "A", "#000", "#fff")]),
"[{\"id\":\"a\",\"label\":\"A\",\"textColor\":\"#000\",\"backgroundColor\":\"#fff\"}]"
);
assert_eq!(encode_badges(&[]), "[]");
}
#[test]
fn decode_badges_is_tolerant() {
assert_eq!(decode_badges(None), None);
assert_eq!(decode_badges(Some("not json")), None);
assert_eq!(
decode_badges(Some("{\"a\":1}")),
None,
"non-array is rejected"
);
assert_eq!(
decode_badges(Some("[]")),
Some(vec![]),
"an explicit empty list means 'hide the row'"
);
let decoded = decode_badges(Some("[{\"label\":\"L\"},{\"label\":\"\"},{\"id\":\"x\"}]"))
.expect("array parses");
assert_eq!(decoded.len(), 1, "label-less badges are dropped");
assert_eq!(decoded[0].id, "badge-0", "missing id falls back to index");
assert_eq!(decoded[0].text_color, "#0f172a");
assert_eq!(decoded[0].background_color, "#f1f5f9");
assert_eq!(decoded[0].border_color, None);
}
#[test]
fn badges_round_trip() {
let encoded = encode_badges(&DEFAULT_BADGES_DARK);
assert_eq!(decode_badges(Some(&encoded)).unwrap(), *DEFAULT_BADGES_DARK);
}
fn source_with(extras: Value) -> BrandingSource {
let mut rules = Map::new();
rules.insert(BRANDING_GROUP_KEY.to_string(), extras);
BrandingSource {
sdk_ui_rules: Some(rules),
..Default::default()
}
}
#[test]
fn decode_branding_without_a_source_is_the_default() {
assert_eq!(decode_branding(None), *DEFAULT_BRANDING);
assert_eq!(
decode_branding(Some(&BrandingSource::default())),
*DEFAULT_BRANDING
);
}
#[test]
fn decode_branding_prefers_the_public_name_aliases() {
let src = BrandingSource {
merchant_name: Some("Public".into()),
seller_name: Some("Request".into()),
merchant_logo: Some("https://a.test/logo.png".into()),
logo: Some("https://b.test/logo.png".into()),
..Default::default()
};
let b = decode_branding(Some(&src));
assert_eq!(b.display_name, "Public");
assert_eq!(b.logo_url, "https://a.test/logo.png");
let src = BrandingSource {
seller_name: Some("Request".into()),
logo: Some("https://b.test/logo.png".into()),
..Default::default()
};
let b = decode_branding(Some(&src));
assert_eq!(
b.display_name, "Request",
"falls back to the request spelling"
);
assert_eq!(b.logo_url, "https://b.test/logo.png");
}
#[test]
fn decode_branding_colour_fallback_chain() {
let mut src = source_with(json!({ "text": "#111111" }));
src.theme = Some("#123456".into());
let b = decode_branding(Some(&src));
assert_eq!(b.primary, "#123456");
assert_eq!(b.accent_text, "#123456", "accentText falls back to theme");
assert_eq!(
b.button_background, "#123456",
"button background falls back to theme"
);
assert_eq!(b.heading, "#111111", "heading falls back to the bag's text");
assert_eq!(b.text, "#111111");
let mut src = source_with(json!({ "heading": "#222222", "accentText": "#333333" }));
src.theme = Some("#123456".into());
src.payment_button_colour = Some("#654321".into());
let b = decode_branding(Some(&src));
assert_eq!(b.heading, "#222222");
assert_eq!(b.accent_text, "#333333");
assert_eq!(b.button_background, "#654321");
}
#[test]
fn decode_branding_tagline_prefers_the_bag() {
let mut src = source_with(json!({ "tagline": "from bag" }));
src.merchant_description = Some("from column".into());
assert_eq!(decode_branding(Some(&src)).tagline, "from bag");
let mut src = source_with(json!({}));
src.merchant_description = Some("from column".into());
assert_eq!(decode_branding(Some(&src)).tagline, "from column");
}
#[test]
fn decode_branding_normalizes_label_style() {
let bagged =
|v: &str| decode_branding(Some(&source_with(json!({ "labelStyle": v })))).label_style;
assert_eq!(bagged("above"), LabelStyle::Above);
assert_eq!(bagged("hidden"), LabelStyle::Hidden);
assert_eq!(
bagged("floating"),
LabelStyle::Above,
"legacy floating -> above"
);
let legacy = |v: &str| {
let src = BrandingSource {
payment_form_label_type: Some(v.to_string()),
..Default::default()
};
decode_branding(Some(&src)).label_style
};
assert_eq!(
legacy("never"),
LabelStyle::Hidden,
"legacy never -> hidden"
);
assert_eq!(legacy("hidden"), LabelStyle::Hidden);
assert_eq!(legacy("floating"), LabelStyle::Above);
assert_eq!(legacy("nonsense"), LabelStyle::Above, "default");
let mut src = source_with(json!({ "labelStyle": "hidden" }));
src.payment_form_label_type = Some("above".into());
assert_eq!(decode_branding(Some(&src)).label_style, LabelStyle::Hidden);
let mut src = source_with(json!({ "labelStyle": "floating" }));
src.payment_form_label_type = Some("never".into());
assert_eq!(decode_branding(Some(&src)).label_style, LabelStyle::Above);
}
#[test]
fn decode_branding_rejects_out_of_range_enum_values() {
let src = source_with(json!({
"radiusSurface": "pill",
"radiusButton": "pill",
"fontFamily": "comic-sans",
"inputSize": "xl",
"layout": "split",
}));
let b = decode_branding(Some(&src));
assert_eq!(
b.radius_surface,
NonPillRadius::Medium,
"a stale 'pill' surface radius drops back to medium"
);
assert_eq!(b.radius_button, CornerRadius::Pill, "buttons may be pill");
assert_eq!(b.font_family, FontFamily::Inter);
assert_eq!(b.input_size, SizeScale::Md);
assert_eq!(b.layout, LayoutStyle::Split);
}
#[test]
fn decode_branding_parses_stringified_booleans() {
let src = source_with(json!({
"showLogo": "true",
"showTotal": "false",
"summaryGradient": true,
"showOrderItems": "yes",
}));
let b = decode_branding(Some(&src));
assert!(b.show_logo, "'true' string flips the default false");
assert!(!b.show_total, "'false' string flips the default true");
assert!(b.summary_gradient, "a real boolean is honoured");
assert!(b.show_order_items, "an unparseable value keeps the default");
}
#[test]
fn decode_branding_powered_by_only_hides_on_explicit_false() {
let with = |v: Option<bool>| {
let src = BrandingSource {
branding_visibility: v,
..Default::default()
};
decode_branding(Some(&src)).show_powered_by
};
assert!(with(None), "absent means shown");
assert!(with(Some(true)));
assert!(!with(Some(false)), "only an explicit false hides it");
}
#[test]
fn decode_branding_reads_flat_copy_and_layout_columns() {
let src = BrandingSource {
payment_form_header_text: Some("Checkout".into()),
payment_button_text: Some("Pay now".into()),
custom_message_for_card_terms: Some("Terms".into()),
sdk_layout: Some("accordion".into()),
..Default::default()
};
let b = decode_branding(Some(&src));
assert_eq!(b.header_text, "Checkout");
assert_eq!(b.pay_button_label, "Pay now");
assert_eq!(b.card_terms_message, "Terms");
assert_eq!(b.payment_layout, PaymentLayout::Accordion);
}
#[test]
fn decode_branding_falls_back_to_default_badges_only_when_absent() {
let b = decode_branding(Some(&source_with(json!({}))));
assert_eq!(b.trust_badges, *DEFAULT_BADGES);
let b = decode_branding(Some(&source_with(json!({ "trustBadges": "[]" }))));
assert!(
b.trust_badges.is_empty(),
"an explicit empty list is honoured"
);
let b = decode_branding(Some(&source_with(json!({ "trustBadges": "broken" }))));
assert_eq!(b.trust_badges, *DEFAULT_BADGES, "malformed -> defaults");
}
#[test]
fn decode_branding_reads_custom_fields_from_the_bag() {
let b = decode_branding(Some(&source_with(json!({}))));
assert!(b.custom_fields.is_empty());
let b = decode_branding(Some(&source_with(json!({ "customFields": "broken" }))));
assert!(b.custom_fields.is_empty(), "malformed -> none");
let b = decode_branding(Some(&source_with(json!({
"customFields": r#"[{"key":"login","type":"email","required":true}]"#
}))));
assert_eq!(b.custom_fields.len(), 1);
assert_eq!(b.custom_fields[0].key, "login");
assert!(b.custom_fields[0].required);
}
#[test]
fn encode_branding_omits_custom_fields_when_there_are_none() {
let e = encode_branding(&default_branding());
let bag = &e.sdk_ui_rules[BRANDING_GROUP_KEY];
assert!(bag.get("customFields").is_none(), "{bag:?}");
}
#[test]
fn encode_branding_round_trips_custom_fields_through_the_bag() {
use crate::core::custom_fields::{CheckoutCustomField, CustomFieldType};
let mut b = default_branding();
let mut field = CheckoutCustomField::new("login");
field.field_type = CustomFieldType::Email;
field.required = true;
b.custom_fields = vec![field];
let encoded = encode_branding(&b);
let source =
source_with(serde_json::to_value(&encoded.sdk_ui_rules[BRANDING_GROUP_KEY]).unwrap());
assert_eq!(
decode_branding(Some(&source)).custom_fields,
b.custom_fields
);
}
fn customized() -> CheckoutBranding {
CheckoutBranding {
display_name: " Acme ".into(),
logo_url: "https://acme.test/logo.png".into(),
tagline: " fast checkout ".into(),
show_logo: true,
logo_shape: LogoShape::Circle,
logo_size: LogoSize::Lg,
primary: "#123456".into(),
surface: "#fefefe".into(),
radius_button: CornerRadius::Pill,
radius_surface: NonPillRadius::Large,
surface_style: SurfaceStyle::Outlined,
layout: LayoutStyle::Compact,
summary_position: SummaryPosition::Right,
show_total: false,
total_label: "Sum".into(),
label_style: LabelStyle::Hidden,
payment_layout: PaymentLayout::SpacedAccordion,
show_powered_by: false,
footer_text: " bye ".into(),
support_email: "help@acme.test".into(),
custom_css: ".a{}".into(),
header_text: " ".into(),
trust_badges: vec![TrustBadge::new("x", "X", "#000000", "#ffffff")],
..default_branding()
}
}
#[test]
fn encode_branding_fills_the_flat_columns() {
let b = customized();
let e = encode_branding(&b);
assert_eq!(e.theme, "#123456");
assert_eq!(e.logo.as_deref(), Some("https://acme.test/logo.png"));
assert_eq!(e.seller_name.as_deref(), Some("Acme"), "trimmed");
assert_eq!(e.payment_form_header_text, None, "blank copy becomes null");
assert_eq!(e.payment_button_colour, b.button_background);
assert_eq!(e.payment_button_text_colour, b.button_text);
assert_eq!(e.background_colour, b.background);
assert_eq!(e.sdk_layout, PaymentLayout::SpacedAccordion);
assert_eq!(
e.payment_form_label_type,
LegacyLabelType::Never,
"hidden maps back to the legacy `never`"
);
assert!(!e.branding_visibility);
let mut above = b.clone();
above.label_style = LabelStyle::Above;
assert_eq!(
encode_branding(&above).payment_form_label_type,
LegacyLabelType::Above
);
}
#[test]
fn encode_branding_writes_the_branding_bag() {
let e = encode_branding(&customized());
let bag = &e.sdk_ui_rules[BRANDING_GROUP_KEY];
assert_eq!(bag["radiusButton"], "pill");
assert_eq!(bag["radiusSurface"], "large");
assert_eq!(bag["surfaceStyle"], "outlined");
assert_eq!(bag["labelStyle"], "hidden");
assert_eq!(bag["showLogo"], "true", "booleans persist as strings");
assert_eq!(bag["showTotal"], "false");
assert_eq!(bag["totalLabel"], "Sum");
assert_eq!(bag["tagline"], "fast checkout", "trimmed");
assert_eq!(bag["footerText"], "bye");
assert_eq!(bag["supportEmail"], "help@acme.test");
assert_eq!(bag["customCss"], ".a{}");
assert_eq!(
bag["trustBadges"],
"[{\"id\":\"x\",\"label\":\"X\",\"textColor\":\"#000000\",\"backgroundColor\":\"#ffffff\"}]"
);
}
#[test]
fn encode_branding_omits_blank_optional_bag_entries() {
let bag = encode_branding(&default_branding()).sdk_ui_rules[BRANDING_GROUP_KEY].clone();
for key in ["tagline", "footerText", "supportEmail", "customCss"] {
assert!(!bag.contains_key(key), "{key} must be omitted when blank");
}
}
#[test]
fn encode_branding_with_base_preserves_unrelated_fields_and_rule_groups() {
let base = json!({
"show_card_terms": true,
"domain_name": "acme.test",
"theme": "#000000",
"sdk_ui_rules": {
"other_group": { "keep": "me" },
"branding": { "stale": "gone" },
},
});
let out = encode_branding_with_base(&customized(), Some(&base));
assert_eq!(
out["show_card_terms"],
json!(true),
"unknown fields survive"
);
assert_eq!(out["domain_name"], json!("acme.test"));
assert_eq!(
out["theme"],
json!("#123456"),
"encoded fields win over base"
);
assert_eq!(out["sdk_ui_rules"]["other_group"]["keep"], json!("me"));
assert_eq!(
out["sdk_ui_rules"]["branding"].get("stale"),
None,
"the branding group is replaced wholesale"
);
assert_eq!(
out["sdk_ui_rules"]["branding"]["radiusButton"],
json!("pill")
);
let bare = encode_branding_with_base(&customized(), None);
assert_eq!(
bare,
serde_json::to_value(encode_branding(&customized())).unwrap()
);
}
#[test]
fn encode_then_decode_round_trips() {
let original = customized();
let encoded = encode_branding(&original);
let source: BrandingSource =
serde_json::from_value(serde_json::to_value(&encoded).unwrap()).unwrap();
let decoded = decode_branding(Some(&source));
let mut expected = original.clone();
expected.display_name = "Acme".into();
expected.tagline = "fast checkout".into();
expected.footer_text = "bye".into();
expected.header_text = String::new();
assert_eq!(decoded, expected);
}
#[test]
fn round_trip_survives_the_dark_default() {
let encoded = encode_branding(&DEFAULT_BRANDING_DARK);
let source: BrandingSource =
serde_json::from_value(serde_json::to_value(&encoded).unwrap()).unwrap();
assert_eq!(decode_branding(Some(&source)), *DEFAULT_BRANDING_DARK);
}
#[test]
fn iso8601_matches_javascript_to_iso_string() {
assert_eq!(iso8601_millis(0), "1970-01-01T00:00:00.000Z");
assert_eq!(
iso8601_millis(1_700_000_000_000),
"2023-11-14T22:13:20.000Z"
);
assert_eq!(
iso8601_millis(1_700_000_000_123),
"2023-11-14T22:13:20.123Z"
);
assert_eq!(
iso8601_millis(1_709_164_800_000),
"2024-02-29T00:00:00.000Z"
);
assert_eq!(iso8601_millis(-1), "1969-12-31T23:59:59.999Z");
}
#[test]
fn build_branding_export_wraps_the_branding() {
let e = build_branding_export_at(&customized(), 1_700_000_000_000);
assert_eq!(e.format, "delopay-checkout-branding");
assert_eq!(e.version, 1);
assert_eq!(e.exported_at, "2023-11-14T22:13:20.000Z");
assert_eq!(e.branding, customized());
let json = serde_json::to_value(&e).unwrap();
assert_eq!(json["branding"]["radiusButton"], json!("pill"));
assert_eq!(json["branding"]["showPoweredBy"], json!(false));
}
#[test]
fn export_import_round_trips() {
let e = build_branding_export_at(&customized(), 0);
let raw = serde_json::to_value(&e).unwrap();
assert_eq!(parse_imported_branding(&raw), customized());
}
#[test]
fn parse_imported_branding_accepts_a_bare_object() {
let raw = serde_json::to_value(customized()).unwrap();
assert_eq!(parse_imported_branding(&raw), customized());
}
#[test]
fn parse_imported_branding_falls_back_on_junk() {
assert_eq!(parse_imported_branding(&json!(null)), *DEFAULT_BRANDING);
assert_eq!(
parse_imported_branding(&json!([1, 2, 3])),
*DEFAULT_BRANDING
);
assert_eq!(parse_imported_branding(&json!("nope")), *DEFAULT_BRANDING);
assert_eq!(parse_imported_branding(&json!({})), *DEFAULT_BRANDING);
}
#[test]
fn parse_imported_branding_validates_each_field_independently() {
let raw = json!({
"displayName": "Acme",
"primary": "not-a-hex",
"background": "#abc",
"surface": 42,
"fontFamily": "comic-sans",
"logoSize": "lg",
"radiusBadge": "square",
"showLogo": "true",
"showPoweredBy": false,
"labelStyle": "floating",
"totalLabel": 7,
"trustBadges": "not-an-array",
"unknownField": "ignored",
});
let b = parse_imported_branding(&raw);
assert_eq!(b.display_name, "Acme");
assert_eq!(
b.primary, DEFAULT_BRANDING.primary,
"bad hex keeps the default"
);
assert_eq!(b.background, "#abc", "a 3-digit hex is valid");
assert_eq!(
b.surface, DEFAULT_BRANDING.surface,
"non-strings keep the default"
);
assert_eq!(b.font_family, FontFamily::Inter);
assert_eq!(b.logo_size, LogoSize::Lg);
assert_eq!(b.radius_badge, CornerRadius::Square);
assert!(b.show_logo);
assert!(!b.show_powered_by);
assert_eq!(
b.label_style, DEFAULT_BRANDING.label_style,
"the importer does not accept the legacy floating value"
);
assert_eq!(b.total_label, DEFAULT_BRANDING.total_label);
assert_eq!(b.trust_badges, *DEFAULT_BADGES);
}
#[test]
fn parse_imported_branding_reads_loose_trust_badges() {
let raw = json!({
"trustBadges": [
{ "id": "a", "label": "A", "textColor": "#010101",
"backgroundColor": "#020202", "borderColor": "#030303" },
{ "label": "B", "textColor": "rgb(1,2,3)", "borderColor": "nope" },
{ "label": "" },
"not-an-object",
],
});
let badges = parse_imported_branding(&raw).trust_badges;
assert_eq!(
badges.len(),
2,
"label-less and non-object entries are dropped"
);
assert_eq!(badges[0].border_color.as_deref(), Some("#030303"));
assert_eq!(badges[1].id, "badge-1", "index-based id fallback");
assert_eq!(badges[1].text_color, "#0f172a", "non-hex colours fall back");
assert_eq!(badges[1].background_color, "#f1f5f9");
assert_eq!(badges[1].border_color, None, "a non-hex border is dropped");
let raw = json!({ "trustBadges": [] });
assert!(parse_imported_branding(&raw).trust_badges.is_empty());
}
#[test]
fn parse_imported_branding_truncates_custom_css() {
let raw = json!({ "customCss": "x".repeat(CUSTOM_CSS_MAX_LENGTH + 10) });
let css = parse_imported_branding(&raw).custom_css;
assert_eq!(css.len(), CUSTOM_CSS_MAX_LENGTH);
let raw = json!({ "customCss": ".a{}" });
assert_eq!(parse_imported_branding(&raw).custom_css, ".a{}");
}
#[test]
fn defaults_are_the_documented_palettes() {
assert_eq!(DEFAULT_BRANDING.primary, "#1E4FEB");
assert_eq!(DEFAULT_BRANDING.button_background, "#0A1130");
assert_eq!(DEFAULT_BRANDING.surface_style, SurfaceStyle::Elevated);
assert_eq!(DEFAULT_BRANDING.radius_badge, CornerRadius::Pill);
assert!(!DEFAULT_BRANDING.show_logo);
assert!(DEFAULT_BRANDING.show_powered_by);
assert_eq!(DEFAULT_BRANDING.trust_badges, *DEFAULT_BADGES);
assert_eq!(DEFAULT_BRANDING_DARK.background, "#020617");
assert_eq!(DEFAULT_BRANDING_DARK.accent_text, "#60a5fa");
assert_eq!(
DEFAULT_BRANDING_DARK.surface_style,
SurfaceStyle::Flat,
"drop shadows don't read on dark surfaces"
);
assert_eq!(DEFAULT_BRANDING_DARK.trust_badges, *DEFAULT_BADGES_DARK);
assert_eq!(
DEFAULT_BRANDING_DARK.total_label,
DEFAULT_BRANDING.total_label
);
assert_eq!(DEFAULT_BRANDING_DARK.layout, DEFAULT_BRANDING.layout);
assert_eq!(default_branding(), *DEFAULT_BRANDING);
assert_eq!(CheckoutBranding::default(), *DEFAULT_BRANDING);
assert_eq!(
clone_branding(&DEFAULT_BRANDING_DARK),
*DEFAULT_BRANDING_DARK
);
}
#[test]
fn branding_variables_cover_every_dp_token() {
let vars = branding_variables(&DEFAULT_BRANDING);
assert_eq!(vars.len(), 22);
let get = |k: &str| {
vars.iter()
.find(|(name, _)| *name == k)
.map(|(_, v)| v.clone())
.unwrap_or_else(|| panic!("missing {k}"))
};
assert_eq!(get("--dp-primary"), "#1E4FEB");
assert_eq!(get("--dp-bg"), "#f8fafc");
assert_eq!(get("--dp-btn-fg"), "#ffffff");
assert_eq!(get("--dp-radius-badge"), "999px");
assert_eq!(get("--dp-radius-surface"), "12px");
assert_eq!(get("--dp-heading-weight"), "600");
assert_eq!(get("--dp-pad-surface"), "1.5rem");
assert_eq!(get("--dp-gap-vertical"), "1rem");
assert_eq!(get("--dp-input-pad"), "0.625rem 0.75rem");
assert_eq!(get("--dp-button-pad"), "0.875rem 1.25rem");
assert_eq!(get("--dp-shadow"), shadow_for(SurfaceStyle::Elevated));
assert_eq!(
get("--dp-surface-border"),
"1px solid transparent",
"only the outlined style paints a border"
);
assert_eq!(vars[0].0, "--dp-primary", "order matches the TS writer");
}
#[test]
fn outlined_surfaces_get_a_real_border() {
let b = CheckoutBranding {
surface_style: SurfaceStyle::Outlined,
border: "#ff0000".into(),
..default_branding()
};
let vars = branding_variables(&b);
let border = vars
.iter()
.find(|(k, _)| *k == "--dp-surface-border")
.map(|(_, v)| v.as_str())
.unwrap();
assert_eq!(border, "1px solid #ff0000");
assert_eq!(
vars.iter()
.find(|(k, _)| *k == "--dp-shadow")
.map(|(_, v)| v.as_str()),
Some("none")
);
}
#[test]
fn branding_variables_css_renders_a_root_rule() {
let css = branding_variables_css(&DEFAULT_BRANDING);
assert!(css.starts_with(":root{--dp-primary:#1E4FEB;"), "{css}");
assert!(
css.ends_with("--dp-surface-border:1px solid transparent;}"),
"{css}"
);
}
#[test]
fn enum_wire_values_survive_serde() {
assert_eq!(
serde_json::to_string(&FontFamily::DmSans).unwrap(),
"\"dm-sans\""
);
assert_eq!(
serde_json::to_string(&PaymentLayout::SpacedAccordion).unwrap(),
"\"spaced_accordion\""
);
assert_eq!(
serde_json::from_str::<FontFamily>("\"jetbrains-mono\"").unwrap(),
FontFamily::JetbrainsMono
);
assert!(serde_json::from_str::<FontFamily>("\"comic-sans\"").is_err());
assert_eq!(NonPillRadius::from_wire("pill"), None);
assert_eq!(CornerRadius::from_wire("pill"), Some(CornerRadius::Pill));
assert_eq!(
CornerRadius::from(NonPillRadius::Large),
CornerRadius::Large
);
assert_eq!(LogoShape::Circle.to_string(), "circle");
}
}