Skip to content

`@palamedes/core`

Palamedes v2 executes compiled catalogs through one parser-free runtime on server and client. ICU is an authoring, translation, validation and compilation format. Framework adapters own ordinary catalog delivery; explicit catalog loading remains available for standalone/custom integrations.

Page outline

@palamedes/core

Exports

The package root and @palamedes/core/compiled share the same implementation. Their complete generated inventories follow. The choice prop types PluralProps, SelectProps, and SelectOrdinalProps are exported from @palamedes/core/macro. CompiledPalamedesI18n is a type alias for PalamedesI18n. Build packages and run pnpm check:core-api-reference to verify source, declarations, ESM and CJS exports.

ExportKind
CatalogMessageType-only
CatalogMessagesType-only
CompiledCatalogMessagesType-only
CompiledMessageType-only
CompiledMessageBranchType-only
CompiledMessageBranchesType-only
CompiledMessageRuntimeType-only
CompiledPalamedesI18nType-only
createI18nRuntime
CreateI18nOptionsType-only
DEFAULT_LOCALERuntime
defineCompiledCatalogRuntime
isCompiledCatalogRuntime
MessageFormatErrorInfoType-only
MessageMetadataType-only
MessageValuesType-only
MissingCompiledMessageErrorRuntime
MissingMessageInfoType-only
PalamedesI18nType-only
ExportKind
CatalogMessageType-only
CatalogMessagesType-only
CompiledCatalogMessagesType-only
CompiledMessageType-only
CompiledMessageBranchType-only
CompiledMessageBranchesType-only
CompiledMessageRuntimeType-only
CompiledPalamedesI18nType-only
createI18nRuntime
CreateI18nOptionsType-only
DEFAULT_LOCALERuntime
defineCompiledCatalogRuntime
isCompiledCatalogRuntime
MessageFormatErrorInfoType-only
MessageMetadataType-only
MessageValuesType-only
MissingCompiledMessageErrorRuntime
MissingMessageInfoType-only
PalamedesI18nType-only

createI18n(options?)

Creates an isolated instance with initial locale (default "en"), optional IANA timeZone, and optional onMissing/onError observers. Use identical time zones during server rendering and hydration. Invalid or empty zones throw RangeError at construction. Dates/timestamps represent instants; date-only ISO strings such as "2026-06-12" retain their civil calendar date in every zone.

A standalone integration can load generated modules explicitly:

import { createI18n } from "@palamedes/core";
import { messages } from "./generated/de.js";

const i18n = createI18n({ locale: "de", timeZone: "Europe/Berlin" });
i18n.load("de", messages);

load() accepts only branded CompiledCatalogMessages: constants are already compiled literal strings; dynamic messages are executable functions. An unbranded ICU string map is rejected. CatalogMessages remains a type for build-time string data; it is not a runtime loading input. Do not mark ICU patterns with defineCompiledCatalog() to bypass compilation: that function brands constants, it does not compile ICU.

PalamedesI18n

interface PalamedesI18n {
  readonly locale: string;
  readonly timeZone?: string;
  number(value: number | string, options?: Intl.NumberFormatOptions & { locale?: string }): string;
  date(
    value: Date | number | string,
    options?: Intl.DateTimeFormatOptions & { locale?: string },
  ): string;
  _(id: string, values?, metadata?): string;
  load(locale: string, messages: CompiledCatalogMessages): void;
  activate(locale: string): void;
  renderMessage<TResult>(id, values, runtime, metadata?): TResult;
}

_() executes a compiled message as text. renderMessage() executes the same message with a framework renderer; the React, Solid and Remix Trans components use it for rich text. Later catalog loads add or override entries for that locale. Invalid entry types are rejected before the existing catalog is modified.

Formatting values outside messages

Use getI18n().number() and getI18n().date() for table cells, charts, and other values outside translated messages. Both methods work before any catalog is loaded. They read the instance's active locale on each call, including after activate(), and accept the platform's Intl options. options.locale overrides the locale for one call; date() also accepts options.timeZone, which takes precedence over the instance's configured time zone for instants.

import { createI18n } from "@palamedes/core";

const i18n = createI18n({ locale: "en-US", timeZone: "America/Los_Angeles" });

i18n.number(1234.56, { style: "currency", currency: "EUR" }); // €1,234.56
i18n.number(1234.56, { style: "currency", currency: "JPY" }); // ¥1,235
i18n.number(1234.56, { style: "currency", currency: "KWD" }); // KWD 1,234.560
i18n.number(0.125, { style: "percent", maximumFractionDigits: 1 }); // 12.5%
i18n.number(12000, { notation: "compact" }); // 12K
i18n.number(1234.56, { locale: "de-DE" }); // 1.234,56

i18n.date("2026-11-03", { dateStyle: "medium" }); // Nov 3, 2026
i18n.date("2026-11-03T00:00:00Z", { dateStyle: "medium" }); // Nov 2, 2026
i18n.date("2026-11-03T00:00:00Z", {
  dateStyle: "medium",
  timeStyle: "short",
  timeZone: "Asia/Tokyo",
});

number() accepts finite numbers and non-empty strings that convert to a finite JavaScript number, matching compiled number arguments. date() accepts valid Date objects, timestamps in milliseconds, and strings parsed by JavaScript's Date constructor. Use ISO strings with an explicit offset or Z for portable instants. A date-only ISO string (YYYY-MM-DD) is a civil date: it is formatted in UTC to preserve its calendar day, even with a per-call time zone. A Date or timestamp created from that string is an instant instead.

Invalid values throw TypeError; invalid Intl options propagate Intl's RangeError or TypeError. These standalone calls do not invoke the message-specific onMissing or onError observers. Missing-value placeholders, currencies, units, and business rounding remain application choices.

Standalone helpers and compiled message arguments share bounded Intl formatter caches keyed by locale and effective options. Per-call overrides do not change the instance or another request's instance. Server/client output agrees when locale, time zone, input values, options, and Intl data match. Without an explicit time zone, instants use the host's time zone.

Internal compiled format

CompiledMessage, CompiledMessageBranch, CompiledMessageBranches, CompiledMessageRuntime and the generated catalog module format are internal. The root exports these types only because renderMessage() names them. The runtime factory createCompiledMessageRuntime() and its ExecutableMessageRenderer input live on the Internal subpath @palamedes/core/internal, where the React, Solid and Remix Trans renderers import them. None of this is an extension point: generated catalogs and the renderer interface change together with the Palamedes packages. Create instances with createI18n() and render rich text through the framework Trans macro.

A missing compiled entry throws MissingCompiledMessageError. Its id, locale and optional metadata identify the failure for developer diagnostics; the error message itself does not expose the internal ID. Use ordinary host error handling with an independently usable error view. Delivery failure is not translation fallback: missing translations are resolved and compiled at build time, following configured fallback locales and then the source message.

onMissing observes misses, and onError receives { id, locale, error, metadata } for execution failures. Neither a hook return value nor a thrown observer error can turn failure into successful message output. Formatter errors and missing required values propagate rather than rendering source patterns or IDs.

MessageMetadata

The optional { message, context, comment } record preserves authored identity for diagnostics only. No field supplies replacement runtime output. The old reportMissing and renderUncompiledPattern controls are removed.

Locale Controls

@palamedes/core/locale exposes headless locale helpers used by the example matrix and reusable in apps:

ExportKind
buildLocaleSwitchItemsRuntime
BuildLocaleSwitchItemsOptionsType-only
consumeChoiceHandoffRuntime
createChoiceHandoffUrlRuntime
defineLocaleControlsRuntime
HostLocaleConfigType-only
LocaleControlsType-only
LocaleControlsConfigType-only
LocaleSeoLinkType-only
LocaleSourceType-only
LocaleSuggestionType-only
LocaleSwitchItemType-only
parseAcceptLanguageRuntime
  • parseAcceptLanguage(header): parses and quality-sorts Accept-Language tags, including base-language fallbacks. Input length, parsed entry count, and tag length are bounded so oversized headers stay fast.
  • buildLocaleSwitchItems(options): builds UI-agnostic switch items with labels, active state, locale, and test ids.
  • defineLocaleControls(config): binds locale resolution, deliberate-choice cookies, canonical URLs, and suggestion decisions for cookie, route, domain, subdomain, and tld strategies. Host-carrying URLs from canonicalUrl and suggest are protocol-relative (//host/path) unless the config sets protocol (e.g. "https"), so HTTPS pages never link users to http://. Invalid configuration is rejected at construction time with field-specific errors. Cookie names, protocols, configured hosts, and TLD labels are validated; locale identifiers must be DNS-safe only for the host-based subdomain and tld strategies. canonicalUrl, suggest, and seoLinks ignore malformed requestHost values, normalize pathname to begin with a single / (preventing protocol-relative, backslash, and userinfo redirects), and require search to be empty or start with ? without control characters. serializeChoice(locale, { secure? }) validates that locale is configured and appends ; Secure when secure: true. Language preferences match case-insensitively, preserve configured output spelling, and infer missing script/region fields with Intl.Locale.maximize(). Exact identities for cookies and routes remain case-sensitive. See language preference matching for quality ordering, exclusions, and ambiguity rules. suggest() derives browser-language hints from Accept-Language. A recorded choice matching the current locale suppresses the hint. An earlier choice for a different locale never replaces the browser preference; host mismatches remain independent of that choice.
  • hosts: { mode: "domain", locales: { en: "product.example", de: "mein-produkt.de" } } selects explicit language domains: an authoritative, complete locale-to-host map without path prefixes. Top-level domain (tld) mode replaces only the final DNS label (product.com to product.de); domain mode can also change the rest of the hostname (my-product.com to mein-produkt.de). Existing TLD sites can keep their strategy. Use resolve({ strategy: "domain", requestHost }) for request detection or retain the fixed locale of a static build. Hosts must identify distinct locales; configured destination ports are preserved without inheriting the request port. The existing map mode retains locale-prefixed paths.
  • controls.seoLinks({ locale, pathname, requestHost?, search?, xDefaultLocale? }) returns LocaleSeoLink descriptors for the canonical, configured language alternates, and the default locale's x-default. An explicit configured xDefaultLocale overrides it; false omits it. Unsupported locales throw TypeError. Set protocol: "https" for absolute URLs, and supply the canonical build host for TLD/subdomain prerendering. Rendering and sitemap XML stay with the application.
  • createChoiceHandoffUrl({ url, locale, currentOrigin, parameterName? }): adds the selected locale to a cross-origin URL using the __palamedes_locale_choice query parameter by default and returns an absolute URL. Same-origin URLs do not receive a handoff parameter. It uses the URL API without accessing window or navigating. The source and target must use HTTP or HTTPS; other schemes throw TypeError.
  • consumeChoiceHandoff({ search, currentLocale, locales, parameterName? }): removes the handoff parameter from a search string and returns { choice, search }. It accepts only one supported locale that matches the destination's current locale. The caller decides when to persist choice with serializeChoice() and whether to replace the browser URL with the cleaned search string.

Macro Entry Point

Macros are imported from @palamedes/core/macro and must be compiled by a Palamedes plugin before runtime.

ExportKind
ChoiceMacroMetadataType-only
pluralRuntime
PluralMacroPropsType-only
PluralPropsType-only
selectRuntime
SelectMacroPropsType-only
selectOrdinalRuntime
SelectOrdinalMacroPropsType-only
SelectOrdinalPropsType-only
SelectPropsType-only
tRuntime

Supported macro names:

  • t
  • plural
  • select
  • selectOrdinal

All four macros resolve translations eagerly. They must therefore be used inside a function, method, or callback, after the application has activated the relevant i18n scope. Palamedes rejects these macros at module scope during transformation and extraction. Class field initializers, including instance fields, do not satisfy this syntactic rule; use a method or getter instead.

Every plural, select, and selectOrdinal branch must be a string literal or a template literal, for example plural(count, { one: "# item", other: `# items for ${name}` }). Extraction and the transform reject any other branch value, such as a constant, a member expression, JSX, or a nested t, plural, or select call, with an error that names the branch and its source location. A nested macro imported under another name, such as plural as p, is reported the same way. Write the complete sentence in each branch instead of composing it from other messages. Branch names must be static as well: spread options ({ ...rest }) and computed keys ({ [key]: "…" }) fail with a located error instead of being dropped.

Runtime Formatting

Compiled messages support values, rich-text tags, select, plural and selectordinal, ICU apostrophe quoting, plural offsets, and the supported Intl formatter subset. Number styles are omitted/default, percent, integer, ::percent, ::integer, and ::currency/ISO; date/time styles are omitted, short, medium, long, or full. Invalid or unsupported ICU fails compilation. Invalid formatter values throw during execution.

The framework renderers share their compiled message runtime factory and Intl formatting helpers through the Internal subpath @palamedes/core/internal. Applications do not import it; format values through compiled messages or the instance's number() and date() methods.

parseMessagePattern(), formatMessagePattern(), getMessage(), getMessageNodes(), parsePattern(), parsed-node types, resolveChoice(), buildChoiceMessage() and reportError() are removed from application runtime exports. Compile authoring catalogs with the existing compiler/tooling APIs. See the v2 runtime migration guide for concrete replacements.

Edit this page on GitHubLast updated: November 28, 2026