AI Tone Rewriter — Swift source
Rewrite any message in a new tone — professional, friendly, concise, formal, or playful — with your own free Groq key, called straight from your browser.
This is the Swift implementation — the same logic the interactive tool runs, in a shareable, citable form.
// tone-rewriter — tone registry, prompt building, and reply cleanup.
//
// Language: Swift (5, Foundation allowed — NSRegularExpression carries the
// fence cleanup; String counts grapheme clusters where the TS lib
// counts UTF-16 units)
// CosmoDev polyglot showcase port of the `tone-rewriter` tool, ported from
// src/lib/tone-rewriter.ts (the canonical TypeScript implementation).
//
// Why this file exists: the tone rewriter is an AI tool, but its contract is
// pure — which registers exist, how the system prompt is assembled, and how
// a raw model reply is cleaned for display. One compiled NSRegularExpression
// is the only machinery the cleanup needs — no provider, no keys, no network.
//
// Run: swift swift.swift
import Foundation
/// The five supported registers (the TS `Tone` string-literal union); the
/// rawValue is the wire id and each case carries its label and prompt
/// sentence in one exhaustive table.
enum Tone: String, CaseIterable {
case professional
case friendly
case concise
case formal
case playful
/// Human label — the TS `ToneOption.label`.
var label: String {
switch self {
case .professional: return "Professional"
case .friendly: return "Friendly"
case .concise: return "Concise"
case .formal: return "Formal"
case .playful: return "Playful"
}
}
/// Per-tone register sentence embedded in the system prompt.
var contract: String {
switch self {
case .professional:
return "polished and businesslike, no slang, clear and direct — the "
+ "register of a status update to stakeholders"
case .friendly:
return "warm and approachable, contractions welcome, like a teammate "
+ "chatting — never stiff"
case .concise:
return "as short as possible while keeping every fact; prefer one "
+ "sentence; cut filler words without exception"
case .formal:
return "ceremonial register, no contractions, complete sentences — "
+ "the register of official correspondence"
case .playful:
return "light and witty, a touch of humor, emojis allowed (at most "
+ "two) — but the facts stay exact"
}
}
}
/// One chat message (`role` is "system" or "user").
struct Message {
let role: String
let content: String
}
/// Payload cap for the user text (the TS `MAX_INPUT_CHARS`).
let maxInputChars = 12_000
/// The TS /```[a-z]*\n?/g fence marker, compiled once.
let fencePattern = try! NSRegularExpression(pattern: "```[a-z]*\\n?")
/// Build the [system, user] chat messages for the provider layer.
///
/// Input longer than `maxInputChars` is sliced and tagged with a visible
/// "… (text truncated)" marker so the model knows the payload was capped.
/// Swift counts Characters (grapheme clusters) where the TS lib counts
/// UTF-16 units — they agree outside emoji/ZWJ and surrogate territory.
func buildPromptMessages(_ text: String, tone: Tone) -> [Message] {
let body = text.count > maxInputChars
? String(text.prefix(maxInputChars)) + "\n… (text truncated)"
: text
let system = "You rewrite text in a target tone. Rewrite the user's text in a "
+ "\(tone.rawValue) tone: \(tone.contract). Keep the same meaning and the "
+ "same facts — only the register changes. Output ONLY the rewritten "
+ "text, no preamble, no notes."
return [Message(role: "system", content: system),
Message(role: "user", content: body)]
}
/// Clean the model's reply into displayable rewritten text.
///
/// Strips every ```lang fence marker (the TS /```[a-z]*\n?/g regex) plus
/// surrounding whitespace; returns nil only when nothing survives.
func parseRewrite(_ text: String) -> String? {
let full = NSRange(text.startIndex..., in: text)
let stripped = fencePattern.stringByReplacingMatches(
in: text, range: full, withTemplate: "")
let cleaned = stripped.trimmingCharacters(in: .whitespacesAndNewlines)
return cleaned.isEmpty ? nil : cleaned
}
let msgs = buildPromptMessages("The Q3 numbers are in.", tone: .professional)
for m in msgs {
print("\(m.role): \(m.content)")
}
print(parseRewrite("```text\nHere you go!\n```\n") ?? "(nil)")
print(parseRewrite("``` \n") ?? "(nil)") // a fence and nothing else
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 →