Files
canina/frontend/application/lib/slug.ts
T

58 lines
1.8 KiB
TypeScript

/**
* Safe slug normalization and encoding for SEO routes.
*
* Handles:
* - Single-encoded Persian/UTF-8 (%D8%A2%D8%BA%D9%88%D8%B2 -> آغوز)
* - Double-encoded slugs (%25D8%25A2... -> آغوز)
* - Raw Unicode (آغوز -> آغوز)
* - Slugs with spaces or encoded spaces (آب پنیر / %D8%A2%D8%A8%20%D9%BE%D9%86%DB%8C%D8%B1)
* - Slashes like EPA/DHA (EPA%2FDHA -> EPA/DHA)
* - Malformed percent sequences without throwing URIError (e.g. 100%pure, %E0%A4%A)
* - Safe single-encoding for outgoing API requests and canonical URLs.
*/
function safeDecode(val: string): string {
try {
return decodeURIComponent(val);
} catch {
return val;
}
}
/**
* Normalizes an incoming route parameter slug to a clean, decoded UTF-8 string.
* Decodes iteratively (up to 2 passes) if double-encoded, but does not alter strings
* where percent is not a valid percent-encoding sequence.
*/
export function normalizeRouteSlug(rawSlug: string): string {
if (!rawSlug) return '';
let current = String(rawSlug).trim();
// If input contains '%', attempt safe decoding
if (current.includes('%')) {
const decodedOnce = safeDecode(current);
if (decodedOnce !== current) {
// Check if it was double-encoded (e.g. %25D8... -> %D8... -> Persian)
if (decodedOnce.includes('%')) {
const decodedTwice = safeDecode(decodedOnce);
// Only accept second decode if it produced a valid string that differs
if (decodedTwice !== decodedOnce) {
return decodedTwice;
}
}
return decodedOnce;
}
}
return current;
}
/**
* Encodes a normalized slug safely for outgoing HTTP query/path or canonical URL.
*/
export function safeEncodeSlug(slug: string): string {
if (!slug) return '';
return encodeURIComponent(slug);
}