CSS Minify & Beautify — Swift source
Minify CSS (strip comments and whitespace, shorten hexes and decimals) or beautify it back to readable one-declaration-per-line form. Strings stay intact. Runs locally with a shareable link.
This is the Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.
// css-minify — CSS minifier & beautifier. Swift port (canonical TS:
// src/lib/css-minify.ts; Go twin: cli/css-minify). One scanner masks string
// literals as "\x00n\x00" sentinels and drops /* */ comments; every textual
// rule then runs on the masked text — NSRegularExpression (ICU) carries the
// TS backreferences natively, and scanning works on UTF-16 units so the
// offsets match the TS byte-for-byte. minify — collapse whitespace, strip
// spaces around {} ; : , > (sibling + and ~ combinators keep theirs), drop
// the last semicolon before }, lowercase hexes, shorten #aabbcc → #abc
// (never 8-digit alpha), strip leading zeros (0.5 → .5) and trailing
// fraction zeros (1.50 → 1.5, 1.00 → 1, .00 → 0). beautify — one selector
// per block, one declaration per line at 2-space depth, each declaration
// keeping its own semicolon. Errors travel in result.error (nil = success);
// empty input is a successful empty output, never an error.
import Foundation
struct CssFormatResult {
let output: String
let error: String?
}
enum CssMinify {
private static func regex(_ pattern: String) -> NSRegularExpression {
try! NSRegularExpression(pattern: pattern)
}
private static let ws = regex("\\s+")
private static let structStrip = regex("\\s*([{};:,>])\\s*")
private static let trailingSemis = regex(";+}")
private static let hexLower = regex("#[0-9a-fA-F]{3,8}")
private static let hexPair = regex("#([0-9a-f])\\1([0-9a-f])\\2([0-9a-f])\\3([^0-9a-f]|$)")
private static let leadingZero = regex("(^|[^A-Za-z0-9_.#$%-])0+(\\.[0-9]+)")
private static let fractionZeros = regex("(\\.[0-9]*[1-9])0+([^0-9]|$)")
private static let integralZeros = regex("(^|[^A-Za-z0-9_.#$%-])([0-9]+)\\.0+([^0-9]|$)")
private static let dotZeros = regex("(^|[^A-Za-z0-9_.#$%-])\\.0+([^0-9]|$)")
/// JS-style trim: ASCII whitespace only, never the \x00 sentinel units.
private static let jsTrimSet = CharacterSet(
charactersIn: " \t\n\u{0B}\u{0C}\r")
private static func sub(_ re: NSRegularExpression, _ s: String, _ template: String) -> String {
re.stringByReplacingMatches(
in: s, options: [],
range: NSRange(location: 0, length: s.utf16.count),
withTemplate: template)
}
/// Scan CSS into (masked text, string table): every string literal
/// becomes a \x00n\x00 sentinel, every /* */ comment is dropped. A
/// backslash escapes the next character, so \' or \" never closes it.
private static func mask(_ raw: String) -> (text: String, strings: [String], error: String?) {
var units: [UInt16] = []
var strings: [String] = []
let src = Array(raw.utf16)
var i = 0
while i < src.count {
let ch = src[i]
if ch == 34 || ch == 39 { // '"' or '\''
let start = i
i += 1
while i < src.count && src[i] != ch {
if src[i] == 92 && i + 1 < src.count { i += 1 } // escaped char
i += 1
}
if i >= src.count {
return ("", [], "Unterminated string")
}
i += 1
strings.append(String(decoding: src[start..<i], as: UTF16.self))
units.append(contentsOf: Array("\u{0000}\(strings.count - 1)\u{0000}".utf16))
} else if ch == 47 && i + 1 < src.count && src[i + 1] == 42 { // "/*"
var end = -1
var j = i + 2
while j + 1 < src.count {
if src[j] == 42 && src[j + 1] == 47 { end = j; break } // "*/"
j += 1
}
if end < 0 {
return ("", [], "Unterminated comment")
}
i = end + 2
} else {
units.append(ch)
i += 1
}
}
return (String(decoding: units, as: UTF16.self), strings, nil)
}
/// Substitute the sentinels back with the original string literals.
private static func unmask(_ text: String, _ strings: [String]) -> String {
var out: [UInt16] = []
let src = Array(text.utf16)
var i = 0
while i < src.count {
if src[i] == 0 {
var j = i + 1
while j < src.count && src[j] >= 48 && src[j] <= 57 { j += 1 }
if j < src.count && src[j] == 0 && j > i + 1,
let idx = Int(String(decoding: src[(i + 1)..<j], as: UTF16.self)),
idx >= 0, idx < strings.count {
out.append(contentsOf: Array(strings[idx].utf16))
i = j + 1
continue
}
}
out.append(src[i])
i += 1
}
return String(decoding: out, as: UTF16.self)
}
/// /#[0-9a-fA-F]{3,8}/g → lowercase (match-evaluator style).
private static func lowerHex(_ s: String) -> String {
let src = Array(s.utf16)
var out: [UInt16] = []
var last = 0
for m in hexLower.matches(in: s, options: [],
range: NSRange(location: 0, length: src.count)) {
let r = m.range
out.append(contentsOf: src[last..<r.location])
for k in r.location..<(r.location + r.length) {
let c = src[k]
out.append((c >= 65 && c <= 70) ? c + 32 : c) // 'A'..'F' → 'a'..'f'
}
last = r.location + r.length
}
out.append(contentsOf: src[last...])
return String(decoding: out, as: UTF16.self)
}
/// Conservative minification — see the header for the exact rule list.
static func minifyCss(_ raw: String) -> CssFormatResult {
let text = raw.trimmingCharacters(in: jsTrimSet)
if text.isEmpty { return CssFormatResult(output: "", error: nil) } // NOT an error
let m = mask(text)
if let e = m.error { return CssFormatResult(output: "", error: e) }
var css = sub(ws, m.text, " ")
css = sub(structStrip, css, "$1")
css = sub(trailingSemis, css, "}")
css = css.trimmingCharacters(in: jsTrimSet)
css = lowerHex(css)
css = sub(hexPair, css, "#$1$2$3$4")
css = sub(leadingZero, css, "$1$2")
css = sub(fractionZeros, css, "$1$2")
css = sub(integralZeros, css, "$1$2$3")
css = sub(dotZeros, css, "${1}0$2") // TS '$10$2' = group 1 + '0' + group 2
return CssFormatResult(output: unmask(css, m.strings), error: nil)
}
/// Structural beautifier — 2-space indentation, declarations one per
/// line; empty declarations (;;, dangling ;) are skipped.
static func beautifyCss(_ raw: String) -> CssFormatResult {
let text = raw.trimmingCharacters(in: jsTrimSet)
if text.isEmpty { return CssFormatResult(output: "", error: nil) }
let m = mask(text)
if let e = m.error { return CssFormatResult(output: "", error: e) }
let css = Array(sub(ws, m.text, " ").utf16)
var out: [UInt16] = []
var buf: [UInt16] = []
var depth = 0
func trimmedBuf() -> String {
String(decoding: buf, as: UTF16.self)
.trimmingCharacters(in: jsTrimSet)
}
func pad() {
for _ in 0..<(2 * depth) { out.append(32) }
}
func flush(_ semi: Bool) {
// Whitespace was already collapsed to single spaces, so only
// trimming remains here.
let decl = trimmedBuf()
if !decl.isEmpty {
pad()
out.append(contentsOf: Array(decl.utf16))
if semi { out.append(59) } // ';'
out.append(10) // '\n'
}
buf.removeAll()
}
for ch in css {
switch ch {
case 123: // '{'
let sel = trimmedBuf()
buf.removeAll()
if sel.isEmpty {
return CssFormatResult(output: "", error: "Block without a selector")
}
pad()
out.append(contentsOf: Array(sel.utf16))
out.append(contentsOf: Array(" {\n".utf16))
depth += 1
case 125: // '}'
flush(false)
depth -= 1
if depth < 0 {
return CssFormatResult(output: "", error: "Unbalanced }")
}
pad()
out.append(contentsOf: Array("}\n".utf16))
case 59: // ';'
flush(true)
default:
buf.append(ch)
}
}
if depth != 0 {
return CssFormatResult(output: "", error: "Unclosed block")
}
flush(false)
return CssFormatResult(output: unmask(String(decoding: out, as: UTF16.self), m.strings),
error: nil)
}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →