@neutrium/formatter - v1.0.1
    Preparing search index...

    Class Formatter<Codecs>

    Strongly typed codec registry and formatting facade.

    The Codecs tuple 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.

    Type Parameters

    • const Codecs extends readonly AnyFormatCodec[] = readonly []

      Ordered tuple of codecs installed on this instance.

    Index
    • 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.

      Type Parameters

      • const Codecs extends readonly AnyFormatCodec[] = readonly []

        Ordered tuple of codecs installed on this instance.

      Parameters

      • ...options:
            | [options: FormatterOptions<Codecs> & { codecs: Codecs }]
            | (
                Codecs extends readonly []
                    ? [options?: FormatterOptions<Codecs>]
                    : never
            )

        Complete codec tuple, default locale (en-US), and application context.

      Returns Formatter<Codecs>

      index!DuplicateFormatError for duplicate codec kinds.

      TypeError for an invalid codec kind or method shape.

      import { Formatter, numberCodec } from "@neutrium/formatter/extensions";

      const numbers = new Formatter({ codecs: [numberCodec], locale: "de-DE" });
      numbers.format(1234.5, { kind: "number" }); // "1.234,5"
    • 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.

      Type Parameters

      • const Spec extends never

      Parameters

      • spec: Spec & FormatSpecBase & Record<
            Exclude<
                keyof Spec,
                | (keyof FormatSpecBase)
                | {
                    toLocaleString(): string;
                    toLocaleString(
                        locales?: string | string[],
                        options?: NumberFormatOptions,
                    ): string;
                    toLocaleString(
                        locales?: LocalesArgument,
                        options?: NumberFormatOptions,
                    ): string;
                    toString(): string;
                    toString(radix?: number): string;
                    valueOf(): string | number | symbol;
                },
            >,
            never,
        >

        Specification to copy and resolve with this instance's defaults.

      Returns CompiledFormat<Codecs, Spec>

      A frozen object with bound methods, a frozen spec, and successful resolution.

      When the specification is invalid or unsupported.

      import { formatter } from "@neutrium/formatter";

      const money = formatter.compile({
      kind: "currency",
      currency: "USD",
      maximumFractionDigits: 2,
      });

      money.format(12); // "$12.00"
      money.formatRange(1, 2);
    • 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.

      Type Parameters

      • const Spec extends never

      Parameters

      • values: readonly NoInfer<FormatValue<Codecs, Spec>>[]

        Representative values used only to choose the shared scale.

      • spec: Spec & FormatSpecBase & Record<
            Exclude<
                keyof Spec,
                | (keyof FormatSpecBase)
                | {
                    toLocaleString(): string;
                    toLocaleString(
                        locales?: string | string[],
                        options?: NumberFormatOptions,
                    ): string;
                    toLocaleString(
                        locales?: LocalesArgument,
                        options?: NumberFormatOptions,
                    ): string;
                    toString(): string;
                    toString(radix?: number): string;
                    valueOf(): string | number | symbol;
                },
            >,
            never,
        >

        Original presentation, optionally with a fixed exponent.

      Returns CompiledFormat<Codecs, {}>

      A compiled formatter whose frozen .spec encodes the effective scale.

      For invalid specifications or invalid values encountered during scale selection.

      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.

      Type Parameters

      • const Spec extends never

      Parameters

      • value: NoInfer<FormatValue<Codecs, Spec>>

        Input accepted by the selected domain, such as a decimal string or duration record.

      • spec: Spec & FormatSpecBase & Record<
            Exclude<
                keyof Spec,
                | (keyof FormatSpecBase)
                | {
                    toLocaleString(): string;
                    toLocaleString(
                        locales?: string | string[],
                        options?: NumberFormatOptions,
                    ): string;
                    toLocaleString(
                        locales?: LocalesArgument,
                        options?: NumberFormatOptions,
                    ): string;
                    toString(): string;
                    toString(radix?: number): string;
                    valueOf(): string | number | symbol;
                },
            >,
            never,
        >

        Domain, locale override, and presentation options.

      Returns string

      Localized display text. Use formatToParts for semantic fragments.

      index!UnknownFormatError if no matching codec is registered.

      Decimal's DecimalError for invalid numeric syntax or exceeded Decimal limits.

      RangeError or TypeError for other invalid values or specifications.

      import { formatter } from "@neutrium/formatter";

      formatter.format("9007199254740993.25", {
      kind: "number",
      maximumFractionDigits: 2,
      });
      // "9,007,199,254,740,993.25"
    • 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.

      Type Parameters

      • const Spec extends never

      Parameters

      • values: readonly NoInfer<FormatValue<Codecs, Spec>>[]

        Values in row order.

      • spec: Spec & FormatSpecBase & Record<
            Exclude<
                keyof Spec,
                | (keyof FormatSpecBase)
                | {
                    toLocaleString(): string;
                    toLocaleString(
                        locales?: string | string[],
                        options?: NumberFormatOptions,
                    ): string;
                    toLocaleString(
                        locales?: LocalesArgument,
                        options?: NumberFormatOptions,
                    ): string;
                    toString(): string;
                    toString(radix?: number): string;
                    valueOf(): string | number | symbol;
                },
            >,
            never,
        >

        Presentation shared by all rows.

      • Optionaloptions: ColumnFormatOptions

        Alignment (decimal), fill (" "), and scale selection (shared).

      Returns readonly string[]

      Padded strings for a monospaced text column, in input order.

      import { formatter } from "@neutrium/formatter";

      formatter.formatColumn(
      [1.2, 12, 123.45],
      { kind: "number", maximumFractionDigits: 2 },
      );
      // [" 1.2 ", " 12 ", "123.45"]
    • 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.

      Type Parameters

      • const Spec extends never

      Parameters

      • value: NoInfer<FormatValue<Codecs, Spec>>

        Value to render and inspect.

      • spec: Spec & FormatSpecBase & Record<
            Exclude<
                keyof Spec,
                | (keyof FormatSpecBase)
                | {
                    toLocaleString(): string;
                    toLocaleString(
                        locales?: string | string[],
                        options?: NumberFormatOptions,
                    ): string;
                    toLocaleString(
                        locales?: LocalesArgument,
                        options?: NumberFormatOptions,
                    ): string;
                    toString(): string;
                    toString(radix?: number): string;
                    valueOf(): string | number | symbol;
                },
            >,
            never,
        >

        Formatting specification.

      Returns DetailedFormatResult<RoundedValue<Codecs, Spec>>

      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.

      Type Parameters

      • const Spec extends never

      Parameters

      • start: NoInfer<FormatValue<Codecs, Spec>>

        First endpoint, accepted by the selected codec.

      • end: NoInfer<FormatValue<Codecs, Spec>>

        Second endpoint, accepted by the selected codec.

      • spec: Spec & FormatSpecBase & Record<
            Exclude<
                keyof Spec,
                | (keyof FormatSpecBase)
                | {
                    toLocaleString(): string;
                    toLocaleString(
                        locales?: string | string[],
                        options?: NumberFormatOptions,
                    ): string;
                    toLocaleString(
                        locales?: LocalesArgument,
                        options?: NumberFormatOptions,
                    ): string;
                    toString(): string;
                    toString(radix?: number): string;
                    valueOf(): string | number | symbol;
                },
            >,
            never,
        > & (
            {
                range: boolean
                | { valueOf(): boolean };
                rounded: unknown;
                spec:
                    | FormatSpecBase
                    | {} & {
                        kind: Extract<CodecMap<(...)>[any[any]], AnyFormatCodec>["kind"];
                    };
                value: unknown;
            }["range"] extends false
                ? never
                : unknown
        )

        Presentation applied to both endpoints.

      Returns string

      Localized range text; punctuation and shared affixes depend on the locale.

      index!UnsupportedRangeError when the selected codec has no range operation.

      import { formatter } from "@neutrium/formatter";

      formatter.formatRange(1, 2, { kind: "currency", currency: "USD" });
      // "$1.00 – $2.00"
    • Formats a range into semantic tokens labelled startRange, endRange, or shared.

      Type Parameters

      • const Spec extends never

      Parameters

      • start: NoInfer<FormatValue<Codecs, Spec>>

        First endpoint.

      • end: NoInfer<FormatValue<Codecs, Spec>>

        Second endpoint.

      • spec: Spec & FormatSpecBase & Record<
            Exclude<
                keyof Spec,
                | (keyof FormatSpecBase)
                | {
                    toLocaleString(): string;
                    toLocaleString(
                        locales?: string | string[],
                        options?: NumberFormatOptions,
                    ): string;
                    toLocaleString(
                        locales?: LocalesArgument,
                        options?: NumberFormatOptions,
                    ): string;
                    toString(): string;
                    toString(radix?: number): string;
                    valueOf(): string | number | symbol;
                },
            >,
            never,
        > & (
            {
                range: boolean
                | { valueOf(): boolean };
                rounded: unknown;
                spec:
                    | FormatSpecBase
                    | {} & {
                        kind: Extract<CodecMap<(...)>[any[any]], AnyFormatCodec>["kind"];
                    };
                value: unknown;
            }["range"] extends false
                ? never
                : unknown
        )

        Presentation for both endpoints.

      Returns readonly RangeFormatToken[]

      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.

      Type Parameters

      • const Spec extends never

      Parameters

      • values: readonly NoInfer<FormatValue<Codecs, Spec>>[]

        Values in output order.

      • spec: Spec & FormatSpecBase & Record<
            Exclude<
                keyof Spec,
                | (keyof FormatSpecBase)
                | {
                    toLocaleString(): string;
                    toLocaleString(
                        locales?: string | string[],
                        options?: NumberFormatOptions,
                    ): string;
                    toLocaleString(
                        locales?: LocalesArgument,
                        options?: NumberFormatOptions,
                    ): string;
                    toString(): string;
                    toString(radix?: number): string;
                    valueOf(): string | number | symbol;
                },
            >,
            never,
        >

        Presentation shared by all values.

      • Optionaloptions: SeriesFormatOptions

        Scale selection; defaults to { scale: "shared" }.

      Returns readonly string[]

      One formatted string per input, in the same order.

      import { formatter } from "@neutrium/formatter";

      formatter.formatSeries([1_200, 1_500, 900], {
      kind: "number",
      notation: "compact",
      maximumFractionDigits: 1,
      });
      // ["1.2K", "1.5K", "0.9K"]
    • Formats multiple values into one semantic token array per value. Scale selection is identical to formatSeries.

      Type Parameters

      • const Spec extends never

      Parameters

      • values: readonly NoInfer<FormatValue<Codecs, Spec>>[]

        Values in output order.

      • spec: Spec & FormatSpecBase & Record<
            Exclude<
                keyof Spec,
                | (keyof FormatSpecBase)
                | {
                    toLocaleString(): string;
                    toLocaleString(
                        locales?: string | string[],
                        options?: NumberFormatOptions,
                    ): string;
                    toLocaleString(
                        locales?: LocalesArgument,
                        options?: NumberFormatOptions,
                    ): string;
                    toString(): string;
                    toString(radix?: number): string;
                    valueOf(): string | number | symbol;
                },
            >,
            never,
        >

        Presentation shared by all rows.

      • Optionaloptions: SeriesFormatOptions

        Shared or individual scale selection; defaults to shared.

      Returns readonly (readonly FormatToken[])[]

      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.

      Type Parameters

      • const Spec extends never

      Parameters

      • value: NoInfer<FormatValue<Codecs, Spec>>

        Value accepted by the selected domain.

      • spec: Spec & FormatSpecBase & Record<
            Exclude<
                keyof Spec,
                | (keyof FormatSpecBase)
                | {
                    toLocaleString(): string;
                    toLocaleString(
                        locales?: string | string[],
                        options?: NumberFormatOptions,
                    ): string;
                    toLocaleString(
                        locales?: LocalesArgument,
                        options?: NumberFormatOptions,
                    ): string;
                    toString(): string;
                    toString(radix?: number): string;
                    valueOf(): string | number | symbol;
                },
            >,
            never,
        >

        Formatting specification.

      Returns readonly FormatToken[]

      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.

      Type Parameters

      Parameters

      • spec: Spec

        Complete specification to validate and inspect.

      Returns ResolvedFormat

      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.

      Type Parameters

      Parameters

      • spec: Spec

        Complete specification to inspect, including required domain options.

      Returns boolean

      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.

      Type Parameters

      • const Codec extends AnyFormatCodec

      Parameters

      • codec: Codec

        Codec for a kind not already registered on this instance.

      Returns Formatter<readonly [Codecs, Codec]>

      A new formatter with the added kind and its inferred value types.

      index!DuplicateFormatError when the format kind is already installed.

      TypeError for an invalid codec kind or method shape.

      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