Introducing a new way to review your PRs.

Read the announcement

generaltranslation / gt

Full-stack localization for every framework

View on GitHub

22 documents · Updated Nov 23, 2026

docs / message-formatting

Message formatting and ICU processing

Message formatting turns localized message text into user-facing content. The system supports plain strings, ICU arguments, locale-aware numbers and dates, plural and select branches, and rich-content tags. The localization runtime supplies the locale and translation result. The translation runtime uses this page's formatting path after it resolves content, while localization configuration explains how locale context is chosen.

Message format model

Message forms

The formatting system treats a message as either literal text or ICU message text. The StringFormat value selects the path: ICU parses and formats message syntax, while STRING returns the content without ICU interpolation. I18NEXT is routed through the plain string path in the translation runtime rather than through the ICU parser.

The same format choice travels with registered and translated content. This keeps a literal string from being mistaken for a message with placeholders and lets translation lookup apply the right formatter after it finds a target.

FormatPurposeResulting behavior
ICUMessages with arguments or locale rulesParse and format the message
STRINGLiteral contentReturn the content as supplied
I18NEXTi18next-style contentUse the plain string interpolation route

References: packages/…/content.ts• L41-58 packages/…/core.ts• L107-130 packages/…/interpolateMessage.ts• L16-61

Abstract syntax tree

The ICU parser converts message text into an abstract syntax tree (AST). An AST is a structured representation of the message that separates literal text from arguments, number and date values, branches, plural markers, and tags. The formatter and printer consume this shared structure, so they agree on the meaning of a message without re-reading its source in different ways.

The parser can attach source locations to AST elements and to syntax errors. These locations help tools report the part of a message that needs correction. The public parser also requires an other branch by default for select and plural messages.

References: packages/…/types.ts• L23-45 packages/…/types.ts• L72-131 packages/…/parser.ts• L45-86 packages/…/parser.ts• L533-571

ICU processing

Parsing

Parsing reads ICU syntax from left to right and builds nested message elements. It recognizes simple arguments such as {name}, typed arguments such as {total, number}, branch arguments such as select and plural, and paired rich-content tags such as <b>...</b>.

ICU apostrophe quoting protects syntax characters when a message needs to show braces, tags, or a plural # as literal text. A parser option can treat tag-looking text as ordinary text. This is useful when a message contains markup that the caller does not want the formatter to process.

References: packages/…/parser.ts• L49-187 packages/…/parser.ts• L201-327 packages/…/parser.ts• L615-623

Formatting

Formatting evaluates the AST with a locale and a variable map. Literal elements pass through unchanged. Direct arguments use their supplied value. Typed arguments use locale-aware Intl services for numbers, dates, and times. The formatter joins adjacent strings but can preserve non-string values or arrays when the direct ICU API returns rich parts.

The format operation follows this sequence:

  1. Resolve the requested locale for locale-sensitive parsing and formatting.
  2. Parse the message into an AST.
  3. Read each referenced variable and evaluate the selected AST branch.
  4. Format numbers, dates, times, and plural markers with the locale.
  5. Return one value when possible, or a list of parts when the result contains non-string values.

This flow is exposed by @generaltranslation/icu. The @generaltranslation/format package provides the application-facing boundary and converts the final ICU result to a string for its string-format APIs. That boundary preserves established serialization behavior for non-string values such as booleans and dates.

References: packages/…/formatter.ts• L60-70 packages/…/formatter.ts• L72-193 packages/…/format.ts• L12-30 packages/…/format.test.ts• L301-317

Choice and plural selection

Select messages choose a branch by matching the variable's string value. Plural messages first check exact selectors such as =1, then use the locale's plural category when category branches exist. The offset value adjusts the number used for category selection and for the # marker.

Cardinal plurals use the normal plural categories for a locale. selectordinal uses ordinal categories instead. Every plural or select message has an other branch in the normal parser path, which provides the final fallback when no more specific branch matches.

References: packages/…/parser.ts• L362-480 packages/…/formatter.ts• L139-170 packages/…/formatter.test.ts• L114-184 packages/…/format.test.ts• L268-299

Rich-content tags

Rich-content tags mark a span whose child parts must be passed to a caller-provided function. For example, <b>Hello {name}</b> asks for a b variable that receives the formatted child content and returns the replacement value. Tags can nest, and child arrays are flattened into the surrounding result without adding separators.

Tag names must have matching open and close forms. A self-closing tag is treated as literal text rather than as a callback span. The tag path preserves the current plural value inside a tag, so # still formats correctly inside plural content.

References: packages/…/parser.ts• L69-87 packages/…/parser.ts• L152-189 packages/…/formatter.ts• L172-187 packages/…/formatter.test.ts• L186-218

Skeletons and canonical text

Number skeletons

Number skeletons are ICU style instructions that describe how a number should appear. They can express currency, percent, units, grouping, compact notation, precision, sign rules, integer width, rounding, and scale. The skeleton parser turns these instructions into native Intl.NumberFormat options before formatting.

Named number styles provide a smaller set of common choices such as integer, currency, and percent. Skeletons are the more detailed form and are written with the :: prefix. Unsupported or malformed instructions stop parsing instead of silently producing a different message.

References: packages/…/parser.ts• L252-327 packages/…/skeleton.ts• L50-201 packages/…/formatter.ts• L107-119

Date-time skeletons

Date-time skeletons describe the fields to show in a date or time. The parser maps fields such as year, month, day, hour, minute, second, weekday, and time zone to Intl.DateTimeFormat options. Locale-aware hour symbols are resolved before the options are built, so a skeleton can follow the requested locale's hour cycle.

The formatter also supports named date and time styles. If no time style is given, the ICU path uses the package's established default for the argument type. The final output remains controlled by the target locale rather than by the source message's spelling.

References: packages/…/skeleton.ts• L352-410 packages/…/skeleton.ts• L413-478 packages/…/formatter.ts• L121-137 packages/…/format.test.ts• L174-209

AST printing

AST printing converts a parsed message back to canonical ICU text. It is used when a tool needs stable message text after inspecting or transforming the AST. The printer preserves branch structure, skeleton meaning, tag nesting, and literal syntax through parse-print-parse round trips.

Literal braces, tags, plural hashes, and apostrophes need quoting in the printed form. The printer groups related syntax into safe quoted spans so the printed message keeps the same meaning when another parser reads it.

References: packages/…/printer.ts• L21-61 packages/…/printer.ts• L125-213 packages/…/printer.test.ts• L171-215

Locale-aware formatting pipeline

Format package boundary

@generaltranslation/format is the locale-aware formatting boundary for the rest of the repository. Its public formatMessage accepts a message, a locale or locale list, variables, and an optional data format. It either returns literal content for STRING data or sends ICU content to @generaltranslation/icu. The package depends on @generaltranslation/icu as its message-format engine.

The package also exposes related locale services for numbers, dates, currencies, lists, relative time, and text cutoffs. These services share the same locale input and cache native Intl formatters where applicable. List-part formatting keeps the original list items while using locale-specific connector text, so rich consumers can preserve item values and order. LocaleConfig adds a configured target locale and default locale to the same pipeline, so callers can format values without rebuilding locale choices for each call.

LocaleConfig also provides the shared locale-resolution scope for approved locales and custom mappings. It prepares that scope only when locale resolution needs it, then reuses it for later checks and lookups. Exact configured spellings and aliases remain visible to callers. If a caller changes the retained locale list or mapping, the next lookup refreshes the scope so formatting and translation decisions use current locale data. This cached scope avoids repeated locale validation during server-side lookups while retaining current results after configuration changes. Locale validation accepts mapped codes and recognized legacy or private-use language forms while rejecting invalid language, region, and script parts.

References: packages/…/core.ts• L40-46 packages/…/core.ts• L107-130 packages/…/format.ts• L21-80 packages/…/format.ts• L125-174 packages/…/LocaleConfig.ts• L70-177 packages/…/LocaleConfig.ts• L270-310 packages/…/LocaleConfig.ts• L325-385 packages/…/isValidLocale.ts• L14-113 packages/…/LocaleConfig.test.ts• L7-81 packages/…/format-package.test.ts• L28-56

Translation interpolation

The translation runtime formats content after lookup. It selects a route from $format, passes the target message and variables to the format package, and applies any configured character cutoff after ICU interpolation. When a translation is absent, the source message is formatted with the source locale so a fallback does not change number or date meaning because of the target locale.

The ICU route also keeps the original source as a fallback when a translated message cannot be formatted. A failed translation therefore does not normally reach the user as broken ICU text: the runtime logs a warning and tries the source or returns the original content according to the active fallback path.

References: packages/…/interpolateMessage.ts• L18-41 packages/…/interpolateIcuMessage.ts• L19-73 packages/…/helpers.ts• L64-111 packages/…/renderDictionaryEntry.ts• L11-40

Message registration

Message registration prepares content for later translation lookup. For ICU messages, registration first formats the source with the default locale when values are supplied, then stores the original source and message metadata in an encoded string. The later message function can decode that metadata and avoid applying the same registration interpolation twice.

Literal registration uses the STRING path and keeps the message unchanged. This distinction matters when a message contains braces that are content rather than placeholders.

References: packages/…/msg.ts• L18-31 packages/…/msg.ts• L75-108 packages/…/msgString.ts• L7-41 packages/…/getMessages.ts• L56-75

Change checklist

When these files or sections are changed, remember to consider these:

  • Keep the AST element types, parser output, formatter cases, and printer output aligned. A new message element is incomplete until all four views agree.
  • Keep skeleton parsing and native Intl option mapping aligned. A parser change can alter both rendered text and the stable text used by message registration.
  • Keep list formatting and list-part formatting aligned. Both paths must give Intl the same item text when connector choice depends on the following item.
  • Keep StringFormat and DataFormat behavior aligned across the format package and translation interpolation router. STRING must continue to bypass ICU processing.
  • Preserve the source-locale rule for missing translations. Formatting a fallback with the target locale can silently change numbers, dates, and times.
  • Preserve the rich-tag contract. Tag names in message text must match callback variable names, and callback results must remain valid output parts for the caller.
  • Keep encoded message metadata compatible with decodeMsg, decodeOptions, and the message resolution path. Registration and later interpolation share this boundary.
  • Keep locale-resolution scope refresh behavior aligned with mutable configured locale lists and custom mappings. Stale approved-locale data can return the wrong spelling or translation decision.
  • Preserve exact configured identity and candidate priority when changing canonicalization or locale validation. Equivalent locale spellings and aliases do not always have the same caller-visible result.

Important failure modes

TriggerConsequenceGuard
Unclosed braces, invalid argument types, duplicate selectors, or mismatched tagsThe parser throws a syntax error with the source message and locationValidate ICU messages before registration or translation delivery
Missing ICU variableFormatting throws instead of silently choosing an empty valueSupply every variable referenced by the selected message branch
Missing other branch in a select or plural messageDefault parsing rejects the messageInclude other in every branch message
Invalid or unsupported skeleton fieldSkeleton parsing stops before native formattingUse supported number and date-time skeleton fields
Missing Intl.PluralRules in the runtimePlural formatting fails with a MISSING_INTL_API errorProvide the required Intl support or a plural-rules polyfill
Tag variable is not a functionRich-content formatting throws a type errorProvide a callback for each processed tag
List-part formatting uses different item text from list formattingLocale-sensitive connectors can differ between string and rich list outputDerive connector text from the same visible item values in both paths
Translation ICU formatting failsThe i18n path logs a warning and tries the source or returns the original contentKeep translated messages valid for the same format and variable contract
A retained locale list or custom mapping changes without scope refreshLocale negotiation or translation checks use old approved locale dataLet LocaleConfig rebuild its resolution scope before the next lookup
A locale has an invalid or unknown language, region, or script subtagLocale setup rejects the code and later resolution cannot use itValidate locale codes and custom mappings before adding them to the approved set

Key files

FileWhy to read it
packages/…/parser.tsDefines the message grammar and the AST produced for ICU content
packages/…/types.tsDefines the shared concepts for message elements, skeletons, locations, and variables
packages/…/formatter.tsShows how AST elements become locale-aware output
packages/…/skeleton.tsExplains how number and date-time styles become native locale options
packages/…/printer.tsShows how AST content becomes stable, parseable ICU text again
packages/…/core.tsDefines the public formatting boundary and the STRING versus ICU choice
packages/…/format.tsConnects the format package to ICU and shared locale formatters, including list parts
packages/…/format.test.tsShows the public behavior for ICU messages, skeletons, list parts, and relative time
packages/…/package.jsonDefines the package boundary and its ICU package dependency
packages/…/LocaleConfig.tsShows how configured locales, mappings, and defaults enter formatting and locale resolution
packages/…/isValidLocale.tsDefines which mapped, legacy, private-use, and standard locale codes are valid
packages/…/format-package.test.tsVerifies the public package entry points and its main formatting services
packages/…/locales.test.tsShows locale validation, matching, aliases, and locale display fallbacks
packages/…/interpolateMessage.tsRoutes translated content to the correct string format
packages/…/interpolateIcuMessage.tsShows ICU fallback and cutoff behavior in the translation runtime
packages/…/msg.tsShows how registered ICU messages carry source and format metadata