Files
CatoandClaude dabd10d66d langkit 0.2.0: remember the choice, hreflang, unused messages, a switcher that fits a phone (#19)
- rememberLocale (+ switchLocaleHref, localeCookie, isSafeNextPath): the route
  that remembers a reader's language in an app with no language in its URL;
  relative 303, checked next, Secure over HTTPS (sbb-fundbuero's lessons)
- alternateLanguages: hreflang alternates for Next metadata
- langkit check --code <dirs> [--fail-unused]: messages no code appears to ask
  for; measured on eight apps, hand-traced samples were dead messages
- fix: with nineteen languages the switcher widened a 390px page to 1081px
  inside sitekit's masthead; now it scrolls inside itself. Checked in a real
  browser at 320/390/1280px
- first public version: private removed, 0.2.0 (0.1.0 was never published)


Claude-Session: https://claude.ai/code/session_019MDtmsTRGc34xnG6koVuAY

Co-authored-by: Claude <noreply@anthropic.com>
2026-11-30 07:41:24 +01:00
..

@bitbaum/langkit

One way to be multilingual, for every app in the fleet.

Twenty-two apps carry more than one language and no two do it the same way (the survey): eight private Accept-Language parsers, four names for the cookie, twelve home-made "is every language complete?" checks, and Swiss spelling kept by a test in one app and by a transform in another. langkit is those parts, written once:

  • the language list — each language's own name, its English name, how it is read, and what it falls back to;
  • how a page picks its language — what the reader chose, then the browser, then the language of the content, then the default;
  • typed messages that work in a server component with no provider and no client bundle;
  • Swiss German as a transform — de-CH is the German table with ss for ß and «guillemets», never a second translation;
  • langkit check — fails verify when a language does not say what the source says;
  • dates, numbers and plurals in each language's conventions;
  • a language switcher that sits in sitekit's header.

Messages are ICU MessageFormat, formatted by use-intl, the engine under next-intl — the format fourteen apps already use. Why that and not something else: the decision.

pnpm add @bitbaum/langkit

The first version on npm is 0.2.0 (0.1.0 was merged private and never published). A brand-new package needs the owner's one npm sign-in before GitLab may publish it (root README, "The one case that does").

The language list

// lib/languages.ts — the one list every other file reads
import { defineLanguages } from "@bitbaum/langkit";

export const languages = defineLanguages({
  locales: ["en", "de", "de-CH", "fr"],
  defaultLocale: "en",
  // Optional: the conventions dates and numbers follow, where not the code's.
  formatTags: { fr: "fr-CH" },
});

languages.name("de-CH"); // "Deutsch (Schweiz)" — for a switcher
languages.english("fr"); // "French" — for the instruction a model is given
languages.html("de"); // { lang: "de", dir: "ltr" } — spread onto <html>
languages.fallbacks("de-CH"); // ["de-CH", "de", "en"]
languages.isLocale(value); // a type guard for a URL segment or a cookie

langkit knows the nineteen languages some app serves today (LANGUAGES). An unknown code is refused when the list is defined; add the language to LANGUAGES in this package (the next app needs it too) or pass it in custom.

Which languages an app offers stays the app's decision. A language is a promise that someone can be served in it.

Picking the language

import { cookies, headers } from "next/headers";
import { LOCALE_COOKIE, pickLocale } from "@bitbaum/langkit";

const { locale, source } = pickLocale(languages, {
  chosen: params.locale ?? (await cookies()).get(LOCALE_COOKIE)?.value,
  acceptLanguage: (await headers()).get("accept-language"),
  content: report.language,
});

The order is fixed: the reader's choice, the browser, the content's language, the default. source says which one decided ("choice", "browser", "content", "default"), for a test or for a "shown in English because…" notice. Leave an input out and that step is skipped: an app whose URL alone decides passes only chosen.

A tag is matched to itself (de-CH), then to its language (de-AT → de), then — for the spoken language — to how it is written (gsw → de-CH, then de), then to the only variant the app has (de → de-CH). LOCALE_COOKIE is NEXT_LOCALE, the name next-intl writes.

Remembering the choice without a language in the URL

An app whose URLs carry no language (BiasLens, sbb-fundbuero, hirnli) needs one route that sets the cookie and sends the reader back:

// app/api/locale/route.ts
import { rememberLocale } from "@bitbaum/langkit";
import { languages } from "@/lib/languages";

export const GET = (request: Request) => rememberLocale(languages, request);

/api/locale?to=fr&next=/fundsachen answers 303 with the cookie set. Three lessons from sbb-fundbuero's route are built in: next must be a path on this site (//evil.example and /\evil.example go to /); the Location is relative, because behind the box's proxy the app's own origin is a loopback port; and an unknown language gets the default, not an error page. Secure is added when the reader came over HTTPS. switchLocaleHref(to, path) builds the link; localeCookie and isSafeNextPath are there for a route of your own.

Search engines

export const generateMetadata = () => ({
  alternates: {
    languages: alternateLanguages(languages, (l) => `/${l}/about`, "https://example.ch"),
  },
});

Every language's page by its lang (zh → zh-Hans), plus x-default for the default language's.

Messages

// lib/messages.ts
import { createMessages } from "@bitbaum/langkit";
import { languages } from "./languages";
import en from "../messages/en.json";
import de from "../messages/de.json";
import fr from "../messages/fr.json";

export const messages = createMessages({ languages, tables: { en, de, fr } });
// any server component — no provider, nothing sent to the browser
const t = messages.translator(locale, "rewrite");
<h1>{t("title")}</h1>
<p>{t("evidence", { count: findings.length })}</p>
{
  "rewrite": {
    "title": "Rewrite studio",
    "evidence": "Cites {count, plural, one {# finding} other {# findings}} from linked studies."
  }
}
  • Keys are typed from the default language's table: a key that is not there does not compile. With a table written as const, so are the arguments each message takes.
  • A message a translation has not reached is the default language's sentence, never a raw key.
  • de-CH has no file. Its table is German respelled. An app whose German is Swiss throughout sets spelling: { de: swissGerman } instead.
  • messages.table(locale) is the finished table, for next-intl's request config: return { locale, messages: messages.table(locale) }.
  • messages.formatter(locale) formats outside a message: .number(1234.5), .dateTime(date, { dateStyle: "long" }), .list([...]), .relativeTime(date).
  • A missing message or a formatting error goes to onError if you pass one; otherwise use-intl logs it and shows the key.

An app with the language in its URL keeps next-intl for routing, navigation and hooks in client components; langkit supplies the list, the picker, the table and the check. See "From next-intl with copied helpers" below.

The check

langkit check messages --source en --swiss de

Reads messages/<language>.json (files starting with _ are skipped), exits 1 with one line per finding, and belongs in the app's verify:

"verify": "pnpm run lint && pnpm run typecheck && langkit check messages --swiss de && pnpm run test"
Finding Means
missing the source has the key, this language does not
extra this language has a key the source does not
empty blank where the source says something
syntax not valid ICU MessageFormat
arguments a {name} or <tag> the source takes is absent, or one it does not take is present
plural a plural lacks a form this language needs for the numbers a page shows (Russian few and many, French one)
spelling ß in a language listed under --swiss

--pending Essays,Roadmap names namespaces that are not translated yet: their keys may be missing, everything else is still checked, and taking a name out is how a translation becomes required. --json prints the findings as data. Tables that are not JSON files go through the function: checkMessages({ source, tables, pending, swiss }) from @bitbaum/langkit/check, in a test.

Messages nobody uses

langkit check messages --code app,components,lib

also lists source messages no code under those folders appears to ask for: a sentence translated into every language for nothing, which nobody notices when it stops being true. The code is read, not run, so a key counts as asked for when the whole key is a string in the code, when a namespace and the rest both are (useTranslations("Nav") … t("home")), when it is built from a fixed start or end (t(`forms.${kind}`), t(`${g.key}.body`)), or when its parent is read whole (t.raw("mega")). It errs towards "used", so what it lists is worth reading. It is a report (exit 0); add --fail-unused to make it fail verify once an app's list is clean.

Measured on 2026-11-30 against the apps' mirrors: causius 61 of 983 messages, solon 30 of 2295, diplodoctor 58 of 663, petvity 111 of 1417, surf-your-life 164 of 1487, vitareba 97 of 398, evig 345 of 6306, hirnli 0 of 56. The samples traced by hand were dead: causius's Nav.cases after its header moved to "matters", diplodoctor's whole Reports namespace, vitareba's auth.login.* labels after its sign-in page took them from accountkit.

The messages are parsed by FormatJS's ICU parser, not matched with a regular expression, so a { inside a plural branch is not mistaken for an argument and a dropped link tag is found.

The switcher

import { LanguageSwitcher } from "@bitbaum/langkit/react";
import "@bitbaum/langkit/styles.css";

<SiteMasthead
  appearance="application"
  actions={
    <LanguageSwitcher
      languages={languages}
      current={locale}
      hrefFor={(to) => `/${to}${pathWithoutLocale}`}
      label={t("language")}
      Link={Link}
    />
  }
  …
/>

Every language is a real link to the same page, so it works without JavaScript and renders on the server. One row of equal 44px cells; many languages scroll sideways instead of wrapping. Each link carries its own lang, so a screen reader pronounces "Français" in French. show="name" shows names instead of codes. Colours follow sitekit's variables (--sk-fg, --sk-muted, --sk-focus, --sk-radius) or your own --lk-*.

An app that keeps the choice in a cookie points hrefFor at the route that sets it: (to) => switchLocaleHref(to, path) (see "Remembering the choice").

In sitekit's application masthead the switcher sits in actions. Up to 380px wide sitekit moves those into the menu, so on the narrowest phones the languages are one tap away. A long list scrolls sideways inside the switcher rather than widening the page: test/switcher-browser.test.js checks four and nineteen languages at 320, 390 and 1280px.

Migrating

From hand-written copy tables (BiasLens, Heidi, s-ink, …)

The starting point is a file like BiasLens's rewrite-copy.ts: an interface, one object per language holding strings and small functions, and a swiss() walk for de-CH. test/biaslens-proof.test.js does this migration on a copy of that file and shows all 107 entries say the same in four languages.

  1. Declare the languages once (lib/languages.ts, above) and delete the app's own list, names and isLocale.

  2. Draft the message files. A function that only places its arguments becomes a message with placeholders; toIcu writes it:

    // scripts/draft-messages.ts — run once, then delete
    import { writeFileSync } from "node:fs";
    import { toIcu } from "@bitbaum/langkit/migrate";
    import { rewriteCopy } from "../src/lib/config/rewrite-copy";
    
    for (const locale of ["en", "de", "fr"]) {
      const { messages, manual } = toIcu(rewriteCopy(locale));
      writeFileSync(`messages/${locale}.json`, JSON.stringify({ rewrite: messages }, null, 2));
      console.log(locale, "write by hand:", manual);
    }
    

    (name) => \Write AI ${name}’s answer`becomes"Write AI {name}’s answer". Draft only the translated languages: not de-CH`.

  3. Write by hand what manual lists. These are the functions that decide something, and each is a plural or a select:

    evidence: (count) => `Cites ${count} finding${count === 1 ? "" : "s"} …`,
    
    "evidence": "Cites {count} {count, plural, one {finding} other {findings}} …"
    

    Write the forms the language has, not the ones English has. French counts zero as singular; Russian needs one, few and many. The check tells you which are missing.

  4. Create the messages (lib/messages.ts, above) and run langkit check messages. Fix what it finds.

  5. Change the call sites, one table at a time. Both can live side by side.

    const copy = rewriteCopy(language);        // before
    copy.title;
    copy.by.ask(name);
    copy.evidence(count);
    
    const t = messages.translator(language, "rewrite"); // after
    t("title");
    t("by.ask", { name });
    t("evidence", { count });
    

    A client component cannot call messages.translator without bundling the tables. Pass it the strings it needs as props from the server component above it, or — in an app that already runs next-intl — use its useTranslations hook there.

  6. Delete the table, its interface, the swiss() walk and the app's localizeSpelling. Keep swissGerman from langkit for text that is not a message (a model's output): languages.spell("de-CH", text).

  7. Make the page one language. Pick the page's language once with pickLocale (the content's language is the third input), put languages.html(locale) on <html>, and move the English page furniture into the same message files. A report in another language than the page keeps its own lang on its own element.

  8. Add the check to verify.

Two things change on purpose, both shown as tests in the proof:

  • A name put into a Swiss German sentence is no longer respelled. BiasLens's walk respells whatever a function returns, so "Alice Weiß" becomes "Alice Weiss"; langkit respells the sentence and leaves the name.
  • Plurals follow the language's rules. count === 1 ? "" : "s" writes "0 résultats"; French makes zero singular.

From next-intl with copied helpers (the template, causius, solon, …)

Nothing about the messages or the components changes.

  1. i18n/routing.ts: build the list with defineLanguages and hand languages.locales and languages.defaultLocale to defineRouting. Delete localeNames, localeEnglishNames and toLocale.
  2. i18n/request.ts: delete the local withFallback; return { locale, messages: messages.table(locale) }.
  3. Delete i18n/parity.test.ts; add langkit check messages --swiss de to verify (--pending for namespaces the app has declared untranslated). Expect findings the old test could not see; the survey lists the ones found on 2026-11-29.
  4. Replace components/LocaleSwitcher.tsx with LanguageSwitcher, passing next-intl's Link.
  5. If the app parses Accept-Language or reads a locale cookie itself, replace that with pickLocale.

What is in the box

Import Holds
@bitbaum/langkit defineLanguages, LANGUAGES, pickLocale, matchLocale, parseAcceptLanguage, LOCALE_COOKIE, LOCALE_COOKIE_MAX_AGE, createMessages, withFallback, swissGerman, spellTree, rememberLocale, switchLocaleHref, localeCookie, isSafeNextPath, alternateLanguages
@bitbaum/langkit/check checkMessages, formatProblems, leaves, findUnused, literalsOf
@bitbaum/langkit/migrate toIcu, escapeIcu
@bitbaum/langkit/react LanguageSwitcher
@bitbaum/langkit/styles.css the switcher's styles
langkit check <dir> the command

Depends on use-intl (MIT) and @formatjs/icu-messageformat-parser (MIT); react is a peer, as it is for use-intl.

Working on it

pnpm run verify   # format, lint, types (incl. test/types/consumer.ts), build, tests

The browser check needs Playwright's Chromium, as sitekit's does. Where the installed Chromium is not the one this Playwright expects, point PLAYWRIGHT_CHROMIUM_EXECUTABLE_PATH at it.

test/fixtures/biaslens/rewrite-copy.ts is a verbatim copy of another repo's file at a named commit. It is not formatted or linted here, and it is not updated when BiasLens changes: it is the evidence for one migration, not a mirror.