SayKit
ReferenceAPI

saykit

API reference for the saykit core runtime

import { createCatalogue, createScope, createStore, createView } from 'saykit';
import type { Catalogue, Message, Scope, Store, View } from 'saykit';

A catalogue owns the locales and where each one's messages come from; it never formats. A view is one locale bound to its messages: callable, immutable, and what application code holds. A store holds one view at a time and says when it changed.

createCatalogue(messages, options?)

createCatalogue<Locale>(
  messages: Record<Locale, Catalogue.Source>,
  options?: View.Options,
): Catalogue<Locale>;
const catalogue = createCatalogue({
  en,
  fr: () => import('./locales/fr.js'),
});

The keys are the locales, in order, and the first is the fallback match resolves to. Each value is the messages, or a thunk producing them that is called the first time the locale is loaded. Throws if the record is empty. options is passed to every view; see view options. The catalogue is frozen.

locales

readonly [Locale, ...Locale[]]: every locale, in the order written.

locale(code)

The view for a locale, memoised. Synchronous, so it throws for a lazy locale that is not loaded yet, and for a locale the catalogue does not have.

loaded(code)

Whether locale(code) would return a view.

load(code)

Calls the locale's thunk if it has not been called, and returns its view.

const say = await catalogue.load('fr');

Returns a promise only when the thunk does, so a loaded locale comes back synchronously. Overlapping loads share one call; a rejected thunk is forgotten and retried on the next load. A locale is filled once and its messages are never replaced, so a view you hold never changes under you.

To load everything at boot:

await Promise.all(catalogue.locales.map((locale) => catalogue.load(locale)));

match(...guesses)

The best supported locale for one or more guesses. Each guess is a string, null, undefined, or an array of those; nullish and empty values are skipped, so cookie and header values can be passed straight in.

catalogue.match(request.cookies.get('locale')?.value, ['fr-CA', 'en-US']);

Tries an exact match, then the language (fr-CA → fr), then falls back to locales[0].

Iteration

A catalogue yields [locale, say] for every locale, and throws if one is not loaded:

for (const [locale, say] of catalogue) console.log(locale, say`Hello!`);

createView(locale, messages, options?)

createView<Locale>(locale: Locale, messages: View.Messages, options?: View.Options): View<Locale>;

A view with no catalogue behind it, for code that only ever has one locale. Not memoised; with a catalogue, use catalogue.locale(code). The messages are copied and frozen.

View options

Prop

Type

Isolation is right for text a person reads, and wrong for text something parses afterwards, such as a Discord mention <#123>:

const catalogue = createCatalogue({ en, fr }, { bidiIsolation: 'none' });

View

One locale and its messages. Callable, frozen, and with no way back to its catalogue, so switching locale means holding a different view.

Prop

Type

call(descriptor)

Formats a message. The transform writes these calls for you:

say.call({ id: 'abc123', _name: 'Ada' }); // → "Hello, Ada!"

The descriptor names a message by id, or carries a compiled message itself, as for a lone say.date(x). The other keys are values, read by the exact keys the compiled message names: an ICU {name} reads _name, and call strips nothing. Throws if the id is not in the view.

A message is compiled into a closure on its first call and cached on the view. A value that cannot be formatted, such as an invalid date, is written as given with a console warning.

createStore(catalogue, locale?)

createStore<Locale>(catalogue: Catalogue<Locale>, locale?: Locale): Store<Locale>;

A store starting on locale, or locales[0]. Throws if that locale is not loaded.

Store

The current view, and when it changed. It is the one thing that mutates, which makes it a browser value: on a server, look a view up per request instead.

say

The current view. Read it per call: store.say`...` follows switches, a const say = store.say does not. Switching back to a locale returns the same view as before.

set(code)

Switches locale, loading it first if needed. Synchronous for a loaded locale, so subscribers see the change in the same tick.

await store.set('ja');

Setting the current locale does nothing. A failed load keeps the current view. Only the last switch counts: a slow load that resolves after a later set is dropped.

subscribe(listener)

Calls listener(view) after each switch, not on subscribe. Returns an unsubscribe function.

const unsubscribe = store.subscribe((say) => render(say));

createScope(storage?)

A say for code that cannot be handed a view. scope.say resolves, on each use, to the view established around the call.

import { AsyncLocalStorage } from 'node:async_hooks';

// A server: one view per request, kept across awaits
export const scope = createScope(new AsyncLocalStorage());
export const { say } = scope;

scope.run(await catalogue.load(locale), handler);
// A browser: one view for the program, read from a store
export const { say, use } = createScope();
use(store);
  • run(view, callback, ...args) runs callback with view in scope. Without a storage, it holds only until the callback's first await.
  • use(source) sets the view read outside any run: a view, a store (read on every access, so it follows switches), or undefined. Returns a function that puts back what was there.
  • Reading say with no view in scope throws.

compileMessage(message, locale, options?)

compileMessage(message: Message, locale: string, options?: View.Options): (values: Message.Values) => string;

Builds the function that formats one compiled message. Views call this for you; use it to format a Message outside a view.

Macros

Recognised by the SayKit plugins and rewritten to say.call(...). They throw without one. See Messages for each in depth.

say`Hello, ${name}!`;
say({ id: 'greeting', context: 'direction' })`Right`;

say.plural(count, { one: 'You have 1 item', other: `You have ${count} items` });
say.ordinal(position, {
  one: `${position}st`,
  two: `${position}nd`,
  few: `${position}rd`,
  other: `${position}th`,
});
say.select(gender, { male: 'He liked it', female: 'She liked it', other: 'They liked it' });

say.number(total, { style: '::currency/EUR' }); // integer, percent, a skeleton, or a pattern
say.date(post.publishedAt, { style: 'long' }); // short, medium, long, full, or a skeleton
say.time(opensAt, { style: '::Hm' });

say`Your total is ${{ cartTotal: getCartTotal() }}`; // a named placeholder

Types

Message

A compiled message: what saykit compile writes and a view formats. Plain strings, numbers and arrays, so it serialises as JSON.

A node is an array that starts with its Kind, and any other array is a concatenation. Operands are descriptor keys, never nested nodes.

const Kind = {
  Value: 0,
  Number: 1,
  DateTime: 2,
  Plural: 3,
  Ordinal: 4,
  Select: 5,
  Hash: 6,
} as const;

type Message =
  | string // literal text
  | Message[] // concatenation
  | [Kind.Value, string] // a value, by descriptor key
  | [Kind.Number, string, Intl.NumberFormatOptions?, number?] // a number, with a scale
  | [Kind.DateTime, string, Intl.DateTimeFormatOptions?] // a date or time
  | [Kind.Plural, string, Message.Cases, number?] // a cardinal plural, with its offset
  | [Kind.Ordinal, string, Message.Cases, number?] // an ordinal plural, with its offset
  | [Kind.Select, string, Message.Cases] // a select
  | [Kind.Hash]; // the enclosing plural's number

The numbers are the format, so a kind is only ever added, never renumbered.

View.Messages

type Messages = { [id: string]: Message };

Catalogue.Source

type Source = View.Messages | (() => Produced | Promise<Produced>);
type Produced = View.Messages | { default: View.Messages };

A thunk is normally a dynamic import; the catalogue reads the messages off its default export.

Option types

NumeralOptions and SelectOptions are the branch records for plural/ordinal and select; both require other. NumberOptions and DateTimeOptions carry an optional style. Skeleton is `::${string}`.

Next

On this page