Ordered tuple of codecs installed on this instance.
Creates a formatter from an explicit codec tuple.
An omitted codecs option creates an empty registry. The tuple is copied and
frozen, as are a shallow copy of context and the canonicalized default locale.
Ordered tuple of codecs installed on this instance.
Complete codec tuple, default locale (en-US), and application context.
index!DuplicateFormatError for duplicate codec kinds.
Validates, snapshots, and deeply freezes a specification into a reusable formatter.
Compilation resolves support once and binds all operations. Range methods are included only when the selected presentation supports them. Specifications may contain only primitives, plain or null-prototype records, and arrays; functions, accessors, and class instances are rejected.
Specification to copy and resolve with this instance's defaults.
A frozen object with bound methods, a frozen spec, and successful resolution.
Selects one shared scale from the supplied values and compiles the effective specification.
Automatic compact and byte scales use the largest finite absolute value.
Empty, non-finite-only, and sub-threshold series bind the base magnitude
(standard notation or bytes). Explicit scales are preserved. The values are
used for selection only: they are not rendered, retained, or fully validated
when the codec does not need them. The returned methods behave like compile.
Custom codecs opt in through selectSeriesSpec; otherwise the spec is unchanged.
Pass the returned .spec to extensions-parse!Parser.compile to parse shared-scale
text; it carries the effective locale. Later calls do not select a new scale;
call compileSeries again with the original spec to choose a new magnitude.
Representative values used only to choose the shared scale.
Original presentation, optionally with a fixed exponent.
A compiled formatter whose frozen .spec encodes the effective scale.
import { formatter } from "@neutrium/formatter";
import { parser } from "@neutrium/formatter/parse";
const thousands = formatter.compileSeries([900, 1200], {
kind: "number", notation: "compact", maximumFractionDigits: 1,
});
thousands.format(900); // "0.9K"
thousands.format(2_000_000); // "2,000K"
parser.compile(thousands.spec).parse("0.9K"); // "900"
Formats a value with the codec selected by spec.kind.
Exact decimal strings, bigints, and structurally compatible numeric objects are passed to Intl without conversion to an imprecise JavaScript number. Built-in numeric values still follow the numeric overflow/underflow limits; exact input does not prevent rounding to the requested display precision.
Input accepted by the selected domain, such as a decimal string or duration record.
Domain, locale override, and presentation options.
Localized display text. Use formatToParts for semantic fragments.
index!UnknownFormatError if no matching codec is registered.
Formats multiple values and pads them into an aligned text column.
Decimal alignment is the default. Width is measured in Unicode code points, not terminal cells, so consumers displaying wide glyphs or ANSI sequences should apply display-specific alignment themselves.
Values in row order.
Presentation shared by all rows.
Optionaloptions: ColumnFormatOptions
Alignment (decimal), fill (" "), and scale selection (shared).
Padded strings for a monospaced text column, in input order.
Formats a value together with semantic parts and resolution metadata.
Numeric and elapsed-duration presentations expose the canonical value represented
by the displayed precision. Localized durations omit roundedValue. Compact
and byte presentations report their selected scale. No parsing import is needed.
Custom codecs may omit metadata or supply a different rounded value type.
Value to render and inspect.
Formatting specification.
text, semantic parts, successful resolution, and optional roundedValue and scale.
import { formatter } from "@neutrium/formatter";
const value = "1234567";
const result = formatter.formatDetailed(value, {
kind: "number",
notation: "compact",
maximumFractionDigits: 2,
});
const chartPoint = {
value, // Keep the original for calculations and chart geometry.
label: result.text,
tooltip: result.roundedValue === undefined ? "" :
`Label represents ${formatter.format(result.roundedValue, { kind: "number" })} visits`,
};
// { value: "1234567", label: "1.23M", tooltip: "Label represents 1,230,000 visits" }
Formats two endpoints as a localized range.
Built-in numeric codecs use native Intl ranges when possible and a locale-derived wrapper fallback for wrapper-specific presentations. Duration ranges are unsupported. Parsing a formatted range is not provided.
First endpoint, accepted by the selected codec.
Second endpoint, accepted by the selected codec.
Presentation applied to both endpoints.
Localized range text; punctuation and shared affixes depend on the locale.
index!UnsupportedRangeError when the selected codec has no range operation.
Formats a range into semantic tokens labelled startRange, endRange, or shared.
First endpoint.
Second endpoint.
Presentation for both endpoints.
Ordered tokens whose source identifies endpoint or shared syntax.
index!UnsupportedRangeError when the selected codec has no range operation.
import { formatter } from "@neutrium/formatter";
const label = document.createElement("span");
const parts = formatter.formatRangeToParts(1, 2, { kind: "number" });
for (const part of parts) {
const span = document.createElement(part.source === "endRange" ? "strong" : "span");
span.textContent = part.value;
label.append(span);
}
document.body.append(label); // 1–2, with the 2 emphasized; shared punctuation is retained.
Formats multiple values with optional shared-scale selection.
Automatic compact notation and byte codecs use the largest finite absolute
value to select one shared magnitude by default. Pass { scale: "individual" }
to choose a magnitude independently for each value.
This returns text only; use compileSeries to retain the selected scale
for future batches or parsing. Empty inputs return an empty array after options are validated.
Values in output order.
Presentation shared by all values.
Optionaloptions: SeriesFormatOptions
Scale selection; defaults to { scale: "shared" }.
One formatted string per input, in the same order.
Formats multiple values into one semantic token array per value. Scale selection is identical to formatSeries.
Values in output order.
Presentation shared by all rows.
Optionaloptions: SeriesFormatOptions
Shared or individual scale selection; defaults to shared.
One ordered token array per input; empty inputs return an empty array.
import { formatter } from "@neutrium/formatter";
const list = document.createElement("ul");
const rows = formatter.formatSeriesToParts([1024, 1536], { kind: "bytes" });
for (const parts of rows) {
const item = document.createElement("li");
for (const part of parts) {
const span = document.createElement(part.type === "unit" ? "small" : "span");
span.textContent = part.value;
item.append(span);
}
list.append(item);
}
document.body.append(list); // 1 KiB and 1.5 KiB, with smaller units.
Formats a value into stable semantic tokens.
Joining each token's value produces the same output as format.
Wrapper domains add semantic token types such as ordinal and duration units.
Preserve literal tokens, including whitespace and bidirectional marks, when rendering.
Value accepted by the selected domain.
Formatting specification.
Ordered tokens with type and value fields.
import { formatter } from "@neutrium/formatter";
const price = document.createElement("span");
const parts = formatter.formatToParts("1234.5", {
kind: "currency", currency: "EUR", locale: "de-DE",
});
for (const part of parts) {
const span = document.createElement("span");
span.textContent = part.value;
if (part.type === "currency") span.style.fontSize = "0.8em";
price.append(span);
}
document.body.append(price); // 1.234,50 € with a smaller €; spacing is preserved.
Resolves a complete specification without throwing for ordinary validation failures.
A successful result includes the effective locale, implementation, available
operations, range strategy, and any backing Intl options. A failed result
contains a serializable error.
Formatting resolutions always report capabilities.parse: false. Inspect
parsing separately with extensions-parse!Parser.resolve.
Complete specification to validate and inspect.
A result discriminated by supported, with capabilities or an error.
import { formatter } from "@neutrium/formatter";
function precisionHelp(currency: string): string {
const result = formatter.resolve({ kind: "currency", currency });
if (!result.supported) return `Currency display unavailable: ${result.error.message}`;
const digits = result.intl?.resolvedOptions.maximumFractionDigits;
return digits === undefined ? "Automatic precision" : `Up to ${digits} decimal places`;
}
precisionHelp("USD"); // "Up to 2 decimal places"
precisionHelp("JPY"); // "Up to 0 decimal places"
Returns whether a complete specification can be resolved by the current runtime. Use resolve when the failure reason or effective Intl options are needed. This checks specification support, not the validity of a value to be formatted.
Complete specification to inspect, including required domain options.
false for unknown kinds, invalid options, or unavailable runtime features.
import { formatter } from "@neutrium/formatter";
formatter.supports({ kind: "unit", unit: "meter" }); // true
formatter.supports({ kind: "bytes", byteBase: 999 }); // false
formatter.supports({ kind: "duration", presentation: "localized" });
// true only when Intl.DurationFormat is available
Returns an independent formatter with one additional codec.
The original instance is unchanged. Its locale and context are preserved, while the returned type immediately includes the new codec's specification and value relationships.
Codec for a kind not already registered on this instance.
A new formatter with the added kind and its inferred value types.
index!DuplicateFormatError when the format kind is already installed.
import { Formatter } from "@neutrium/formatter/extensions";
import type { FormatCodec } from "@neutrium/formatter/extensions";
const labelCodec = {
kind: "label",
format(value: string) {
return [{ type: "literal", value }];
},
} satisfies FormatCodec<"label", string>;
const empty = new Formatter();
const labels = empty.withCodec(labelCodec);
labels.format("ready", { kind: "label" }); // "ready"
empty.supports({ kind: "label" }); // false
Strongly typed codec registry and formatting facade.
The
Codecstuple determines accepted specifications, corresponding input values, rounded metadata, and compiled capabilities. Most applications should use the shared index!formatter or index!createFormatter; direct construction starts with exactly the codecs supplied to the constructor.