All 48 libraries

SugarColorprofile

Terminal color profile detection and color degradation

inspired by charmbracelet/colorprofile colorterminaloutput

SugarColorprofile code coverage

Detect the terminal's color capability (TrueColor / Ansi256 / Ansi / Ascii / NoTTY — the five detection-emittable levels) and degrade colors, strings and whole output streams to match it — one-way, TrueColor down, never up; an opt-in perceptual family picks the nearest palette color when a degraded value must land on a fixed set. Detection reads the shared env ladder, honoring NO_COLOR, FORCE_COLOR, TERM=dumb and the reduced-motion request. It ports the concepts of charmbracelet/colorprofile, which detects a terminal's color profile and downgrades output to match.

Install

composer require sugarcraft/sugar-colorprofile

No tagged releases ship yet — Packagist serves the dev-master branch only, so require it as sugarcraft/sugar-colorprofile:dev-master; on a default-stable project a bare sugarcraft/sugar-colorprofile request does not resolve.

Requires PHP 8.3+ and the ext-mbstring extension — the UTF-8 sweep in Env::sanitize and the TERM cap run mb_convert_encoding/mb_strcut unguarded, and until this was declared the dependency was satisfied only transitively via sugar-core while the docs claimed the opposite. The probes' optional posix_* calls remain feature-detected, and an absent or unreadable infocmp child degrades the phase-2 answer instead of failing. Direct dependencies: sugarcraft/sugar-core, react/event-loop, react/child-process, react/promise (the latter three back the async AsyncProbe consult).

Supported targets: POSIX terminals. The phase-2 infocmp consult is POSIX-only by design — it queries the compiled terminfo database. The env ladder's Windows/macOS legs (WT_SESSION, the TERM_PROGRAM=iTerm.app hint, the only macOS terminal name matched, since Apple_Terminal is deliberately excluded) are untested by this repository's CI, whose ladder legs run on Linux only; on Windows the library answers from the env ladder alone. Case matters more there than anywhere else: env keys are matched case-exactly, while the Windows environment block is case-insensitive at the OS layer — an unusual spelling such as No_Color can exist in the shell's view and still miss detection, because the library deliberately does not alias-match env keys (Env::resolve).

Quickstart

use SugarCraft\ColorProfile\{Color, ColorProfile, Palette, ProfileWriter};

$profile = Palette::detect(STDOUT);      // ColorProfile::TrueColor | Ansi256 | Ansi | Ascii | NoTTY
echo $profile->label();                  // e.g. "No TTY" when piped

// Downsample one color to an explicit profile
$coral = Color::parse('#ff6b6b');        // r 255, g 107, b 107
$c256  = Palette::toProfile($coral, ColorProfile::Ansi256);
echo $c256->toAnsi256Index();            // 203
echo $c256->toAnsi256Foreground();       // "\x1b[38;5;203m"

// Rewrite every color in a string for a given profile
$ansi = (new Palette())->withProfile(ColorProfile::Ansi256)
    ->degrade("\x1b[38;2;255;107;107mhi\x1b[0m"); // "\x1b[38;5;203mhi\x1b[0m"

// Or wrap a stream and let it degrade (or strip, under NoTTY) on write
ProfileWriter::wrap(STDOUT)->write("\x1b[38;2;107;80;255mFancy\x1b[0m\n");

Concepts

A color profile is the richest color an output stream can carry: TrueColor, Ansi256, Ansi, Ascii or NoTTY. Detection picks one of them from the environment, and degradation only goes down. A TrueColor value is rewritten to the nearest color the chosen profile can show, and nothing is ever raised to a richer profile. Ascii drops the color and keeps decoration such as bold and underline. NoTTY strips every escape, so use it for streams that are not terminals.

What's in the box

Profile detectionOne canonical 14-step ladder every surface shares, override-first: CLICOLOR_FORCE=1 / FORCE_COLOR outrank every later leg (a falsy FORCE_COLOR spelling lands on the Ascii floor). Suppressors come next: NO_COLOR (empty = unset), CLICOLOR=0 and TERM=dumb (case-insensitive) turn color off — dumb outranks an advertised COLORTERM, it is a promise of minimal capabilities. Advertised depth follows: COLORTERM (24bit/truecolor, plus the legacy marker yes, which the ladder reads as a 256-color promise, not a 24-bit one), TERM_PROGRAM, WT_SESSION, GOOGLE_CLOUD_SHELL (exactly true grants TrueColor; any other value, false and 1 included, carries no 24-bit promise), the TMUX/STY + screen*/tmux* rung and the TERM depth patterns. Palette adds the stream TTY gate on top; Probe/AsyncProbe/TerminalProbe add the phase-2 infocmp Tc/RGB upgrade (a fixed-path binary, run with a minimal child environment). The detection ladder emits five levels (TrueColor, Ansi256, Ansi, Ascii and NoTTY), and the ColorProfile enum that carries the result has eight.
Color degradationPalette::toProfile() / Color::convert() downsample a color to the 256-color cube and gray ramp or to the 16 ANSI slots.
String rewritingdegrade() rewrites the SGR colors in a string for the current profile; under NoTTY it strips every escape — SGR, CSI, OSC and DCS sequences, SS3/APC/PM/SOS strings, the Fe escape pairs and charset selectors — decoration included, so pin the Ascii floor for a color-only strip. ProfileWriter does the same to everything written to a stream.
StandardColorsThe 16 ANSI colors as Color values via the non-mutating read API — StandardColors::all(), fromIndex(1), catalog(). (The $red/$brightBlack statics are deprecated process-global mutables; see the README deprecation window.)
Perceptual distanceCIELAB conversion with ΔE*76 / ΔE*94 / CIEDE2000 (DeltaE) and an opt-in nearest-palette matcher (NearestColor).

Detection phases

The capability probes run in four phases; phase 1 is the shared DetectionChain, so the ladder cannot drift between surfaces:

PhaseSourceWhat it can set
1 — env ladderDetectionChain over Env::resolve()Any of the five detection-emittable levels: TrueColor / Ansi256 / Ansi / Ascii / NoTTY
2 — terminfoinfocmp -1 at a fixed absolute-path roster, never looked up on PATHPromotes an Ansi/Ansi256 rung to TrueColor on Tc/RGB; Sixel from terminfo capability names
3 — advertisedTERM_PROGRAM capability map (interactive streams only)Advertised TrueColor (WezTerm/vscode/Ghostty), ITerm2 (iTerm.app), Hyperlinks (Hyper)
4 — floorsSuppression and minimal-capability floorsHolds the Ascii/NoTTY landings and the reserved-capability gates

The terminfo leg is an exec surface: the infocmp binary is launched from a fixed absolute-path roster (never looked up on PATH), and the child environment is built in one place — the queried TERM plus a fixed PATH only. TERMINFO, TERMINFO_DIRS and HOME each steer infocmp's database lookup and are never inherited. The parser's name-position guard protects the parse from a hostile terminfo entry but cannot vouch for the source: whoever can write the system terminfo directories owns that answer. Treat every detection result as a rendering hint, never as an authorization signal.

Source & demos

Try the quickstart →

Tasks

Pin the profile for a test or a CI log. A non-empty $env replaces the ambient environment, so the answer is the same on every host.

use SugarCraft\ColorProfile\Palette;

$profile = Palette::detect(STDOUT, ['FORCE_COLOR' => '2']);
echo $profile->label();   // ANSI 256

Strip the color and keep the decoration. Pin the Ascii floor and run the string through degrade().

use SugarCraft\ColorProfile\{ColorProfile, Palette};

$plain = (new Palette())
    ->withProfile(ColorProfile::Ascii)
    ->degrade("\x1b[1;38;2;255;0;0mERROR\x1b[0m");
// "\x1b[1mERROR\x1b[0m": the bold stays and the color goes

Pin one stream to a rung. ProfileWriter::wrap() takes the same environment array, so every write to the stream degrades to that rung.

use SugarCraft\ColorProfile\ProfileWriter;

$writer = ProfileWriter::wrap(STDOUT, ['FORCE_COLOR' => '1']);
$writer->write("\x1b[38;2;255;0;0mdisk low\x1b[0m\n");   // written with the ANSI red, \x1b[91m

API reference

ClassMethodDescription
Palettestatic detect($stream = null, array $env = []): ColorProfileDetect the color profile for a stream
Palette__construct($stream = null, array $env = []) / profile() / withProfile(ColorProfile)Detected profile, or an explicit one
Paletteconvert(Color) / static toProfile(Color, ColorProfile)Downsample a color
Palettedegrade(string) / static stripAnsi(string)Rewrite or strip the escapes in a string
Palettedescribe() / comment()Plain-language capability announcement instead of painting escapes (accessibility-friendly)
Colorstatic parse('#rrggbb') / static fromHex(0xrrggbb) / new Color(r, g, b, a)Construct a color
ColortoHex() / toAnsi256Index() / toAnsi16Index() / toAnsiForeground() / toAnsi256Foreground() / toAnsi16Foreground()Encode a color
ColortoAnsiBackground() / toAnsi16Background() / toAnsi8Index() / static ansi16Sgr(int, bool) / static fromAnsi256Index(int)Background escapes, the 8-color index, SGR pairing and reverse decoding
Colorequals(Color) / perceivedBrightness() / isDark() / convert(ColorProfile)Compare, measure and downsample a color
ColorProfileTrueColor, Ansi256, Ansi240, Ansi, Ansi8, Fgbg, Ascii, NoTTY / label() / description() / maxColors() / degradedTo() / allowsColor()Enum of color profiles
ProfileWriterstatic wrap($stream, array $env = []) / write(string) / printf(format, ...)Stream that degrades color on write
StandardColorsall(), fromIndex(int), catalog()The 16 ANSI colors (non-mutating read API; the $black…$brightWhite statics are deprecated — see README)
DetectionChainstatic detect(array $env = []) → level() / source() / term() / allowsColor() / isForced() / toColorProfile(); static userOptedOut(array $env = []): boolThe shared 14-step env ladder every detector agrees on; on the TMUX/STY rung the inner TERM is the base — no re-anchoring happens
Probestatic colorProfile() / isNoColor() / isForceColor() / reducedMotion() / resetForTesting()Static env-probe layer + infocmp upgrade
Envstatic resolve(array $injected) / value(resolved, key) / sanitize(value)Env resolution (a non-empty injected map fully replaces the ambient env) + sanitized source strings
AsyncProbestatic colorProfile(?LoopInterface $loop = null): PromiseInterface / static report(?LoopInterface $loop = null): PromiseInterface<ProbeReport> / resetForTesting()The async surfaces: a bounded ReactPHP infocmp child on the loop you pass (queried TERM + fixed PATH only). colorProfile() settles from the detection chain, and its only non-chain answer is the TrueColor promotion read from the child's terminfo output. report() is the full capability report and the async replacement for the deprecated Probe\TerminalProbe. Without a loop both resolve in place through the bounded sync door, and no child is parked on the event-loop singleton
Probe\TerminalProberun() / runProbe() → ProbeReportDeprecated (REMOVED-IN: 2.0.0): use AsyncProbe::report(). Its terminfo leg blocks the calling thread for up to the 5 s deadline plus the 1 s grace, so do not call run() on an event-loop thread. Phased capability report (TrueColor/Color256/Color16/NoColor/BasicAscii + Sixel, KittyKeyboard, ITerm2, Hyperlinks; BracketedPaste/FocusEvents reserved) with per-capability sources
Probe\ProbeReporthas(Capability) / hasTrueColor() / hasColor256() / hasNoColor() / all() / allWithSource() / colorDescription() / toColorProfile()Per-capability verdicts with the source that set each one
ColorMathstatic toLab(int, int, int) / rgbToXyz / srgbToLinear / linearToXyz / xyzToLabsRGB → CIELAB conversion building blocks
ColorDistancebetween(Color, Color) / betweenLab(array, array): floatThe selected ΔE metric (Euclidean / Cie76 / Cie94 / Cie2000) applied to colors or Lab triples
DeltaEstatic cie76(array, array) / cie94(array, array) / cie2000(array, array): floatThe three perceptual-distance formulas
NearestColor__construct(ColorDistance) / ansi256(Color) / ansi16(Color) / closest(Color, array) / withError(Color, ?&err) / metric() / static palette256() / palette256Lab() / palette16Lab()Opt-in nearest-palette matcher over the cached Lab palettes
PaletteIndexstatic fromPalette(array, ColorDistance) / nearest(Color) / metric() / palette() / count()Precomputed Lab index over any fixed palette

Only methods declared in sugar-colorprofile/src, or inherited from a parent declared there, are listed. A type that extends a class outside that tree, such as \RuntimeException, does not show the methods of that class.

SugarCraft\ColorProfile

AsyncProbe final class

Asynchronous terminal color profile probe using ReactPHP ChildProcess.

MethodSummary
static colorProfile(?LoopInterface $loop = null): PromiseInterfaceDetect the terminal color profile asynchronously.
static report(?LoopInterface $loop = null): PromiseInterfaceFull terminal capability report on the same loop contract as colorProfile(): the infocmp leg runs as a child on the loop you pass in, and the promise settles with the ProbeReport the sync pipeline composes, not a second implementation of it.
static _reset(): void

Color final class

RGBA color value object.

MethodSummary
__construct(int $r, int $g, int $b, int $a = 255)The constructor is the ONE documented deliberate clamp in this class: quantisers and blend pipelines feed raw RGB runs and must not explode mid-frame (the one out-of-range policy otherwise is fail-loud on DECODER-shaped inputs — see self::ansi16Sgr() and self::fromAnsi256Index(), which throw).
static fromHex(int $hex, int $a = 255): selfConstruct from a 24-bit hex integer (0xRRGGBB).
static parse(string $hex, int $a = 255): selfParse from CSS hex string ("#rrggbb" or "#rgb").
convert(ColorProfile $profile): selfConvert this color to the closest approximation representable in $profile.
toAnsi256Index(): intConvert to 256-color ANSI palette index (0-255).
toAnsi16Index(): intConvert to ANSI 16-color palette index (0-15).
toAnsi8Index(): intConvert to the ANSI 8-color basic palette index (0-7).
toTrueColorForeground(): stringRender as a 24-bit truecolor SGR foreground escape: \x1b[38;2;R;G;Bm
toTrueColorBackground(): stringRender as a 24-bit truecolor SGR background escape: \x1b[48;2;R;G;Bm
toAnsiForeground(): string
toAnsiBackground(): string
toAnsi256Foreground(): stringEmit a 256-color ANSI foreground escape.
toAnsi256Background(): stringEmit a 256-color ANSI background escape.
toAnsi16Foreground(): stringEmit a 16-color ANSI foreground escape using 4-bit SGR.
toAnsi16Background(): stringEmit a 16-color ANSI background escape using 4-bit SGR.
toAnsiFor(ColorProfile $profile, bool $background = false): stringEmit the SGR escape that renders this color on a given profile rung — the value-object sibling of Palette::emitColor() (CP-18).
static ansi16Sgr(int $idx, bool $background): intMap an ANSI 16-color index (0-15) to a 4-bit SGR code.
static fromAnsi256Index(int $idx): selfDecode an ANSI 256-color index back to an RGB color.
toLab(): arrayCIE L*a*b* (D65) coordinates of this color.
toHex(): stringReturn "#rrggbb" hex string.
perceivedBrightness(): floatPerceived brightness (0-255) — the BT.601-weighted root-mean-square this library uses to pick black/white in self::toAscii() and the classic xterm "is this dark?" heuristic. Public so callers can choose a light or dark text variant of a background themselves instead of re-deriving the formula.
isDark(): boolTrue when the color is darker than the mid-gray point of self::perceivedBrightness() — i.e. white text reads better on it.
static namedColors(): arrayEnumerate the names of the standard named colors.
static fromName(string $name): selfResolve a standard color by name (case-insensitive).
static fromAnsi16Index(int $idx): selfDecode an ANSI 16-color index (0-15) to its reference RGB color.
static fromAnsi8Index(int $idx): selfDecode an ANSI 8-color index (0-7) to its reference RGB color.
equals(Color $other): bool

ColorDistance enum

Distance-metric strategy for nearest-color matching.

Cases: Euclidean · Cie76 · Cie94 · Cie2000

PHP also provides cases(), from() and tryFrom().

MethodSummary
between(Color $a, Color $b): floatDistance between two colors under this metric.
betweenLab(array $labA, array $labB): floatDistance between pre-computed Lab triples — the hot-loop entry point, letting callers amortize the sRGB -> Lab conversion over a memoized palette. EUCLIDEAN is an RGB-space metric with no meaning here: it throws instead of silently substituting Lab-space magnitudes, so mixing the two scales fails loudly.

ColorMath final class

Perceptual color-space conversion math: sRGB -> linear -> CIE XYZ (D65) -> CIE L*a*b*.

MethodSummary
static toLab(int $r, int $g, int $b): arrayConvert an sRGB byte triplet to CIE L*a*b* (D65).
static rgbToXyz(int $r, int $g, int $b): arrayConvert an sRGB byte triplet to CIE XYZ (D65), Y normalized to 0-1.
static srgbToLinear(int $byte): floatInverse-compatibility (gamma) decode one sRGB byte to linear light 0-1.
static linearToXyz(float $r, float $g, float $b): arrayApply the IEC 61966-2-1 sRGB -> CIE XYZ (D65) matrix to linear light.
static xyzToLab(array $xyz): arrayConvert CIE XYZ (D65) to CIE L*a*b* (CIE 1976).

ColorProfile enum

Terminal color capability profile — THE single vocabulary.

Cases: TrueColor · Ansi256 · Ansi240 · Ansi · Ansi8 · Fgbg · Ascii · NoTTY

PHP also provides cases(), from() and tryFrom().

MethodSummary
static fromColorProfile(self $p): self
static fromCore(\SugarCraft\Core\Util\ColorProfile $core): selfLift a sugar-core Util\ColorProfile onto this vocabulary (CP-22).
toCore(): \SugarCraft\Core\Util\ColorProfileProject onto the five-rung Core enum (CP-22). Lossy on purpose: Core has no 240/8/fgbg rungs, so each lands on the nearest rung that never emits a color the profile could not render — Ansi240 to Ansi256, Ansi8 to Ansi, Fgbg to Ascii.
label(): stringHuman-readable label for display.
description(): stringShort description for display.
maxColors(): intMaximum colors this profile supports.
degradedTo(): ?selfWalk the profile downgrade chain to the next simpler profile. Returns null when already at the simplest (NoTTY). The walk is about emission richness, not provenance: standing on either colorless rung it cannot tell an operator opt-out from absent hardware — DetectionChain::userOptedOut() answers that (CP-20).
allowsColor(): boolWhether this profile permits ANSI COLOR rendering.

DeltaE final class

CIE color-difference (delta-E) metrics computed on CIE L*a*b* (D65) triples.

MethodSummary
static cie76(array $labA, array $labB): floatCIE 1976 color difference: Euclidean distance in L*a*b*.
static cie94(array $labA, array $labB): floatCIE 1994 color difference in the graphic-arts parametrisation.
static cie2000(array $labA, array $labB): floatCIEDE2000 (ΔE00) color difference.
static between(Color $a, Color $b, ColorDistance $metric = ColorDistance::Cie76): floatPublic Color-level door: convert each Color to Lab exactly once, then dispatch to the array-form trio by metric.

DetectionChain final class

Shared terminal color detection chain — the single source of truth for environment-based color capability detection.

MethodSummary
static detect(array $env = []): selfRun the detection chain on an environment array.
level(): stringGet the detected level as a string.
source(): stringGet the source of the detection result.
term(): stringGet the TERM value used in detection. Values at or below self::TERM_MAX_BYTES come back byte-identical; a longer value is clamped to the ceiling here rather than exported raw — the accessor is where TERM leaves the chain, and detection itself already matched it by equality before any consumer could see it.
allowsColor(): boolWhether the ladder answered on a rung that renders color at all.
isForced(): boolTrue when the answer came from an explicit force leg rather than a capability read or a suppression. Callers gating on TTY presence use this to yield: upstream parity is Detect() = isatty() || forced() (CP-07), so an operator who PINNED color through the force machinery keeps that rung even on a piped stream. Suppression legs are NOT force — NO_COLOR/CLICOLOR=0/TERM=dumb ask for less output, never for escape sequences past a pipe, so they keep the gate.
static userOptedOut(array $env = []): boolDid the OPERATOR opt out of color, as opposed to the hardware lacking a TTY? True iff a suppression leg (NO_COLOR, CLICOLOR=0, TERM=dumb) actually FIRED the answer. A force leg outranking a suppression reads FALSE here — the rung in force is not a suppression, whoever asked. This is the discriminator the profile enums deliberately do not carry: since CP-05 both stories answer colorless rungs (Ascii for the opt-out, NoTTY for absent hardware) and a name cannot hold two truths, while a CLI repairing its own defaults (--color=always) or drawing a doctor panel needs the WHY (CP-20, sugar-colorprofile-023; the full enum split is reserved for 2.0 — decision candidate #4).
toProfile(): ColorProfileConvert the detection level to the profile enum.
toColorProfile(): ColorProfileConvert the detection level to a ColorProfile enum.

Env final class

Single environment-resolution rule shared by every detection surface.

MethodSummary
static resolve(array $injected): arrayResolve the effective environment map for one detection run.
static value(array $resolved, string $key): ?stringRead one variable from a resolved map, normalizing absent/false/null to null.
static isForceValue(?string $value): boolThe force-value grammar shared by every CLICOLOR_FORCE reader: a value forces when it is SET and is neither the empty string nor the exact falsy spelling '0' — the termenv/chafa rule ("any non-empty != 0"), which the README's chalk-escape-hatch justification invokes while the old literal '1'-only reading silently stripped color for the CLICOLOR_FORCE=true|yes|on|2 spellings real dotfiles and CI images export. Only '0' and unset/empty are falsy; every other non-empty string forces. Env owns this single rule so the three readers — DetectionChain step 1, TerminalProbe's capability mapping and Probe::isForceColor — cannot drift apart (XPLAT-02).
static sanitize(string $value): stringMake an untrusted environment value safe to interpolate into a source string: strip C0/C1/DEL control bytes (which could forge escape sequences downstream consumers print) and cap the length.

Lang final class

Per-library translation facade for sugar-colorprofile.

NearestColor final class

True nearest-color matching against fixed (or arbitrary) palettes.

MethodSummary
static new(ColorDistance $metric = ColorDistance::DEFAULT_METRIC): selfHouse front door: a matcher on the default metric seat (CP-49).
static forMetric(ColorDistance $metric): selfHouse front door spelling an intentional strategy choice (CP-49).
metric(): ColorDistanceThe distance strategy this matcher was built with.
withError(Color $color, ?array &$err = null): int
ansi256(Color $color): intNearest index (0-255) in the ANSI-256 palette.
ansi16(Color $color): intNearest index (0-15) in the standard ANSI-16 palette.
closest(Color $color, array $palette): int|stringNearest key in an arbitrary palette map of Colors.
bestMatchWithError(Color $color, ?array &$err = null): intError-compensated nearest lookup against the ANSI-256 palette.
static palette256(): arrayThe 256-color palette as Colors — memoized, keyed on the live StandardColors slots (indices 0-15) so a redefinition rebuilds it.
static palette256Lab(): arrayL*a*b* of self::palette256(), memoized behind the same slot fingerprint — the hot-loop guard that makes CIEDE2000 nearest matching affordable while the ANSI-16 slots stay untouched.
static palette16Lab(): arrayL*a*b* of the ANSI-16 palette, memoized behind the slot fingerprint so a StandardColors reassignment lands on the next call.

Palette final class

Detect and query the terminal color profile.

MethodSummary
__construct($stream = null, array $env = [])Detect the terminal color profile from the environment.
profile(): ColorProfileGet the detected profile.
withProfile(ColorProfile $profile): selfOverride the detected profile (e.g. manually downgrade for testing).
static detect($stream = null, array $env = []): ColorProfileShortcut: detect and return the profile enum.
convert(Color $color): ColorConvert a color to the detected (or manually set) profile.
static toProfile(Color $color, ColorProfile $profile): ColorStatic shortcut for one-off color conversion.
degrade(string $ansi): stringConvert any TrueColor/ANSI256/ANSI sequence in a string to match the current profile. At the colorless Ascii rung every COLOR segment drops while decoration and all other sequences pass (CP-05); NoTTY strips everything.
static stripAnsi(string $s): stringStrip all ANSI escape sequences from a string. Used when NoTTY is active.
comment(): stringComment on the detected profile in a human-readable way.
describe(): stringFull descriptive sentence about the terminal's color capabilities.

PaletteIndex final class

PCA-bucketed accelerator for nearest-color lookup over a fixed palette.

MethodSummary
static fromPalette(array $colors, ColorDistance $metric = ColorDistance::Cie76): selfBuild (or reuse) an index over $colors under $metric.
nearest(Color $color): intNearest palette index (lowest index on exact ties).
metric(): ColorDistanceThe distance strategy this index was built with.
palette(): arrayThe palette this index was built from, in caller order.
count(): int

Probe final class

Static probe for terminal color profile and environment-based color detection.

MethodSummary
static colorProfile(): ColorProfileNegotiated color profile after walking every environment variable in the canonical precedence order, then the optional infocmp phase-2 upgrade.
static isNoColor(): boolNO_COLOR is set to a non-empty value. An empty string means UNSET per the no-color.org convention the whole ecosystem follows.
static isForceColor(): boolCLICOLOR_FORCE carries a force value — set, non-empty, and not exactly '0' (the termenv/chafa grammar owned by Env::isForceValue(), shared with DetectionChain step 1 and TerminalProbe) — forcing TrueColor regardless of other settings.
static reducedMotion(): boolReduced motion preference — checks REDUCE_MOTION then PREFERS_REDUCED_MOTION. Explicit negative spellings (0/false/no/off, case-insensitive) mean "not reduced"; any other non-empty value means reduced. The old polarity treated REDUCE_MOTION=false as TRUE, inverting the operator's declared preference.
static _reset(): void

ProfileWriter final class

ProfileWriter — stream wrapper that automatically degrades ANSI color sequences to match the terminal's detected color profile.

MethodSummary
static wrap($stream, array $env = []): self
__construct($stream, ColorProfile $profile)Create a new ProfileWriter wrapping $stream.
contents(): ?stringThe bytes written so far, read back — for consumers that wrap a memory stream (php://memory / php://temp) in tests and pipelines and want the accumulated output without the ftell/rewind dance themselves.
profile(): ColorProfileGet the current target profile.
withProfile(ColorProfile $profile): selfManually change the target profile (e.g. force ASCII mode).
write(string $data): int|falseWrite data to the stream, degrading color codes to match the target profile.
printf(string $format, ...$args): int|falseAlias of write() for printf-style calls.

StandardColors final class

Standard 16-color ANSI palette as named Color objects.

MethodSummary
static all(): arrayAll 16 colors as an indexed array.
static fromIndex(int $index): ColorGet a color by ANSI 16-color index (0-15).
static catalog(): arrayReturns a list of all available standard color names.

SugarCraft\ColorProfile\Probe

Capability enum

Terminal capability enum discovered via TerminalProbe.

Cases: TrueColor · Color256 · Color16 · NoColor · Sixel · KittyKeyboard · ITerm2 · Hyperlinks · BracketedPaste · FocusEvents · BasicAscii

PHP also provides cases(), from() and tryFrom().

MethodSummary
label(): stringHuman-readable label for display.
static key(self $cap): stringThe string key a Capability occupies in a raw caps map.

InfocmpBinary final class

Single source of truth for locating the infocmp terminfo binary.

MethodSummary
static path(): ?stringAbsolute path to infocmp, or null when no roster candidate is a present AND executable file. The executable leg is what keeps this gate from drifting from sugar-image's ChafaBinary roster gate — see the class docblock's shared-rule note.
static runBounded(string $term, ?float $timeoutSeconds = null): ?stringThe ONE bounded infocmp execution surface, shared by every surface (synchronous Probe, the TerminalProbe phase-2 leg, and future callers). The pre-CP-11 shape carried two unbounded waits: the child was untimed (a wedged infocmp blocked the caller for its whole life) and its output was slurped without limit. Both arms are now bounded, and the answer is memoized per TERM so a per-tick consumer multiplies nothing.
static childEnvironment(?string $term = null): arrayThe environment every infocmp child receives, at every exec surface.
static isSafeTermName(string $term): boolIs $term shaped like a terminal name rather than an infocmp option?

ProbeReport final readonly class

Readonly value object holding the result of a terminal capability probe.

MethodSummary
__construct(array $capabilities, public \DateTimeImmutable $detectedAt = new \DateTimeImmutable())
has(Capability $cap): boolCheck if a capability was detected.
source(Capability $cap): ?stringGet the source string for a detected capability.
all(): arrayReturn all detected capabilities as a list.
allWithSource(): arrayReturn all detected capabilities with their sources.
__get(string $name): mixedOne-release deprecation shim for the pre-CP-51 public map read ($report->capabilities) — answers the map and raises E_USER_DEPRECATED. Removal target: 2.0. New code must use all() or allWithSource(); writes never answered here (the class is readonly, so $report->capabilities = … throws regardless of this shim).
hasTrueColor(): boolCheck if the probe detected TrueColor support.
hasColor256(): boolCheck if the probe detected 256-color support.
hasNoColor(): boolCheck if colors are disabled.
toColorProfile(): ColorProfileBridge the capability set onto the emission-side profile enum.
colorDescription(): stringReturn a human-readable description of the highest color capability.

TerminalProbe class

Terminal capability probe — the full capability report (color depth plus Sixel/Kitty/iTerm2/Hyperlinks/keyboard flags).

MethodSummary
__construct(array $environment = [], bool $interactive = true)Create a new probe with an optional complete environment replacement.
static run(): ProbeReportRun the full probe pipeline and return a report.
runProbe(array $overrides = [], ?bool $interactive = null): ProbeReportRun the full probe pipeline with optional environment overrides.

TerminfoParser final class

Name-position terminfo capability matcher.

MethodSummary
static hasCapName(string $output, array $names): boolWhether the terminfo dump declares any of $names as a capability name (compared lowercased, name position only).

Configuration and options

Detection has no config file. The answer comes from the environment, and the host can pin it in code. The table lists the environment variables in ladder order. The first leg that matches wins.

Env varStepEffect
CLICOLOR_FORCE=11Forces TrueColor past every other variable, NO_COLOR included. It also keeps the forced rung on a non-TTY stream.
FORCE_COLOR2Sets the level: 3 or more gives TrueColor, and so do true, yes and on. 2 gives Ansi256, 1 gives Ansi. Any other spelling, such as 0 or false, lands on the Ascii floor.
NO_COLOR3A non-empty value gives the colorless Ascii rung. Color codes are dropped, and decoration such as bold and underline is kept.
CLICOLOR=04Suppresses color.
TERM=dumb5Suppresses color. It outranks COLORTERM.
TMUX / STY with screen*6Caps the level at Ansi256 before COLORTERM is read.
COLORTERM7truecolor or 24bit gives TrueColor. yes gives Ansi256.
TERM_PROGRAM=iTerm.app8Gives TrueColor. Matching is case-sensitive.
WT_SESSION9A non-empty value gives TrueColor (Windows Terminal).
GOOGLE_CLOUD_SHELL10Exactly true gives TrueColor.
TMUX / STY with tmux*11Caps the level at Ansi256, but only when COLORTERM has not already answered. truecolor or 24bit at step 7 still gives TrueColor under tmux.
TERM12–13*-256color, xterm-kitty and xterm-ghostty give Ansi256. xterm*, screen* and tmux* give Ansi.
REDUCE_MOTION / PREFERS_REDUCED_MOTION—Not part of the color ladder. A non-empty value other than 0, false, no or off sets Probe::reducedMotion().

A host that needs a fixed answer pins it with (new Palette())->withProfile(ColorProfile::Ansi). A Palette or TerminalProbe built with a non-empty $env array is hermetic: the array replaces the ambient environment, so pass every key the check reads. An empty array is not hermetic, and falls through to the process environment.

Keys and input

The library reads no keystrokes and binds no keys. Detection takes its input from the environment and the stream being written to. The optional probes add the output of a fixed-path infocmp run.

Theming and styling

Degradation is one-way. A TrueColor value can drop to Ansi256, Ansi or Ascii, but never rises. Palette::toProfile() and Color::convert() downsample one color, and degrade() rewrites every SGR color in a string. Under the NoTTY profile, degrade() strips all escape sequences, decoration included, so pin the Ascii floor for a color-only strip. The 16 ANSI colors come from StandardColors::all(), fromIndex() and catalog(). Opt into the perceptual family, NearestColor with DeltaE, when a degraded value must land on a fixed palette.

Examples

  • examples/detect.php detects the profile for STDOUT, and prints the plain-language description from Palette::comment().
  • examples/convert.php builds colors from an int and a hex string, then converts each one to every profile level.
  • examples/degrade.php wraps a stream with ProfileWriter and forces each of the Ansi256, Ansi and Ascii profiles in turn.
  • examples/standard-colors.php lists the 16 ANSI colors through the non-mutating read API.
  • examples/probe-report.php prints the phased capability report for a hermetic environment map.
  • examples/async-probe.php runs the ReactPHP infocmp probe on a loop that the example hands in.
php examples/detect.php
php examples/convert.php
php examples/degrade.php
php examples/standard-colors.php
php examples/probe-report.php
php examples/async-probe.php

Testing

composer install
vendor/bin/phpunit

The suite pins the detection ladder against its drift guards (LadderDriftTest, EnvUnificationTest), the palette tables against their parity tests (Ansi256TableParityTest, Ansi16TableParityTest), and the degrade output (DegradeTest, DegradeFidelityTest). ProbeTest, ProbeInfocmpTest and the AsyncProbe* files cover the probes, and LangParityTest checks the catalogs.

Troubleshooting and FAQ

Output is plain when the program is piped

That is the design. A stream with no TTY in front of it gets no color, so piping into a file stays safe to read. To keep color on a non-TTY stream, set CLICOLOR_FORCE=1. The force legs outrank the stream gate.

Color still appears with NO_COLOR set

CLICOLOR_FORCE and FORCE_COLOR outrank NO_COLOR. An exported force variable, from a shell alias or a CI image, can re-enable color for a user who set NO_COLOR. Unset the force variables, and check Probe::isNoColor() before you honor a force override.

A truecolor terminal reports Ansi256

Two legs cap the level. COLORTERM=yes is read as a 256-color promise, and a screen session caps the level at Ansi256. A tmux session does the same unless COLORTERM advertises truecolor. Set COLORTERM=truecolor where the terminal honors it, or let the phase-2 terminfo probe promote the rung when the entry advertises Tc or RGB.

An environment key is ignored

Env keys are matched case-exactly, so No_Color does not count as NO_COLOR. Windows reports its environment case-insensitively at the OS layer, so the same spelling can look set in a shell and still miss detection here. Use the exact spelling from the table.

Detection ignores the variables I did set

A non-empty $env array replaces the whole environment rather than overlaying it. Pass every key the check reads, or leave $env out so the process environment is used.

Upstream mapping

The port follows the concepts of charmbracelet/colorprofile: detect a profile from the environment, convert colors down to it, and wrap a writer so that output is downgraded to match. The mapping is behavioral. SugarCraft is developed as a native PHP project.

ConceptSugarCraftNotes
Profile detection from the environmentPalette::detect(), DetectionChainOne shared ladder, so every surface answers the same way.
Color profile levelsColorProfile enumEight levels. The detection ladder emits five of them.
Color conversionColor::convert(), Palette::toProfile()One-way downsampling only.
Writer that downgrades outputProfileWriterApplies degrade() to everything written to a stream.
Perceptual distance (beyond detection)DeltaE, NearestColorOpt-in. Not needed for detection or degradation.

Architecture

DetectionChain is the one precedence core, and Env resolves and sanitizes the environment for it. Palette is the instance over that chain. It adds the stream TTY gate, and it does the degrading and stripping. The static Probe layer answers the questions that do not need an instance. AsyncProbe runs infocmp on a ReactPHP loop with bounded children, and Probe\TerminalProbe produces the phased report. The color math is ColorMath (sRGB to Lab), with DeltaE for the metrics and NearestColor for the matcher. ProfileWriter wraps a stream for automatic degradation.

Changelog and versioning

The library is pre-1.0, so consume dev-master. The mutable StandardColors statics are deprecated in favor of all(), fromIndex() and catalog(), and the Profile name is a deprecated alias for ColorProfile. The deprecation window is set out in the README.

  • sugar-core supplies the Clamp helper and the I18n catalog base that this library's Color and Lang build on.

Demos.

VHS-recorded GIFs of the four examples that have a tape: detect, standard-colors, convert and degrade. The probe-report and async-probe examples have no recording. Regenerated automatically on every push that touches the source.

Detecting the terminal profile, then the same sentence forced through each profile

Profile detection

Forced rungs print [TrueColor] -> "fancy" through [No TTY] -> "naughty!".
The sixteen-index ANSI color catalog printed with swatches

Standard colors

all() rows from 0 black #000000 to 15 brightWhite #ffffff, plus fromIndex() lookups.
One hex converted for each profile with its per-rung escape shown

Conversion

One hex, a different encoder per rung: \e[38;2;107;80;255m → \e[38;5;63m → \e[94m; No TTY strips.
One TrueColor string written through a ProfileWriter on each rung, escapes shrinking per row

Degrade

Same input written per rung: 38;2 → 38;5 → 91; the Ascii row drops the color codes, and the No TTY row prints [Orange] [Teal] [Purple] with no escapes.