DocsCore

ICU messages

Parse, validate, format and inspect ICU messages with @generic-translation/core.

On this page

These functions implement the message format. The React and Node libraries are built on them, and they are public so you can format messages anywhere: in a Worker, a script, an email renderer.

import {
  parseMessage,
  validateMessage,
  formatMessage,
  renderMessage,
  extractVariables,
  extractTags,
  messagesCompatible,
  escapeMessage,
  MessageSyntaxError,
} from "@generic-translation/core";

formatMessage(message, values?, opts?)

Formats a message to a string.

formatMessage(
  "Hello {name}, you have {count, plural, one {# message} other {# messages}}.",
  { name: "Ada", count: 3 },
  { locales: "en" },
);
// "Hello Ada, you have 3 messages."
Option Type Default Meaning
locales string | string[] runtime default Locale for plural rules and number/date formatting.
dataFormat "ICU" | "STRING" "ICU" With "STRING" the message is returned untouched.

Tags are stripped to their inner text unless you provide a function for that tag in values. The function receives the already-formatted inner text:

formatMessage("Read the <0>docs</0> or <b>ask</b>.", {
  0: (chunks: string) => `<a href="/docs">${chunks}</a>`,
});
// 'Read the <a href="/docs">docs</a> or ask.'

formatMessage does not escape HTML. If you build HTML this way, escape the interpolated values yourself.

renderMessage(message, values, opts)

The general form: instead of a string it returns an array of parts, and you decide what a tag becomes. This is how @generic-translation/react turns a translation back into elements.

function renderMessage<T>(
  message: string | MessageNode[],
  values: Record<string, unknown>,
  opts: {
    locales?: string | string[];
    tag: (name: string, children: (string | T)[], index: number) => T | string;
  },
): (string | T)[];
const parts = renderMessage<React.ReactNode>(
  "Read the <0>terms</0> first.",
  {},
  {
    locales: "en",
    tag: (name, children, index) => <a key={index} href="/terms">{children}</a>,
  },
);
// ["Read the ", <a href="/terms">terms</a>, " first."]

message may be a pre-parsed node array, which avoids parsing the same message on every render.

parseMessage(message)

Parses a message into an array of MessageNode. Throws MessageSyntaxError when the message is malformed. The error message says what was expected, and the error carries position (a character offset), reason and the source message.

try {
  parseMessage("{count, plural, one {# file}}");
} catch (e) {
  if (e instanceof MessageSyntaxError) console.error(e.message);
}

Node types, exported individually: TextNode, ArgumentNode, NumberNode, DateNode, TimeNode, PluralNode, SelectOrdinalNode, SelectNode, TagNode, PoundNode (the # inside a plural).

validateMessage(message)

The non-throwing version, convenient in forms and CI checks.

validateMessage("Hello {name}");      // { valid: true }
validateMessage("Hello {name");
// { valid: false, error: "Unclosed argument: expected '}' (at position 6)" }

extractVariables(message)

Lists the arguments a message uses, with their types.

extractVariables("{name} bought {count, plural, one {# item} other {# items}} for {total, number, ::currency/USD}");
// [
//   { name: "name",  type: "argument" },
//   { name: "count", type: "plural" },
//   { name: "total", type: "number" },
// ]

extractTags(message)

Lists the tag names in a message.

extractTags("Read <0>this</0> and <1>that</1>.<2/>");  // ["0", "1", "2"]

messagesCompatible(source, translation)

Checks that a translation uses the same variables and tags as its source. This is the rule the API enforces when a translation is saved.

messagesCompatible("Hello <0>{name}</0>", "Hola <0>{name}</0>");
// { ok: true, problems: [] }

messagesCompatible("Hello <0>{name}</0>", "Hola {nombre}");
// { ok: false, problems: ["Missing variable {name}", "Unexpected variable {nombre}", "Missing tag <0>"] }

Plural and select branches are allowed to differ, because languages need different plural categories.

escapeMessage(text)

Escapes literal text so it can be embedded in an ICU message without being read as syntax.

escapeMessage("Use {curly} braces");  // "Use '{'curly'}' braces"

Use it when you build messages programmatically from text you do not control.

JSX serialization

Two functions define how JSX turns into a message. Application code rarely calls them; they are public because the CLI and @generic-translation/react must share one implementation, and so that other tools can produce identical messages and hashes.

type JsxNode =
  | { type: "text"; value: string }
  | { type: "element"; children: JsxNode[] }
  | { type: "var"; kind: "var" | "num" | "currency" | "datetime"; name?: string; currency?: string }
  | { type: "plural"; name?: string; branches: Record<string, JsxNode[]> }
  | { type: "branch"; name?: string; branches: Record<string, JsxNode[]>; fallback: JsxNode[] };

function serializeJsx(nodes: JsxNode[]): { message: string; variables: string[]; tagCount: number };
function cleanJsxText(raw: string): string;
  • cleanJsxText applies the standard JSX whitespace rules to raw text between tags: lines are trimmed, blank lines dropped, and remaining lines joined with a single space.
  • serializeJsx produces the message. The rules are listed under how JSX becomes a message.
serializeJsx([
  { type: "text", value: "Hello " },
  { type: "element", children: [{ type: "var", kind: "var", name: "name" }] },
]);
// { message: "Hello <0>{name}</0>", variables: ["name"], tagCount: 1 }

Something wrong or unclear on this page? Open an issue.

Type to search the documentation.